Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1172.2.12
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1172.2.12! raeburn 4: # $Id: lonnet.pm,v 1.1172.2.11 2012/09/25 23:06:07 raeburn Exp $
1.178 www 5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27: #
1.169 harris41 28: ###
29:
1.971 jms 30: =pod
31:
1.972 jms 32: =head1 NAME
33:
34: Apache::lonnet.pm
35:
36: =head1 SYNOPSIS
37:
38: This file is an interface to the lonc processes of
39: the LON-CAPA network as well as set of elaborated functions for handling information
40: necessary for navigating through a given cluster of LON-CAPA machines within a
41: domain. There are over 40 specialized functions in this module which handle the
42: reading and transmission of metadata, user information (ids, names, environments, roles,
43: logs), file information (storage, reading, directories, extensions, replication, embedded
44: styles and descriptors), educational resources (course descriptions, section names and
45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
46: and from more descriptive phrases or explanations.
47:
48: This is part of the LearningOnline Network with CAPA project
49: described at http://www.lon-capa.org.
50:
1.971 jms 51: =head1 Package Variables
52:
53: These are largely undocumented, so if you decipher one please note it here.
54:
55: =over 4
56:
57: =item $processmarker
58:
59: Contains the time this process was started and this servers host id.
60:
61: =item $dumpcount
62:
63: Counts the number of times a message log flush has been attempted (regardless
64: of success) by this process. Used as part of the filename when messages are
65: delayed.
66:
67: =back
68:
69: =cut
70:
1.1 albertel 71: package Apache::lonnet;
72:
73: use strict;
1.8 www 74: use LWP::UserAgent();
1.486 www 75: use HTTP::Date;
1.977 amueller 76: use Image::Magick;
77:
1.871 albertel 78: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.1138 raeburn 79: $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
80: %managerstab);
1.871 albertel 81:
82: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
83: %userrolehash, $processmarker, $dumpcount, %coursedombuf,
84: %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958 www 85: %courseownerbuf, %coursetypebuf,$locknum);
1.403 www 86:
1.1 albertel 87: use IO::Socket;
1.31 www 88: use GDBM_File;
1.208 albertel 89: use HTML::LCParser;
1.88 www 90: use Fcntl qw(:flock);
1.870 albertel 91: use Storable qw(thaw nfreeze);
1.539 albertel 92: use Time::HiRes qw( gettimeofday tv_interval );
1.599 albertel 93: use Cache::Memcached;
1.676 albertel 94: use Digest::MD5;
1.790 albertel 95: use Math::Random;
1.1024 raeburn 96: use File::MMagic;
1.807 albertel 97: use LONCAPA qw(:DEFAULT :match);
1.740 www 98: use LONCAPA::Configuration;
1.1160 www 99: use LONCAPA::lonmetadata;
1.1117 foxr 100:
1.1090 raeburn 101: use File::Copy;
1.676 albertel 102:
1.195 www 103: my $readit;
1.550 foxr 104: my $max_connection_retries = 10; # Or some such value.
1.1 albertel 105:
1.619 albertel 106: require Exporter;
107:
108: our @ISA = qw (Exporter);
109: our @EXPORT = qw(%env);
110:
1.1172.2.9 raeburn 111: # ------------------------------------ Logging (parameters, docs, slots, roles)
1.729 www 112: {
113: my $logid;
1.1172.2.9 raeburn 114: sub write_log {
115: my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
116: if ($context eq 'course') {
117: if (($cnum eq '') || ($cdom eq '')) {
118: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
119: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
120: }
1.957 raeburn 121: }
1.729 www 122: $logid++;
1.957 raeburn 123: my $now = time();
124: my $id=$now.'00000'.$$.'00000'.$logid;
1.1172.2.9 raeburn 125: my $logentry = {
126: $id => {
127: 'exe_uname' => $env{'user.name'},
128: 'exe_udom' => $env{'user.domain'},
129: 'exe_time' => $now,
130: 'exe_ip' => $ENV{'REMOTE_ADDR'},
131: 'delflag' => $delflag,
132: 'logentry' => $storehash,
133: 'uname' => $uname,
134: 'udom' => $udom,
135: }
136: };
137: return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
1.729 www 138: }
139: }
1.1 albertel 140:
1.163 harris41 141: sub logtouch {
142: my $execdir=$perlvar{'lonDaemons'};
1.448 albertel 143: unless (-e "$execdir/logs/lonnet.log") {
144: open(my $fh,">>$execdir/logs/lonnet.log");
1.163 harris41 145: close $fh;
146: }
147: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
148: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
149: }
150:
1.1 albertel 151: sub logthis {
152: my $message=shift;
153: my $execdir=$perlvar{'lonDaemons'};
154: my $now=time;
155: my $local=localtime($now);
1.448 albertel 156: if (open(my $fh,">>$execdir/logs/lonnet.log")) {
1.986 foxr 157: my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
158: print $fh $logstring;
1.448 albertel 159: close($fh);
160: }
1.1 albertel 161: return 1;
162: }
163:
164: sub logperm {
165: my $message=shift;
166: my $execdir=$perlvar{'lonDaemons'};
167: my $now=time;
168: my $local=localtime($now);
1.448 albertel 169: if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
170: print $fh "$now:$message:$local\n";
171: close($fh);
172: }
1.1 albertel 173: return 1;
174: }
175:
1.850 albertel 176: sub create_connection {
1.853 albertel 177: my ($hostname,$lonid) = @_;
1.851 albertel 178: my $client=IO::Socket::UNIX->new(Peer => $perlvar{'lonSockCreate'},
1.850 albertel 179: Type => SOCK_STREAM,
180: Timeout => 10);
181: return 0 if (!$client);
1.890 albertel 182: print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850 albertel 183: my $result = <$client>;
184: chomp($result);
185: return 1 if ($result eq 'done');
186: return 0;
187: }
188:
1.983 raeburn 189: sub get_server_timezone {
190: my ($cnum,$cdom) = @_;
191: my $home=&homeserver($cnum,$cdom);
192: if ($home ne 'no_host') {
193: my $cachetime = 24*3600;
194: my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
195: if (defined($cached)) {
196: return $timezone;
197: } else {
198: my $timezone = &reply('servertimezone',$home);
199: return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
200: }
201: }
202: }
1.850 albertel 203:
1.1106 raeburn 204: sub get_server_distarch {
205: my ($lonhost,$ignore_cache) = @_;
206: if (defined($lonhost)) {
207: if (!defined(&hostname($lonhost))) {
208: return;
209: }
210: my $cachetime = 12*3600;
211: if (!$ignore_cache) {
212: my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
213: if (defined($cached)) {
214: return $distarch;
215: }
216: }
217: my $rep = &reply('serverdistarch',$lonhost);
218: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
219: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
220: $rep eq '') {
221: return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
222: }
223: }
224: return;
225: }
226:
1.993 raeburn 227: sub get_server_loncaparev {
1.1073 raeburn 228: my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993 raeburn 229: if (defined($lonhost)) {
230: if (!defined(&hostname($lonhost))) {
231: undef($lonhost);
232: }
233: }
234: if (!defined($lonhost)) {
235: if (defined(&domain($dom,'primary'))) {
236: $lonhost=&domain($dom,'primary');
237: if ($lonhost eq 'no_host') {
238: undef($lonhost);
239: }
240: }
241: }
242: if (defined($lonhost)) {
1.1073 raeburn 243: my $cachetime = 12*3600;
244: if (!$ignore_cache) {
245: my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
246: if (defined($cached)) {
247: return $loncaparev;
248: }
249: }
250: my ($answer,$loncaparev);
251: my @ids=¤t_machine_ids();
252: if (grep(/^\Q$lonhost\E$/,@ids)) {
253: $answer = $perlvar{'lonVersion'};
1.1081 raeburn 254: if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 255: $loncaparev = $1;
256: }
257: } else {
258: $answer = &reply('serverloncaparev',$lonhost);
259: if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
260: if ($caller eq 'loncron') {
261: my $ua=new LWP::UserAgent;
1.1082 raeburn 262: $ua->timeout(4);
1.1073 raeburn 263: my $protocol = $protocol{$lonhost};
264: $protocol = 'http' if ($protocol ne 'https');
265: my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
266: my $request=new HTTP::Request('GET',$url);
267: my $response=$ua->request($request);
268: unless ($response->is_error()) {
269: my $content = $response->content;
1.1081 raeburn 270: if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073 raeburn 271: $loncaparev = $1;
272: }
273: }
274: } else {
275: $loncaparev = $loncaparevs{$lonhost};
276: }
1.1081 raeburn 277: } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 278: $loncaparev = $1;
279: }
1.993 raeburn 280: }
1.1073 raeburn 281: return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993 raeburn 282: }
283: }
284:
1.1074 raeburn 285: sub get_server_homeID {
286: my ($hostname,$ignore_cache,$caller) = @_;
287: unless ($ignore_cache) {
288: my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
289: if (defined($cached)) {
290: return $serverhomeID;
291: }
292: }
293: my $cachetime = 12*3600;
294: my $serverhomeID;
295: if ($caller eq 'loncron') {
296: my @machine_ids = &machine_ids($hostname);
297: foreach my $id (@machine_ids) {
298: my $response = &reply('serverhomeID',$id);
299: unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
300: $serverhomeID = $response;
301: last;
302: }
303: }
304: if ($serverhomeID eq '') {
305: $serverhomeID = $machine_ids[-1];
306: }
307: } else {
308: $serverhomeID = $serverhomeIDs{$hostname};
309: }
310: return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
311: }
312:
1.1121 raeburn 313: sub get_remote_globals {
314: my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125 raeburn 315: my ($result,%returnhash,%whatneeded);
316: if (ref($whathash) eq 'HASH') {
1.1121 raeburn 317: foreach my $what (sort(keys(%{$whathash}))) {
318: my $hashid = $lonhost.'-'.$what;
1.1125 raeburn 319: my ($response,$cached);
1.1121 raeburn 320: unless ($ignore_cache) {
1.1125 raeburn 321: ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121 raeburn 322: }
323: if (defined($cached)) {
1.1125 raeburn 324: $returnhash{$what} = $response;
1.1121 raeburn 325: } else {
1.1125 raeburn 326: $whatneeded{$what} = 1;
1.1121 raeburn 327: }
328: }
1.1125 raeburn 329: if (keys(%whatneeded) == 0) {
330: $result = 'ok';
331: } else {
1.1121 raeburn 332: my $requested = &freeze_escape(\%whatneeded);
333: my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125 raeburn 334: if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
335: ($rep eq 'unknown_cmd')) {
336: $result = $rep;
337: } else {
338: $result = 'ok';
1.1121 raeburn 339: my @pairs=split(/\&/,$rep);
1.1125 raeburn 340: foreach my $item (@pairs) {
341: my ($key,$value)=split(/=/,$item,2);
342: my $what = &unescape($key);
343: my $hashid = $lonhost.'-'.$what;
344: $returnhash{$what}=&thaw_unescape($value);
345: &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121 raeburn 346: }
347: }
348: }
349: }
1.1125 raeburn 350: return ($result,\%returnhash);
1.1121 raeburn 351: }
352:
1.1124 raeburn 353: sub remote_devalidate_cache {
354: my ($lonhost,$name,$id) = @_;
1.1130 raeburn 355: my $response = &reply('devalidatecache:'.&escape($name).':'.&escape($id),$lonhost);
1.1124 raeburn 356: return $response;
357: }
358:
1.1 albertel 359: # -------------------------------------------------- Non-critical communication
360: sub subreply {
361: my ($cmd,$server)=@_;
1.838 albertel 362: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549 foxr 363: #
364: # With loncnew process trimming, there's a timing hole between lonc server
365: # process exit and the master server picking up the listen on the AF_UNIX
366: # socket. In that time interval, a lock file will exist:
367:
368: my $lockfile=$peerfile.".lock";
369: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
370: sleep(1);
371: }
372: # At this point, either a loncnew parent is listening or an old lonc
1.550 foxr 373: # or loncnew child is listening so we can connect or everything's dead.
1.549 foxr 374: #
1.550 foxr 375: # We'll give the connection a few tries before abandoning it. If
376: # connection is not possible, we'll con_lost back to the client.
377: #
378: my $client;
379: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
380: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
381: Type => SOCK_STREAM,
382: Timeout => 10);
1.869 albertel 383: if ($client) {
1.550 foxr 384: last; # Connected!
1.850 albertel 385: } else {
1.853 albertel 386: &create_connection(&hostname($server),$server);
1.550 foxr 387: }
1.850 albertel 388: sleep(1); # Try again later if failed connection.
1.550 foxr 389: }
390: my $answer;
391: if ($client) {
1.704 albertel 392: print $client "sethost:$server:$cmd\n";
1.550 foxr 393: $answer=<$client>;
394: if (!$answer) { $answer="con_lost"; }
395: chomp($answer);
396: } else {
397: $answer = 'con_lost'; # Failed connection.
398: }
1.1 albertel 399: return $answer;
400: }
401:
402: sub reply {
403: my ($cmd,$server)=@_;
1.838 albertel 404: unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1 albertel 405: my $answer=subreply($cmd,$server);
1.65 www 406: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672 albertel 407: &logthis("<font color=\"blue\">WARNING:".
1.12 www 408: " $cmd to $server returned $answer</font>");
409: }
1.1 albertel 410: return $answer;
411: }
412:
413: # ----------------------------------------------------------- Send USR1 to lonc
414:
415: sub reconlonc {
1.891 albertel 416: my ($lonid) = @_;
417: my $hostname = &hostname($lonid);
418: if ($lonid) {
419: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
420: if ($hostname && -e $peerfile) {
421: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
422: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
423: Type => SOCK_STREAM,
424: Timeout => 10);
425: if ($client) {
426: print $client ("reset_retries\n");
427: my $answer=<$client>;
428: #reset just this one.
429: }
430: }
431: return;
432: }
433:
1.836 www 434: &logthis("Trying to reconnect lonc");
1.1 albertel 435: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448 albertel 436: if (open(my $fh,"<$loncfile")) {
1.1 albertel 437: my $loncpid=<$fh>;
438: chomp($loncpid);
439: if (kill 0 => $loncpid) {
440: &logthis("lonc at pid $loncpid responding, sending USR1");
441: kill USR1 => $loncpid;
442: sleep 1;
1.836 www 443: } else {
1.12 www 444: &logthis(
1.672 albertel 445: "<font color=\"blue\">WARNING:".
1.12 www 446: " lonc at pid $loncpid not responding, giving up</font>");
1.1 albertel 447: }
448: } else {
1.836 www 449: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1 albertel 450: }
451: }
452:
453: # ------------------------------------------------------ Critical communication
1.12 www 454:
1.1 albertel 455: sub critical {
456: my ($cmd,$server)=@_;
1.838 albertel 457: unless (&hostname($server)) {
1.672 albertel 458: &logthis("<font color=\"blue\">WARNING:".
1.89 www 459: " Critical message to unknown server ($server)</font>");
460: return 'no_such_host';
461: }
1.1 albertel 462: my $answer=reply($cmd,$server);
463: if ($answer eq 'con_lost') {
464: &reconlonc("$perlvar{'lonSockDir'}/$server");
1.589 albertel 465: my $answer=reply($cmd,$server);
1.1 albertel 466: if ($answer eq 'con_lost') {
467: my $now=time;
468: my $middlename=$cmd;
1.5 www 469: $middlename=substr($middlename,0,16);
1.1 albertel 470: $middlename=~s/\W//g;
471: my $dfilename=
1.305 www 472: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
473: $dumpcount++;
1.1 albertel 474: {
1.448 albertel 475: my $dfh;
476: if (open($dfh,">$dfilename")) {
477: print $dfh "$cmd\n";
478: close($dfh);
479: }
1.1 albertel 480: }
481: sleep 2;
482: my $wcmd='';
483: {
1.448 albertel 484: my $dfh;
485: if (open($dfh,"<$dfilename")) {
486: $wcmd=<$dfh>;
487: close($dfh);
488: }
1.1 albertel 489: }
490: chomp($wcmd);
1.7 www 491: if ($wcmd eq $cmd) {
1.672 albertel 492: &logthis("<font color=\"blue\">WARNING: ".
1.12 www 493: "Connection buffer $dfilename: $cmd</font>");
1.1 albertel 494: &logperm("D:$server:$cmd");
495: return 'con_delayed';
496: } else {
1.672 albertel 497: &logthis("<font color=\"red\">CRITICAL:"
1.12 www 498: ." Critical connection failed: $server $cmd</font>");
1.1 albertel 499: &logperm("F:$server:$cmd");
500: return 'con_failed';
501: }
502: }
503: }
504: return $answer;
1.405 albertel 505: }
506:
1.755 albertel 507: # ------------------------------------------- check if return value is an error
508:
509: sub error {
510: my ($result) = @_;
1.756 albertel 511: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755 albertel 512: if ($2 == 2) { return undef; }
513: return $1;
514: }
515: return undef;
516: }
517:
1.783 albertel 518: sub convert_and_load_session_env {
519: my ($lonidsdir,$handle)=@_;
520: my @profile;
521: {
1.917 albertel 522: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
523: if (!$opened) {
1.915 albertel 524: return 0;
525: }
1.783 albertel 526: flock($idf,LOCK_SH);
527: @profile=<$idf>;
528: close($idf);
529: }
530: my %temp_env;
531: foreach my $line (@profile) {
1.786 albertel 532: if ($line !~ m/=/) {
533: return 0;
534: }
1.783 albertel 535: chomp($line);
536: my ($envname,$envvalue)=split(/=/,$line,2);
537: $temp_env{&unescape($envname)} = &unescape($envvalue);
538: }
539: unlink("$lonidsdir/$handle.id");
540: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
541: 0640)) {
542: %disk_env = %temp_env;
543: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
544: untie(%disk_env);
545: }
1.786 albertel 546: return 1;
1.783 albertel 547: }
548:
1.374 www 549: # ------------------------------------------- Transfer profile into environment
1.780 albertel 550: my $env_loaded;
551: sub transfer_profile_to_env {
1.788 albertel 552: my ($lonidsdir,$handle,$force_transfer) = @_;
553: if (!$force_transfer && $env_loaded) { return; }
1.374 www 554:
1.720 albertel 555: if (!defined($lonidsdir)) {
556: $lonidsdir = $perlvar{'lonIDsDir'};
557: }
558: if (!defined($handle)) {
559: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
560: }
561:
1.786 albertel 562: my $convert;
563: {
1.917 albertel 564: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
565: if (!$opened) {
1.915 albertel 566: return;
567: }
1.786 albertel 568: flock($idf,LOCK_SH);
569: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
570: &GDBM_READER(),0640)) {
571: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
572: untie(%disk_env);
573: } else {
574: $convert = 1;
575: }
576: }
577: if ($convert) {
578: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
579: &logthis("Failed to load session, or convert session.");
580: }
1.374 www 581: }
1.783 albertel 582:
1.786 albertel 583: my %remove;
1.783 albertel 584: while ( my $envname = each(%env) ) {
1.433 matthew 585: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
586: if ($time < time-300) {
1.783 albertel 587: $remove{$key}++;
1.433 matthew 588: }
589: }
590: }
1.783 albertel 591:
1.619 albertel 592: $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780 albertel 593: $env_loaded=1;
1.783 albertel 594: foreach my $expired_key (keys(%remove)) {
1.433 matthew 595: &delenv($expired_key);
1.374 www 596: }
1.1 albertel 597: }
598:
1.916 albertel 599: # ---------------------------------------------------- Check for valid session
600: sub check_for_valid_session {
1.1155 raeburn 601: my ($r,$name) = @_;
1.916 albertel 602: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1155 raeburn 603: if ($name eq '') {
604: $name = 'lonID';
605: }
606: my $lonid=$cookies{$name};
1.916 albertel 607: return undef if (!$lonid);
608:
609: my $handle=&LONCAPA::clean_handle($lonid->value);
1.1155 raeburn 610: my $lonidsdir;
611: if ($name eq 'lonDAV') {
612: $lonidsdir=$r->dir_config('lonDAVsessDir');
613: } else {
614: $lonidsdir=$r->dir_config('lonIDsDir');
615: }
1.916 albertel 616: return undef if (!-e "$lonidsdir/$handle.id");
617:
1.917 albertel 618: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
619: return undef if (!$opened);
1.916 albertel 620:
621: flock($idf,LOCK_SH);
622: my %disk_env;
623: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
624: &GDBM_READER(),0640)) {
625: return undef;
626: }
627:
628: if (!defined($disk_env{'user.name'})
629: || !defined($disk_env{'user.domain'})) {
630: return undef;
631: }
632: return $handle;
633: }
634:
1.830 albertel 635: sub timed_flock {
636: my ($file,$lock_type) = @_;
637: my $failed=0;
638: eval {
639: local $SIG{__DIE__}='DEFAULT';
640: local $SIG{ALRM}=sub {
641: $failed=1;
642: die("failed lock");
643: };
644: alarm(13);
645: flock($file,$lock_type);
646: alarm(0);
647: };
648: if ($failed) {
649: return undef;
650: } else {
651: return 1;
652: }
653: }
654:
1.5 www 655: # ---------------------------------------------------------- Append Environment
656:
657: sub appenv {
1.949 raeburn 658: my ($newenv,$roles) = @_;
659: if (ref($newenv) eq 'HASH') {
660: foreach my $key (keys(%{$newenv})) {
661: my $refused = 0;
662: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
663: $refused = 1;
664: if (ref($roles) eq 'ARRAY') {
665: my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
666: if (grep(/^\Q$role\E$/,@{$roles})) {
667: $refused = 0;
668: }
669: }
670: }
671: if ($refused) {
672: &logthis("<font color=\"blue\">WARNING: ".
673: "Attempt to modify environment ".$key." to ".$newenv->{$key}
674: .'</font>');
675: delete($newenv->{$key});
676: } else {
677: $env{$key}=$newenv->{$key};
678: }
679: }
680: my $opened = open(my $env_file,'+<',$env{'user.environment'});
681: if ($opened
682: && &timed_flock($env_file,LOCK_EX)
683: &&
684: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
685: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
686: while (my ($key,$value) = each(%{$newenv})) {
687: $disk_env{$key} = $value;
688: }
689: untie(%disk_env);
1.35 www 690: }
1.191 harris41 691: }
1.56 www 692: return 'ok';
693: }
694: # ----------------------------------------------------- Delete from Environment
695:
696: sub delenv {
1.1104 raeburn 697: my ($delthis,$regexp,$roles) = @_;
698: if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
699: my $refused = 1;
700: if (ref($roles) eq 'ARRAY') {
701: my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
702: if (grep(/^\Q$role\E$/,@{$roles})) {
703: $refused = 0;
704: }
705: }
706: if ($refused) {
707: &logthis("<font color=\"blue\">WARNING: ".
708: "Attempt to delete from environment ".$delthis);
709: return 'error';
710: }
1.56 www 711: }
1.917 albertel 712: my $opened = open(my $env_file,'+<',$env{'user.environment'});
713: if ($opened
1.915 albertel 714: && &timed_flock($env_file,LOCK_EX)
1.830 albertel 715: &&
716: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
717: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 718: foreach my $key (keys(%disk_env)) {
1.987 raeburn 719: if ($regexp) {
720: if ($key=~/^$delthis/) {
721: delete($env{$key});
722: delete($disk_env{$key});
723: }
724: } else {
725: if ($key=~/^\Q$delthis\E/) {
726: delete($env{$key});
727: delete($disk_env{$key});
728: }
729: }
1.448 albertel 730: }
1.783 albertel 731: untie(%disk_env);
1.5 www 732: }
733: return 'ok';
1.369 albertel 734: }
735:
1.790 albertel 736: sub get_env_multiple {
737: my ($name) = @_;
738: my @values;
739: if (defined($env{$name})) {
740: # exists is it an array
741: if (ref($env{$name})) {
742: @values=@{ $env{$name} };
743: } else {
744: $values[0]=$env{$name};
745: }
746: }
747: return(@values);
748: }
749:
1.958 www 750: # ------------------------------------------------------------------- Locking
751:
752: sub set_lock {
753: my ($text)=@_;
754: $locknum++;
755: my $id=$$.'-'.$locknum;
756: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
757: 'session.lock.'.$id => $text});
758: return $id;
759: }
760:
761: sub get_locks {
762: my $num=0;
763: my %texts=();
764: foreach my $lock (split(/\,/,$env{'session.locks'})) {
765: if ($lock=~/\w/) {
766: $num++;
767: $texts{$lock}=$env{'session.lock.'.$lock};
768: }
769: }
770: return ($num,%texts);
771: }
772:
773: sub remove_lock {
774: my ($id)=@_;
775: my $newlocks='';
776: foreach my $lock (split(/\,/,$env{'session.locks'})) {
777: if (($lock=~/\w/) && ($lock ne $id)) {
778: $newlocks.=','.$lock;
779: }
780: }
781: &appenv({'session.locks' => $newlocks});
782: &delenv('session.lock.'.$id);
783: }
784:
785: sub remove_all_locks {
786: my $activelocks=$env{'session.locks'};
787: foreach my $lock (split(/\,/,$env{'session.locks'})) {
788: if ($lock=~/\w/) {
789: &remove_lock($lock);
790: }
791: }
792: }
793:
794:
1.369 albertel 795: # ------------------------------------------ Find out current server userload
796: sub userload {
797: my $numusers=0;
798: {
799: opendir(LONIDS,$perlvar{'lonIDsDir'});
800: my $filename;
801: my $curtime=time;
802: while ($filename=readdir(LONIDS)) {
1.925 albertel 803: next if ($filename eq '.' || $filename eq '..');
804: next if ($filename =~ /publicuser_\d+\.id/);
1.404 albertel 805: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437 albertel 806: if ($curtime-$mtime < 1800) { $numusers++; }
1.369 albertel 807: }
808: closedir(LONIDS);
809: }
810: my $userloadpercent=0;
811: my $maxuserload=$perlvar{'lonUserLoadLim'};
812: if ($maxuserload) {
1.371 albertel 813: $userloadpercent=100*$numusers/$maxuserload;
1.369 albertel 814: }
1.372 albertel 815: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369 albertel 816: return $userloadpercent;
1.283 www 817: }
818:
1.1 albertel 819: # ------------------------------ Find server with least workload from spare.tab
1.11 www 820:
1.1 albertel 821: sub spareserver {
1.1083 raeburn 822: my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784 albertel 823: my $spare_server;
1.370 albertel 824: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784 albertel 825: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
826: : $userloadpercent;
1.1083 raeburn 827: my ($uint_dom,$remotesessions);
828: if (($udom ne '') && (&domain($udom) ne '')) {
829: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
830: $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
831: my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
832: $remotesessions = $udomdefaults{'remotesessions'};
833: }
1.1123 raeburn 834: my $spareshash = &this_host_spares($udom);
835: if (ref($spareshash) eq 'HASH') {
836: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
837: foreach my $try_server (@{ $spareshash->{'primary'} }) {
838: if ($uint_dom) {
839: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
840: $try_server));
841: }
842: ($spare_server, $lowest_load) =
843: &compare_server_load($try_server, $spare_server, $lowest_load);
844: }
1.1083 raeburn 845: }
1.784 albertel 846:
1.1123 raeburn 847: my $found_server = ($spare_server ne '' && $lowest_load < 100);
848:
849: if (!$found_server) {
850: if (ref($spareshash->{'default'}) eq 'ARRAY') {
851: foreach my $try_server (@{ $spareshash->{'default'} }) {
852: if ($uint_dom) {
853: next unless (&spare_can_host($udom,$uint_dom,
854: $remotesessions,$try_server));
855: }
856: ($spare_server, $lowest_load) =
857: &compare_server_load($try_server, $spare_server, $lowest_load);
858: }
859: }
860: }
1.784 albertel 861: }
862:
863: if (!$want_server_name) {
1.968 raeburn 864: my $protocol = 'http';
865: if ($protocol{$spare_server} eq 'https') {
866: $protocol = $protocol{$spare_server};
867: }
1.1001 raeburn 868: if (defined($spare_server)) {
869: my $hostname = &hostname($spare_server);
1.1083 raeburn 870: if (defined($hostname)) {
1.1001 raeburn 871: $spare_server = $protocol.'://'.$hostname;
872: }
873: }
1.784 albertel 874: }
875: return $spare_server;
876: }
877:
878: sub compare_server_load {
879: my ($try_server, $spare_server, $lowest_load) = @_;
880:
881: my $loadans = &reply('load', $try_server);
882: my $userloadans = &reply('userload',$try_server);
883:
884: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114 raeburn 885: return ($spare_server, $lowest_load); #didn't get a number from the server
1.784 albertel 886: }
887:
888: my $load;
889: if ($loadans =~ /\d/) {
890: if ($userloadans =~ /\d/) {
891: #both are numbers, pick the bigger one
892: $load = ($loadans > $userloadans) ? $loadans
893: : $userloadans;
1.411 albertel 894: } else {
1.784 albertel 895: $load = $loadans;
1.411 albertel 896: }
1.784 albertel 897: } else {
898: $load = $userloadans;
899: }
900:
901: if (($load =~ /\d/) && ($load < $lowest_load)) {
902: $spare_server = $try_server;
903: $lowest_load = $load;
1.370 albertel 904: }
1.784 albertel 905: return ($spare_server,$lowest_load);
1.202 matthew 906: }
1.914 albertel 907:
908: # --------------------------- ask offload servers if user already has a session
909: sub find_existing_session {
910: my ($udom,$uname) = @_;
1.1123 raeburn 911: my $spareshash = &this_host_spares($udom);
912: if (ref($spareshash) eq 'HASH') {
913: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
914: foreach my $try_server (@{ $spareshash->{'primary'} }) {
915: return $try_server if (&has_user_session($try_server, $udom, $uname));
916: }
917: }
918: if (ref($spareshash->{'default'}) eq 'ARRAY') {
919: foreach my $try_server (@{ $spareshash->{'default'} }) {
920: return $try_server if (&has_user_session($try_server, $udom, $uname));
921: }
922: }
1.914 albertel 923: }
924: return;
925: }
926:
927: # -------------------------------- ask if server already has a session for user
928: sub has_user_session {
929: my ($lonid,$udom,$uname) = @_;
930: my $result = &reply(join(':','userhassession',
931: map {&escape($_)} ($udom,$uname)),$lonid);
932: return 1 if ($result eq 'ok');
933:
934: return 0;
935: }
936:
1.1076 raeburn 937: # --------- determine least loaded server in a user's domain which allows login
938:
939: sub choose_server {
1.1115 raeburn 940: my ($udom,$checkloginvia) = @_;
1.1076 raeburn 941: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077 raeburn 942: my %servers = &get_servers($udom);
1.1076 raeburn 943: my $lowest_load = 30000;
1.1151 raeburn 944: my ($login_host,$hostname,$portal_path,$isredirect);
1.1076 raeburn 945: foreach my $lonhost (keys(%servers)) {
1.1115 raeburn 946: my $loginvia;
947: if ($checkloginvia) {
948: $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116 raeburn 949: if ($loginvia) {
950: my ($server,$path) = split(/:/,$loginvia);
951: ($login_host, $lowest_load) =
952: &compare_server_load($server, $login_host, $lowest_load);
953: if ($login_host eq $server) {
954: $portal_path = $path;
1.1151 raeburn 955: $isredirect = 1;
1.1116 raeburn 956: }
957: } else {
958: ($login_host, $lowest_load) =
959: &compare_server_load($lonhost, $login_host, $lowest_load);
960: if ($login_host eq $lonhost) {
961: $portal_path = '';
1.1151 raeburn 962: $isredirect = '';
1.1116 raeburn 963: }
964: }
965: } else {
1.1076 raeburn 966: ($login_host, $lowest_load) =
1.1116 raeburn 967: &compare_server_load($lonhost, $login_host, $lowest_load);
1.1076 raeburn 968: }
969: }
970: if ($login_host ne '') {
1.1116 raeburn 971: $hostname = &hostname($login_host);
1.1076 raeburn 972: }
1.1151 raeburn 973: return ($login_host,$hostname,$portal_path,$isredirect);
1.1076 raeburn 974: }
975:
1.202 matthew 976: # --------------------------------------------- Try to change a user's password
977:
978: sub changepass {
1.799 raeburn 979: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 980: $currentpass = &escape($currentpass);
981: $newpass = &escape($newpass);
1.1030 raeburn 982: my $lonhost = $perlvar{'lonHostID'};
983: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202 matthew 984: $server);
985: if (! $answer) {
986: &logthis("No reply on password change request to $server ".
987: "by $uname in domain $udom.");
988: } elsif ($answer =~ "^ok") {
989: &logthis("$uname in $udom successfully changed their password ".
990: "on $server.");
991: } elsif ($answer =~ "^pwchange_failure") {
992: &logthis("$uname in $udom was unable to change their password ".
993: "on $server. The action was blocked by either lcpasswd ".
994: "or pwchange");
995: } elsif ($answer =~ "^non_authorized") {
996: &logthis("$uname in $udom did not get their password correct when ".
997: "attempting to change it on $server.");
998: } elsif ($answer =~ "^auth_mode_error") {
999: &logthis("$uname in $udom attempted to change their password despite ".
1000: "not being locally or internally authenticated on $server.");
1001: } elsif ($answer =~ "^unknown_user") {
1002: &logthis("$uname in $udom attempted to change their password ".
1003: "on $server but were unable to because $server is not ".
1004: "their home server.");
1005: } elsif ($answer =~ "^refused") {
1006: &logthis("$server refused to change $uname in $udom password because ".
1007: "it was sent an unencrypted request to change the password.");
1.1030 raeburn 1008: } elsif ($answer =~ "invalid_client") {
1009: &logthis("$server refused to change $uname in $udom password because ".
1010: "it was a reset by e-mail originating from an invalid server.");
1.202 matthew 1011: }
1012: return $answer;
1.1 albertel 1013: }
1014:
1.169 harris41 1015: # ----------------------- Try to determine user's current authentication scheme
1016:
1017: sub queryauthenticate {
1018: my ($uname,$udom)=@_;
1.456 albertel 1019: my $uhome=&homeserver($uname,$udom);
1020: if (!$uhome) {
1021: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
1022: return 'no_host';
1023: }
1024: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
1025: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
1026: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 1027: }
1.456 albertel 1028: return $answer;
1.169 harris41 1029: }
1030:
1.1 albertel 1031: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 1032:
1.1 albertel 1033: sub authenticate {
1.1073 raeburn 1034: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807 albertel 1035: $upass=&escape($upass);
1036: $uname= &LONCAPA::clean_username($uname);
1.836 www 1037: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 1038: my $newhome;
1.836 www 1039: if ((!$uhome) || ($uhome eq 'no_host')) {
1040: # Maybe the machine was offline and only re-appeared again recently?
1041: &reconlonc();
1042: # One more
1.952 raeburn 1043: $uhome=&homeserver($uname,$udom,1);
1044: if (($uhome eq 'no_host') && $checkdefauth) {
1045: if (defined(&domain($udom,'primary'))) {
1046: $newhome=&domain($udom,'primary');
1047: }
1048: if ($newhome ne '') {
1049: $uhome = $newhome;
1050: }
1051: }
1.836 www 1052: if ((!$uhome) || ($uhome eq 'no_host')) {
1053: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 1054: return 'no_host';
1055: }
1.1 albertel 1056: }
1.1073 raeburn 1057: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471 albertel 1058: if ($answer eq 'authorized') {
1.952 raeburn 1059: if ($newhome) {
1060: &logthis("User $uname at $udom authorized by $uhome, but needs account");
1061: return 'no_account_on_host';
1062: } else {
1063: &logthis("User $uname at $udom authorized by $uhome");
1064: return $uhome;
1065: }
1.471 albertel 1066: }
1067: if ($answer eq 'non_authorized') {
1068: &logthis("User $uname at $udom rejected by $uhome");
1069: return 'no_host';
1.9 www 1070: }
1.471 albertel 1071: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 1072: return 'no_host';
1073: }
1074:
1.1073 raeburn 1075: sub can_host_session {
1.1074 raeburn 1076: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073 raeburn 1077: my $canhost = 1;
1.1074 raeburn 1078: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073 raeburn 1079: if (ref($remotesessions) eq 'HASH') {
1080: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074 raeburn 1081: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073 raeburn 1082: $canhost = 0;
1083: } else {
1084: $canhost = 1;
1085: }
1086: }
1087: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074 raeburn 1088: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073 raeburn 1089: $canhost = 1;
1090: } else {
1091: $canhost = 0;
1092: }
1093: }
1094: if ($canhost) {
1095: if ($remotesessions->{'version'} ne '') {
1096: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1097: if ($reqmajor ne '' && $reqminor ne '') {
1098: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1099: my $major = $1;
1100: my $minor = $2;
1101: if (($major < $reqmajor ) ||
1102: (($major == $reqmajor) && ($minor < $reqminor))) {
1103: $canhost = 0;
1104: }
1105: } else {
1106: $canhost = 0;
1107: }
1108: }
1109: }
1110: }
1111: }
1112: if ($canhost) {
1113: if (ref($hostedsessions) eq 'HASH') {
1.1120 raeburn 1114: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1115: my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073 raeburn 1116: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120 raeburn 1117: if (($uint_dom ne '') &&
1118: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073 raeburn 1119: $canhost = 0;
1120: } else {
1121: $canhost = 1;
1122: }
1123: }
1124: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120 raeburn 1125: if (($uint_dom ne '') &&
1126: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073 raeburn 1127: $canhost = 1;
1128: } else {
1129: $canhost = 0;
1130: }
1131: }
1132: }
1133: }
1134: return $canhost;
1135: }
1136:
1.1083 raeburn 1137: sub spare_can_host {
1138: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1139: my $canhost=1;
1140: my @intdoms;
1141: my $internet_names = &Apache::lonnet::get_internet_names($try_server);
1142: if (ref($internet_names) eq 'ARRAY') {
1143: @intdoms = @{$internet_names};
1144: }
1145: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1146: my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
1147: my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
1148: my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
1149: my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
1150: $canhost = &can_host_session($udom,$try_server,$remoterev,
1151: $remotesessions,
1152: $defdomdefaults{'hostedsessions'});
1153: }
1154: return $canhost;
1155: }
1156:
1.1123 raeburn 1157: sub this_host_spares {
1158: my ($dom) = @_;
1.1126 raeburn 1159: my ($dom_in_use,$lonhost_in_use,$result);
1.1123 raeburn 1160: my @hosts = ¤t_machine_ids();
1161: foreach my $lonhost (@hosts) {
1162: if (&host_domain($lonhost) eq $dom) {
1.1126 raeburn 1163: $dom_in_use = $dom;
1164: $lonhost_in_use = $lonhost;
1.1123 raeburn 1165: last;
1166: }
1167: }
1.1126 raeburn 1168: if ($dom_in_use ne '') {
1169: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1170: }
1171: if (ref($result) ne 'HASH') {
1172: $lonhost_in_use = $perlvar{'lonHostID'};
1173: $dom_in_use = &host_domain($lonhost_in_use);
1174: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1175: if (ref($result) ne 'HASH') {
1176: $result = \%spareid;
1177: }
1178: }
1179: return $result;
1180: }
1181:
1182: sub spares_for_offload {
1183: my ($dom_in_use,$lonhost_in_use) = @_;
1184: my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123 raeburn 1185: if (defined($cached)) {
1186: return $result;
1187: } else {
1.1126 raeburn 1188: my $cachetime = 60*60*24;
1189: my %domconfig =
1190: &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
1191: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1192: if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
1193: if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
1194: return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123 raeburn 1195: }
1196: }
1197: }
1198: }
1.1126 raeburn 1199: return;
1.1123 raeburn 1200: }
1201:
1.1129 raeburn 1202: sub get_lonbalancer_config {
1203: my ($servers) = @_;
1204: my ($currbalancer,$currtargets);
1205: if (ref($servers) eq 'HASH') {
1206: foreach my $server (keys(%{$servers})) {
1207: my %what = (
1208: spareid => 1,
1209: perlvar => 1,
1210: );
1211: my ($result,$returnhash) = &get_remote_globals($server,\%what);
1212: if ($result eq 'ok') {
1213: if (ref($returnhash) eq 'HASH') {
1214: if (ref($returnhash->{'perlvar'}) eq 'HASH') {
1215: if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
1216: $currbalancer = $server;
1217: $currtargets = {};
1218: if (ref($returnhash->{'spareid'}) eq 'HASH') {
1219: if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
1220: $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
1221: }
1222: if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
1223: $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
1224: }
1225: }
1226: last;
1227: }
1228: }
1229: }
1230: }
1231: }
1232: }
1233: return ($currbalancer,$currtargets);
1234: }
1235:
1236: sub check_loadbalancing {
1237: my ($uname,$udom) = @_;
1.1172.2.12! raeburn 1238: my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
! 1239: $rule_in_effect,$offloadto,$otherserver);
1.1129 raeburn 1240: my $lonhost = $perlvar{'lonHostID'};
1.1172.2.4 raeburn 1241: my @hosts = ¤t_machine_ids();
1.1129 raeburn 1242: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1243: my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
1244: my $intdom = &Apache::lonnet::internet_dom($lonhost);
1245: my $serverhomedom = &host_domain($lonhost);
1246:
1247: my $cachetime = 60*60*24;
1248:
1249: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1250: $dom_in_use = $udom;
1251: $homeintdom = 1;
1252: } else {
1253: $dom_in_use = $serverhomedom;
1254: }
1255: my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
1256: unless (defined($cached)) {
1257: my %domconfig =
1258: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
1259: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1260: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129 raeburn 1261: }
1262: }
1263: if (ref($result) eq 'HASH') {
1.1172.2.12! raeburn 1264: ($is_balancer,$currtargets,$currrules) =
! 1265: &check_balancer_result($result,@hosts);
1.1129 raeburn 1266: if ($is_balancer) {
1267: if (ref($currrules) eq 'HASH') {
1268: if ($homeintdom) {
1269: if ($uname ne '') {
1270: if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
1271: my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
1272: if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
1273: $rule_in_effect = $currrules->{'_LC_author'};
1274: } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
1275: $rule_in_effect = $currrules->{'_LC_adv'}
1276: }
1277: }
1278: if ($rule_in_effect eq '') {
1279: my %userenv = &userenvironment($udom,$uname,'inststatus');
1280: if ($userenv{'inststatus'} ne '') {
1281: my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
1282: my ($othertitle,$usertypes,$types) =
1283: &Apache::loncommon::sorted_inst_types($udom);
1284: if (ref($types) eq 'ARRAY') {
1285: foreach my $type (@{$types}) {
1286: if (grep(/^\Q$type\E$/,@statuses)) {
1287: if (exists($currrules->{$type})) {
1288: $rule_in_effect = $currrules->{$type};
1289: }
1290: }
1291: }
1292: }
1293: } else {
1294: if (exists($currrules->{'default'})) {
1295: $rule_in_effect = $currrules->{'default'};
1296: }
1297: }
1298: }
1299: } else {
1300: if (exists($currrules->{'default'})) {
1301: $rule_in_effect = $currrules->{'default'};
1302: }
1303: }
1304: } else {
1305: if ($currrules->{'_LC_external'} ne '') {
1306: $rule_in_effect = $currrules->{'_LC_external'};
1307: }
1308: }
1309: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1310: $uname,$udom);
1311: }
1312: }
1313: } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1314: my ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1315: unless (defined($cached)) {
1316: my %domconfig =
1317: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
1318: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1319: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129 raeburn 1320: }
1321: }
1322: if (ref($result) eq 'HASH') {
1.1172.2.12! raeburn 1323: ($is_balancer,$currtargets,$currrules) =
! 1324: &check_balancer_result($result,@hosts);
! 1325: if ($is_balancer) {
1.1129 raeburn 1326: if (ref($currrules) eq 'HASH') {
1327: if ($currrules->{'_LC_internetdom'} ne '') {
1328: $rule_in_effect = $currrules->{'_LC_internetdom'};
1329: }
1330: }
1331: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1332: $uname,$udom);
1333: }
1334: } else {
1335: if ($perlvar{'lonBalancer'} eq 'yes') {
1336: $is_balancer = 1;
1337: $offloadto = &this_host_spares($dom_in_use);
1338: }
1339: }
1340: } else {
1341: if ($perlvar{'lonBalancer'} eq 'yes') {
1342: $is_balancer = 1;
1343: $offloadto = &this_host_spares($dom_in_use);
1344: }
1345: }
1.1172.2.5 raeburn 1346: if ($is_balancer) {
1347: my $lowest_load = 30000;
1348: if (ref($offloadto) eq 'HASH') {
1349: if (ref($offloadto->{'primary'}) eq 'ARRAY') {
1350: foreach my $try_server (@{$offloadto->{'primary'}}) {
1351: ($otherserver,$lowest_load) =
1352: &compare_server_load($try_server,$otherserver,$lowest_load);
1353: }
1.1129 raeburn 1354: }
1.1172.2.5 raeburn 1355: my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129 raeburn 1356:
1.1172.2.5 raeburn 1357: if (!$found_server) {
1358: if (ref($offloadto->{'default'}) eq 'ARRAY') {
1359: foreach my $try_server (@{$offloadto->{'default'}}) {
1360: ($otherserver,$lowest_load) =
1361: &compare_server_load($try_server,$otherserver,$lowest_load);
1362: }
1363: }
1364: }
1365: } elsif (ref($offloadto) eq 'ARRAY') {
1366: if (@{$offloadto} == 1) {
1367: $otherserver = $offloadto->[0];
1368: } elsif (@{$offloadto} > 1) {
1369: foreach my $try_server (@{$offloadto}) {
1.1129 raeburn 1370: ($otherserver,$lowest_load) =
1371: &compare_server_load($try_server,$otherserver,$lowest_load);
1372: }
1373: }
1374: }
1.1172.2.5 raeburn 1375: if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
1376: $is_balancer = 0;
1377: if ($uname ne '' && $udom ne '') {
1378: if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1379:
1380: &appenv({'user.loadbalexempt' => $lonhost,
1381: 'user.loadbalcheck.time' => time});
1382: }
1.1129 raeburn 1383: }
1384: }
1385: }
1386: return ($is_balancer,$otherserver);
1387: }
1388:
1.1172.2.12! raeburn 1389: sub check_balancer_result {
! 1390: my ($result,@hosts) = @_;
! 1391: my ($is_balancer,$currtargets,$currrules);
! 1392: if (ref($result) eq 'HASH') {
! 1393: if ($result->{'lonhost'} ne '') {
! 1394: my $currbalancer = $result->{'lonhost'};
! 1395: if (grep(/^\Q$currbalancer\E$/,@hosts)) {
! 1396: $is_balancer = 1;
! 1397: $currtargets = $result->{'targets'};
! 1398: $currrules = $result->{'rules'};
! 1399: }
! 1400: } else {
! 1401: foreach my $key (keys(%{$result})) {
! 1402: if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
! 1403: (ref($result->{$key}) eq 'HASH')) {
! 1404: $is_balancer = 1;
! 1405: $currrules = $result->{$key}{'rules'};
! 1406: $currtargets = $result->{$key}{'targets'};
! 1407: last;
! 1408: }
! 1409: }
! 1410: }
! 1411: }
! 1412: return ($is_balancer,$currtargets,$currrules);
! 1413: }
! 1414:
1.1129 raeburn 1415: sub get_loadbalancer_targets {
1416: my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
1417: my $offloadto;
1.1172.2.4 raeburn 1418: if ($rule_in_effect eq 'none') {
1419: return [$perlvar{'lonHostID'}];
1420: } elsif ($rule_in_effect eq '') {
1.1129 raeburn 1421: $offloadto = $currtargets;
1422: } else {
1423: if ($rule_in_effect eq 'homeserver') {
1424: my $homeserver = &homeserver($uname,$udom);
1425: if ($homeserver ne 'no_host') {
1426: $offloadto = [$homeserver];
1427: }
1428: } elsif ($rule_in_effect eq 'externalbalancer') {
1429: my %domconfig =
1430: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1431: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1432: if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
1433: if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
1434: $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
1435: }
1436: }
1437: } else {
1.1172.2.7 raeburn 1438: my %servers = &internet_dom_servers($udom);
1.1129 raeburn 1439: my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
1440: if (&hostname($remotebalancer) ne '') {
1441: $offloadto = [$remotebalancer];
1442: }
1443: }
1444: } elsif (&hostname($rule_in_effect) ne '') {
1445: $offloadto = [$rule_in_effect];
1446: }
1447: }
1448: return $offloadto;
1449: }
1450:
1.1127 raeburn 1451: sub internet_dom_servers {
1452: my ($dom) = @_;
1453: my (%uniqservers,%servers);
1454: my $primaryserver = &hostname(&domain($dom,'primary'));
1455: my @machinedoms = &machine_domains($primaryserver);
1456: foreach my $mdom (@machinedoms) {
1457: my %currservers = %servers;
1458: my %server = &get_servers($mdom);
1459: %servers = (%currservers,%server);
1460: }
1461: my %by_hostname;
1462: foreach my $id (keys(%servers)) {
1463: push(@{$by_hostname{$servers{$id}}},$id);
1464: }
1465: foreach my $hostname (sort(keys(%by_hostname))) {
1466: if (@{$by_hostname{$hostname}} > 1) {
1467: my $match = 0;
1468: foreach my $id (@{$by_hostname{$hostname}}) {
1469: if (&host_domain($id) eq $dom) {
1470: $uniqservers{$id} = $hostname;
1471: $match = 1;
1472: }
1473: }
1474: unless ($match) {
1475: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1476: }
1477: } else {
1478: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1479: }
1480: }
1481: return %uniqservers;
1482: }
1483:
1.1 albertel 1484: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 1485:
1.599 albertel 1486: my %homecache;
1.1 albertel 1487: sub homeserver {
1.230 stredwic 1488: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 1489: my $index="$uname:$udom";
1.426 albertel 1490:
1.599 albertel 1491: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 1492:
1493: my %servers = &get_servers($udom,'library');
1494: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 1495: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 1496: exists($badServerCache{$tryserver}));
1.841 albertel 1497:
1498: my $answer=reply("home:$udom:$uname",$tryserver);
1499: if ($answer eq 'found') {
1500: delete($badServerCache{$tryserver});
1501: return $homecache{$index}=$tryserver;
1502: } elsif ($answer eq 'no_host') {
1503: $badServerCache{$tryserver}=1;
1504: }
1.1 albertel 1505: }
1506: return 'no_host';
1.70 www 1507: }
1508:
1509: # ------------------------------------- Find the usernames behind a list of IDs
1510:
1511: sub idget {
1512: my ($udom,@ids)=@_;
1513: my %returnhash=();
1514:
1.841 albertel 1515: my %servers = &get_servers($udom,'library');
1516: foreach my $tryserver (keys(%servers)) {
1517: my $idlist=join('&',@ids);
1518: $idlist=~tr/A-Z/a-z/;
1519: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
1520: my @answer=();
1521: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1522: @answer=split(/\&/,$reply);
1523: } ;
1524: my $i;
1525: for ($i=0;$i<=$#ids;$i++) {
1526: if ($answer[$i]) {
1527: $returnhash{$ids[$i]}=$answer[$i];
1528: }
1529: }
1530: }
1.70 www 1531: return %returnhash;
1532: }
1533:
1534: # ------------------------------------- Find the IDs behind a list of usernames
1535:
1536: sub idrget {
1537: my ($udom,@unames)=@_;
1538: my %returnhash=();
1.800 albertel 1539: foreach my $uname (@unames) {
1540: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 1541: }
1.70 www 1542: return %returnhash;
1543: }
1544:
1545: # ------------------------------- Store away a list of names and associated IDs
1546:
1547: sub idput {
1548: my ($udom,%ids)=@_;
1549: my %servers=();
1.800 albertel 1550: foreach my $uname (keys(%ids)) {
1551: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1552: my $uhom=&homeserver($uname,$udom);
1.70 www 1553: if ($uhom ne 'no_host') {
1.800 albertel 1554: my $id=&escape($ids{$uname});
1.70 www 1555: $id=~tr/A-Z/a-z/;
1.800 albertel 1556: my $esc_unam=&escape($uname);
1.70 www 1557: if ($servers{$uhom}) {
1.800 albertel 1558: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70 www 1559: } else {
1.800 albertel 1560: $servers{$uhom}=$id.'='.$esc_unam;
1.70 www 1561: }
1562: }
1.191 harris41 1563: }
1.800 albertel 1564: foreach my $server (keys(%servers)) {
1565: &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191 harris41 1566: }
1.344 www 1567: }
1568:
1.1023 raeburn 1569: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 1570: sub dump_dom {
1.1165 droeschl 1571: my ($namespace, $udom, $regexp) = @_;
1572:
1573: $udom ||= $env{'user.domain'};
1574:
1575: return () unless $udom;
1576:
1577: return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012 raeburn 1578: }
1579:
1.1023 raeburn 1580: # ------------------------------------------ get items from domain db files
1.806 raeburn 1581:
1582: sub get_dom {
1.860 raeburn 1583: my ($namespace,$storearr,$udom,$uhome)=@_;
1.806 raeburn 1584: my $items='';
1585: foreach my $item (@$storearr) {
1586: $items.=&escape($item).'&';
1587: }
1588: $items=~s/\&$//;
1.860 raeburn 1589: if (!$udom) {
1590: $udom=$env{'user.domain'};
1591: if (defined(&domain($udom,'primary'))) {
1592: $uhome=&domain($udom,'primary');
1593: } else {
1.874 albertel 1594: undef($uhome);
1.860 raeburn 1595: }
1596: } else {
1597: if (!$uhome) {
1598: if (defined(&domain($udom,'primary'))) {
1599: $uhome=&domain($udom,'primary');
1600: }
1601: }
1602: }
1603: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1604: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866 raeburn 1605: my %returnhash;
1.875 albertel 1606: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 1607: return %returnhash;
1608: }
1.806 raeburn 1609: my @pairs=split(/\&/,$rep);
1610: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1611: return @pairs;
1612: }
1613: my $i=0;
1614: foreach my $item (@$storearr) {
1615: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1616: $i++;
1617: }
1618: return %returnhash;
1619: } else {
1.880 banghart 1620: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 1621: }
1622: }
1623:
1624: # -------------------------------------------- put items in domain db files
1625:
1626: sub put_dom {
1.860 raeburn 1627: my ($namespace,$storehash,$udom,$uhome)=@_;
1628: if (!$udom) {
1629: $udom=$env{'user.domain'};
1630: if (defined(&domain($udom,'primary'))) {
1631: $uhome=&domain($udom,'primary');
1632: } else {
1.874 albertel 1633: undef($uhome);
1.860 raeburn 1634: }
1635: } else {
1636: if (!$uhome) {
1637: if (defined(&domain($udom,'primary'))) {
1638: $uhome=&domain($udom,'primary');
1639: }
1640: }
1641: }
1642: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1643: my $items='';
1644: foreach my $item (keys(%$storehash)) {
1645: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1646: }
1647: $items=~s/\&$//;
1648: return &reply("putdom:$udom:$namespace:$items",$uhome);
1649: } else {
1.860 raeburn 1650: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 1651: }
1652: }
1653:
1.1023 raeburn 1654: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 1655: sub newput_dom {
1.1023 raeburn 1656: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 1657: my $result;
1658: if (!$udom) {
1659: $udom=$env{'user.domain'};
1660: }
1.1023 raeburn 1661: if ($udom) {
1662: my $uname = &get_domainconfiguser($udom);
1663: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 1664: }
1665: return $result;
1666: }
1667:
1.1023 raeburn 1668: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 1669: sub del_dom {
1.1023 raeburn 1670: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 1671: if (ref($storearr) eq 'ARRAY') {
1672: if (!$udom) {
1673: $udom=$env{'user.domain'};
1674: }
1.1023 raeburn 1675: if ($udom) {
1676: my $uname = &get_domainconfiguser($udom);
1677: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 1678: }
1679: }
1680: }
1681:
1.1023 raeburn 1682: # ----------------------------------construct domainconfig user for a domain
1683: sub get_domainconfiguser {
1684: my ($udom) = @_;
1685: return $udom.'-domainconfig';
1686: }
1687:
1.837 raeburn 1688: sub retrieve_inst_usertypes {
1689: my ($udom) = @_;
1690: my (%returnhash,@order);
1.989 raeburn 1691: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1692: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1693: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1694: %returnhash = %{$domdefs{'inststatustypes'}};
1695: @order = @{$domdefs{'inststatusorder'}};
1696: } else {
1697: if (defined(&domain($udom,'primary'))) {
1698: my $uhome=&domain($udom,'primary');
1699: my $rep=&reply("inst_usertypes:$udom",$uhome);
1700: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1701: &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
1702: return (\%returnhash,\@order);
1703: }
1704: my ($hashitems,$orderitems) = split(/:/,$rep);
1705: my @pairs=split(/\&/,$hashitems);
1706: foreach my $item (@pairs) {
1707: my ($key,$value)=split(/=/,$item,2);
1708: $key = &unescape($key);
1709: next if ($key =~ /^error: 2 /);
1710: $returnhash{$key}=&thaw_unescape($value);
1711: }
1712: my @esc_order = split(/\&/,$orderitems);
1713: foreach my $item (@esc_order) {
1714: push(@order,&unescape($item));
1715: }
1716: } else {
1717: &logthis("get_dom failed - no primary domain server for $udom");
1.837 raeburn 1718: }
1719: }
1720: return (\%returnhash,\@order);
1721: }
1722:
1.868 raeburn 1723: sub is_domainimage {
1724: my ($url) = @_;
1725: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
1726: if (&domain($1) ne '') {
1727: return '1';
1728: }
1729: }
1730: return;
1731: }
1732:
1.899 raeburn 1733: sub inst_directory_query {
1734: my ($srch) = @_;
1735: my $udom = $srch->{'srchdomain'};
1736: my %results;
1737: my $homeserver = &domain($udom,'primary');
1.909 raeburn 1738: my $outcome;
1.899 raeburn 1739: if ($homeserver ne '') {
1.904 albertel 1740: my $queryid=&reply("querysend:instdirsearch:".
1741: &escape($srch->{'srchby'}).':'.
1742: &escape($srch->{'srchterm'}).':'.
1743: &escape($srch->{'srchtype'}),$homeserver);
1744: my $host=&hostname($homeserver);
1745: if ($queryid !~/^\Q$host\E\_/) {
1746: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1747: return;
1748: }
1749: my $response = &get_query_reply($queryid);
1750: my $maxtries = 5;
1751: my $tries = 1;
1752: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1753: $response = &get_query_reply($queryid);
1754: $tries ++;
1755: }
1756:
1757: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 1758: if ($response eq 'unavailable') {
1759: $outcome = $response;
1760: } else {
1761: $outcome = 'ok';
1762: my @matches = split(/\n/,$response);
1763: foreach my $match (@matches) {
1764: my ($key,$value) = split(/=/,$match);
1765: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1766: }
1.899 raeburn 1767: }
1768: }
1769: }
1.909 raeburn 1770: return ($outcome,%results);
1.899 raeburn 1771: }
1772:
1773: sub usersearch {
1774: my ($srch) = @_;
1775: my $dom = $srch->{'srchdomain'};
1776: my %results;
1777: my %libserv = &all_library();
1778: my $query = 'usersearch';
1779: foreach my $tryserver (keys(%libserv)) {
1780: if (&host_domain($tryserver) eq $dom) {
1781: my $host=&hostname($tryserver);
1782: my $queryid=
1.911 raeburn 1783: &reply("querysend:".&escape($query).':'.
1784: &escape($srch->{'srchby'}).':'.
1.899 raeburn 1785: &escape($srch->{'srchtype'}).':'.
1786: &escape($srch->{'srchterm'}),$tryserver);
1787: if ($queryid !~/^\Q$host\E\_/) {
1788: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 1789: next;
1.899 raeburn 1790: }
1791: my $reply = &get_query_reply($queryid);
1792: my $maxtries = 1;
1793: my $tries = 1;
1794: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1795: $reply = &get_query_reply($queryid);
1796: $tries ++;
1797: }
1798: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1799: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1800: } else {
1.911 raeburn 1801: my @matches;
1802: if ($reply =~ /\n/) {
1803: @matches = split(/\n/,$reply);
1804: } else {
1805: @matches = split(/\&/,$reply);
1806: }
1.899 raeburn 1807: foreach my $match (@matches) {
1808: my ($uname,$udom,%userhash);
1.911 raeburn 1809: foreach my $entry (split(/:/,$match)) {
1810: my ($key,$value) =
1811: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 1812: $userhash{$key} = $value;
1813: if ($key eq 'username') {
1814: $uname = $value;
1815: } elsif ($key eq 'domain') {
1816: $udom = $value;
1.911 raeburn 1817: }
1.899 raeburn 1818: }
1819: $results{$uname.':'.$udom} = \%userhash;
1820: }
1821: }
1822: }
1823: }
1824: return %results;
1825: }
1826:
1.912 raeburn 1827: sub get_instuser {
1828: my ($udom,$uname,$id) = @_;
1829: my $homeserver = &domain($udom,'primary');
1830: my ($outcome,%results);
1831: if ($homeserver ne '') {
1832: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1833: &escape($id).':'.&escape($udom),$homeserver);
1834: my $host=&hostname($homeserver);
1835: if ($queryid !~/^\Q$host\E\_/) {
1836: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1837: return;
1838: }
1839: my $response = &get_query_reply($queryid);
1840: my $maxtries = 5;
1841: my $tries = 1;
1842: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1843: $response = &get_query_reply($queryid);
1844: $tries ++;
1845: }
1846: if (!&error($response) && $response ne 'refused') {
1847: if ($response eq 'unavailable') {
1848: $outcome = $response;
1849: } else {
1850: $outcome = 'ok';
1851: my @matches = split(/\n/,$response);
1852: foreach my $match (@matches) {
1853: my ($key,$value) = split(/=/,$match);
1854: $results{&unescape($key)} = &thaw_unescape($value);
1855: }
1856: }
1857: }
1858: }
1859: my %userinfo;
1860: if (ref($results{$uname}) eq 'HASH') {
1861: %userinfo = %{$results{$uname}};
1862: }
1863: return ($outcome,%userinfo);
1864: }
1865:
1866: sub inst_rulecheck {
1.923 raeburn 1867: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 1868: my %returnhash;
1869: if ($udom ne '') {
1870: if (ref($rules) eq 'ARRAY') {
1871: @{$rules} = map {&escape($_);} (@{$rules});
1872: my $rulestr = join(':',@{$rules});
1873: my $homeserver=&domain($udom,'primary');
1874: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1875: my $response;
1876: if ($item eq 'username') {
1877: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
1878: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 1879: $homeserver));
1.923 raeburn 1880: } elsif ($item eq 'id') {
1881: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
1882: ':'.&escape($id).':'.$rulestr,
1883: $homeserver));
1.945 raeburn 1884: } elsif ($item eq 'selfcreate') {
1885: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 1886: &escape($udom).':'.&escape($uname).
1887: ':'.$rulestr,$homeserver));
1.923 raeburn 1888: }
1.912 raeburn 1889: if ($response ne 'refused') {
1890: my @pairs=split(/\&/,$response);
1891: foreach my $item (@pairs) {
1892: my ($key,$value)=split(/=/,$item,2);
1893: $key = &unescape($key);
1894: next if ($key =~ /^error: 2 /);
1895: $returnhash{$key}=&thaw_unescape($value);
1896: }
1897: }
1898: }
1899: }
1900: }
1901: return %returnhash;
1902: }
1903:
1904: sub inst_userrules {
1.923 raeburn 1905: my ($udom,$check) = @_;
1.912 raeburn 1906: my (%ruleshash,@ruleorder);
1907: if ($udom ne '') {
1908: my $homeserver=&domain($udom,'primary');
1909: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1910: my $response;
1911: if ($check eq 'id') {
1912: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 1913: $homeserver);
1.943 raeburn 1914: } elsif ($check eq 'email') {
1915: $response=&reply('instemailrules:'.&escape($udom),
1916: $homeserver);
1.923 raeburn 1917: } else {
1918: $response=&reply('instuserrules:'.&escape($udom),
1919: $homeserver);
1920: }
1.912 raeburn 1921: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 1922: ($response ne 'unknown_cmd') &&
1.912 raeburn 1923: ($response ne 'no_such_host')) {
1924: my ($hashitems,$orderitems) = split(/:/,$response);
1925: my @pairs=split(/\&/,$hashitems);
1926: foreach my $item (@pairs) {
1927: my ($key,$value)=split(/=/,$item,2);
1928: $key = &unescape($key);
1929: next if ($key =~ /^error: 2 /);
1930: $ruleshash{$key}=&thaw_unescape($value);
1931: }
1932: my @esc_order = split(/\&/,$orderitems);
1933: foreach my $item (@esc_order) {
1934: push(@ruleorder,&unescape($item));
1935: }
1936: }
1937: }
1938: }
1939: return (\%ruleshash,\@ruleorder);
1940: }
1941:
1.976 raeburn 1942: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 1943:
1944: sub get_domain_defaults {
1945: my ($domain) = @_;
1946: my $cachetime = 60*60*24;
1947: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
1948: if (defined($cached)) {
1949: if (ref($result) eq 'HASH') {
1950: return %{$result};
1951: }
1952: }
1953: my %domdefaults;
1954: my %domconfig =
1.989 raeburn 1955: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 1956: 'requestcourses','inststatus',
1.1172.2.9 raeburn 1957: 'coursedefaults','usersessions',
1958: 'requestauthor'],$domain);
1.943 raeburn 1959: if (ref($domconfig{'defaults'}) eq 'HASH') {
1960: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
1961: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
1962: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 1963: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 1964: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147 raeburn 1965: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943 raeburn 1966: } else {
1967: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
1968: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
1969: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
1970: }
1.976 raeburn 1971: if (ref($domconfig{'quotas'}) eq 'HASH') {
1972: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
1973: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
1974: } else {
1975: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1976: }
1.1172.2.6 raeburn 1977: my @usertools = ('aboutme','blog','webdav','portfolio');
1.976 raeburn 1978: foreach my $item (@usertools) {
1979: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
1980: $domdefaults{$item} = $domconfig{'quotas'}{$item};
1981: }
1982: }
1983: }
1.985 raeburn 1984: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006 raeburn 1985: foreach my $item ('official','unofficial','community') {
1.985 raeburn 1986: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
1987: }
1988: }
1.1172.2.9 raeburn 1989: if (ref($domconfig{'requestauthor'}) eq 'HASH') {
1990: $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
1991: }
1.989 raeburn 1992: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1993: foreach my $item ('inststatustypes','inststatusorder') {
1994: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
1995: }
1996: }
1.1047 raeburn 1997: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1998: foreach my $item ('canuse_pdfforms') {
1999: $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
2000: }
2001: }
1.1073 raeburn 2002: if (ref($domconfig{'usersessions'}) eq 'HASH') {
2003: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
2004: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
2005: }
2006: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
2007: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
2008: }
2009: }
1.943 raeburn 2010: &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
2011: $cachetime);
2012: return %domdefaults;
2013: }
2014:
1.344 www 2015: # --------------------------------------------------- Assign a key to a student
2016:
2017: sub assign_access_key {
1.364 www 2018: #
2019: # a valid key looks like uname:udom#comments
2020: # comments are being appended
2021: #
1.498 www 2022: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
2023: $kdom=
1.620 albertel 2024: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 2025: $knum=
1.620 albertel 2026: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 2027: $cdom=
1.620 albertel 2028: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2029: $cnum=
1.620 albertel 2030: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2031: $udom=$env{'user.name'} unless (defined($udom));
2032: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 2033: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 2034: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 2035: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 2036: # assigned to this person
2037: # - this should not happen,
1.345 www 2038: # unless something went wrong
2039: # the first time around
2040: # ready to assign
1.364 www 2041: $logentry=$1.'; '.$logentry;
1.496 www 2042: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 2043: $kdom,$knum) eq 'ok') {
1.345 www 2044: # key now belongs to user
1.346 www 2045: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 2046: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 2047: &appenv({'environment.'.$envkey => $ckey});
1.345 www 2048: return 'ok';
2049: } else {
2050: return
2051: 'error: Count not permanently assign key, will need to be re-entered later.';
2052: }
2053: } else {
2054: return 'error: Could not assign key, try again later.';
2055: }
1.364 www 2056: } elsif (!$existing{$ckey}) {
1.345 www 2057: # the key does not exist
2058: return 'error: The key does not exist';
2059: } else {
2060: # the key is somebody else's
2061: return 'error: The key is already in use';
2062: }
1.344 www 2063: }
2064:
1.364 www 2065: # ------------------------------------------ put an additional comment on a key
2066:
2067: sub comment_access_key {
2068: #
2069: # a valid key looks like uname:udom#comments
2070: # comments are being appended
2071: #
2072: my ($ckey,$cdom,$cnum,$logentry)=@_;
2073: $cdom=
1.620 albertel 2074: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 2075: $cnum=
1.620 albertel 2076: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 2077: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2078: if ($existing{$ckey}) {
2079: $existing{$ckey}.='; '.$logentry;
2080: # ready to assign
1.367 www 2081: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 2082: $cdom,$cnum) eq 'ok') {
2083: return 'ok';
2084: } else {
2085: return 'error: Count not store comment.';
2086: }
2087: } else {
2088: # the key does not exist
2089: return 'error: The key does not exist';
2090: }
2091: }
2092:
1.344 www 2093: # ------------------------------------------------------ Generate a set of keys
2094:
2095: sub generate_access_keys {
1.364 www 2096: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 2097: $cdom=
1.620 albertel 2098: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2099: $cnum=
1.620 albertel 2100: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 2101: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 2102: unless (($cdom) && ($cnum)) { return 0; }
2103: if ($number>10000) { return 0; }
2104: sleep(2); # make sure don't get same seed twice
2105: srand(time()^($$+($$<<15))); # from "Programming Perl"
2106: my $total=0;
2107: for (my $i=1;$i<=$number;$i++) {
2108: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
2109: sprintf("%lx",int(100000*rand)).'-'.
2110: sprintf("%lx",int(100000*rand));
2111: $newkey=~s/1/g/g; # folks mix up 1 and l
2112: $newkey=~s/0/h/g; # and also 0 and O
2113: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
2114: if ($existing{$newkey}) {
2115: $i--;
2116: } else {
1.364 www 2117: if (&put('accesskeys',
2118: { $newkey => '# generated '.localtime().
1.620 albertel 2119: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 2120: '; '.$logentry },
2121: $cdom,$cnum) eq 'ok') {
1.344 www 2122: $total++;
2123: }
2124: }
2125: }
1.620 albertel 2126: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 2127: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
2128: return $total;
2129: }
2130:
2131: # ------------------------------------------------------- Validate an accesskey
2132:
2133: sub validate_access_key {
2134: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
2135: $cdom=
1.620 albertel 2136: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2137: $cnum=
1.620 albertel 2138: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2139: $udom=$env{'user.domain'} unless (defined($udom));
2140: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 2141: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 2142: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 2143: }
2144:
2145: # ------------------------------------- Find the section of student in a course
1.652 albertel 2146: sub devalidate_getsection_cache {
2147: my ($udom,$unam,$courseid)=@_;
2148: my $hashid="$udom:$unam:$courseid";
2149: &devalidate_cache_new('getsection',$hashid);
2150: }
1.298 matthew 2151:
1.815 albertel 2152: sub courseid_to_courseurl {
2153: my ($courseid) = @_;
2154: #already url style courseid
2155: return $courseid if ($courseid =~ m{^/});
2156:
2157: if (exists($env{'course.'.$courseid.'.num'})) {
2158: my $cnum = $env{'course.'.$courseid.'.num'};
2159: my $cdom = $env{'course.'.$courseid.'.domain'};
2160: return "/$cdom/$cnum";
2161: }
2162:
2163: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
2164: if (exists($courseinfo{'num'})) {
2165: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
2166: }
2167:
2168: return undef;
2169: }
2170:
1.298 matthew 2171: sub getsection {
2172: my ($udom,$unam,$courseid)=@_;
1.599 albertel 2173: my $cachetime=1800;
1.551 albertel 2174:
2175: my $hashid="$udom:$unam:$courseid";
1.599 albertel 2176: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 2177: if (defined($cached)) { return $result; }
2178:
1.298 matthew 2179: my %Pending;
2180: my %Expired;
2181: #
2182: # Each role can either have not started yet (pending), be active,
2183: # or have expired.
2184: #
2185: # If there is an active role, we are done.
2186: #
2187: # If there is more than one role which has not started yet,
2188: # choose the one which will start sooner
2189: # If there is one role which has not started yet, return it.
2190: #
2191: # If there is more than one expired role, choose the one which ended last.
2192: # If there is a role which has expired, return it.
2193: #
1.815 albertel 2194: $courseid = &courseid_to_courseurl($courseid);
1.1166 raeburn 2195: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817 raeburn 2196: foreach my $key (keys(%roleshash)) {
1.479 albertel 2197: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 2198: my $section=$1;
2199: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 2200: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 2201: my $now=time;
1.548 albertel 2202: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 2203: $Expired{$end}=$section;
2204: next;
2205: }
1.548 albertel 2206: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 2207: $Pending{$start}=$section;
2208: next;
2209: }
1.599 albertel 2210: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 2211: }
2212: #
2213: # Presumedly there will be few matching roles from the above
2214: # loop and the sorting time will be negligible.
2215: if (scalar(keys(%Pending))) {
2216: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 2217: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 2218: }
2219: if (scalar(keys(%Expired))) {
2220: my @sorted = sort {$a <=> $b} keys(%Expired);
2221: my $time = pop(@sorted);
1.599 albertel 2222: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 2223: }
1.599 albertel 2224: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 2225: }
1.70 www 2226:
1.599 albertel 2227: sub save_cache {
2228: &purge_remembered();
1.722 albertel 2229: #&Apache::loncommon::validate_page();
1.620 albertel 2230: undef(%env);
1.780 albertel 2231: undef($env_loaded);
1.599 albertel 2232: }
1.452 albertel 2233:
1.599 albertel 2234: my $to_remember=-1;
2235: my %remembered;
2236: my %accessed;
2237: my $kicks=0;
2238: my $hits=0;
1.849 albertel 2239: sub make_key {
2240: my ($name,$id) = @_;
1.872 albertel 2241: if (length($id) > 65
2242: && length(&escape($id)) > 200) {
2243: $id=length($id).':'.&Digest::MD5::md5_hex($id);
2244: }
1.849 albertel 2245: return &escape($name.':'.$id);
2246: }
2247:
1.599 albertel 2248: sub devalidate_cache_new {
2249: my ($name,$id,$debug) = @_;
2250: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849 albertel 2251: $id=&make_key($name,$id);
1.599 albertel 2252: $memcache->delete($id);
2253: delete($remembered{$id});
2254: delete($accessed{$id});
2255: }
2256:
2257: sub is_cached_new {
2258: my ($name,$id,$debug) = @_;
1.849 albertel 2259: $id=&make_key($name,$id);
1.599 albertel 2260: if (exists($remembered{$id})) {
1.1133 foxr 2261: if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
1.599 albertel 2262: $accessed{$id}=[&gettimeofday()];
2263: $hits++;
2264: return ($remembered{$id},1);
2265: }
2266: my $value = $memcache->get($id);
2267: if (!(defined($value))) {
2268: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 2269: return (undef,undef);
1.416 albertel 2270: }
1.599 albertel 2271: if ($value eq '__undef__') {
2272: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
2273: $value=undef;
2274: }
2275: &make_room($id,$value,$debug);
2276: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
2277: return ($value,1);
2278: }
2279:
2280: sub do_cache_new {
2281: my ($name,$id,$value,$time,$debug) = @_;
1.849 albertel 2282: $id=&make_key($name,$id);
1.599 albertel 2283: my $setvalue=$value;
2284: if (!defined($setvalue)) {
2285: $setvalue='__undef__';
2286: }
1.623 albertel 2287: if (!defined($time) ) {
2288: $time=600;
2289: }
1.599 albertel 2290: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 2291: my $result = $memcache->set($id,$setvalue,$time);
2292: if (! $result) {
1.872 albertel 2293: &logthis("caching of id -> $id failed");
1.910 albertel 2294: $memcache->disconnect_all();
1.872 albertel 2295: }
1.600 albertel 2296: # need to make a copy of $value
1.919 albertel 2297: &make_room($id,$value,$debug);
1.599 albertel 2298: return $value;
2299: }
2300:
2301: sub make_room {
2302: my ($id,$value,$debug)=@_;
1.919 albertel 2303:
2304: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
2305: : $value;
1.599 albertel 2306: if ($to_remember<0) { return; }
2307: $accessed{$id}=[&gettimeofday()];
2308: if (scalar(keys(%remembered)) <= $to_remember) { return; }
2309: my $to_kick;
2310: my $max_time=0;
2311: foreach my $other (keys(%accessed)) {
2312: if (&tv_interval($accessed{$other}) > $max_time) {
2313: $to_kick=$other;
2314: $max_time=&tv_interval($accessed{$other});
2315: }
2316: }
2317: delete($remembered{$to_kick});
2318: delete($accessed{$to_kick});
2319: $kicks++;
2320: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 2321: return;
2322: }
2323:
1.599 albertel 2324: sub purge_remembered {
1.604 albertel 2325: #&logthis("Tossing ".scalar(keys(%remembered)));
2326: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 2327: undef(%remembered);
2328: undef(%accessed);
1.428 albertel 2329: }
1.70 www 2330: # ------------------------------------- Read an entry from a user's environment
2331:
2332: sub userenvironment {
2333: my ($udom,$unam,@what)=@_;
1.976 raeburn 2334: my $items;
2335: foreach my $item (@what) {
2336: $items.=&escape($item).'&';
2337: }
2338: $items=~s/\&$//;
1.70 www 2339: my %returnhash=();
1.1009 raeburn 2340: my $uhome = &homeserver($unam,$udom);
2341: unless ($uhome eq 'no_host') {
2342: my @answer=split(/\&/,
2343: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 2344: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
2345: return %returnhash;
2346: }
1.1009 raeburn 2347: my $i;
2348: for ($i=0;$i<=$#what;$i++) {
2349: $returnhash{$what[$i]}=&unescape($answer[$i]);
2350: }
1.70 www 2351: }
2352: return %returnhash;
1.1 albertel 2353: }
2354:
1.617 albertel 2355: # ---------------------------------------------------------- Get a studentphoto
2356: sub studentphoto {
2357: my ($udom,$unam,$ext) = @_;
2358: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 2359: if (defined($env{'request.course.id'})) {
1.708 raeburn 2360: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 2361: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
2362: return(&retrievestudentphoto($udom,$unam,$ext));
2363: } else {
2364: my ($result,$perm_reqd)=
1.707 albertel 2365: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2366: if ($result eq 'ok') {
2367: if (!($perm_reqd eq 'yes')) {
2368: return(&retrievestudentphoto($udom,$unam,$ext));
2369: }
2370: }
2371: }
2372: }
2373: } else {
2374: my ($result,$perm_reqd) =
1.707 albertel 2375: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2376: if ($result eq 'ok') {
2377: if (!($perm_reqd eq 'yes')) {
2378: return(&retrievestudentphoto($udom,$unam,$ext));
2379: }
2380: }
2381: }
2382: return '/adm/lonKaputt/lonlogo_broken.gif';
2383: }
2384:
2385: sub retrievestudentphoto {
2386: my ($udom,$unam,$ext,$type) = @_;
2387: my $home=&Apache::lonnet::homeserver($unam,$udom);
2388: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
2389: if ($ret eq 'ok') {
2390: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
2391: if ($type eq 'thumbnail') {
2392: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
2393: }
2394: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
2395: return $tokenurl;
2396: } else {
2397: if ($type eq 'thumbnail') {
2398: return '/adm/lonKaputt/genericstudent_tn.gif';
2399: } else {
2400: return '/adm/lonKaputt/lonlogo_broken.gif';
2401: }
1.617 albertel 2402: }
2403: }
2404:
1.263 www 2405: # -------------------------------------------------------------------- New chat
2406:
2407: sub chatsend {
1.724 raeburn 2408: my ($newentry,$anon,$group)=@_;
1.620 albertel 2409: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
2410: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2411: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 2412: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 2413: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 2414: &escape($newentry)).':'.$group,$chome);
1.292 www 2415: }
2416:
2417: # ------------------------------------------ Find current version of a resource
2418:
2419: sub getversion {
2420: my $fname=&clutter(shift);
1.1172.2.10 raeburn 2421: unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292 www 2422: return ¤tversion(&filelocation('',$fname));
2423: }
2424:
2425: sub currentversion {
2426: my $fname=shift;
2427: my $author=$fname;
2428: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2429: my ($udom,$uname)=split(/\//,$author);
1.1112 www 2430: my $home=&homeserver($uname,$udom);
1.292 www 2431: if ($home eq 'no_host') {
2432: return -1;
2433: }
1.1112 www 2434: my $answer=&reply("currentversion:$fname",$home);
1.292 www 2435: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2436: return -1;
2437: }
1.1112 www 2438: return $answer;
1.263 www 2439: }
2440:
1.1111 www 2441: #
2442: # Return special version number of resource if set by override, empty otherwise
2443: #
2444: sub usedversion {
2445: my $fname=shift;
2446: unless ($fname) { $fname=$env{'request.uri'}; }
2447: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
2448: if ($urlversion) { return $urlversion; }
2449: return '';
2450: }
2451:
1.1 albertel 2452: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 2453:
1.1 albertel 2454: sub subscribe {
2455: my $fname=shift;
1.761 raeburn 2456: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 2457: $fname=~s/[\n\r]//g;
1.1 albertel 2458: my $author=$fname;
2459: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2460: my ($udom,$uname)=split(/\//,$author);
2461: my $home=homeserver($uname,$udom);
1.335 albertel 2462: if ($home eq 'no_host') {
2463: return 'not_found';
1.1 albertel 2464: }
2465: my $answer=reply("sub:$fname",$home);
1.64 www 2466: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2467: $answer.=' by '.$home;
2468: }
1.1 albertel 2469: return $answer;
2470: }
2471:
1.8 www 2472: # -------------------------------------------------------------- Replicate file
2473:
2474: sub repcopy {
2475: my $filename=shift;
1.23 www 2476: $filename=~s/\/+/\//g;
1.1142 raeburn 2477: my $londocroot = $perlvar{'lonDocRoot'};
2478: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164 raeburn 2479: if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142 raeburn 2480: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
2481: $filename=~m{^/*(uploaded|editupload)/}) {
1.538 albertel 2482: return &repcopy_userfile($filename);
2483: }
1.532 albertel 2484: $filename=~s/[\n\r]//g;
1.8 www 2485: my $transname="$filename.in.transfer";
1.828 www 2486: # FIXME: this should flock
1.607 raeburn 2487: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 2488: my $remoteurl=subscribe($filename);
1.64 www 2489: if ($remoteurl =~ /^con_lost by/) {
2490: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2491: return 'unavailable';
1.8 www 2492: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 2493: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 2494: return 'not_found';
1.64 www 2495: } elsif ($remoteurl =~ /^rejected by/) {
2496: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2497: return 'forbidden';
1.20 www 2498: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 2499: return 'ok';
1.8 www 2500: } else {
1.290 www 2501: my $author=$filename;
2502: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2503: my ($udom,$uname)=split(/\//,$author);
2504: my $home=homeserver($uname,$udom);
2505: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 2506: my @parts=split(/\//,$filename);
2507: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142 raeburn 2508: if ($path ne "$londocroot/res") {
1.8 www 2509: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 2510: return 'bad_request';
1.8 www 2511: }
2512: my $count;
2513: for ($count=5;$count<$#parts;$count++) {
2514: $path.="/$parts[$count]";
2515: if ((-e $path)!=1) {
2516: mkdir($path,0777);
2517: }
2518: }
2519: my $ua=new LWP::UserAgent;
2520: my $request=new HTTP::Request('GET',"$remoteurl");
2521: my $response=$ua->request($request,$transname);
2522: if ($response->is_error()) {
2523: unlink($transname);
2524: my $message=$response->status_line;
1.672 albertel 2525: &logthis("<font color=\"blue\">WARNING:"
1.12 www 2526: ." LWP get: $message: $filename</font>");
1.607 raeburn 2527: return 'unavailable';
1.8 www 2528: } else {
1.16 www 2529: if ($remoteurl!~/\.meta$/) {
2530: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2531: my $mresponse=$ua->request($mrequest,$filename.'.meta');
2532: if ($mresponse->is_error()) {
2533: unlink($filename.'.meta');
2534: &logthis(
1.672 albertel 2535: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 2536: }
2537: }
1.8 www 2538: rename($transname,$filename);
1.607 raeburn 2539: return 'ok';
1.8 www 2540: }
1.290 www 2541: }
1.8 www 2542: }
1.330 www 2543: }
2544:
2545: # ------------------------------------------------ Get server side include body
2546: sub ssi_body {
1.381 albertel 2547: my ($filelink,%form)=@_;
1.606 matthew 2548: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
2549: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
2550: }
1.953 www 2551: my $output='';
2552: my $response;
1.980 raeburn 2553: if ($filelink=~/^https?\:/) {
1.954 raeburn 2554: ($output,$response)=&externalssi($filelink);
1.953 www 2555: } else {
1.1004 droeschl 2556: $filelink .= $filelink=~/\?/ ? '&' : '?';
2557: $filelink .= 'inhibitmenu=yes';
1.953 www 2558: ($output,$response)=&ssi($filelink,%form);
2559: }
1.778 albertel 2560: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 2561: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 2562: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 2563: if (wantarray) {
2564: return ($output, $response);
2565: } else {
2566: return $output;
2567: }
1.8 www 2568: }
2569:
1.15 www 2570: # --------------------------------------------------------- Server Side Include
2571:
1.782 albertel 2572: sub absolute_url {
2573: my ($host_name) = @_;
2574: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
2575: if ($host_name eq '') {
2576: $host_name = $ENV{'SERVER_NAME'};
2577: }
2578: return $protocol.$host_name;
2579: }
2580:
1.942 foxr 2581: #
2582: # Server side include.
2583: # Parameters:
2584: # fn Possibly encrypted resource name/id.
2585: # form Hash that describes how the rendering should be done
2586: # and other things.
1.944 foxr 2587: # Returns:
1.950 raeburn 2588: # Scalar context: The content of the response.
2589: # Array context: 2 element list of the content and the full response object.
1.942 foxr 2590: #
1.15 www 2591: sub ssi {
2592:
1.944 foxr 2593: my ($fn,%form)=@_;
1.15 www 2594: my $ua=new LWP::UserAgent;
1.23 www 2595: my $request;
1.711 albertel 2596:
2597: $form{'no_update_last_known'}=1;
1.895 albertel 2598: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 2599: if (%form) {
1.782 albertel 2600: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000 raeburn 2601: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23 www 2602: } else {
1.782 albertel 2603: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 2604: }
2605:
1.15 www 2606: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.2 raeburn 2607: my $response= $ua->request($request);
1.944 foxr 2608: if (wantarray) {
1.1172.2.3 raeburn 2609: return ($response->content, $response);
1.944 foxr 2610: } else {
1.1172.2.3 raeburn 2611: return $response->content;
1.942 foxr 2612: }
1.324 www 2613: }
2614:
2615: sub externalssi {
2616: my ($url)=@_;
2617: my $ua=new LWP::UserAgent;
2618: my $request=new HTTP::Request('GET',$url);
2619: my $response=$ua->request($request);
1.954 raeburn 2620: if (wantarray) {
2621: return ($response->content, $response);
2622: } else {
2623: return $response->content;
2624: }
1.15 www 2625: }
1.254 www 2626:
1.492 albertel 2627: # -------------------------------- Allow a /uploaded/ URI to be vouched for
2628:
2629: sub allowuploaded {
2630: my ($srcurl,$url)=@_;
2631: $url=&clutter(&declutter($url));
2632: my $dir=$url;
2633: $dir=~s/\/[^\/]+$//;
2634: my %httpref=();
2635: my $httpurl=&hreflocation('',$url);
2636: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 2637: &Apache::lonnet::appenv(\%httpref);
1.254 www 2638: }
1.477 raeburn 2639:
1.478 albertel 2640: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 2641: # input: action, courseID, current domain, intended
1.637 raeburn 2642: # path to file, source of file, instruction to parse file for objects,
2643: # ref to hash for embedded objects,
2644: # ref to hash for codebase of java objects.
1.1095 raeburn 2645: # reference to scalar to accommodate mime type determined
2646: # from File::MMagic if $parser = parse.
1.637 raeburn 2647: #
1.485 raeburn 2648: # output: url to file (if action was uploaddoc),
2649: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 2650: #
1.478 albertel 2651: # Allows directory structure to be used within lonUsers/../userfiles/ for a
2652: # course.
1.477 raeburn 2653: #
1.478 albertel 2654: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2655: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
2656: # course's home server.
1.477 raeburn 2657: #
1.478 albertel 2658: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
2659: # be copied from $source (current location) to
2660: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2661: # and will then be copied to
2662: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
2663: # course's home server.
1.485 raeburn 2664: #
1.481 raeburn 2665: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 2666: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 2667: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2668: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
2669: # in course's home server.
1.637 raeburn 2670: #
1.477 raeburn 2671:
2672: sub process_coursefile {
1.1095 raeburn 2673: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
2674: $mimetype)=@_;
1.477 raeburn 2675: my $fetchresult;
1.638 albertel 2676: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 2677: if ($action eq 'propagate') {
1.638 albertel 2678: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2679: $home);
1.481 raeburn 2680: } else {
1.477 raeburn 2681: my $fpath = '';
2682: my $fname = $file;
1.478 albertel 2683: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 2684: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 2685: my $filepath = &build_filepath($fpath);
1.481 raeburn 2686: if ($action eq 'copy') {
2687: if ($source eq '') {
2688: $fetchresult = 'no source file';
2689: return $fetchresult;
2690: } else {
2691: my $destination = $filepath.'/'.$fname;
2692: rename($source,$destination);
2693: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2694: $home);
1.481 raeburn 2695: }
2696: } elsif ($action eq 'uploaddoc') {
2697: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 2698: print $fh $env{'form.'.$source};
1.481 raeburn 2699: close($fh);
1.637 raeburn 2700: if ($parser eq 'parse') {
1.1024 raeburn 2701: my $mm = new File::MMagic;
1.1095 raeburn 2702: my $type = $mm->checktype_filename($filepath.'/'.$fname);
2703: if ($type eq 'text/html') {
1.1024 raeburn 2704: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
2705: unless ($parse_result eq 'ok') {
2706: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
2707: }
1.637 raeburn 2708: }
1.1095 raeburn 2709: if (ref($mimetype)) {
2710: $$mimetype = $type;
2711: }
1.637 raeburn 2712: }
1.477 raeburn 2713: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2714: $home);
1.481 raeburn 2715: if ($fetchresult eq 'ok') {
2716: return '/uploaded/'.$fpath.'/'.$fname;
2717: } else {
2718: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 2719: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 2720: return '/adm/notfound.html';
2721: }
1.477 raeburn 2722: }
2723: }
1.485 raeburn 2724: unless ( $fetchresult eq 'ok') {
1.477 raeburn 2725: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 2726: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 2727: }
2728: return $fetchresult;
2729: }
2730:
1.637 raeburn 2731: sub build_filepath {
2732: my ($fpath) = @_;
2733: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
2734: unless ($fpath eq '') {
2735: my @parts=split('/',$fpath);
2736: foreach my $part (@parts) {
2737: $filepath.= '/'.$part;
2738: if ((-e $filepath)!=1) {
2739: mkdir($filepath,0777);
2740: }
2741: }
2742: }
2743: return $filepath;
2744: }
2745:
2746: sub store_edited_file {
1.638 albertel 2747: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 2748: my $file = $primary_url;
2749: $file =~ s#^/uploaded/$docudom/$docuname/##;
2750: my $fpath = '';
2751: my $fname = $file;
2752: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
2753: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
2754: my $filepath = &build_filepath($fpath);
2755: open(my $fh,'>'.$filepath.'/'.$fname);
2756: print $fh $content;
2757: close($fh);
1.638 albertel 2758: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 2759: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2760: $home);
1.637 raeburn 2761: if ($$fetchresult eq 'ok') {
2762: return '/uploaded/'.$fpath.'/'.$fname;
2763: } else {
1.638 albertel 2764: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
2765: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 2766: return '/adm/notfound.html';
2767: }
2768: }
2769:
1.531 albertel 2770: sub clean_filename {
1.831 albertel 2771: my ($fname,$args)=@_;
1.315 www 2772: # Replace Windows backslashes by forward slashes
1.257 www 2773: $fname=~s/\\/\//g;
1.831 albertel 2774: if (!$args->{'keep_path'}) {
2775: # Get rid of everything but the actual filename
2776: $fname=~s/^.*\/([^\/]+)$/$1/;
2777: }
1.315 www 2778: # Replace spaces by underscores
2779: $fname=~s/\s+/\_/g;
2780: # Replace all other weird characters by nothing
1.831 albertel 2781: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 2782: # Replace all .\d. sequences with _\d. so they no longer look like version
2783: # numbers
2784: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 2785: return $fname;
2786: }
1.1051 raeburn 2787: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
2788: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
2789: # image with the same aspect ratio as the original, but with dimensions which do
2790: # not exceed $resizewidth and $resizeheight.
2791:
1.984 neumanie 2792: sub resizeImage {
1.1051 raeburn 2793: my ($img_path,$resizewidth,$resizeheight) = @_;
2794: my $ima = Image::Magick->new;
2795: my $resized;
2796: if (-e $img_path) {
2797: $ima->Read($img_path);
2798: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
2799: my $width = $ima->Get('width');
2800: my $height = $ima->Get('height');
2801: if ($width > $resizewidth) {
2802: my $factor = $width/$resizewidth;
2803: my $newheight = $height/$factor;
2804: $ima->Scale(width=>$resizewidth,height=>$newheight);
2805: $resized = 1;
2806: }
2807: }
2808: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
2809: my $width = $ima->Get('width');
2810: my $height = $ima->Get('height');
2811: if ($height > $resizeheight) {
2812: my $factor = $height/$resizeheight;
2813: my $newwidth = $width/$factor;
2814: $ima->Scale(width=>$newwidth,height=>$resizeheight);
2815: $resized = 1;
2816: }
2817: }
2818: if ($resized) {
2819: $ima->Write($img_path);
2820: }
2821: }
2822: return;
1.977 amueller 2823: }
2824:
1.608 albertel 2825: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 2826: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093 raeburn 2827: # the desired filename is in $env{"form.$formname.filename"}
1.1090 raeburn 2828: # $context - possible values: coursedoc, existingfile, overwrite,
2829: # canceloverwrite, or ''.
2830: # if 'coursedoc': upload to the current course
2831: # if 'existingfile': write file to tmp/overwrites directory
2832: # if 'canceloverwrite': delete file written to tmp/overwrites directory
2833: # $context is passed as argument to &finishuserfileupload
1.686 albertel 2834: # $subdir - directory in userfile to store the file into
1.858 raeburn 2835: # $parser - instruction to parse file for objects ($parser = parse)
2836: # $allfiles - reference to hash for embedded objects
2837: # $codebase - reference to hash for codebase of java objects
2838: # $desuname - username for permanent storage of uploaded file
2839: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 2840: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
2841: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 2842: # $resizewidth - width (pixels) to which to resize uploaded image
2843: # $resizeheight - height (pixels) to which to resize uploaded image
1.1095 raeburn 2844: # $mimetype - reference to scalar to accommodate mime type determined
1.1152 raeburn 2845: # from File::MMagic.
1.858 raeburn 2846: #
1.686 albertel 2847: # output: url of file in userspace, or error: <message>
2848: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 2849:
1.531 albertel 2850: sub userfileupload {
1.1090 raeburn 2851: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095 raeburn 2852: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531 albertel 2853: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 2854: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 2855: $fname=&clean_filename($fname);
1.1090 raeburn 2856: # See if there is anything left
1.257 www 2857: unless ($fname) { return 'error: no uploaded file'; }
1.1090 raeburn 2858: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
2859: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
2860: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
2861: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523 raeburn 2862: my $now = time;
1.1090 raeburn 2863: my $filepath;
1.1095 raeburn 2864: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090 raeburn 2865: $filepath = 'tmp/helprequests/'.$now;
2866: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
2867: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
2868: '_'.$env{'user.domain'}.'/pending';
2869: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
2870: my ($docuname,$docudom);
2871: if ($destudom) {
2872: $docudom = $destudom;
2873: } else {
2874: $docudom = $env{'user.domain'};
2875: }
2876: if ($destuname) {
2877: $docuname = $destuname;
2878: } else {
2879: $docuname = $env{'user.name'};
2880: }
2881: if (exists($env{'form.group'})) {
2882: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2883: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2884: }
2885: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
2886: if ($context eq 'canceloverwrite') {
2887: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
2888: if (-e $tempfile) {
2889: my @info = stat($tempfile);
2890: if ($info[9] eq $env{'form.timestamp'}) {
2891: unlink($tempfile);
2892: }
2893: }
2894: return;
1.523 raeburn 2895: }
2896: }
1.1090 raeburn 2897: # Create the directory if not present
1.741 raeburn 2898: my @parts=split(/\//,$filepath);
2899: my $fullpath = $perlvar{'lonDaemons'};
2900: for (my $i=0;$i<@parts;$i++) {
2901: $fullpath .= '/'.$parts[$i];
2902: if ((-e $fullpath)!=1) {
2903: mkdir($fullpath,0777);
2904: }
2905: }
2906: open(my $fh,'>'.$fullpath.'/'.$fname);
2907: print $fh $env{'form.'.$formname};
2908: close($fh);
1.1090 raeburn 2909: if ($context eq 'existingfile') {
2910: my @info = stat($fullpath.'/'.$fname);
2911: return ($fullpath.'/'.$fname,$info[9]);
2912: } else {
2913: return $fullpath.'/'.$fname;
2914: }
1.523 raeburn 2915: }
1.995 raeburn 2916: if ($subdir eq 'scantron') {
2917: $fname = 'scantron_orig_'.$fname;
1.1093 raeburn 2918: } else {
1.995 raeburn 2919: $fname="$subdir/$fname";
2920: }
1.1090 raeburn 2921: if ($context eq 'coursedoc') {
1.638 albertel 2922: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2923: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 2924: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 2925: return &finishuserfileupload($docuname,$docudom,
2926: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 2927: $codebase,$thumbwidth,$thumbheight,
1.1095 raeburn 2928: $resizewidth,$resizeheight,$context,$mimetype);
1.481 raeburn 2929: } else {
1.620 albertel 2930: $fname=$env{'form.folder'}.'/'.$fname;
1.638 albertel 2931: return &process_coursefile('uploaddoc',$docuname,$docudom,
2932: $fname,$formname,$parser,
1.1095 raeburn 2933: $allfiles,$codebase,$mimetype);
1.481 raeburn 2934: }
1.719 banghart 2935: } elsif (defined($destuname)) {
2936: my $docuname=$destuname;
2937: my $docudom=$destudom;
1.860 raeburn 2938: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2939: $parser,$allfiles,$codebase,
1.1051 raeburn 2940: $thumbwidth,$thumbheight,
1.1095 raeburn 2941: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 2942: } else {
1.638 albertel 2943: my $docuname=$env{'user.name'};
2944: my $docudom=$env{'user.domain'};
1.714 raeburn 2945: if (exists($env{'form.group'})) {
2946: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2947: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2948: }
1.860 raeburn 2949: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2950: $parser,$allfiles,$codebase,
1.1051 raeburn 2951: $thumbwidth,$thumbheight,
1.1095 raeburn 2952: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 2953: }
1.271 www 2954: }
2955:
2956: sub finishuserfileupload {
1.860 raeburn 2957: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095 raeburn 2958: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477 raeburn 2959: my $path=$docudom.'/'.$docuname.'/';
1.258 www 2960: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 2961:
1.860 raeburn 2962: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 2963: $file=$fname;
2964: if ($fname=~m|/|) {
2965: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
2966: $path.=$fnamepath.'/';
2967: }
1.259 www 2968: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 2969: my $count;
2970: for ($count=4;$count<=$#parts;$count++) {
2971: $filepath.="/$parts[$count]";
2972: if ((-e $filepath)!=1) {
2973: mkdir($filepath,0777);
2974: }
2975: }
1.984 neumanie 2976:
1.258 www 2977: # Save the file
2978: {
1.701 albertel 2979: if (!open(FH,'>'.$filepath.'/'.$file)) {
2980: &logthis('Failed to create '.$filepath.'/'.$file);
2981: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
2982: return '/adm/notfound.html';
2983: }
1.1090 raeburn 2984: if ($context eq 'overwrite') {
1.1117 foxr 2985: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090 raeburn 2986: my $target = $filepath.'/'.$file;
2987: if (-e $source) {
2988: my @info = stat($source);
2989: if ($info[9] eq $env{'form.timestamp'}) {
2990: unless (&File::Copy::move($source,$target)) {
2991: &logthis('Failed to overwrite '.$filepath.'/'.$file);
2992: return "Moving from $source failed";
2993: }
2994: } else {
2995: return "Temporary file: $source had unexpected date/time for last modification";
2996: }
2997: } else {
2998: return "Temporary file: $source missing";
2999: }
3000: } elsif (!print FH ($env{'form.'.$formname})) {
1.701 albertel 3001: &logthis('Failed to write to '.$filepath.'/'.$file);
3002: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
3003: return '/adm/notfound.html';
3004: }
1.570 albertel 3005: close(FH);
1.1051 raeburn 3006: if ($resizewidth && $resizeheight) {
3007: my $mm = new File::MMagic;
3008: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
3009: if ($mime_type =~ m{^image/}) {
3010: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
3011: }
1.977 amueller 3012: }
1.258 www 3013: }
1.1152 raeburn 3014: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
3015: if (ref($mimetype)) {
3016: if ($$mimetype eq '') {
3017: my $mm = new File::MMagic;
3018: my $type = $mm->checktype_filename($filepath.'/'.$file);
3019: $$mimetype = $type;
3020: }
3021: }
3022: }
1.637 raeburn 3023: if ($parser eq 'parse') {
1.1152 raeburn 3024: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024 raeburn 3025: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
3026: $allfiles,$codebase);
3027: unless ($parse_result eq 'ok') {
3028: &logthis('Failed to parse '.$filepath.$file.
3029: ' for embedded media: '.$parse_result);
3030: }
1.637 raeburn 3031: }
3032: }
1.860 raeburn 3033: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
3034: my $input = $filepath.'/'.$file;
3035: my $output = $filepath.'/'.'tn-'.$file;
3036: my $thumbsize = $thumbwidth.'x'.$thumbheight;
3037: system("convert -sample $thumbsize $input $output");
3038: if (-e $filepath.'/'.'tn-'.$file) {
3039: $fetchthumb = 1;
3040: }
3041: }
1.858 raeburn 3042:
1.259 www 3043: # Notify homeserver to grep it
3044: #
1.984 neumanie 3045: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 3046: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 3047: if ($fetchresult eq 'ok') {
1.860 raeburn 3048: if ($fetchthumb) {
3049: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
3050: if ($thumbresult ne 'ok') {
3051: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
3052: $docuhome.': '.$thumbresult);
3053: }
3054: }
1.259 www 3055: #
1.258 www 3056: # Return the URL to it
1.494 albertel 3057: return '/uploaded/'.$path.$file;
1.263 www 3058: } else {
1.494 albertel 3059: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
3060: ': '.$fetchresult);
1.263 www 3061: return '/adm/notfound.html';
1.858 raeburn 3062: }
1.493 albertel 3063: }
3064:
1.637 raeburn 3065: sub extract_embedded_items {
1.961 raeburn 3066: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 3067: my @state = ();
1.1164 raeburn 3068: my (%lastids,%related,%shockwave,%flashvars);
1.637 raeburn 3069: my %javafiles = (
3070: codebase => '',
3071: code => '',
3072: archive => ''
3073: );
3074: my %mediafiles = (
3075: src => '',
3076: movie => '',
3077: );
1.648 raeburn 3078: my $p;
3079: if ($content) {
3080: $p = HTML::LCParser->new($content);
3081: } else {
1.961 raeburn 3082: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 3083: }
1.641 albertel 3084: while (my $t=$p->get_token()) {
1.640 albertel 3085: if ($t->[0] eq 'S') {
3086: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 3087: push(@state, $tagname);
1.648 raeburn 3088: if (lc($tagname) eq 'allow') {
3089: &add_filetype($allfiles,$attr->{'src'},'src');
3090: }
1.640 albertel 3091: if (lc($tagname) eq 'img') {
3092: &add_filetype($allfiles,$attr->{'src'},'src');
3093: }
1.886 albertel 3094: if (lc($tagname) eq 'a') {
3095: &add_filetype($allfiles,$attr->{'href'},'href');
3096: }
1.645 raeburn 3097: if (lc($tagname) eq 'script') {
1.1164 raeburn 3098: my $src;
1.645 raeburn 3099: if ($attr->{'archive'} =~ /\.jar$/i) {
3100: &add_filetype($allfiles,$attr->{'archive'},'archive');
3101: } else {
1.1164 raeburn 3102: if ($attr->{'src'} ne '') {
3103: $src = $attr->{'src'};
3104: &add_filetype($allfiles,$src,'src');
3105: }
3106: }
3107: my $text = $p->get_trimmed_text();
3108: if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
3109: my @swfargs = split(/,/,$1);
3110: foreach my $item (@swfargs) {
3111: $item =~ s/["']//g;
3112: $item =~ s/^\s+//;
3113: $item =~ s/\s+$//;
3114: }
3115: if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
3116: if (ref($related{$swfargs[0]}) eq 'ARRAY') {
3117: push(@{$related{$swfargs[0]}},$swfargs[2]);
3118: } else {
3119: $related{$swfargs[0]} = [$swfargs[2]];
3120: }
3121: }
1.645 raeburn 3122: }
3123: }
3124: if (lc($tagname) eq 'link') {
3125: if (lc($attr->{'rel'}) eq 'stylesheet') {
3126: &add_filetype($allfiles,$attr->{'href'},'href');
3127: }
3128: }
1.640 albertel 3129: if (lc($tagname) eq 'object' ||
3130: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
3131: foreach my $item (keys(%javafiles)) {
3132: $javafiles{$item} = '';
3133: }
1.1164 raeburn 3134: if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
3135: $lastids{lc($tagname)} = $attr->{'id'};
3136: }
1.640 albertel 3137: }
3138: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
3139: my $name = lc($attr->{'name'});
3140: foreach my $item (keys(%javafiles)) {
3141: if ($name eq $item) {
3142: $javafiles{$item} = $attr->{'value'};
3143: last;
3144: }
3145: }
1.1164 raeburn 3146: my $pathfrom;
1.640 albertel 3147: foreach my $item (keys(%mediafiles)) {
3148: if ($name eq $item) {
1.1164 raeburn 3149: $pathfrom = $attr->{'value'};
3150: $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
3151: &add_filetype($allfiles,$pathfrom,$name);
1.640 albertel 3152: last;
3153: }
3154: }
1.1164 raeburn 3155: if ($name eq 'flashvars') {
3156: $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
3157: }
3158: if ($pathfrom ne '') {
3159: &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
3160: $pathfrom);
3161: }
1.640 albertel 3162: }
3163: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
3164: foreach my $item (keys(%javafiles)) {
3165: if ($attr->{$item}) {
3166: $javafiles{$item} = $attr->{$item};
3167: last;
3168: }
3169: }
3170: foreach my $item (keys(%mediafiles)) {
3171: if ($attr->{$item}) {
3172: &add_filetype($allfiles,$attr->{$item},$item);
3173: last;
3174: }
3175: }
1.1164 raeburn 3176: if (lc($tagname) eq 'embed') {
3177: if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
3178: &embedded_dependency($allfiles,\%related,$attr->{'name'},
3179: $attr->{'src'});
3180: }
3181: }
1.640 albertel 3182: }
1.1164 raeburn 3183: if ($t->[4] =~ m{/>$}) {
3184: pop(@state);
3185: }
1.640 albertel 3186: } elsif ($t->[0] eq 'E') {
3187: my ($tagname) = ($t->[1]);
3188: if ($javafiles{'codebase'} ne '') {
3189: $javafiles{'codebase'} .= '/';
3190: }
3191: if (lc($tagname) eq 'applet' ||
3192: lc($tagname) eq 'object' ||
3193: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
3194: ) {
3195: foreach my $item (keys(%javafiles)) {
3196: if ($item ne 'codebase' && $javafiles{$item} ne '') {
3197: my $file=$javafiles{'codebase'}.$javafiles{$item};
3198: &add_filetype($allfiles,$file,$item);
3199: }
3200: }
3201: }
3202: pop @state;
3203: }
3204: }
1.1164 raeburn 3205: foreach my $id (sort(keys(%flashvars))) {
3206: if ($shockwave{$id} ne '') {
3207: my @pairs = split(/\&/,$flashvars{$id});
3208: foreach my $pair (@pairs) {
3209: my ($key,$value) = split(/\=/,$pair);
3210: if ($key eq 'thumb') {
3211: &add_filetype($allfiles,$value,$key);
3212: } elsif ($key eq 'content') {
3213: my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
3214: my ($ext) = ($value =~ /\.([^.]+)$/);
3215: if ($ext ne '') {
3216: &add_filetype($allfiles,$path.$value,$ext);
3217: }
3218: }
3219: }
3220: }
3221: }
1.637 raeburn 3222: return 'ok';
3223: }
3224:
1.639 albertel 3225: sub add_filetype {
3226: my ($allfiles,$file,$type)=@_;
3227: if (exists($allfiles->{$file})) {
3228: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
3229: push(@{$allfiles->{$file}}, &escape($type));
3230: }
3231: } else {
3232: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 3233: }
3234: }
3235:
1.1164 raeburn 3236: sub embedded_dependency {
3237: my ($allfiles,$related,$identifier,$pathfrom) = @_;
3238: if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
3239: if (($identifier ne '') &&
3240: (ref($related->{$identifier}) eq 'ARRAY') &&
3241: ($pathfrom ne '')) {
3242: my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
3243: foreach my $dep (@{$related->{$identifier}}) {
3244: &add_filetype($allfiles,$path.$dep,'object');
3245: }
3246: }
3247: }
3248: return;
3249: }
3250:
1.493 albertel 3251: sub removeuploadedurl {
1.984 neumanie 3252: my ($url)=@_;
3253: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 3254: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 3255: }
3256:
3257: sub removeuserfile {
3258: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 3259: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3260: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 3261: if ($result eq 'ok') {
1.798 raeburn 3262: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
3263: my $metafile = $fname.'.meta';
3264: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 3265: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 3266: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3267: my $sqlresult =
1.823 albertel 3268: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3269: 'portfolio_metadata',$group,
3270: 'delete');
1.798 raeburn 3271: }
3272: }
3273: return $result;
1.257 www 3274: }
1.15 www 3275:
1.530 albertel 3276: sub mkdiruserfile {
3277: my ($docuname,$docudom,$dir)=@_;
3278: my $home=&homeserver($docuname,$docudom);
3279: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
3280: }
3281:
1.531 albertel 3282: sub renameuserfile {
3283: my ($docuname,$docudom,$old,$new)=@_;
3284: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3285: my $result = &reply("renameuserfile:$docudom:$docuname:".
3286: &escape("$old").':'.&escape("$new"),$home);
3287: if ($result eq 'ok') {
3288: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
3289: my $oldmeta = $old.'.meta';
3290: my $newmeta = $new.'.meta';
3291: my $metaresult =
3292: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 3293: my $url = "/uploaded/$docudom/$docuname/$old";
3294: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3295: my $sqlresult =
1.823 albertel 3296: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3297: 'portfolio_metadata',$group,
3298: 'delete');
1.798 raeburn 3299: }
3300: }
3301: return $result;
1.531 albertel 3302: }
3303:
1.14 www 3304: # ------------------------------------------------------------------------- Log
3305:
3306: sub log {
3307: my ($dom,$nam,$hom,$what)=@_;
1.47 www 3308: return critical("log:$dom:$nam:$what",$hom);
1.157 www 3309: }
3310:
3311: # ------------------------------------------------------------------ Course Log
1.352 www 3312: #
3313: # This routine flushes several buffers of non-mission-critical nature
3314: #
1.157 www 3315:
3316: sub flushcourselogs {
1.352 www 3317: &logthis('Flushing log buffers');
3318: #
3319: # course logs
3320: # This is a log of all transactions in a course, which can be used
3321: # for data mining purposes
3322: #
3323: # It also collects the courseid database, which lists last transaction
3324: # times and course titles for all courseids
3325: #
3326: my %courseidbuffer=();
1.921 raeburn 3327: foreach my $crsid (keys(%courselogs)) {
1.352 www 3328: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 3329: &escape($courselogs{$crsid}),
3330: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 3331: delete $courselogs{$crsid};
3332: } else {
3333: &logthis('Failed to flush log buffer for '.$crsid);
3334: if (length($courselogs{$crsid})>40000) {
1.672 albertel 3335: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 3336: " exceeded maximum size, deleting.</font>");
3337: delete $courselogs{$crsid};
3338: }
1.352 www 3339: }
1.920 raeburn 3340: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 3341: 'description' => $coursedescrbuf{$crsid},
3342: 'inst_code' => $courseinstcodebuf{$crsid},
3343: 'type' => $coursetypebuf{$crsid},
3344: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 3345: };
1.191 harris41 3346: }
1.352 www 3347: #
3348: # Write course id database (reverse lookup) to homeserver of courses
3349: # Is used in pickcourse
3350: #
1.840 albertel 3351: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 3352: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 3353: $courseidbuffer{$crs_home},
3354: $crs_home,'timeonly');
1.352 www 3355: }
3356: #
3357: # File accesses
3358: # Writes to the dynamic metadata of resources to get hit counts, etc.
3359: #
1.449 matthew 3360: foreach my $entry (keys(%accesshash)) {
1.458 matthew 3361: if ($entry =~ /___count$/) {
3362: my ($dom,$name);
1.807 albertel 3363: ($dom,$name,undef)=
1.811 albertel 3364: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 3365: if (! defined($dom) || $dom eq '' ||
3366: ! defined($name) || $name eq '') {
1.620 albertel 3367: my $cid = $env{'request.course.id'};
3368: $dom = $env{'request.'.$cid.'.domain'};
3369: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 3370: }
1.450 matthew 3371: my $value = $accesshash{$entry};
3372: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
3373: my %temphash=($url => $value);
1.449 matthew 3374: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
3375: if ($result eq 'ok') {
3376: delete $accesshash{$entry};
3377: }
3378: } else {
1.811 albertel 3379: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159 www 3380: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450 matthew 3381: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 3382: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
3383: delete $accesshash{$entry};
3384: }
1.185 www 3385: }
1.191 harris41 3386: }
1.352 www 3387: #
3388: # Roles
3389: # Reverse lookup of user roles for course faculty/staff and co-authorship
3390: #
1.800 albertel 3391: foreach my $entry (keys(%userrolehash)) {
1.351 www 3392: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 3393: split(/\:/,$entry);
3394: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 3395: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 3396: $rudom,$runame) eq 'ok') {
3397: delete $userrolehash{$entry};
3398: }
3399: }
1.662 raeburn 3400: #
3401: # Reverse lookup of domain roles (dc, ad, li, sc, au)
3402: #
3403: my %domrolebuffer = ();
1.1000 raeburn 3404: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 3405: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 3406: if ($domrolebuffer{$rudom}) {
3407: $domrolebuffer{$rudom}.='&'.&escape($entry).
3408: '='.&escape($domainrolehash{$entry});
3409: } else {
3410: $domrolebuffer{$rudom}.=&escape($entry).
3411: '='.&escape($domainrolehash{$entry});
3412: }
3413: delete $domainrolehash{$entry};
3414: }
3415: foreach my $dom (keys(%domrolebuffer)) {
1.841 albertel 3416: my %servers = &get_servers($dom,'library');
3417: foreach my $tryserver (keys(%servers)) {
3418: unless (&reply('domroleput:'.$dom.':'.
3419: $domrolebuffer{$dom},$tryserver) eq 'ok') {
3420: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
3421: }
1.662 raeburn 3422: }
3423: }
1.186 www 3424: $dumpcount++;
1.157 www 3425: }
3426:
3427: sub courselog {
3428: my $what=shift;
1.158 www 3429: $what=time.':'.$what;
1.620 albertel 3430: unless ($env{'request.course.id'}) { return ''; }
3431: $coursedombuf{$env{'request.course.id'}}=
3432: $env{'course.'.$env{'request.course.id'}.'.domain'};
3433: $coursenumbuf{$env{'request.course.id'}}=
3434: $env{'course.'.$env{'request.course.id'}.'.num'};
3435: $coursehombuf{$env{'request.course.id'}}=
3436: $env{'course.'.$env{'request.course.id'}.'.home'};
3437: $coursedescrbuf{$env{'request.course.id'}}=
3438: $env{'course.'.$env{'request.course.id'}.'.description'};
3439: $courseinstcodebuf{$env{'request.course.id'}}=
3440: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
3441: $courseownerbuf{$env{'request.course.id'}}=
3442: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 3443: $coursetypebuf{$env{'request.course.id'}}=
3444: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 3445: if (defined $courselogs{$env{'request.course.id'}}) {
3446: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 3447: } else {
1.620 albertel 3448: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 3449: }
1.620 albertel 3450: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 3451: &flushcourselogs();
3452: }
1.158 www 3453: }
3454:
3455: sub courseacclog {
3456: my $fnsymb=shift;
1.620 albertel 3457: unless ($env{'request.course.id'}) { return ''; }
3458: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144 www 3459: if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187 www 3460: $what.=':POST';
1.583 matthew 3461: # FIXME: Probably ought to escape things....
1.800 albertel 3462: foreach my $key (keys(%env)) {
3463: if ($key=~/^form\.(.*)/) {
1.975 raeburn 3464: my $formitem = $1;
3465: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
3466: $what.=':'.$formitem.'='.$env{$key};
3467: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
3468: $what.=':'.$formitem.'='.$env{$key};
3469: }
1.158 www 3470: }
1.191 harris41 3471: }
1.583 matthew 3472: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
3473: # FIXME: We should not be depending on a form parameter that someone
3474: # editing lonsearchcat.pm might change in the future.
1.620 albertel 3475: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 3476: $what.= ':POST';
3477: # FIXME: Probably ought to escape things....
3478: foreach my $element ('courseexp','crsfulltext','crsrelated',
3479: 'crsdiscuss') {
1.620 albertel 3480: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 3481: }
3482: }
1.158 www 3483: }
3484: &courselog($what);
1.149 www 3485: }
3486:
1.185 www 3487: sub countacc {
3488: my $url=&declutter(shift);
1.458 matthew 3489: return if (! defined($url) || $url eq '');
1.620 albertel 3490: unless ($env{'request.course.id'}) { return ''; }
1.1158 www 3491: #
3492: # Mark that this url was used in this course
3493: #
1.620 albertel 3494: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158 www 3495: #
3496: # Increase the access count for this resource in this child process
3497: #
1.281 www 3498: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 3499: $accesshash{$key}++;
1.185 www 3500: }
1.349 www 3501:
1.361 www 3502: sub linklog {
3503: my ($from,$to)=@_;
3504: $from=&declutter($from);
3505: $to=&declutter($to);
3506: $accesshash{$from.'___'.$to.'___comefrom'}=1;
3507: $accesshash{$to.'___'.$from.'___goto'}=1;
3508: }
1.1160 www 3509:
3510: sub statslog {
3511: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
3512: if ($users<2) { return; }
3513: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
3514: 'course' => $env{'request.course.id'},
3515: 'sections' => '"all"',
3516: 'num_students' => $users,
3517: 'part' => $part,
3518: 'symb' => $symb,
3519: 'mean_tries' => $av_attempts,
3520: 'deg_of_diff' => $degdiff});
3521: foreach my $key (keys(%dynstore)) {
3522: $accesshash{$key}=$dynstore{$key};
3523: }
3524: }
1.361 www 3525:
1.349 www 3526: sub userrolelog {
3527: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169 droeschl 3528: if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350 www 3529: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3530: $userrolehash
3531: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 3532: =$tend.':'.$tstart;
1.662 raeburn 3533: }
1.1169 droeschl 3534: if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898 albertel 3535: $userrolehash
3536: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
3537: =$tend.':'.$tstart;
3538: }
1.1169 droeschl 3539: if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
1.662 raeburn 3540: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3541: $domainrolehash
3542: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
3543: = $tend.':'.$tstart;
3544: }
1.351 www 3545: }
3546:
1.957 raeburn 3547: sub courserolelog {
3548: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9 raeburn 3549: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
3550: my $cdom = $1;
3551: my $cnum = $2;
3552: my $sec = $3;
3553: my $namespace = 'rolelog';
3554: my %storehash = (
3555: role => $trole,
3556: start => $tstart,
3557: end => $tend,
3558: selfenroll => $selfenroll,
3559: context => $context,
3560: );
3561: if ($trole eq 'gr') {
3562: $namespace = 'groupslog';
3563: $storehash{'group'} = $sec;
3564: } else {
3565: $storehash{'section'} = $sec;
3566: }
3567: &write_log('course',$namespace,\%storehash,$delflag,$username,
3568: $domain,$cnum,$cdom);
3569: if (($trole ne 'st') || ($sec ne '')) {
3570: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957 raeburn 3571: }
3572: }
3573: return;
3574: }
3575:
1.1172.2.9 raeburn 3576: sub domainrolelog {
3577: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
3578: if ($area =~ m{^/($match_domain)/$}) {
3579: my $cdom = $1;
3580: my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
3581: my $namespace = 'rolelog';
3582: my %storehash = (
3583: role => $trole,
3584: start => $tstart,
3585: end => $tend,
3586: context => $context,
3587: );
3588: &write_log('domain',$namespace,\%storehash,$delflag,$username,
3589: $domain,$domconfiguser,$cdom);
3590: }
3591: return;
3592:
3593: }
3594:
3595: sub coauthorrolelog {
3596: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
3597: if ($area =~ m{^/($match_domain)/($match_username)$}) {
3598: my $audom = $1;
3599: my $auname = $2;
3600: my $namespace = 'rolelog';
3601: my %storehash = (
3602: role => $trole,
3603: start => $tstart,
3604: end => $tend,
3605: context => $context,
3606: );
3607: &write_log('author',$namespace,\%storehash,$delflag,$username,
3608: $domain,$auname,$audom);
3609: }
3610: return;
3611: }
3612:
1.351 www 3613: sub get_course_adv_roles {
1.948 raeburn 3614: my ($cid,$codes) = @_;
1.620 albertel 3615: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 3616: my %coursehash=&coursedescription($cid);
1.988 raeburn 3617: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 3618: my %nothide=();
1.800 albertel 3619: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 3620: if ($user !~ /:/) {
3621: $nothide{join(':',split(/[\@]/,$user))}=1;
3622: } else {
3623: $nothide{$user}=1;
3624: }
1.470 www 3625: }
1.351 www 3626: my %returnhash=();
3627: my %dumphash=
3628: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
3629: my $now=time;
1.997 raeburn 3630: my %privileged;
1.1000 raeburn 3631: foreach my $entry (keys(%dumphash)) {
1.800 albertel 3632: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 3633: if (($tstart) && ($tstart<0)) { next; }
3634: if (($tend) && ($tend<$now)) { next; }
3635: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 3636: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 3637: if ($username eq '' || $domain eq '') { next; }
1.997 raeburn 3638: unless (ref($privileged{$domain}) eq 'HASH') {
3639: my %dompersonnel =
1.998 raeburn 3640: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
1.997 raeburn 3641: $privileged{$domain} = {};
3642: foreach my $server (keys(%dompersonnel)) {
1.999 raeburn 3643: if (ref($dompersonnel{$server}) eq 'HASH') {
1.997 raeburn 3644: foreach my $user (keys(%{$dompersonnel{$server}})) {
3645: my ($trole,$uname,$udom) = split(/:/,$user);
3646: $privileged{$udom}{$uname} = 1;
3647: }
3648: }
3649: }
3650: }
3651: if ((exists($privileged{$domain}{$username})) &&
3652: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 3653: if ($role eq 'cr') { next; }
1.948 raeburn 3654: if ($codes) {
3655: if ($section) { $role .= ':'.$section; }
3656: if ($returnhash{$role}) {
3657: $returnhash{$role}.=','.$username.':'.$domain;
3658: } else {
3659: $returnhash{$role}=$username.':'.$domain;
3660: }
1.351 www 3661: } else {
1.988 raeburn 3662: my $key=&plaintext($role,$crstype);
1.973 bisitz 3663: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 3664: if ($returnhash{$key}) {
3665: $returnhash{$key}.=','.$username.':'.$domain;
3666: } else {
3667: $returnhash{$key}=$username.':'.$domain;
3668: }
1.351 www 3669: }
1.948 raeburn 3670: }
1.400 www 3671: return %returnhash;
3672: }
3673:
3674: sub get_my_roles {
1.937 raeburn 3675: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 3676: unless (defined($uname)) { $uname=$env{'user.name'}; }
3677: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 3678: my (%dumphash,%nothide);
1.1086 raeburn 3679: if ($context eq 'userroles') {
1.1166 raeburn 3680: %dumphash = &dump('roles',$udom,$uname);
1.858 raeburn 3681: } else {
3682: %dumphash=
1.400 www 3683: &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 3684: if ($hidepriv) {
3685: my %coursehash=&coursedescription($udom.'_'.$uname);
3686: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3687: if ($user !~ /:/) {
3688: $nothide{join(':',split(/[\@]/,$user))} = 1;
3689: } else {
3690: $nothide{$user} = 1;
3691: }
3692: }
3693: }
1.858 raeburn 3694: }
1.400 www 3695: my %returnhash=();
3696: my $now=time;
1.999 raeburn 3697: my %privileged;
1.800 albertel 3698: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 3699: my ($role,$tend,$tstart);
3700: if ($context eq 'userroles') {
1.1149 raeburn 3701: next if ($entry =~ /^rolesdef/);
1.867 raeburn 3702: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
3703: } else {
3704: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
3705: }
1.400 www 3706: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 3707: my $status = 'active';
1.939 raeburn 3708: if (($tend) && ($tend<=$now)) {
1.832 raeburn 3709: $status = 'previous';
3710: }
3711: if (($tstart) && ($now<$tstart)) {
3712: $status = 'future';
3713: }
3714: if (ref($types) eq 'ARRAY') {
3715: if (!grep(/^\Q$status\E$/,@{$types})) {
3716: next;
3717: }
3718: } else {
3719: if ($status ne 'active') {
3720: next;
3721: }
3722: }
1.867 raeburn 3723: my ($rolecode,$username,$domain,$section,$area);
3724: if ($context eq 'userroles') {
1.1172.2.9 raeburn 3725: ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867 raeburn 3726: (undef,$domain,$username,$section) = split(/\//,$area);
3727: } else {
3728: ($role,$username,$domain,$section) = split(/\:/,$entry);
3729: }
1.832 raeburn 3730: if (ref($roledoms) eq 'ARRAY') {
3731: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
3732: next;
3733: }
3734: }
3735: if (ref($roles) eq 'ARRAY') {
3736: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 3737: if ($role =~ /^cr\//) {
3738: if (!grep(/^cr$/,@{$roles})) {
3739: next;
3740: }
1.1104 raeburn 3741: } elsif ($role =~ /^gr\//) {
3742: if (!grep(/^gr$/,@{$roles})) {
3743: next;
3744: }
1.922 raeburn 3745: } else {
3746: next;
3747: }
1.832 raeburn 3748: }
1.867 raeburn 3749: }
1.937 raeburn 3750: if ($hidepriv) {
1.999 raeburn 3751: if ($context eq 'userroles') {
3752: if ((&privileged($username,$domain)) &&
3753: (!$nothide{$username.':'.$domain})) {
3754: next;
3755: }
3756: } else {
3757: unless (ref($privileged{$domain}) eq 'HASH') {
3758: my %dompersonnel =
3759: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
3760: $privileged{$domain} = {};
3761: if (keys(%dompersonnel)) {
3762: foreach my $server (keys(%dompersonnel)) {
3763: if (ref($dompersonnel{$server}) eq 'HASH') {
3764: foreach my $user (keys(%{$dompersonnel{$server}})) {
3765: my ($trole,$uname,$udom) = split(/:/,$user);
3766: $privileged{$udom}{$uname} = $trole;
3767: }
3768: }
3769: }
3770: }
3771: }
3772: if (exists($privileged{$domain}{$username})) {
3773: if (!$nothide{$username.':'.$domain}) {
3774: next;
3775: }
3776: }
1.937 raeburn 3777: }
3778: }
1.933 raeburn 3779: if ($withsec) {
3780: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
3781: $tstart.':'.$tend;
3782: } else {
3783: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
3784: }
1.832 raeburn 3785: }
1.373 www 3786: return %returnhash;
1.399 www 3787: }
3788:
3789: # ----------------------------------------------------- Frontpage Announcements
3790: #
3791: #
3792:
3793: sub postannounce {
3794: my ($server,$text)=@_;
1.844 albertel 3795: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 3796: unless ($text=~/\w/) { $text=''; }
3797: return &reply('setannounce:'.&escape($text),$server);
3798: }
3799:
3800: sub getannounce {
1.448 albertel 3801:
3802: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 3803: my $announcement='';
1.800 albertel 3804: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 3805: close($fh);
1.399 www 3806: if ($announcement=~/\w/) {
3807: return
3808: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 3809: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 3810: } else {
3811: return '';
3812: }
3813: } else {
3814: return '';
3815: }
1.351 www 3816: }
1.353 www 3817:
3818: # ---------------------------------------------------------- Course ID routines
3819: # Deal with domain's nohist_courseid.db files
3820: #
3821:
3822: sub courseidput {
1.921 raeburn 3823: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 3824: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 3825: my $outcome;
3826: if ($caller eq 'timeonly') {
3827: my $cids = '';
3828: foreach my $item (keys(%$storehash)) {
3829: $cids.=&escape($item).'&';
3830: }
3831: $cids=~s/\&$//;
3832: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
3833: $coursehome);
3834: } else {
3835: my $items = '';
3836: foreach my $item (keys(%$storehash)) {
3837: $items.= &escape($item).'='.
3838: &freeze_escape($$storehash{$item}).'&';
3839: }
3840: $items=~s/\&$//;
3841: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
3842: $coursehome);
1.918 raeburn 3843: }
3844: if ($outcome eq 'unknown_cmd') {
3845: my $what;
3846: foreach my $cid (keys(%$storehash)) {
3847: $what .= &escape($cid).'=';
1.921 raeburn 3848: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 3849: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 3850: }
3851: $what =~ s/\:$/&/;
3852: }
3853: $what =~ s/\&$//;
3854: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
3855: } else {
3856: return $outcome;
3857: }
1.353 www 3858: }
3859:
3860: sub courseiddump {
1.921 raeburn 3861: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 3862: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 3863: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1071 raeburn 3864: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918 raeburn 3865: my $as_hash = 1;
3866: my %returnhash;
3867: if (!$domfilter) { $domfilter=''; }
1.845 albertel 3868: my %libserv = &all_library();
3869: foreach my $tryserver (keys(%libserv)) {
3870: if ( ( $hostidflag == 1
3871: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
3872: || (!defined($hostidflag)) ) {
3873:
1.918 raeburn 3874: if (($domfilter eq '') ||
3875: (&host_domain($tryserver) eq $domfilter)) {
3876: my $rep =
3877: &reply('courseiddump:'.&host_domain($tryserver).':'.
3878: $sincefilter.':'.&escape($descfilter).':'.
3879: &escape($instcodefilter).':'.&escape($ownerfilter).
3880: ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947 raeburn 3881: ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962 raeburn 3882: &escape($selfenrollonly).':'.&escape($catfilter).':'.
1.1008 raeburn 3883: $showhidden.':'.$caller.':'.&escape($cloner).':'.
1.1029 raeburn 3884: &escape($cc_clone).':'.$cloneonly.':'.
3885: &escape($createdbefore).':'.&escape($createdafter).':'.
1.1071 raeburn 3886: &escape($creationcontext).':'.$domcloner,
3887: $tryserver);
1.918 raeburn 3888: my @pairs=split(/\&/,$rep);
3889: foreach my $item (@pairs) {
3890: my ($key,$value)=split(/\=/,$item,2);
3891: $key = &unescape($key);
3892: next if ($key =~ /^error: 2 /);
3893: my $result = &thaw_unescape($value);
3894: if (ref($result) eq 'HASH') {
3895: $returnhash{$key}=$result;
3896: } else {
1.921 raeburn 3897: my @responses = split(/:/,$value);
3898: my @items = ('description','inst_code','owner','type');
1.918 raeburn 3899: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 3900: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 3901: }
1.1008 raeburn 3902: }
1.353 www 3903: }
3904: }
3905: }
3906: }
3907: return %returnhash;
3908: }
3909:
1.1055 raeburn 3910: sub courselastaccess {
3911: my ($cdom,$cnum,$hostidref) = @_;
3912: my %returnhash;
3913: if ($cdom && $cnum) {
3914: my $chome = &homeserver($cnum,$cdom);
3915: if ($chome ne 'no_host') {
3916: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
3917: &extract_lastaccess(\%returnhash,$rep);
3918: }
3919: } else {
3920: if (!$cdom) { $cdom=''; }
3921: my %libserv = &all_library();
3922: foreach my $tryserver (keys(%libserv)) {
3923: if (ref($hostidref) eq 'ARRAY') {
3924: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
3925: }
3926: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
3927: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
3928: &extract_lastaccess(\%returnhash,$rep);
3929: }
3930: }
3931: }
3932: return %returnhash;
3933: }
3934:
3935: sub extract_lastaccess {
3936: my ($returnhash,$rep) = @_;
3937: if (ref($returnhash) eq 'HASH') {
3938: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
3939: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
3940: $rep eq '') {
3941: my @pairs=split(/\&/,$rep);
3942: foreach my $item (@pairs) {
3943: my ($key,$value)=split(/\=/,$item,2);
3944: $key = &unescape($key);
3945: next if ($key =~ /^error: 2 /);
3946: $returnhash->{$key} = &thaw_unescape($value);
3947: }
3948: }
3949: }
3950: return;
3951: }
3952:
1.658 raeburn 3953: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 3954:
3955: sub dcmailput {
1.685 raeburn 3956: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 3957: my $status = &Apache::lonnet::critical(
1.740 www 3958: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
3959: &escape($message),$server);
1.662 raeburn 3960: return $status;
3961: }
3962:
1.658 raeburn 3963: sub dcmaildump {
3964: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 3965: my %returnhash=();
1.846 albertel 3966:
3967: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 3968: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
3969: &escape($enddate).':';
3970: my @esc_senders=map { &escape($_)} @$senders;
3971: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 3972: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 3973: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 3974: if (($key) && ($value)) {
3975: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 3976: }
3977: }
3978: }
3979: return %returnhash;
3980: }
1.662 raeburn 3981: # ---------------------------------------------------------- Domain roles
3982:
3983: sub get_domain_roles {
3984: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 3985: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 3986: $startdate = '.';
3987: }
1.1018 raeburn 3988: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 3989: $enddate = '.';
3990: }
1.922 raeburn 3991: my $rolelist;
3992: if (ref($roles) eq 'ARRAY') {
3993: $rolelist = join(':',@{$roles});
3994: }
1.662 raeburn 3995: my %personnel = ();
1.841 albertel 3996:
3997: my %servers = &get_servers($dom,'library');
3998: foreach my $tryserver (keys(%servers)) {
3999: %{$personnel{$tryserver}}=();
4000: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
4001: &escape($startdate).':'.
4002: &escape($enddate).':'.
4003: &escape($rolelist), $tryserver))) {
4004: my ($key,$value) = split(/\=/,$line,2);
4005: if (($key) && ($value)) {
4006: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
4007: }
4008: }
1.662 raeburn 4009: }
4010: return %personnel;
4011: }
1.658 raeburn 4012:
1.1057 www 4013: # ----------------------------------------------------------- Interval timing
1.149 www 4014:
1.1153 www 4015: {
4016: # Caches needed for speedup of navmaps
4017: # We don't want to cache this for very long at all (5 seconds at most)
4018: #
4019: # The user for whom we cache
4020: my $cachedkey='';
4021: # The cached times for this user
4022: my %cachedtimes=();
4023: # When this was last done
4024: my $cachedtime=();
4025:
4026: sub load_all_first_access {
1.1154 raeburn 4027: my ($uname,$udom)=@_;
1.1156 www 4028: if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.2 raeburn 4029: (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154 raeburn 4030: return;
4031: }
4032: $cachedtime=time;
4033: $cachedkey=$uname.':'.$udom;
4034: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153 www 4035: }
4036:
1.504 albertel 4037: sub get_first_access {
1.1162 raeburn 4038: my ($type,$argsymb,$argmap)=@_;
1.790 albertel 4039: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4040: if ($argsymb) { $symb=$argsymb; }
4041: my ($map,$id,$res)=&decode_symb($symb);
1.1162 raeburn 4042: if ($argmap) { $map = $argmap; }
1.926 albertel 4043: if ($type eq 'course') {
4044: $res='course';
4045: } elsif ($type eq 'map') {
1.588 albertel 4046: $res=&symbread($map);
4047: } else {
4048: $res=$symb;
4049: }
1.1153 www 4050: &load_all_first_access($uname,$udom);
4051: return $cachedtimes{"$courseid\0$res"};
1.504 albertel 4052: }
4053:
4054: sub set_first_access {
1.1162 raeburn 4055: my ($type,$interval)=@_;
1.790 albertel 4056: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4057: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 4058: if ($type eq 'course') {
4059: $res='course';
4060: } elsif ($type eq 'map') {
1.588 albertel 4061: $res=&symbread($map);
4062: } else {
4063: $res=$symb;
4064: }
1.1153 www 4065: $cachedkey='';
1.1162 raeburn 4066: my $firstaccess=&get_first_access($type,$symb,$map);
1.505 albertel 4067: if (!$firstaccess) {
1.1162 raeburn 4068: my $start = time;
4069: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
4070: $udom,$uname);
4071: if ($putres eq 'ok') {
4072: &put('timerinterval',{"$courseid\0$res"=>$interval},
4073: $udom,$uname);
4074: &appenv(
4075: {
4076: 'course.'.$courseid.'.firstaccess.'.$res => $start,
4077: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
4078: }
4079: );
4080: }
4081: return $putres;
1.505 albertel 4082: }
4083: return 'already_set';
1.504 albertel 4084: }
1.1153 www 4085: }
1.110 www 4086: # --------------------------------------------- Set Expire Date for Spreadsheet
4087:
4088: sub expirespread {
4089: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 4090: my $cid=$env{'request.course.id'};
1.110 www 4091: if ($cid) {
4092: my $now=time;
4093: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 4094: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
4095: $env{'course.'.$cid.'.num'}.
1.110 www 4096: ':nohist_expirationdates:'.
4097: &escape($key).'='.$now,
1.620 albertel 4098: $env{'course.'.$cid.'.home'})
1.110 www 4099: }
4100: return 'ok';
1.14 www 4101: }
4102:
1.109 www 4103: # ----------------------------------------------------- Devalidate Spreadsheets
4104:
4105: sub devalidate {
1.325 www 4106: my ($symb,$uname,$udom)=@_;
1.620 albertel 4107: my $cid=$env{'request.course.id'};
1.109 www 4108: if ($cid) {
1.391 matthew 4109: # delete the stored spreadsheets for
4110: # - the student level sheet of this user in course's homespace
4111: # - the assessment level sheet for this resource
4112: # for this user in user's homespace
1.553 albertel 4113: # - current conditional state info
1.325 www 4114: my $key=$uname.':'.$udom.':';
1.109 www 4115: my $status=
1.299 matthew 4116: &del('nohist_calculatedsheets',
1.391 matthew 4117: [$key.'studentcalc:'],
1.620 albertel 4118: $env{'course.'.$cid.'.domain'},
4119: $env{'course.'.$cid.'.num'})
1.133 albertel 4120: .' '.
4121: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 4122: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 4123: unless ($status eq 'ok ok') {
4124: &logthis('Could not devalidate spreadsheet '.
1.325 www 4125: $uname.' at '.$udom.' for '.
1.109 www 4126: $symb.': '.$status);
1.133 albertel 4127: }
1.553 albertel 4128: &delenv('user.state.'.$cid);
1.109 www 4129: }
4130: }
4131:
1.265 albertel 4132: sub get_scalar {
4133: my ($string,$end) = @_;
4134: my $value;
4135: if ($$string =~ s/^([^&]*?)($end)/$2/) {
4136: $value = $1;
4137: } elsif ($$string =~ s/^([^&]*?)&//) {
4138: $value = $1;
4139: }
4140: return &unescape($value);
4141: }
4142:
4143: sub array2str {
4144: my (@array) = @_;
4145: my $result=&arrayref2str(\@array);
4146: $result=~s/^__ARRAY_REF__//;
4147: $result=~s/__END_ARRAY_REF__$//;
4148: return $result;
4149: }
4150:
1.204 albertel 4151: sub arrayref2str {
4152: my ($arrayref) = @_;
1.265 albertel 4153: my $result='__ARRAY_REF__';
1.204 albertel 4154: foreach my $elem (@$arrayref) {
1.265 albertel 4155: if(ref($elem) eq 'ARRAY') {
4156: $result.=&arrayref2str($elem).'&';
4157: } elsif(ref($elem) eq 'HASH') {
4158: $result.=&hashref2str($elem).'&';
4159: } elsif(ref($elem)) {
4160: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 4161: } else {
4162: $result.=&escape($elem).'&';
4163: }
4164: }
4165: $result=~s/\&$//;
1.265 albertel 4166: $result .= '__END_ARRAY_REF__';
1.204 albertel 4167: return $result;
4168: }
4169:
1.168 albertel 4170: sub hash2str {
1.204 albertel 4171: my (%hash) = @_;
4172: my $result=&hashref2str(\%hash);
1.265 albertel 4173: $result=~s/^__HASH_REF__//;
4174: $result=~s/__END_HASH_REF__$//;
1.204 albertel 4175: return $result;
4176: }
4177:
4178: sub hashref2str {
4179: my ($hashref)=@_;
1.265 albertel 4180: my $result='__HASH_REF__';
1.800 albertel 4181: foreach my $key (sort(keys(%$hashref))) {
4182: if (ref($key) eq 'ARRAY') {
4183: $result.=&arrayref2str($key).'=';
4184: } elsif (ref($key) eq 'HASH') {
4185: $result.=&hashref2str($key).'=';
4186: } elsif (ref($key)) {
1.265 albertel 4187: $result.='=';
1.800 albertel 4188: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 4189: } else {
1.1132 raeburn 4190: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 4191: }
4192:
1.800 albertel 4193: if(ref($hashref->{$key}) eq 'ARRAY') {
4194: $result.=&arrayref2str($hashref->{$key}).'&';
4195: } elsif(ref($hashref->{$key}) eq 'HASH') {
4196: $result.=&hashref2str($hashref->{$key}).'&';
4197: } elsif(ref($hashref->{$key})) {
1.265 albertel 4198: $result.='&';
1.800 albertel 4199: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 4200: } else {
1.800 albertel 4201: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 4202: }
4203: }
1.168 albertel 4204: $result=~s/\&$//;
1.265 albertel 4205: $result .= '__END_HASH_REF__';
1.168 albertel 4206: return $result;
4207: }
4208:
4209: sub str2hash {
1.265 albertel 4210: my ($string)=@_;
4211: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
4212: return %$hash;
4213: }
4214:
4215: sub str2hashref {
1.168 albertel 4216: my ($string) = @_;
1.265 albertel 4217:
4218: my %hash;
4219:
4220: if($string !~ /^__HASH_REF__/) {
4221: if (! ($string eq '' || !defined($string))) {
4222: $hash{'error'}='Not hash reference';
4223: }
4224: return (\%hash, $string);
4225: }
4226:
4227: $string =~ s/^__HASH_REF__//;
4228:
4229: while($string !~ /^__END_HASH_REF__/) {
4230: #key
4231: my $key='';
4232: if($string =~ /^__HASH_REF__/) {
4233: ($key, $string)=&str2hashref($string);
4234: if(defined($key->{'error'})) {
4235: $hash{'error'}='Bad data';
4236: return (\%hash, $string);
4237: }
4238: } elsif($string =~ /^__ARRAY_REF__/) {
4239: ($key, $string)=&str2arrayref($string);
4240: if($key->[0] eq 'Array reference error') {
4241: $hash{'error'}='Bad data';
4242: return (\%hash, $string);
4243: }
4244: } else {
4245: $string =~ s/^(.*?)=//;
1.267 albertel 4246: $key=&unescape($1);
1.265 albertel 4247: }
4248: $string =~ s/^=//;
4249:
4250: #value
4251: my $value='';
4252: if($string =~ /^__HASH_REF__/) {
4253: ($value, $string)=&str2hashref($string);
4254: if(defined($value->{'error'})) {
4255: $hash{'error'}='Bad data';
4256: return (\%hash, $string);
4257: }
4258: } elsif($string =~ /^__ARRAY_REF__/) {
4259: ($value, $string)=&str2arrayref($string);
4260: if($value->[0] eq 'Array reference error') {
4261: $hash{'error'}='Bad data';
4262: return (\%hash, $string);
4263: }
4264: } else {
4265: $value=&get_scalar(\$string,'__END_HASH_REF__');
4266: }
4267: $string =~ s/^&//;
4268:
4269: $hash{$key}=$value;
1.204 albertel 4270: }
1.265 albertel 4271:
4272: $string =~ s/^__END_HASH_REF__//;
4273:
4274: return (\%hash, $string);
1.204 albertel 4275: }
4276:
4277: sub str2array {
1.265 albertel 4278: my ($string)=@_;
4279: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
4280: return @$array;
4281: }
4282:
4283: sub str2arrayref {
1.204 albertel 4284: my ($string) = @_;
1.265 albertel 4285: my @array;
4286:
4287: if($string !~ /^__ARRAY_REF__/) {
4288: if (! ($string eq '' || !defined($string))) {
4289: $array[0]='Array reference error';
4290: }
4291: return (\@array, $string);
4292: }
4293:
4294: $string =~ s/^__ARRAY_REF__//;
4295:
4296: while($string !~ /^__END_ARRAY_REF__/) {
4297: my $value='';
4298: if($string =~ /^__HASH_REF__/) {
4299: ($value, $string)=&str2hashref($string);
4300: if(defined($value->{'error'})) {
4301: $array[0] ='Array reference error';
4302: return (\@array, $string);
4303: }
4304: } elsif($string =~ /^__ARRAY_REF__/) {
4305: ($value, $string)=&str2arrayref($string);
4306: if($value->[0] eq 'Array reference error') {
4307: $array[0] ='Array reference error';
4308: return (\@array, $string);
4309: }
4310: } else {
4311: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
4312: }
4313: $string =~ s/^&//;
4314:
4315: push(@array, $value);
1.191 harris41 4316: }
1.265 albertel 4317:
4318: $string =~ s/^__END_ARRAY_REF__//;
4319:
4320: return (\@array, $string);
1.168 albertel 4321: }
4322:
1.167 albertel 4323: # -------------------------------------------------------------------Temp Store
4324:
1.168 albertel 4325: sub tmpreset {
4326: my ($symb,$namespace,$domain,$stuname) = @_;
4327: if (!$symb) {
4328: $symb=&symbread();
1.620 albertel 4329: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4330: }
4331: $symb=escape($symb);
4332:
1.620 albertel 4333: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 4334: $namespace=~s/\//\_/g;
4335: $namespace=~s/\W//g;
4336:
1.620 albertel 4337: if (!$domain) { $domain=$env{'user.domain'}; }
4338: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4339: if ($domain eq 'public' && $stuname eq 'public') {
4340: $stuname=$ENV{'REMOTE_ADDR'};
4341: }
1.1117 foxr 4342: my $path=LONCAPA::tempdir();
1.168 albertel 4343: my %hash;
4344: if (tie(%hash,'GDBM_File',
4345: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4346: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 4347: foreach my $key (keys(%hash)) {
1.180 albertel 4348: if ($key=~ /:$symb/) {
1.168 albertel 4349: delete($hash{$key});
4350: }
4351: }
4352: }
4353: }
4354:
1.167 albertel 4355: sub tmpstore {
1.168 albertel 4356: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4357:
4358: if (!$symb) {
4359: $symb=&symbread();
1.620 albertel 4360: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4361: }
4362: $symb=escape($symb);
4363:
4364: if (!$namespace) {
4365: # I don't think we would ever want to store this for a course.
4366: # it seems this will only be used if we don't have a course.
1.620 albertel 4367: #$namespace=$env{'request.course.id'};
1.168 albertel 4368: #if (!$namespace) {
1.620 albertel 4369: $namespace=$env{'request.state'};
1.168 albertel 4370: #}
4371: }
4372: $namespace=~s/\//\_/g;
4373: $namespace=~s/\W//g;
1.620 albertel 4374: if (!$domain) { $domain=$env{'user.domain'}; }
4375: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4376: if ($domain eq 'public' && $stuname eq 'public') {
4377: $stuname=$ENV{'REMOTE_ADDR'};
4378: }
1.168 albertel 4379: my $now=time;
4380: my %hash;
1.1117 foxr 4381: my $path=LONCAPA::tempdir();
1.168 albertel 4382: if (tie(%hash,'GDBM_File',
4383: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4384: &GDBM_WRCREAT(),0640)) {
1.168 albertel 4385: $hash{"version:$symb"}++;
4386: my $version=$hash{"version:$symb"};
4387: my $allkeys='';
4388: foreach my $key (keys(%$storehash)) {
4389: $allkeys.=$key.':';
1.591 albertel 4390: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 4391: }
4392: $hash{"$version:$symb:timestamp"}=$now;
4393: $allkeys.='timestamp';
4394: $hash{"$version:keys:$symb"}=$allkeys;
4395: if (untie(%hash)) {
4396: return 'ok';
4397: } else {
4398: return "error:$!";
4399: }
4400: } else {
4401: return "error:$!";
4402: }
4403: }
1.167 albertel 4404:
1.168 albertel 4405: # -----------------------------------------------------------------Temp Restore
1.167 albertel 4406:
1.168 albertel 4407: sub tmprestore {
4408: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 4409:
1.168 albertel 4410: if (!$symb) {
4411: $symb=&symbread();
1.620 albertel 4412: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4413: }
4414: $symb=escape($symb);
4415:
1.620 albertel 4416: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 4417:
1.620 albertel 4418: if (!$domain) { $domain=$env{'user.domain'}; }
4419: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4420: if ($domain eq 'public' && $stuname eq 'public') {
4421: $stuname=$ENV{'REMOTE_ADDR'};
4422: }
1.168 albertel 4423: my %returnhash;
4424: $namespace=~s/\//\_/g;
4425: $namespace=~s/\W//g;
4426: my %hash;
1.1117 foxr 4427: my $path=LONCAPA::tempdir();
1.168 albertel 4428: if (tie(%hash,'GDBM_File',
4429: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4430: &GDBM_READER(),0640)) {
1.168 albertel 4431: my $version=$hash{"version:$symb"};
4432: $returnhash{'version'}=$version;
4433: my $scope;
4434: for ($scope=1;$scope<=$version;$scope++) {
4435: my $vkeys=$hash{"$scope:keys:$symb"};
4436: my @keys=split(/:/,$vkeys);
4437: my $key;
4438: $returnhash{"$scope:keys"}=$vkeys;
4439: foreach $key (@keys) {
1.591 albertel 4440: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
4441: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 4442: }
4443: }
1.168 albertel 4444: if (!(untie(%hash))) {
4445: return "error:$!";
4446: }
4447: } else {
4448: return "error:$!";
4449: }
4450: return %returnhash;
1.167 albertel 4451: }
4452:
1.9 www 4453: # ----------------------------------------------------------------------- Store
4454:
4455: sub store {
1.124 www 4456: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4457: my $home='';
4458:
1.168 albertel 4459: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4460:
1.213 www 4461: $symb=&symbclean($symb);
1.122 albertel 4462: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 4463:
1.620 albertel 4464: if (!$domain) { $domain=$env{'user.domain'}; }
4465: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 4466:
4467: &devalidate($symb,$stuname,$domain);
1.109 www 4468:
4469: $symb=escape($symb);
1.187 www 4470: if (!$namespace) {
1.620 albertel 4471: unless ($namespace=$env{'request.course.id'}) {
1.187 www 4472: return '';
4473: }
4474: }
1.620 albertel 4475: if (!$home) { $home=$env{'user.home'}; }
1.447 www 4476:
4477: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4478: $$storehash{'host'}=$perlvar{'lonHostID'};
4479:
1.12 www 4480: my $namevalue='';
1.800 albertel 4481: foreach my $key (keys(%$storehash)) {
4482: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 4483: }
1.12 www 4484: $namevalue=~s/\&$//;
1.187 www 4485: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124 www 4486: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9 www 4487: }
4488:
1.47 www 4489: # -------------------------------------------------------------- Critical Store
4490:
4491: sub cstore {
1.124 www 4492: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4493: my $home='';
4494:
1.168 albertel 4495: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4496:
1.213 www 4497: $symb=&symbclean($symb);
1.122 albertel 4498: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 4499:
1.620 albertel 4500: if (!$domain) { $domain=$env{'user.domain'}; }
4501: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 4502:
4503: &devalidate($symb,$stuname,$domain);
1.109 www 4504:
4505: $symb=escape($symb);
1.187 www 4506: if (!$namespace) {
1.620 albertel 4507: unless ($namespace=$env{'request.course.id'}) {
1.187 www 4508: return '';
4509: }
4510: }
1.620 albertel 4511: if (!$home) { $home=$env{'user.home'}; }
1.447 www 4512:
4513: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4514: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 4515:
1.47 www 4516: my $namevalue='';
1.800 albertel 4517: foreach my $key (keys(%$storehash)) {
4518: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 4519: }
1.47 www 4520: $namevalue=~s/\&$//;
1.187 www 4521: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 4522: return critical
4523: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47 www 4524: }
4525:
1.9 www 4526: # --------------------------------------------------------------------- Restore
4527:
4528: sub restore {
1.124 www 4529: my ($symb,$namespace,$domain,$stuname) = @_;
4530: my $home='';
4531:
1.168 albertel 4532: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4533:
1.122 albertel 4534: if (!$symb) {
4535: unless ($symb=escape(&symbread())) { return ''; }
4536: } else {
1.213 www 4537: $symb=&escape(&symbclean($symb));
1.122 albertel 4538: }
1.188 www 4539: if (!$namespace) {
1.620 albertel 4540: unless ($namespace=$env{'request.course.id'}) {
1.188 www 4541: return '';
4542: }
4543: }
1.620 albertel 4544: if (!$domain) { $domain=$env{'user.domain'}; }
4545: if (!$stuname) { $stuname=$env{'user.name'}; }
4546: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 4547: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
4548:
1.12 www 4549: my %returnhash=();
1.800 albertel 4550: foreach my $line (split(/\&/,$answer)) {
4551: my ($name,$value)=split(/\=/,$line);
1.591 albertel 4552: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 4553: }
1.75 www 4554: my $version;
4555: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 4556: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
4557: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 4558: }
1.75 www 4559: }
1.13 www 4560: return %returnhash;
1.34 www 4561: }
4562:
4563: # ---------------------------------------------------------- Course Description
1.1118 foxr 4564: #
4565: #
1.34 www 4566:
4567: sub coursedescription {
1.731 albertel 4568: my ($courseid,$args)=@_;
1.34 www 4569: $courseid=~s/^\///;
1.49 www 4570: $courseid=~s/\_/\//g;
1.34 www 4571: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 4572: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 4573: my $normalid=$cdomain.'_'.$cnum;
4574: # need to always cache even if we get errors otherwise we keep
4575: # trying and trying and trying to get the course description.
4576: my %envhash=();
4577: my %returnhash=();
1.731 albertel 4578:
4579: my $expiretime=600;
4580: if ($env{'request.course.id'} eq $normalid) {
4581: $expiretime=120;
4582: }
4583:
4584: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
4585: if (!$args->{'freshen_cache'}
4586: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
4587: foreach my $key (keys(%env)) {
4588: next if ($key !~ /^\Q$prefix\E(.*)/);
4589: my ($setting) = $1;
4590: $returnhash{$setting} = $env{$key};
4591: }
4592: return %returnhash;
4593: }
4594:
1.1118 foxr 4595: # get the data again
4596:
1.731 albertel 4597: if (!$args->{'one_time'}) {
4598: $envhash{'course.'.$normalid.'.last_cache'}=time;
4599: }
1.811 albertel 4600:
1.34 www 4601: if ($chome ne 'no_host') {
1.302 albertel 4602: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 4603: if (!exists($returnhash{'con_lost'})) {
1.1118 foxr 4604: my $username = $env{'user.name'}; # Defult username
4605: if(defined $args->{'user'}) {
4606: $username = $args->{'user'};
4607: }
1.129 albertel 4608: $returnhash{'home'}= $chome;
4609: $returnhash{'domain'} = $cdomain;
4610: $returnhash{'num'} = $cnum;
1.741 raeburn 4611: if (!defined($returnhash{'type'})) {
4612: $returnhash{'type'} = 'Course';
4613: }
1.130 albertel 4614: while (my ($name,$value) = each %returnhash) {
1.53 www 4615: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 4616: }
1.270 www 4617: $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117 foxr 4618: $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118 foxr 4619: $username.'_'.$cdomain.'_'.$cnum;
1.60 www 4620: $envhash{'course.'.$normalid.'.home'}=$chome;
4621: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
4622: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 4623: }
4624: }
1.731 albertel 4625: if (!$args->{'one_time'}) {
1.949 raeburn 4626: &appenv(\%envhash);
1.731 albertel 4627: }
1.302 albertel 4628: return %returnhash;
1.461 www 4629: }
4630:
1.1080 raeburn 4631: sub update_released_required {
4632: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
4633: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
4634: $cid = $env{'request.course.id'};
4635: $cdom = $env{'course.'.$cid.'.domain'};
4636: $cnum = $env{'course.'.$cid.'.num'};
4637: $chome = $env{'course.'.$cid.'.home'};
4638: }
4639: if ($needsrelease) {
4640: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
4641: my $needsupdate;
4642: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
4643: $needsupdate = 1;
4644: } else {
4645: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
4646: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
4647: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
4648: $needsupdate = 1;
4649: }
4650: }
4651: if ($needsupdate) {
4652: my %needshash = (
4653: 'internal.releaserequired' => $needsrelease,
4654: );
4655: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
4656: if ($putresult eq 'ok') {
4657: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
4658: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
4659: if (ref($crsinfo{$cid}) eq 'HASH') {
4660: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
4661: &courseidput($cdom,\%crsinfo,$chome,'notime');
4662: }
4663: }
4664: }
4665: }
4666: return;
4667: }
4668:
1.461 www 4669: # -------------------------------------------------See if a user is privileged
4670:
4671: sub privileged {
4672: my ($username,$domain)=@_;
1.1170 droeschl 4673:
4674: my %rolesdump = &dump("roles", $domain, $username) or return 0;
4675: my $now = time;
4676:
4677: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys %rolesdump}) {
4678: my ($trole, $tend, $tstart) = split(/_/, $role);
4679: if (($trole eq 'dc') || ($trole eq 'su')) {
4680: return 1 unless ($tend && $tend < $now)
4681: or ($tstart && $tstart > $now);
4682: }
1.461 www 4683: }
1.1170 droeschl 4684:
1.461 www 4685: return 0;
1.9 www 4686: }
1.1 albertel 4687:
1.103 harris41 4688: # -------------------------------------------------------- Get user privileges
1.11 www 4689:
4690: sub rolesinit {
1.1169 droeschl 4691: my ($domain, $username) = @_;
4692: my %userroles = ('user.login.time' => time);
4693: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
4694:
4695: # firstaccess and timerinterval are related to timed maps/resources.
4696: # also, blocking can be triggered by an activating timer
4697: # it's saved in the user's %env.
4698: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
4699: my %timerinterval = &dump('timerinterval', $domain, $username);
4700: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
4701: %timerintchk, %timerintenv);
4702:
1.1162 raeburn 4703: foreach my $key (keys(%firstaccess)) {
1.1169 droeschl 4704: my ($cid, $rest) = split(/\0/, $key);
1.1162 raeburn 4705: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
4706: }
1.1169 droeschl 4707:
1.1162 raeburn 4708: foreach my $key (keys(%timerinterval)) {
4709: my ($cid,$rest) = split(/\0/,$key);
4710: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
4711: }
1.1169 droeschl 4712:
1.11 www 4713: my %allroles=();
1.1162 raeburn 4714: my %allgroups=();
1.11 www 4715:
1.1169 droeschl 4716: for my $area (grep { ! /^rolesdef_/ } keys %rolesdump) {
4717: my $role = $rolesdump{$area};
4718: $area =~ s/\_\w\w$//;
4719:
4720: my ($trole, $tend, $tstart, $group_privs);
4721:
4722: if ($role =~ /^cr/) {
4723: # Custom role, defined by a user
4724: # e.g., user.role.cr/msu/smith/mynewrole
4725: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
4726: $trole = $1;
4727: ($tend, $tstart) = split('_', $2);
4728: } else {
4729: $trole = $role;
4730: }
4731: } elsif ($role =~ m|^gr/|) {
4732: # Role of member in a group, defined within a course/community
4733: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
4734: ($trole, $tend, $tstart) = split(/_/, $role);
4735: next if $tstart eq '-1';
4736: ($trole, $group_privs) = split(/\//, $trole);
4737: $group_privs = &unescape($group_privs);
4738: } else {
4739: # Just a normal role, defined in roles.tab
4740: ($trole, $tend, $tstart) = split(/_/,$role);
4741: }
4742:
4743: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
4744: $username);
4745: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
4746:
4747: # role expired or not available yet?
4748: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
4749: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
4750:
4751: next if $area eq '' or $trole eq '';
4752:
4753: my $spec = "$trole.$area";
4754: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
4755:
4756: if ($trole =~ /^cr\//) {
4757: # Custom role, defined by a user
4758: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
4759: } elsif ($trole eq 'gr') {
4760: # Role of a member in a group, defined within a course/community
4761: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
4762: next;
4763: } else {
4764: # Normal role, defined in roles.tab
4765: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
4766: }
4767:
4768: my $cid = $tdomain.'_'.$trest;
4769: unless ($firstaccchk{$cid}) {
4770: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
4771: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
4772: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
4773: $coursetimerstarts{$cid}{$item};
4774: }
4775: }
4776: $firstaccchk{$cid} = 1;
4777: }
4778: unless ($timerintchk{$cid}) {
4779: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
4780: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
4781: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
4782: $coursetimerintervals{$cid}{$item};
1.1162 raeburn 4783: }
1.12 www 4784: }
1.1169 droeschl 4785: $timerintchk{$cid} = 1;
1.191 harris41 4786: }
1.11 www 4787: }
1.1169 droeschl 4788:
4789: @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
4790: \%allroles, \%allgroups);
4791: $env{'user.adv'} = $userroles{'user.adv'};
4792:
1.1162 raeburn 4793: return (\%userroles,\%firstaccenv,\%timerintenv);
1.11 www 4794: }
4795:
1.567 raeburn 4796: sub set_arearole {
4797: my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
4798: # log the associated role with the area
4799: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743 albertel 4800: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 4801: }
4802:
4803: sub custom_roleprivs {
4804: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
4805: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
4806: my $homsvr=homeserver($rauthor,$rdomain);
1.838 albertel 4807: if (&hostname($homsvr) ne '') {
1.567 raeburn 4808: my ($rdummy,$roledef)=
4809: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
4810: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
4811: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
4812: if (defined($syspriv)) {
1.1043 raeburn 4813: if ($trest =~ /^$match_community$/) {
4814: $syspriv =~ s/bre\&S//;
4815: }
1.567 raeburn 4816: $$allroles{'cm./'}.=':'.$syspriv;
4817: $$allroles{$spec.'./'}.=':'.$syspriv;
4818: }
4819: if ($tdomain ne '') {
4820: if (defined($dompriv)) {
4821: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
4822: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
4823: }
4824: if (($trest ne '') && (defined($coursepriv))) {
4825: $$allroles{'cm.'.$area}.=':'.$coursepriv;
4826: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
4827: }
4828: }
4829: }
4830: }
4831: }
4832:
1.678 raeburn 4833: sub group_roleprivs {
4834: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
4835: my $access = 1;
4836: my $now = time;
4837: if (($tend!=0) && ($tend<$now)) { $access = 0; }
4838: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
4839: if ($access) {
1.811 albertel 4840: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 4841: $$allgroups{$course}{$group} .=':'.$group_privs;
4842: }
4843: }
1.567 raeburn 4844:
4845: sub standard_roleprivs {
4846: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
4847: if (defined($pr{$trole.':s'})) {
4848: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
4849: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
4850: }
4851: if ($tdomain ne '') {
4852: if (defined($pr{$trole.':d'})) {
4853: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
4854: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
4855: }
4856: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
4857: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
4858: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
4859: }
4860: }
4861: }
4862:
4863: sub set_userprivs {
1.1064 raeburn 4864: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 4865: my $author=0;
4866: my $adv=0;
1.678 raeburn 4867: my %grouproles = ();
4868: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 4869: my @groupkeys;
1.1000 raeburn 4870: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 4871: push(@groupkeys,$role);
4872: }
4873: if (ref($groups_roles) eq 'HASH') {
4874: foreach my $key (keys(%{$groups_roles})) {
4875: unless (grep(/^\Q$key\E$/,@groupkeys)) {
4876: push(@groupkeys,$key);
4877: }
4878: }
4879: }
4880: if (@groupkeys > 0) {
4881: foreach my $role (@groupkeys) {
4882: my ($trole,$area,$sec,$extendedarea);
4883: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
4884: $trole = $1;
4885: $area = $2;
4886: $sec = $3;
4887: $extendedarea = $area.$sec;
4888: if (exists($$allgroups{$area})) {
4889: foreach my $group (keys(%{$$allgroups{$area}})) {
4890: my $spec = $trole.'.'.$extendedarea;
4891: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 4892: $$allgroups{$area}{$group};
1.1064 raeburn 4893: }
1.678 raeburn 4894: }
4895: }
4896: }
4897: }
4898: }
1.800 albertel 4899: foreach my $group (keys(%grouproles)) {
4900: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 4901: }
1.800 albertel 4902: foreach my $role (keys(%{$allroles})) {
4903: my %thesepriv;
1.941 raeburn 4904: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 4905: foreach my $item (split(/:/,$$allroles{$role})) {
4906: if ($item ne '') {
4907: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 4908: if ($restrictions eq '') {
4909: $thesepriv{$privilege}='F';
4910: } elsif ($thesepriv{$privilege} ne 'F') {
4911: $thesepriv{$privilege}.=$restrictions;
4912: }
4913: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
4914: }
4915: }
4916: my $thesestr='';
1.1104 raeburn 4917: foreach my $priv (sort(keys(%thesepriv))) {
1.800 albertel 4918: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
4919: }
4920: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 4921: }
4922: return ($author,$adv);
4923: }
4924:
1.994 raeburn 4925: sub role_status {
1.1104 raeburn 4926: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 4927: my @pwhere = ();
4928: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
4929: (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
4930: unless (!defined($$role) || $$role eq '') {
4931: $$where=join('.',@pwhere);
4932: $$trolecode=$$role.'.'.$$where;
4933: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
4934: $$tstatus='is';
1.1104 raeburn 4935: if ($$tstart && $$tstart>$update) {
1.994 raeburn 4936: $$tstatus='future';
1.1034 raeburn 4937: if ($$tstart<$now) {
4938: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 4939: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 4940: my (%allroles,%allgroups,$group_privs,
4941: %groups_roles,@rolecodes);
1.1002 raeburn 4942: my %userroles = (
4943: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
4944: );
1.1064 raeburn 4945: @rolecodes = ('cm');
1.1002 raeburn 4946: my $spec=$$role.'.'.$$where;
4947: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
4948: if ($$role =~ /^cr\//) {
4949: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 4950: push(@rolecodes,'cr');
1.1002 raeburn 4951: } elsif ($$role eq 'gr') {
1.1064 raeburn 4952: push(@rolecodes,$$role);
1.1002 raeburn 4953: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
4954: $env{'user.name'});
1.1064 raeburn 4955: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 4956: (undef,my $group_privs) = split(/\//,$trole);
4957: $group_privs = &unescape($group_privs);
4958: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 4959: 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 4960: &get_groups_roles($tdomain,$trest,
4961: \%course_roles,\@rolecodes,
4962: \%groups_roles);
1.1002 raeburn 4963: } else {
1.1064 raeburn 4964: push(@rolecodes,$$role);
1.1002 raeburn 4965: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
4966: }
1.1064 raeburn 4967: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
4968: &appenv(\%userroles,\@rolecodes);
1.1002 raeburn 4969: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
4970: }
4971: }
1.1034 raeburn 4972: $$tstatus = 'is';
1.1002 raeburn 4973: }
1.994 raeburn 4974: }
4975: if ($$tend) {
1.1104 raeburn 4976: if ($$tend<$update) {
1.994 raeburn 4977: $$tstatus='expired';
4978: } elsif ($$tend<$now) {
4979: $$tstatus='will_not';
4980: }
4981: }
4982: }
4983: }
4984: }
4985:
1.1104 raeburn 4986: sub get_groups_roles {
4987: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
4988: return unless((ref($cdom_courseroles) eq 'HASH') &&
4989: (ref($rolecodes) eq 'ARRAY') &&
4990: (ref($groups_roles) eq 'HASH'));
4991: if (keys(%{$cdom_courseroles}) > 0) {
4992: my ($cnum) = ($rest =~ /^($match_courseid)/);
4993: if ($cdom ne '' && $cnum ne '') {
4994: foreach my $key (keys(%{$cdom_courseroles})) {
4995: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
4996: my $crsrole = $1;
4997: my $crssec = $2;
4998: if ($crsrole =~ /^cr/) {
4999: unless (grep(/^cr$/,@{$rolecodes})) {
5000: push(@{$rolecodes},'cr');
5001: }
5002: } else {
5003: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
5004: push(@{$rolecodes},$crsrole);
5005: }
5006: }
5007: my $rolekey = "$crsrole./$cdom/$cnum";
5008: if ($crssec ne '') {
5009: $rolekey .= "/$crssec";
5010: }
5011: $rolekey .= './';
5012: $groups_roles->{$rolekey} = $rolecodes;
5013: }
5014: }
5015: }
5016: }
5017: return;
5018: }
5019:
5020: sub delete_env_groupprivs {
5021: my ($where,$courseroles,$possroles) = @_;
5022: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
5023: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
5024: unless (ref($courseroles->{$udom}) eq 'HASH') {
5025: %{$courseroles->{$udom}} =
5026: &get_my_roles('','','userroles',['active'],
5027: $possroles,[$udom],1);
5028: }
5029: if (ref($courseroles->{$udom}) eq 'HASH') {
5030: foreach my $item (keys(%{$courseroles->{$udom}})) {
5031: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
5032: my $area = '/'.$cdom.'/'.$cnum;
5033: my $privkey = "user.priv.$crsrole.$area";
5034: if ($crssec ne '') {
5035: $privkey .= '/'.$crssec;
5036: }
5037: $privkey .= ".$area/$group";
5038: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
5039: }
5040: }
5041: return;
5042: }
5043:
1.994 raeburn 5044: sub check_adhoc_privs {
1.1104 raeburn 5045: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994 raeburn 5046: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.9 raeburn 5047: my $setprivs;
1.994 raeburn 5048: if ($env{$cckey}) {
5049: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104 raeburn 5050: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 5051: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088 raeburn 5052: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1172.2.9 raeburn 5053: $setprivs = 1;
1.994 raeburn 5054: }
5055: } else {
1.1088 raeburn 5056: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1172.2.9 raeburn 5057: $setprivs = 1;
1.994 raeburn 5058: }
1.1172.2.9 raeburn 5059: return $setprivs;
1.994 raeburn 5060: }
5061:
5062: sub set_adhoc_privileges {
5063: # role can be cc or ca
1.1088 raeburn 5064: my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994 raeburn 5065: my $area = '/'.$dcdom.'/'.$pickedcourse;
5066: my $spec = $role.'.'.$area;
5067: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
5068: $env{'user.name'});
5069: my %ccrole = ();
5070: &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
5071: my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
5072: &appenv(\%userroles,[$role,'cm']);
5073: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088 raeburn 5074: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
5075: &appenv( {'request.role' => $spec,
5076: 'request.role.domain' => $dcdom,
5077: 'request.course.sec' => ''
5078: }
5079: );
5080: my $tadv=0;
5081: if (&allowed('adv') eq 'F') { $tadv=1; }
5082: &appenv({'request.role.adv' => $tadv});
5083: }
1.994 raeburn 5084: }
5085:
1.12 www 5086: # --------------------------------------------------------------- get interface
5087:
5088: sub get {
1.131 albertel 5089: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 5090: my $items='';
1.800 albertel 5091: foreach my $item (@$storearr) {
5092: $items.=&escape($item).'&';
1.191 harris41 5093: }
1.12 www 5094: $items=~s/\&$//;
1.620 albertel 5095: if (!$udomain) { $udomain=$env{'user.domain'}; }
5096: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 5097: my $uhome=&homeserver($uname,$udomain);
5098:
1.133 albertel 5099: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 5100: my @pairs=split(/\&/,$rep);
1.273 albertel 5101: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
5102: return @pairs;
5103: }
1.15 www 5104: my %returnhash=();
1.42 www 5105: my $i=0;
1.800 albertel 5106: foreach my $item (@$storearr) {
5107: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 5108: $i++;
1.191 harris41 5109: }
1.15 www 5110: return %returnhash;
1.27 www 5111: }
5112:
5113: # --------------------------------------------------------------- del interface
5114:
5115: sub del {
1.133 albertel 5116: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 5117: my $items='';
1.800 albertel 5118: foreach my $item (@$storearr) {
5119: $items.=&escape($item).'&';
1.191 harris41 5120: }
1.984 neumanie 5121:
1.27 www 5122: $items=~s/\&$//;
1.620 albertel 5123: if (!$udomain) { $udomain=$env{'user.domain'}; }
5124: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 5125: my $uhome=&homeserver($uname,$udomain);
5126: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 5127: }
5128:
5129: # -------------------------------------------------------------- dump interface
5130:
5131: sub dump {
1.1166 raeburn 5132: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.755 albertel 5133: if (!$udomain) { $udomain=$env{'user.domain'}; }
5134: if (!$uname) { $uname=$env{'user.name'}; }
5135: my $uhome=&homeserver($uname,$udomain);
1.1167 droeschl 5136:
1.755 albertel 5137: if ($regexp) {
5138: $regexp=&escape($regexp);
5139: } else {
5140: $regexp='.';
5141: }
1.1166 raeburn 5142: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755 albertel 5143: my @pairs=split(/\&/,$rep);
5144: my %returnhash=();
1.1098 foxr 5145: if (!($rep =~ /^error/ )) {
5146: foreach my $item (@pairs) {
5147: my ($key,$value)=split(/=/,$item,2);
5148: $key = &unescape($key);
5149: next if ($key =~ /^error: 2 /);
5150: $returnhash{$key}=&thaw_unescape($value);
5151: }
1.755 albertel 5152: }
5153: return %returnhash;
1.407 www 5154: }
5155:
1.1098 foxr 5156:
1.717 albertel 5157: # --------------------------------------------------------- dumpstore interface
5158:
5159: sub dumpstore {
5160: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822 albertel 5161: if (!$udomain) { $udomain=$env{'user.domain'}; }
5162: if (!$uname) { $uname=$env{'user.name'}; }
5163: my $uhome=&homeserver($uname,$udomain);
5164: if ($regexp) {
5165: $regexp=&escape($regexp);
5166: } else {
5167: $regexp='.';
5168: }
5169: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
5170: my @pairs=split(/\&/,$rep);
5171: my %returnhash=();
5172: foreach my $item (@pairs) {
5173: my ($key,$value)=split(/=/,$item,2);
5174: next if ($key =~ /^error: 2 /);
5175: $returnhash{$key}=&thaw_unescape($value);
5176: }
5177: return %returnhash;
1.717 albertel 5178: }
5179:
1.407 www 5180: # -------------------------------------------------------------- keys interface
5181:
5182: sub getkeys {
5183: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 5184: if (!$udomain) { $udomain=$env{'user.domain'}; }
5185: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 5186: my $uhome=&homeserver($uname,$udomain);
5187: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
5188: my @keyarray=();
1.800 albertel 5189: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 5190: next if ($key =~ /^error: 2 /);
1.800 albertel 5191: push(@keyarray,&unescape($key));
1.407 www 5192: }
5193: return @keyarray;
1.318 matthew 5194: }
5195:
1.319 matthew 5196: # --------------------------------------------------------------- currentdump
5197: sub currentdump {
1.328 matthew 5198: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 5199: $courseid = $env{'request.course.id'} if (! defined($courseid));
5200: $sdom = $env{'user.domain'} if (! defined($sdom));
5201: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 5202: my $uhome = &homeserver($sname,$sdom);
5203: my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318 matthew 5204: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 5205: #
1.318 matthew 5206: my %returnhash=();
1.319 matthew 5207: #
5208: if ($rep eq "unknown_cmd") {
5209: # an old lond will not know currentdump
5210: # Do a dump and make it look like a currentdump
1.822 albertel 5211: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 5212: return if ($tmp[0] =~ /^(error:|no_such_host)/);
5213: my %hash = @tmp;
5214: @tmp=();
1.424 matthew 5215: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 5216: } else {
5217: my @pairs=split(/\&/,$rep);
1.800 albertel 5218: foreach my $pair (@pairs) {
5219: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 5220: my ($symb,$param) = split(/:/,$key);
5221: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 5222: &thaw_unescape($value);
1.319 matthew 5223: }
1.191 harris41 5224: }
1.12 www 5225: return %returnhash;
1.424 matthew 5226: }
5227:
5228: sub convert_dump_to_currentdump{
5229: my %hash = %{shift()};
5230: my %returnhash;
5231: # Code ripped from lond, essentially. The only difference
5232: # here is the unescaping done by lonnet::dump(). Conceivably
5233: # we might run in to problems with parameter names =~ /^v\./
5234: while (my ($key,$value) = each(%hash)) {
5235: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 5236: $symb = &unescape($symb);
5237: $param = &unescape($param);
1.424 matthew 5238: next if ($v eq 'version' || $symb eq 'keys');
5239: next if (exists($returnhash{$symb}) &&
5240: exists($returnhash{$symb}->{$param}) &&
5241: $returnhash{$symb}->{'v.'.$param} > $v);
5242: $returnhash{$symb}->{$param}=$value;
5243: $returnhash{$symb}->{'v.'.$param}=$v;
5244: }
5245: #
5246: # Remove all of the keys in the hashes which keep track of
5247: # the version of the parameter.
5248: while (my ($symb,$param_hash) = each(%returnhash)) {
5249: # use a foreach because we are going to delete from the hash.
5250: foreach my $key (keys(%$param_hash)) {
5251: delete($param_hash->{$key}) if ($key =~ /^v\./);
5252: }
5253: }
5254: return \%returnhash;
1.12 www 5255: }
5256:
1.627 albertel 5257: # ------------------------------------------------------ critical inc interface
5258:
5259: sub cinc {
5260: return &inc(@_,'critical');
5261: }
5262:
1.449 matthew 5263: # --------------------------------------------------------------- inc interface
5264:
5265: sub inc {
1.627 albertel 5266: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 5267: if (!$udomain) { $udomain=$env{'user.domain'}; }
5268: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 5269: my $uhome=&homeserver($uname,$udomain);
5270: my $items='';
5271: if (! ref($store)) {
5272: # got a single value, so use that instead
5273: $items = &escape($store).'=&';
5274: } elsif (ref($store) eq 'SCALAR') {
5275: $items = &escape($$store).'=&';
5276: } elsif (ref($store) eq 'ARRAY') {
5277: $items = join('=&',map {&escape($_);} @{$store});
5278: } elsif (ref($store) eq 'HASH') {
5279: while (my($key,$value) = each(%{$store})) {
5280: $items.= &escape($key).'='.&escape($value).'&';
5281: }
5282: }
5283: $items=~s/\&$//;
1.627 albertel 5284: if ($critical) {
5285: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
5286: } else {
5287: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
5288: }
1.449 matthew 5289: }
5290:
1.12 www 5291: # --------------------------------------------------------------- put interface
5292:
5293: sub put {
1.134 albertel 5294: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 5295: if (!$udomain) { $udomain=$env{'user.domain'}; }
5296: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 5297: my $uhome=&homeserver($uname,$udomain);
1.12 www 5298: my $items='';
1.800 albertel 5299: foreach my $item (keys(%$storehash)) {
5300: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 5301: }
1.12 www 5302: $items=~s/\&$//;
1.134 albertel 5303: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 5304: }
5305:
1.631 albertel 5306: # ------------------------------------------------------------ newput interface
5307:
5308: sub newput {
5309: my ($namespace,$storehash,$udomain,$uname)=@_;
5310: if (!$udomain) { $udomain=$env{'user.domain'}; }
5311: if (!$uname) { $uname=$env{'user.name'}; }
5312: my $uhome=&homeserver($uname,$udomain);
5313: my $items='';
5314: foreach my $key (keys(%$storehash)) {
5315: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
5316: }
5317: $items=~s/\&$//;
5318: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
5319: }
5320:
5321: # --------------------------------------------------------- putstore interface
5322:
1.524 raeburn 5323: sub putstore {
1.715 albertel 5324: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620 albertel 5325: if (!$udomain) { $udomain=$env{'user.domain'}; }
5326: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 5327: my $uhome=&homeserver($uname,$udomain);
5328: my $items='';
1.715 albertel 5329: foreach my $key (keys(%$storehash)) {
5330: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 5331: }
1.715 albertel 5332: $items=~s/\&$//;
1.716 albertel 5333: my $esc_symb=&escape($symb);
5334: my $esc_v=&escape($version);
1.715 albertel 5335: my $reply =
1.716 albertel 5336: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 5337: $uhome);
5338: if ($reply eq 'unknown_cmd') {
1.716 albertel 5339: # gfall back to way things use to be done
1.715 albertel 5340: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
5341: $uname);
1.524 raeburn 5342: }
1.715 albertel 5343: return $reply;
5344: }
5345:
5346: sub old_putstore {
1.716 albertel 5347: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
5348: if (!$udomain) { $udomain=$env{'user.domain'}; }
5349: if (!$uname) { $uname=$env{'user.name'}; }
5350: my $uhome=&homeserver($uname,$udomain);
5351: my %newstorehash;
1.800 albertel 5352: foreach my $item (keys(%$storehash)) {
5353: my $key = $version.':'.&escape($symb).':'.$item;
5354: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 5355: }
5356: my $items='';
5357: my %allitems = ();
1.800 albertel 5358: foreach my $item (keys(%newstorehash)) {
5359: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 5360: my $key = $1.':keys:'.$2;
5361: $allitems{$key} .= $3.':';
5362: }
1.800 albertel 5363: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 5364: }
1.800 albertel 5365: foreach my $item (keys(%allitems)) {
5366: $allitems{$item} =~ s/\:$//;
5367: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 5368: }
5369: $items=~s/\&$//;
5370: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 5371: }
5372:
1.47 www 5373: # ------------------------------------------------------ critical put interface
5374:
5375: sub cput {
1.134 albertel 5376: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 5377: if (!$udomain) { $udomain=$env{'user.domain'}; }
5378: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 5379: my $uhome=&homeserver($uname,$udomain);
1.47 www 5380: my $items='';
1.800 albertel 5381: foreach my $item (keys(%$storehash)) {
5382: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 5383: }
1.47 www 5384: $items=~s/\&$//;
1.134 albertel 5385: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 5386: }
5387:
5388: # -------------------------------------------------------------- eget interface
5389:
5390: sub eget {
1.133 albertel 5391: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 5392: my $items='';
1.800 albertel 5393: foreach my $item (@$storearr) {
5394: $items.=&escape($item).'&';
1.191 harris41 5395: }
1.12 www 5396: $items=~s/\&$//;
1.620 albertel 5397: if (!$udomain) { $udomain=$env{'user.domain'}; }
5398: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 5399: my $uhome=&homeserver($uname,$udomain);
5400: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 5401: my @pairs=split(/\&/,$rep);
5402: my %returnhash=();
1.42 www 5403: my $i=0;
1.800 albertel 5404: foreach my $item (@$storearr) {
5405: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 5406: $i++;
1.191 harris41 5407: }
1.12 www 5408: return %returnhash;
5409: }
5410:
1.667 albertel 5411: # ------------------------------------------------------------ tmpput interface
5412: sub tmpput {
1.802 raeburn 5413: my ($storehash,$server,$context)=@_;
1.667 albertel 5414: my $items='';
1.800 albertel 5415: foreach my $item (keys(%$storehash)) {
5416: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 5417: }
5418: $items=~s/\&$//;
1.802 raeburn 5419: if (defined($context)) {
5420: $items .= ':'.&escape($context);
5421: }
1.667 albertel 5422: return &reply("tmpput:$items",$server);
5423: }
5424:
5425: # ------------------------------------------------------------ tmpget interface
5426: sub tmpget {
1.688 albertel 5427: my ($token,$server)=@_;
5428: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5429: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 5430: my %returnhash;
5431: foreach my $item (split(/\&/,$rep)) {
5432: my ($key,$value)=split(/=/,$item);
1.951 raeburn 5433: next if ($key =~ /^error: 2 /);
1.667 albertel 5434: $returnhash{&unescape($key)}=&thaw_unescape($value);
5435: }
5436: return %returnhash;
5437: }
5438:
1.1113 raeburn 5439: # ------------------------------------------------------------ tmpdel interface
1.688 albertel 5440: sub tmpdel {
5441: my ($token,$server)=@_;
5442: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5443: return &reply("tmpdel:$token",$server);
5444: }
5445:
1.765 albertel 5446: # -------------------------------------------------- portfolio access checking
5447:
5448: sub portfolio_access {
1.766 albertel 5449: my ($requrl) = @_;
1.765 albertel 5450: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
5451: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814 raeburn 5452: if ($result) {
5453: my %setters;
5454: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
5455: my ($startblock,$endblock) =
5456: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
5457: if ($startblock && $endblock) {
5458: return 'B';
5459: }
5460: } else {
5461: my ($startblock,$endblock) =
5462: &Apache::loncommon::blockcheck(\%setters,'port');
5463: if ($startblock && $endblock) {
5464: return 'B';
5465: }
5466: }
5467: }
1.765 albertel 5468: if ($result eq 'ok') {
1.766 albertel 5469: return 'F';
1.765 albertel 5470: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 5471: return 'A';
1.765 albertel 5472: }
1.766 albertel 5473: return '';
1.765 albertel 5474: }
5475:
5476: sub get_portfolio_access {
1.767 albertel 5477: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
5478:
5479: if (!ref($access_hash)) {
5480: my $current_perms = &get_portfile_permissions($udom,$unum);
5481: my %access_controls = &get_access_controls($current_perms,$group,
5482: $file_name);
5483: $access_hash = $access_controls{$file_name};
5484: }
5485:
1.765 albertel 5486: my ($public,$guest,@domains,@users,@courses,@groups);
5487: my $now = time;
5488: if (ref($access_hash) eq 'HASH') {
5489: foreach my $key (keys(%{$access_hash})) {
5490: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
5491: if ($start > $now) {
5492: next;
5493: }
5494: if ($end && $end<$now) {
5495: next;
5496: }
5497: if ($scope eq 'public') {
5498: $public = $key;
5499: last;
5500: } elsif ($scope eq 'guest') {
5501: $guest = $key;
5502: } elsif ($scope eq 'domains') {
5503: push(@domains,$key);
5504: } elsif ($scope eq 'users') {
5505: push(@users,$key);
5506: } elsif ($scope eq 'course') {
5507: push(@courses,$key);
5508: } elsif ($scope eq 'group') {
5509: push(@groups,$key);
5510: }
5511: }
5512: if ($public) {
5513: return 'ok';
5514: }
5515: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
5516: if ($guest) {
5517: return $guest;
5518: }
5519: } else {
5520: if (@domains > 0) {
5521: foreach my $domkey (@domains) {
5522: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
5523: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
5524: return 'ok';
5525: }
5526: }
5527: }
5528: }
5529: if (@users > 0) {
5530: foreach my $userkey (@users) {
1.865 raeburn 5531: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
5532: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
5533: if (ref($item) eq 'HASH') {
5534: if (($item->{'uname'} eq $env{'user.name'}) &&
5535: ($item->{'udom'} eq $env{'user.domain'})) {
5536: return 'ok';
5537: }
5538: }
5539: }
5540: }
1.765 albertel 5541: }
5542: }
5543: my %roleshash;
5544: my @courses_and_groups = @courses;
5545: push(@courses_and_groups,@groups);
5546: if (@courses_and_groups > 0) {
5547: my (%allgroups,%allroles);
5548: my ($start,$end,$role,$sec,$group);
5549: foreach my $envkey (%env) {
1.1060 raeburn 5550: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 5551: my $cid = $2.'_'.$3;
5552: if ($1 eq 'gr') {
5553: $group = $4;
5554: $allgroups{$cid}{$group} = $env{$envkey};
5555: } else {
5556: if ($4 eq '') {
5557: $sec = 'none';
5558: } else {
5559: $sec = $4;
5560: }
5561: $allroles{$cid}{$1}{$sec} = $env{$envkey};
5562: }
1.811 albertel 5563: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 5564: my $cid = $2.'_'.$3;
5565: if ($4 eq '') {
5566: $sec = 'none';
5567: } else {
5568: $sec = $4;
5569: }
5570: $allroles{$cid}{$1}{$sec} = $env{$envkey};
5571: }
5572: }
5573: if (keys(%allroles) == 0) {
5574: return;
5575: }
5576: foreach my $key (@courses_and_groups) {
5577: my %content = %{$$access_hash{$key}};
5578: my $cnum = $content{'number'};
5579: my $cdom = $content{'domain'};
5580: my $cid = $cdom.'_'.$cnum;
5581: if (!exists($allroles{$cid})) {
5582: next;
5583: }
5584: foreach my $role_id (keys(%{$content{'roles'}})) {
5585: my @sections = @{$content{'roles'}{$role_id}{'section'}};
5586: my @groups = @{$content{'roles'}{$role_id}{'group'}};
5587: my @status = @{$content{'roles'}{$role_id}{'access'}};
5588: my @roles = @{$content{'roles'}{$role_id}{'role'}};
5589: foreach my $role (keys(%{$allroles{$cid}})) {
5590: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
5591: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
5592: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
5593: if (grep/^all$/,@sections) {
5594: return 'ok';
5595: } else {
5596: if (grep/^$sec$/,@sections) {
5597: return 'ok';
5598: }
5599: }
5600: }
5601: }
5602: if (keys(%{$allgroups{$cid}}) == 0) {
5603: if (grep/^none$/,@groups) {
5604: return 'ok';
5605: }
5606: } else {
5607: if (grep/^all$/,@groups) {
5608: return 'ok';
5609: }
5610: foreach my $group (keys(%{$allgroups{$cid}})) {
5611: if (grep/^$group$/,@groups) {
5612: return 'ok';
5613: }
5614: }
5615: }
5616: }
5617: }
5618: }
5619: }
5620: }
5621: if ($guest) {
5622: return $guest;
5623: }
5624: }
5625: }
5626: return;
5627: }
5628:
5629: sub course_group_datechecker {
5630: my ($dates,$now,$status) = @_;
5631: my ($start,$end) = split(/\./,$dates);
5632: if (!$start && !$end) {
5633: return 'ok';
5634: }
5635: if (grep/^active$/,@{$status}) {
5636: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
5637: return 'ok';
5638: }
5639: }
5640: if (grep/^previous$/,@{$status}) {
5641: if ($end > $now ) {
5642: return 'ok';
5643: }
5644: }
5645: if (grep/^future$/,@{$status}) {
5646: if ($start > $now) {
5647: return 'ok';
5648: }
5649: }
5650: return;
5651: }
5652:
5653: sub parse_portfolio_url {
5654: my ($url) = @_;
5655:
5656: my ($type,$udom,$unum,$group,$file_name);
5657:
1.823 albertel 5658: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 5659: $type = 1;
5660: $udom = $1;
5661: $unum = $2;
5662: $file_name = $3;
1.823 albertel 5663: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 5664: $type = 2;
5665: $udom = $1;
5666: $unum = $2;
5667: $group = $3;
5668: $file_name = $3.'/'.$4;
5669: }
5670: if (wantarray) {
5671: return ($type,$udom,$unum,$file_name,$group);
5672: }
5673: return $type;
5674: }
5675:
5676: sub is_portfolio_url {
5677: my ($url) = @_;
5678: return scalar(&parse_portfolio_url($url));
5679: }
5680:
1.798 raeburn 5681: sub is_portfolio_file {
5682: my ($file) = @_;
1.820 raeburn 5683: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 5684: return 1;
5685: }
5686: return;
5687: }
5688:
1.976 raeburn 5689: sub usertools_access {
1.1084 raeburn 5690: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 5691: my ($access,%tools);
5692: if ($context eq '') {
5693: $context = 'tools';
5694: }
5695: if ($context eq 'requestcourses') {
5696: %tools = (
5697: official => 1,
5698: unofficial => 1,
1.1006 raeburn 5699: community => 1,
1.985 raeburn 5700: );
1.1172.2.9 raeburn 5701: } elsif ($context eq 'requestauthor') {
5702: %tools = (
5703: requestauthor => 1,
5704: );
1.985 raeburn 5705: } else {
5706: %tools = (
5707: aboutme => 1,
5708: blog => 1,
1.1172.2.6 raeburn 5709: webdav => 1,
1.985 raeburn 5710: portfolio => 1,
5711: );
5712: }
1.976 raeburn 5713: return if (!defined($tools{$tool}));
5714:
5715: if ((!defined($udom)) || (!defined($uname))) {
5716: $udom = $env{'user.domain'};
5717: $uname = $env{'user.name'};
5718: }
5719:
1.978 raeburn 5720: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
5721: if ($action ne 'reload') {
1.985 raeburn 5722: if ($context eq 'requestcourses') {
5723: return $env{'environment.canrequest.'.$tool};
1.1172.2.9 raeburn 5724: } elsif ($context eq 'requestauthor') {
5725: return $env{'environment.canrequest.author'};
1.985 raeburn 5726: } else {
5727: return $env{'environment.availabletools.'.$tool};
5728: }
5729: }
1.976 raeburn 5730: }
5731:
1.1172.2.9 raeburn 5732: my ($toolstatus,$inststatus,$envkey);
5733: if ($context eq 'requestauthor') {
5734: $envkey = $context;
5735: } else {
5736: $envkey = $context.'.'.$tool;
5737: }
1.976 raeburn 5738:
1.985 raeburn 5739: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
5740: ($action ne 'reload')) {
1.1172.2.9 raeburn 5741: $toolstatus = $env{'environment.'.$envkey};
1.976 raeburn 5742: $inststatus = $env{'environment.inststatus'};
5743: } else {
1.1084 raeburn 5744: if (ref($userenvref) eq 'HASH') {
1.1172.2.9 raeburn 5745: $toolstatus = $userenvref->{$envkey};
1.1084 raeburn 5746: $inststatus = $userenvref->{'inststatus'};
5747: } else {
1.1172.2.9 raeburn 5748: my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
5749: $toolstatus = $userenv{$envkey};
1.1084 raeburn 5750: $inststatus = $userenv{'inststatus'};
5751: }
1.976 raeburn 5752: }
5753:
5754: if ($toolstatus ne '') {
5755: if ($toolstatus) {
5756: $access = 1;
5757: } else {
5758: $access = 0;
5759: }
5760: return $access;
5761: }
5762:
1.1084 raeburn 5763: my ($is_adv,%domdef);
5764: if (ref($is_advref) eq 'HASH') {
5765: $is_adv = $is_advref->{'is_adv'};
5766: } else {
5767: $is_adv = &is_advanced_user($udom,$uname);
5768: }
5769: if (ref($domdefref) eq 'HASH') {
5770: %domdef = %{$domdefref};
5771: } else {
5772: %domdef = &get_domain_defaults($udom);
5773: }
1.976 raeburn 5774: if (ref($domdef{$tool}) eq 'HASH') {
5775: if ($is_adv) {
5776: if ($domdef{$tool}{'_LC_adv'} ne '') {
5777: if ($domdef{$tool}{'_LC_adv'}) {
5778: $access = 1;
5779: } else {
5780: $access = 0;
5781: }
5782: return $access;
5783: }
5784: }
5785: if ($inststatus ne '') {
5786: my ($hasaccess,$hasnoaccess);
5787: foreach my $affiliation (split(/:/,$inststatus)) {
5788: if ($domdef{$tool}{$affiliation} ne '') {
5789: if ($domdef{$tool}{$affiliation}) {
5790: $hasaccess = 1;
5791: } else {
5792: $hasnoaccess = 1;
5793: }
5794: }
5795: }
5796: if ($hasaccess || $hasnoaccess) {
5797: if ($hasaccess) {
5798: $access = 1;
5799: } elsif ($hasnoaccess) {
5800: $access = 0;
5801: }
5802: return $access;
5803: }
5804: } else {
5805: if ($domdef{$tool}{'default'} ne '') {
5806: if ($domdef{$tool}{'default'}) {
5807: $access = 1;
5808: } elsif ($domdef{$tool}{'default'} == 0) {
5809: $access = 0;
5810: }
5811: return $access;
5812: }
5813: }
5814: } else {
1.1172.2.6 raeburn 5815: if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985 raeburn 5816: $access = 1;
5817: } else {
5818: $access = 0;
5819: }
1.976 raeburn 5820: return $access;
5821: }
5822: }
5823:
1.1050 raeburn 5824: sub is_course_owner {
5825: my ($cdom,$cnum,$udom,$uname) = @_;
5826: if (($udom eq '') || ($uname eq '')) {
5827: $udom = $env{'user.domain'};
5828: $uname = $env{'user.name'};
5829: }
5830: unless (($udom eq '') || ($uname eq '')) {
5831: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
5832: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
5833: return 1;
5834: } else {
5835: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
5836: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
5837: return 1;
5838: }
5839: }
5840: }
5841: }
5842: return;
5843: }
5844:
1.976 raeburn 5845: sub is_advanced_user {
5846: my ($udom,$uname) = @_;
1.1085 raeburn 5847: if ($udom ne '' && $uname ne '') {
5848: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128 raeburn 5849: if (wantarray) {
5850: return ($env{'user.adv'},$env{'user.author'});
5851: } else {
5852: return $env{'user.adv'};
5853: }
1.1085 raeburn 5854: }
5855: }
1.976 raeburn 5856: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
5857: my %allroles;
1.1128 raeburn 5858: my ($is_adv,$is_author);
1.976 raeburn 5859: foreach my $role (keys(%roleshash)) {
5860: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
5861: my $area = '/'.$tdomain.'/'.$trest;
5862: if ($sec ne '') {
5863: $area .= '/'.$sec;
5864: }
5865: if (($area ne '') && ($trole ne '')) {
5866: my $spec=$trole.'.'.$area;
5867: if ($trole =~ /^cr\//) {
5868: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5869: } elsif ($trole ne 'gr') {
5870: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5871: }
1.1128 raeburn 5872: if ($trole eq 'au') {
5873: $is_author = 1;
5874: }
1.976 raeburn 5875: }
5876: }
5877: foreach my $role (keys(%allroles)) {
5878: last if ($is_adv);
5879: foreach my $item (split(/:/,$allroles{$role})) {
5880: if ($item ne '') {
5881: my ($privilege,$restrictions)=split(/&/,$item);
5882: if ($privilege eq 'adv') {
5883: $is_adv = 1;
5884: last;
5885: }
5886: }
5887: }
5888: }
1.1128 raeburn 5889: if (wantarray) {
5890: return ($is_adv,$is_author);
5891: }
1.976 raeburn 5892: return $is_adv;
5893: }
1.798 raeburn 5894:
1.1035 raeburn 5895: sub check_can_request {
1.1036 raeburn 5896: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 5897: my $canreq = 0;
5898: my ($types,$typename) = &Apache::loncommon::course_types();
5899: my @options = ('approval','validate','autolimit');
5900: my $optregex = join('|',@options);
5901: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
5902: foreach my $type (@{$types}) {
5903: if (&usertools_access($env{'user.name'},
5904: $env{'user.domain'},
5905: $type,undef,'requestcourses')) {
5906: $canreq ++;
1.1036 raeburn 5907: if (ref($request_domains) eq 'HASH') {
5908: push(@{$request_domains->{$type}},$env{'user.domain'});
5909: }
1.1035 raeburn 5910: if ($dom eq $env{'user.domain'}) {
5911: $can_request->{$type} = 1;
5912: }
5913: }
5914: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
5915: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
5916: if (@curr > 0) {
1.1036 raeburn 5917: foreach my $item (@curr) {
5918: if (ref($request_domains) eq 'HASH') {
5919: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
5920: if ($otherdom ne '') {
5921: if (ref($request_domains->{$type}) eq 'ARRAY') {
5922: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
5923: push(@{$request_domains->{$type}},$otherdom);
5924: }
5925: } else {
5926: push(@{$request_domains->{$type}},$otherdom);
5927: }
5928: }
5929: }
5930: }
5931: unless($dom eq $env{'user.domain'}) {
5932: $canreq ++;
1.1035 raeburn 5933: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
5934: $can_request->{$type} = 1;
5935: }
5936: }
5937: }
5938: }
5939: }
5940: }
5941: return $canreq;
5942: }
5943:
1.341 www 5944: # ---------------------------------------------- Custom access rule evaluation
5945:
5946: sub customaccess {
5947: my ($priv,$uri)=@_;
1.807 albertel 5948: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 5949: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 5950: $udom = &LONCAPA::clean_domain($udom);
5951: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 5952: my $access=0;
1.800 albertel 5953: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 5954: my ($effect,$realm,$role,$type)=split(/\:/,$right);
5955: if ($type eq 'user') {
5956: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 5957: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 5958: if ($tdom) {
5959: if ($tdom ne $env{'user.domain'}) { next; }
5960: }
1.896 albertel 5961: if ($tuname) {
5962: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 5963: }
5964: $access=($effect eq 'allow');
5965: last;
5966: }
5967: } else {
5968: if ($role) {
5969: if ($role ne $urole) { next; }
5970: }
5971: foreach my $scope (split(/\s*\,\s*/,$realm)) {
5972: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
5973: if ($tdom) {
5974: if ($tdom ne $udom) { next; }
5975: }
5976: if ($tcrs) {
5977: if ($tcrs ne $ucrs) { next; }
5978: }
5979: if ($tsec) {
5980: if ($tsec ne $usec) { next; }
5981: }
5982: $access=($effect eq 'allow');
5983: last;
5984: }
5985: if ($realm eq '' && $role eq '') {
5986: $access=($effect eq 'allow');
5987: }
1.402 bowersj2 5988: }
1.341 www 5989: }
5990: return $access;
5991: }
5992:
1.103 harris41 5993: # ------------------------------------------------- Check for a user privilege
1.12 www 5994:
5995: sub allowed {
1.810 raeburn 5996: my ($priv,$uri,$symb,$role)=@_;
1.705 albertel 5997: my $ver_orguri=$uri;
1.439 www 5998: $uri=&deversion($uri);
1.152 www 5999: my $orguri=$uri;
1.52 www 6000: $uri=&declutter($uri);
1.809 raeburn 6001:
1.810 raeburn 6002: if ($priv eq 'evb') {
6003: # Evade communication block restrictions for specified role in a course
6004: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
6005: return $1;
6006: } else {
6007: return;
6008: }
6009: }
6010:
1.620 albertel 6011: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 6012: # Free bre access to adm and meta resources
1.775 albertel 6013: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 6014: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
6015: && ($priv eq 'bre')) {
1.14 www 6016: return 'F';
1.159 www 6017: }
6018:
1.545 banghart 6019: # Free bre access to user's own portfolio contents
1.714 raeburn 6020: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 6021: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 6022: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 6023: my %setters;
6024: my ($startblock,$endblock) =
6025: &Apache::loncommon::blockcheck(\%setters,'port');
6026: if ($startblock && $endblock) {
6027: return 'B';
6028: } else {
6029: return 'F';
6030: }
1.545 banghart 6031: }
6032:
1.762 raeburn 6033: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 6034: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
6035: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
6036: if (exists($env{'request.course.id'})) {
6037: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6038: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6039: if (($domain eq $cdom) && ($name eq $cnum)) {
6040: my $courseprivid=$env{'request.course.id'};
6041: $courseprivid=~s/\_/\//;
6042: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
6043: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
6044: return $1;
1.762 raeburn 6045: } else {
6046: if ($env{'request.course.sec'}) {
6047: $courseprivid.='/'.$env{'request.course.sec'};
6048: }
6049: if ($env{'user.priv.'.$env{'request.role'}.'./'.
6050: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
6051: return $2;
6052: }
1.714 raeburn 6053: }
6054: }
6055: }
6056: }
6057:
1.159 www 6058: # Free bre to public access
6059:
6060: if ($priv eq 'bre') {
1.238 www 6061: my $copyright=&metadata($uri,'copyright');
1.620 albertel 6062: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 6063: return 'F';
6064: }
1.238 www 6065: if ($copyright eq 'priv') {
6066: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 6067: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 6068: return '';
6069: }
6070: }
6071: if ($copyright eq 'domain') {
6072: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 6073: unless (($env{'user.domain'} eq $1) ||
6074: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 6075: return '';
6076: }
1.262 matthew 6077: }
1.620 albertel 6078: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 6079: # Library role, so allow browsing of resources in this domain.
6080: return 'F';
1.238 www 6081: }
1.341 www 6082: if ($copyright eq 'custom') {
6083: unless (&customaccess($priv,$uri)) { return ''; }
6084: }
1.14 www 6085: }
1.264 matthew 6086: # Domain coordinator is trying to create a course
1.620 albertel 6087: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 6088: # uri is the requested domain in this case.
6089: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 6090: # a role of dc for the domain in question.
1.620 albertel 6091: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 6092: }
1.29 www 6093:
1.52 www 6094: my $thisallowed='';
6095: my $statecond=0;
6096: my $courseprivid='';
6097:
1.1039 raeburn 6098: my $ownaccess;
1.1043 raeburn 6099: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 6100: if (($priv eq 'bro') && ($env{'user.author'})) {
6101: if ($uri eq '') {
6102: $ownaccess = 1;
6103: } else {
6104: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
6105: my $udom = $env{'user.domain'};
6106: my $uname = $env{'user.name'};
6107: if ($uri =~ m{^\Q$udom\E/?$}) {
6108: $ownaccess = 1;
1.1040 raeburn 6109: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 6110: unless ($uri =~ m{\.\./}) {
6111: $ownaccess = 1;
6112: }
6113: } elsif (($udom ne 'public') && ($uname ne 'public')) {
6114: my $now = time;
6115: if ($uri =~ m{^([^/]+)/?$}) {
6116: my $adom = $1;
6117: foreach my $key (keys(%env)) {
1.1042 raeburn 6118: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 6119: my ($start,$end) = split('.',$env{$key});
6120: if (($now >= $start) && (!$end || $end < $now)) {
6121: $ownaccess = 1;
6122: last;
6123: }
6124: }
6125: }
6126: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
6127: my $adom = $1;
6128: my $aname = $2;
1.1042 raeburn 6129: foreach my $role ('ca','aa') {
6130: if ($env{"user.role.$role./$adom/$aname"}) {
6131: my ($start,$end) =
6132: split('.',$env{"user.role.$role./$adom/$aname"});
6133: if (($now >= $start) && (!$end || $end < $now)) {
6134: $ownaccess = 1;
6135: last;
6136: }
1.1039 raeburn 6137: }
6138: }
6139: }
6140: }
6141: }
6142: }
6143: }
6144:
1.52 www 6145: # Course
6146:
1.620 albertel 6147: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6148: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6149: $thisallowed.=$1;
6150: }
1.52 www 6151: }
1.29 www 6152:
1.52 www 6153: # Domain
6154:
1.620 albertel 6155: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 6156: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6157: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6158: $thisallowed.=$1;
6159: }
1.12 www 6160: }
1.52 www 6161:
1.1141 raeburn 6162: # User who is not author or co-author might still be able to edit
6163: # resource of an author in the domain (e.g., if Domain Coordinator).
6164: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
6165: (&allowed('mdc',$env{'request.course.id'}))) {
6166: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
6167: $thisallowed.=$1;
6168: }
6169: }
6170:
1.52 www 6171: # Course: uri itself is a course
1.66 www 6172: my $courseuri=$uri;
6173: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 6174: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 6175:
1.620 albertel 6176: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 6177: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6178: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6179: $thisallowed.=$1;
6180: }
1.12 www 6181: }
1.29 www 6182:
1.665 albertel 6183: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 6184: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 6185: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 6186: $thisallowed='';
1.671 raeburn 6187: my ($match)=&is_on_map($uri);
6188: if ($match) {
6189: if ($env{'user.priv.'.$env{'request.role'}.'./'}
6190: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6191: my @blockers = &has_comm_blocking($priv,$symb,$uri);
6192: if (@blockers > 0) {
6193: $thisallowed = 'B';
6194: } else {
6195: $thisallowed.=$1;
6196: }
1.671 raeburn 6197: }
6198: } else {
1.705 albertel 6199: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 6200: if ($refuri) {
6201: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 6202: $thisallowed='F';
1.671 raeburn 6203: } else {
6204: $refuri=&declutter($refuri);
6205: my ($match) = &is_on_map($refuri);
6206: if ($match) {
1.1162 raeburn 6207: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
6208: if (@blockers > 0) {
6209: $thisallowed = 'B';
6210: } else {
6211: $thisallowed='F';
6212: }
1.671 raeburn 6213: }
1.669 raeburn 6214: }
1.671 raeburn 6215: }
6216: }
1.314 www 6217: }
1.492 albertel 6218:
1.766 albertel 6219: if ($priv eq 'bre'
6220: && $thisallowed ne 'F'
6221: && $thisallowed ne '2'
6222: && &is_portfolio_url($uri)) {
6223: $thisallowed = &portfolio_access($uri);
6224: }
6225:
1.52 www 6226: # Full access at system, domain or course-wide level? Exit.
1.29 www 6227: if ($thisallowed=~/F/) {
6228: return 'F';
6229: }
6230:
1.52 www 6231: # If this is generating or modifying users, exit with special codes
1.29 www 6232:
1.643 www 6233: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
6234: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 6235: my ($audom,$auname)=split('/',$uri);
1.643 www 6236: # no author name given, so this just checks on the general right to make a co-author in this domain
6237: unless ($auname) { return $thisallowed; }
6238: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 6239: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
6240: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
6241: ($audom ne $env{'request.role.domain'}))) { return ''; }
6242: }
1.52 www 6243: return $thisallowed;
6244: }
6245: #
1.103 harris41 6246: # Gathered so far: system, domain and course wide privileges
1.52 www 6247: #
6248: # Course: See if uri or referer is an individual resource that is part of
6249: # the course
6250:
1.620 albertel 6251: if ($env{'request.course.id'}) {
1.232 www 6252:
1.620 albertel 6253: $courseprivid=$env{'request.course.id'};
6254: if ($env{'request.course.sec'}) {
6255: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 6256: }
6257: $courseprivid=~s/\_/\//;
6258: my $checkreferer=1;
1.232 www 6259: my ($match,$cond)=&is_on_map($uri);
6260: if ($match) {
6261: $statecond=$cond;
1.620 albertel 6262: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 6263: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6264: my $value = $1;
6265: if ($priv eq 'bre') {
6266: my @blockers = &has_comm_blocking($priv,$symb,$uri);
6267: if (@blockers > 0) {
6268: $thisallowed = 'B';
6269: } else {
6270: $thisallowed.=$value;
6271: }
6272: } else {
6273: $thisallowed.=$value;
6274: }
1.52 www 6275: $checkreferer=0;
6276: }
1.29 www 6277: }
1.83 www 6278:
1.148 www 6279: if ($checkreferer) {
1.620 albertel 6280: my $refuri=$env{'httpref.'.$orguri};
1.148 www 6281: unless ($refuri) {
1.800 albertel 6282: foreach my $key (keys(%env)) {
6283: if ($key=~/^httpref\..*\*/) {
6284: my $pattern=$key;
1.156 www 6285: $pattern=~s/^httpref\.\/res\///;
1.148 www 6286: $pattern=~s/\*/\[\^\/\]\+/g;
6287: $pattern=~s/\//\\\//g;
1.152 www 6288: if ($orguri=~/$pattern/) {
1.800 albertel 6289: $refuri=$env{$key};
1.148 www 6290: }
6291: }
1.191 harris41 6292: }
1.148 www 6293: }
1.232 www 6294:
1.148 www 6295: if ($refuri) {
1.152 www 6296: $refuri=&declutter($refuri);
1.232 www 6297: my ($match,$cond)=&is_on_map($refuri);
6298: if ($match) {
6299: my $refstatecond=$cond;
1.620 albertel 6300: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 6301: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6302: my $value = $1;
6303: if ($priv eq 'bre') {
6304: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
6305: if (@blockers > 0) {
6306: $thisallowed = 'B';
6307: } else {
6308: $thisallowed.=$value;
6309: }
6310: } else {
6311: $thisallowed.=$value;
6312: }
1.53 www 6313: $uri=$refuri;
6314: $statecond=$refstatecond;
1.52 www 6315: }
6316: }
1.148 www 6317: }
1.29 www 6318: }
1.52 www 6319: }
1.29 www 6320:
1.52 www 6321: #
1.103 harris41 6322: # Gathered now: all privileges that could apply, and condition number
1.52 www 6323: #
6324: #
6325: # Full or no access?
6326: #
1.29 www 6327:
1.52 www 6328: if ($thisallowed=~/F/) {
6329: return 'F';
6330: }
1.29 www 6331:
1.52 www 6332: unless ($thisallowed) {
6333: return '';
6334: }
1.29 www 6335:
1.52 www 6336: # Restrictions exist, deal with them
6337: #
6338: # C:according to course preferences
6339: # R:according to resource settings
6340: # L:unless locked
6341: # X:according to user session state
6342: #
6343:
6344: # Possibly locked functionality, check all courses
1.54 www 6345: # Locks might take effect only after 10 minutes cache expiration for other
6346: # courses, and 2 minutes for current course
1.52 www 6347:
6348: my $envkey;
6349: if ($thisallowed=~/L/) {
1.1000 raeburn 6350: foreach $envkey (keys(%env)) {
1.54 www 6351: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
6352: my $courseid=$2;
6353: my $roleid=$1.'.'.$2;
1.92 www 6354: $courseid=~s/^\///;
1.54 www 6355: my $expiretime=600;
1.620 albertel 6356: if ($env{'request.role'} eq $roleid) {
1.54 www 6357: $expiretime=120;
6358: }
6359: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
6360: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 6361: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 6362: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 6363: }
1.620 albertel 6364: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
6365: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
6366: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
6367: &log($env{'user.domain'},$env{'user.name'},
6368: $env{'user.home'},
1.57 www 6369: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 6370: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 6371: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 6372: return '';
6373: }
6374: }
1.620 albertel 6375: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
6376: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
6377: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
6378: &log($env{'user.domain'},$env{'user.name'},
6379: $env{'user.home'},
1.57 www 6380: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 6381: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 6382: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 6383: return '';
6384: }
6385: }
6386: }
1.29 www 6387: }
1.52 www 6388: }
6389:
6390: #
6391: # Rest of the restrictions depend on selected course
6392: #
6393:
1.620 albertel 6394: unless ($env{'request.course.id'}) {
1.766 albertel 6395: if ($thisallowed eq 'A') {
6396: return 'A';
1.814 raeburn 6397: } elsif ($thisallowed eq 'B') {
6398: return 'B';
1.766 albertel 6399: } else {
6400: return '1';
6401: }
1.52 www 6402: }
1.29 www 6403:
1.52 www 6404: #
6405: # Now user is definitely in a course
6406: #
1.53 www 6407:
6408:
6409: # Course preferences
6410:
6411: if ($thisallowed=~/C/) {
1.620 albertel 6412: my $rolecode=(split(/\./,$env{'request.role'}))[0];
6413: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
6414: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 6415: =~/\Q$rolecode\E/) {
1.1103 raeburn 6416: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 6417: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
6418: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
6419: $env{'request.course.id'});
6420: }
1.237 www 6421: return '';
6422: }
6423:
1.620 albertel 6424: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 6425: =~/\Q$unamedom\E/) {
1.1103 raeburn 6426: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 6427: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
6428: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
6429: $env{'request.course.id'});
6430: }
1.54 www 6431: return '';
6432: }
1.53 www 6433: }
6434:
6435: # Resource preferences
6436:
6437: if ($thisallowed=~/R/) {
1.620 albertel 6438: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 6439: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103 raeburn 6440: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 6441: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
6442: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
6443: }
6444: return '';
1.54 www 6445: }
1.53 www 6446: }
1.30 www 6447:
1.246 www 6448: # Restricted by state or randomout?
1.30 www 6449:
1.52 www 6450: if ($thisallowed=~/X/) {
1.620 albertel 6451: if ($env{'acc.randomout'}) {
1.579 albertel 6452: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 6453: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 6454: return '';
6455: }
1.247 www 6456: }
6457: if (&condval($statecond)) {
1.52 www 6458: return '2';
6459: } else {
6460: return '';
6461: }
6462: }
1.30 www 6463:
1.766 albertel 6464: if ($thisallowed eq 'A') {
6465: return 'A';
1.814 raeburn 6466: } elsif ($thisallowed eq 'B') {
6467: return 'B';
1.766 albertel 6468: }
1.52 www 6469: return 'F';
1.232 www 6470: }
1.1162 raeburn 6471:
6472: sub get_comm_blocks {
6473: my ($cdom,$cnum) = @_;
6474: if ($cdom eq '' || $cnum eq '') {
6475: return unless ($env{'request.course.id'});
6476: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6477: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6478: }
6479: my %commblocks;
6480: my $hashid=$cdom.'_'.$cnum;
6481: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
6482: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
6483: %commblocks = %{$blocksref};
6484: } else {
6485: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
6486: my $cachetime = 600;
6487: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
6488: }
6489: return %commblocks;
6490: }
6491:
6492: sub has_comm_blocking {
6493: my ($priv,$symb,$uri,$blocks) = @_;
6494: return unless ($env{'request.course.id'});
6495: return unless ($priv eq 'bre');
6496: return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
6497: my %commblocks;
6498: if (ref($blocks) eq 'HASH') {
6499: %commblocks = %{$blocks};
6500: } else {
6501: %commblocks = &get_comm_blocks();
6502: }
6503: return unless (keys(%commblocks) > 0);
6504: if (!$symb) { $symb=&symbread($uri,1); }
6505: my ($map,$resid,undef)=&decode_symb($symb);
6506: my %tocheck = (
6507: maps => $map,
6508: resources => $symb,
6509: );
6510: my @blockers;
6511: my $now = time;
1.1163 raeburn 6512: my $navmap = Apache::lonnavmaps::navmap->new();
1.1162 raeburn 6513: foreach my $block (keys(%commblocks)) {
6514: if ($block =~ /^(\d+)____(\d+)$/) {
6515: my ($start,$end) = ($1,$2);
6516: if ($start <= $now && $end >= $now) {
6517: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
6518: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
6519: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
6520: if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
6521: unless (grep(/^\Q$block\E$/,@blockers)) {
6522: push(@blockers,$block);
6523: }
6524: }
6525: }
6526: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
6527: if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
6528: unless (grep(/^\Q$block\E$/,@blockers)) {
6529: push(@blockers,$block);
6530: }
6531: }
6532: }
6533: }
6534: }
6535: }
6536: } elsif ($block =~ /^firstaccess____(.+)$/) {
6537: my $item = $1;
1.1163 raeburn 6538: my @to_test;
1.1162 raeburn 6539: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
6540: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
6541: my $check_interval;
6542: if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
6543: my @interval;
6544: my $type = 'map';
6545: if ($item eq 'course') {
6546: $type = 'course';
6547: @interval=&EXT("resource.0.interval");
6548: } else {
6549: if ($item =~ /___\d+___/) {
6550: $type = 'resource';
6551: @interval=&EXT("resource.0.interval",$item);
1.1163 raeburn 6552: if (ref($navmap)) {
6553: my $res = $navmap->getBySymb($item);
6554: push(@to_test,$res);
6555: }
1.1162 raeburn 6556: } else {
6557: my $mapsymb = &symbread($item,1);
6558: if ($mapsymb) {
6559: if (ref($navmap)) {
6560: my $mapres = $navmap->getBySymb($mapsymb);
1.1163 raeburn 6561: @to_test = $mapres->retrieveResources($mapres,undef,0,1);
6562: foreach my $res (@to_test) {
1.1162 raeburn 6563: my $symb = $res->symb();
6564: next if ($symb eq $mapsymb);
6565: if ($symb ne '') {
6566: @interval=&EXT("resource.0.interval",$symb);
6567: last;
6568: }
6569: }
6570: }
6571: }
6572: }
6573: }
6574: if ($interval[0] =~ /\d+/) {
6575: my $first_access;
6576: if ($type eq 'resource') {
6577: $first_access=&get_first_access($interval[1],$item);
6578: } elsif ($type eq 'map') {
6579: $first_access=&get_first_access($interval[1],undef,$item);
6580: } else {
6581: $first_access=&get_first_access($interval[1]);
6582: }
6583: if ($first_access) {
6584: my $timesup = $first_access+$interval[0];
6585: if ($timesup > $now) {
1.1163 raeburn 6586: foreach my $res (@to_test) {
6587: if ($res->is_problem()) {
6588: if ($res->completable()) {
6589: unless (grep(/^\Q$block\E$/,@blockers)) {
6590: push(@blockers,$block);
6591: }
6592: last;
6593: }
6594: }
1.1162 raeburn 6595: }
6596: }
6597: }
6598: }
6599: }
6600: }
6601: }
6602: }
6603: }
6604: return @blockers;
6605: }
6606:
6607: sub check_docs_block {
6608: my ($docsblock,$tocheck) =@_;
6609: if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
6610: return;
6611: }
6612: if (ref($docsblock->{'maps'}) eq 'HASH') {
6613: if ($tocheck->{'maps'}) {
6614: if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
6615: return 1;
6616: }
6617: }
6618: }
6619: if (ref($docsblock->{'resources'}) eq 'HASH') {
6620: if ($tocheck->{'resources'}) {
6621: if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
6622: return 1;
6623: }
6624: }
6625: }
6626: return;
6627: }
6628:
1.1133 foxr 6629: #
6630: # Removes the versino from a URI and
6631: # splits it in to its filename and path to the filename.
6632: # Seems like File::Basename could have done this more clearly.
6633: # Parameters:
6634: # $uri - input URI
6635: # Returns:
6636: # Two element list consisting of
6637: # $pathname - the URI up to and excluding the trailing /
6638: # $filename - The part of the URI following the last /
6639: # NOTE:
6640: # Another realization of this is simply:
6641: # use File::Basename;
6642: # ...
6643: # $uri = shift;
6644: # $filename = basename($uri);
6645: # $path = dirname($uri);
6646: # return ($filename, $path);
6647: #
6648: # The implementation below is probably faster however.
6649: #
1.710 albertel 6650: sub split_uri_for_cond {
6651: my $uri=&deversion(&declutter(shift));
6652: my @uriparts=split(/\//,$uri);
6653: my $filename=pop(@uriparts);
6654: my $pathname=join('/',@uriparts);
6655: return ($pathname,$filename);
6656: }
1.232 www 6657: # --------------------------------------------------- Is a resource on the map?
6658:
6659: sub is_on_map {
1.710 albertel 6660: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 6661: #Trying to find the conditional for the file
1.620 albertel 6662: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 6663: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 6664: if ($match) {
1.289 bowersj2 6665: return (1,$1);
6666: } else {
1.434 www 6667: return (0,0);
1.289 bowersj2 6668: }
1.12 www 6669: }
6670:
1.427 www 6671: # --------------------------------------------------------- Get symb from alias
6672:
6673: sub get_symb_from_alias {
6674: my $symb=shift;
6675: my ($map,$resid,$url)=&decode_symb($symb);
6676: # Already is a symb
6677: if ($url) { return $symb; }
6678: # Must be an alias
6679: my $aliassymb='';
6680: my %bighash;
1.620 albertel 6681: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 6682: &GDBM_READER(),0640)) {
6683: my $rid=$bighash{'mapalias_'.$symb};
6684: if ($rid) {
6685: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 6686: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
6687: $resid,$bighash{'src_'.$rid});
1.427 www 6688: }
6689: untie %bighash;
6690: }
6691: return $aliassymb;
6692: }
6693:
1.12 www 6694: # ----------------------------------------------------------------- Define Role
6695:
6696: sub definerole {
6697: if (allowed('mcr','/')) {
6698: my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800 albertel 6699: foreach my $role (split(':',$sysrole)) {
6700: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 6701: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
6702: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
6703: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 6704: return "refused:s:$crole&$cqual";
6705: }
6706: }
1.191 harris41 6707: }
1.800 albertel 6708: foreach my $role (split(':',$domrole)) {
6709: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 6710: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
6711: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
6712: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 6713: return "refused:d:$crole&$cqual";
6714: }
6715: }
1.191 harris41 6716: }
1.800 albertel 6717: foreach my $role (split(':',$courole)) {
6718: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 6719: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
6720: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
6721: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 6722: return "refused:c:$crole&$cqual";
6723: }
6724: }
1.191 harris41 6725: }
1.620 albertel 6726: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
6727: "$env{'user.domain'}:$env{'user.name'}:".
1.21 www 6728: "rolesdef_$rolename=".
6729: escape($sysrole.'_'.$domrole.'_'.$courole);
1.620 albertel 6730: return reply($command,$env{'user.home'});
1.12 www 6731: } else {
6732: return 'refused';
6733: }
1.105 harris41 6734: }
6735:
6736: # ---------------- Make a metadata query against the network of library servers
6737:
6738: sub metadata_query {
1.244 matthew 6739: my ($query,$custom,$customshow,$server_array)=@_;
1.120 harris41 6740: my %rhash;
1.845 albertel 6741: my %libserv = &all_library();
1.244 matthew 6742: my @server_list = (defined($server_array) ? @$server_array
6743: : keys(%libserv) );
6744: for my $server (@server_list) {
1.118 harris41 6745: unless ($custom or $customshow) {
6746: my $reply=&reply("querysend:".&escape($query),$server);
6747: $rhash{$server}=$reply;
6748: }
6749: else {
6750: my $reply=&reply("querysend:".&escape($query).':'.
6751: &escape($custom).':'.&escape($customshow),
6752: $server);
6753: $rhash{$server}=$reply;
6754: }
1.112 harris41 6755: }
1.118 harris41 6756: return \%rhash;
1.240 www 6757: }
6758:
6759: # ----------------------------------------- Send log queries and wait for reply
6760:
6761: sub log_query {
6762: my ($uname,$udom,$query,%filters)=@_;
6763: my $uhome=&homeserver($uname,$udom);
6764: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 6765: my $uhost=&hostname($uhome);
1.800 albertel 6766: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 6767: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
6768: $uhome);
1.479 albertel 6769: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 6770: return get_query_reply($queryid);
6771: }
6772:
1.818 raeburn 6773: # -------------------------- Update MySQL table for portfolio file
6774:
6775: sub update_portfolio_table {
1.821 raeburn 6776: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 6777: if ($group ne '') {
6778: $file_name =~s /^\Q$group\E//;
6779: }
1.818 raeburn 6780: my $homeserver = &homeserver($uname,$udom);
6781: my $queryid=
1.821 raeburn 6782: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
6783: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 6784: my $reply = &get_query_reply($queryid);
6785: return $reply;
6786: }
6787:
1.899 raeburn 6788: # -------------------------- Update MySQL allusers table
6789:
6790: sub update_allusers_table {
6791: my ($uname,$udom,$names) = @_;
6792: my $homeserver = &homeserver($uname,$udom);
6793: my $queryid=
6794: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
6795: 'lastname='.&escape($names->{'lastname'}).'%%'.
6796: 'firstname='.&escape($names->{'firstname'}).'%%'.
6797: 'middlename='.&escape($names->{'middlename'}).'%%'.
6798: 'generation='.&escape($names->{'generation'}).'%%'.
6799: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
6800: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 6801: return;
1.899 raeburn 6802: }
6803:
1.508 raeburn 6804: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 6805:
6806: sub fetch_enrollment_query {
1.511 raeburn 6807: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508 raeburn 6808: my $homeserver;
1.547 raeburn 6809: my $maxtries = 1;
1.508 raeburn 6810: if ($context eq 'automated') {
6811: $homeserver = $perlvar{'lonHostID'};
1.547 raeburn 6812: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 6813: } else {
6814: $homeserver = &homeserver($cnum,$dom);
6815: }
1.838 albertel 6816: my $host=&hostname($homeserver);
1.506 raeburn 6817: my $cmd = '';
1.1000 raeburn 6818: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 6819: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 6820: }
6821: $cmd =~ s/%%$//;
6822: $cmd = &escape($cmd);
6823: my $query = 'fetchenrollment';
1.620 albertel 6824: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 6825: unless ($queryid=~/^\Q$host\E\_/) {
6826: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
6827: return 'error: '.$queryid;
6828: }
1.506 raeburn 6829: my $reply = &get_query_reply($queryid);
1.547 raeburn 6830: my $tries = 1;
6831: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
6832: $reply = &get_query_reply($queryid);
6833: $tries ++;
6834: }
1.526 raeburn 6835: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 6836: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 6837: } else {
1.901 albertel 6838: my @responses = split(/:/,$reply);
1.515 raeburn 6839: if ($homeserver eq $perlvar{'lonHostID'}) {
1.800 albertel 6840: foreach my $line (@responses) {
6841: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 6842: $$replyref{$key} = $value;
6843: }
6844: } else {
1.1117 foxr 6845: my $pathname = LONCAPA::tempdir();
1.800 albertel 6846: foreach my $line (@responses) {
6847: my ($key,$value) = split(/=/,$line);
1.506 raeburn 6848: $$replyref{$key} = $value;
6849: if ($value > 0) {
1.800 albertel 6850: foreach my $item (@{$$affiliatesref{$key}}) {
6851: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 6852: my $destname = $pathname.'/'.$filename;
6853: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 6854: if ($xml_classlist =~ /^error/) {
6855: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
6856: } else {
1.506 raeburn 6857: if ( open(FILE,">$destname") ) {
6858: print FILE &unescape($xml_classlist);
6859: close(FILE);
1.526 raeburn 6860: } else {
6861: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 6862: }
6863: }
6864: }
6865: }
6866: }
6867: }
6868: return 'ok';
6869: }
6870: return 'error';
6871: }
6872:
1.242 www 6873: sub get_query_reply {
6874: my $queryid=shift;
1.1117 foxr 6875: my $replyfile=LONCAPA::tempdir().$queryid;
1.240 www 6876: my $reply='';
6877: for (1..100) {
6878: sleep 2;
6879: if (-e $replyfile.'.end') {
1.448 albertel 6880: if (open(my $fh,$replyfile)) {
1.904 albertel 6881: $reply = join('',<$fh>);
6882: close($fh);
1.240 www 6883: } else { return 'error: reply_file_error'; }
1.242 www 6884: return &unescape($reply);
6885: }
1.240 www 6886: }
1.242 www 6887: return 'timeout:'.$queryid;
1.240 www 6888: }
6889:
6890: sub courselog_query {
1.241 www 6891: #
6892: # possible filters:
6893: # url: url or symb
6894: # username
6895: # domain
6896: # action: view, submit, grade
6897: # start: timestamp
6898: # end: timestamp
6899: #
1.240 www 6900: my (%filters)=@_;
1.620 albertel 6901: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 6902: if ($filters{'url'}) {
6903: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
6904: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
6905: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
6906: }
1.620 albertel 6907: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
6908: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 6909: return &log_query($cname,$cdom,'courselog',%filters);
6910: }
6911:
6912: sub userlog_query {
1.858 raeburn 6913: #
6914: # possible filters:
6915: # action: log check role
6916: # start: timestamp
6917: # end: timestamp
6918: #
1.240 www 6919: my ($uname,$udom,%filters)=@_;
6920: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 6921: }
6922:
1.506 raeburn 6923: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
6924:
6925: sub auto_run {
1.508 raeburn 6926: my ($cnum,$cdom) = @_;
1.876 raeburn 6927: my $response = 0;
6928: my $settings;
6929: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
6930: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
6931: $settings = $domconfig{'autoenroll'};
6932: if ($settings->{'run'} eq '1') {
6933: $response = 1;
6934: }
6935: } else {
1.934 raeburn 6936: my $homeserver;
6937: if (&is_course($cdom,$cnum)) {
6938: $homeserver = &homeserver($cnum,$cdom);
6939: } else {
6940: $homeserver = &domain($cdom,'primary');
6941: }
6942: if ($homeserver ne 'no_host') {
6943: $response = &reply('autorun:'.$cdom,$homeserver);
6944: }
1.876 raeburn 6945: }
1.506 raeburn 6946: return $response;
6947: }
1.776 albertel 6948:
1.506 raeburn 6949: sub auto_get_sections {
1.508 raeburn 6950: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 6951: my $homeserver;
6952: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6953: $homeserver = &homeserver($cnum,$cdom);
6954: }
6955: if (!defined($homeserver)) {
6956: if ($cdom =~ /^$match_domain$/) {
6957: $homeserver = &domain($cdom,'primary');
6958: }
6959: }
6960: my @secs;
6961: if (defined($homeserver)) {
6962: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
6963: unless ($response eq 'refused') {
6964: @secs = split(/:/,$response);
6965: }
1.506 raeburn 6966: }
6967: return @secs;
6968: }
1.776 albertel 6969:
1.506 raeburn 6970: sub auto_new_course {
1.1099 raeburn 6971: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 6972: my $homeserver = &homeserver($cnum,$cdom);
1.1099 raeburn 6973: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 6974: return $response;
6975: }
1.776 albertel 6976:
1.506 raeburn 6977: sub auto_validate_courseID {
1.508 raeburn 6978: my ($cnum,$cdom,$inst_course_id) = @_;
6979: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 6980: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 6981: return $response;
6982: }
1.776 albertel 6983:
1.1007 raeburn 6984: sub auto_validate_instcode {
1.1020 raeburn 6985: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 6986: my ($homeserver,$response);
6987: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6988: $homeserver = &homeserver($cnum,$cdom);
6989: }
6990: if (!defined($homeserver)) {
6991: if ($cdom =~ /^$match_domain$/) {
6992: $homeserver = &domain($cdom,'primary');
6993: }
6994: }
1.1065 raeburn 6995: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
6996: &escape($instcode).':'.&escape($owner),$homeserver));
1.1027 raeburn 6997: my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
6998: return ($outcome,$description);
1.1007 raeburn 6999: }
7000:
1.506 raeburn 7001: sub auto_create_password {
1.873 raeburn 7002: my ($cnum,$cdom,$authparam,$udom) = @_;
7003: my ($homeserver,$response);
1.506 raeburn 7004: my $create_passwd = 0;
7005: my $authchk = '';
1.873 raeburn 7006: if ($udom =~ /^$match_domain$/) {
7007: $homeserver = &domain($udom,'primary');
7008: }
7009: if ($homeserver eq '') {
7010: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7011: $homeserver = &homeserver($cnum,$cdom);
7012: }
7013: }
7014: if ($homeserver eq '') {
7015: $authchk = 'nodomain';
1.506 raeburn 7016: } else {
1.873 raeburn 7017: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
7018: if ($response eq 'refused') {
7019: $authchk = 'refused';
7020: } else {
1.901 albertel 7021: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 7022: }
1.506 raeburn 7023: }
7024: return ($authparam,$create_passwd,$authchk);
7025: }
7026:
1.706 raeburn 7027: sub auto_photo_permission {
7028: my ($cnum,$cdom,$students) = @_;
7029: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 7030: my ($outcome,$perm_reqd,$conditions) =
7031: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 7032: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7033: return (undef,undef);
7034: }
1.706 raeburn 7035: return ($outcome,$perm_reqd,$conditions);
7036: }
7037:
7038: sub auto_checkphotos {
7039: my ($uname,$udom,$pid) = @_;
7040: my $homeserver = &homeserver($uname,$udom);
7041: my ($result,$resulttype);
7042: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 7043: &escape($uname).':'.&escape($pid),
7044: $homeserver));
1.709 albertel 7045: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7046: return (undef,undef);
7047: }
1.706 raeburn 7048: if ($outcome) {
7049: ($result,$resulttype) = split(/:/,$outcome);
7050: }
7051: return ($result,$resulttype);
7052: }
7053:
7054: sub auto_photochoice {
7055: my ($cnum,$cdom) = @_;
7056: my $homeserver = &homeserver($cnum,$cdom);
7057: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 7058: &escape($cdom),
7059: $homeserver)));
1.709 albertel 7060: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7061: return (undef,undef);
7062: }
1.706 raeburn 7063: return ($update,$comment);
7064: }
7065:
7066: sub auto_photoupdate {
7067: my ($affiliatesref,$dom,$cnum,$photo) = @_;
7068: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 7069: my $host=&hostname($homeserver);
1.706 raeburn 7070: my $cmd = '';
7071: my $maxtries = 1;
1.800 albertel 7072: foreach my $affiliate (keys(%{$affiliatesref})) {
7073: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 7074: }
7075: $cmd =~ s/%%$//;
7076: $cmd = &escape($cmd);
7077: my $query = 'institutionalphotos';
7078: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
7079: unless ($queryid=~/^\Q$host\E\_/) {
7080: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
7081: return 'error: '.$queryid;
7082: }
7083: my $reply = &get_query_reply($queryid);
7084: my $tries = 1;
7085: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
7086: $reply = &get_query_reply($queryid);
7087: $tries ++;
7088: }
7089: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
7090: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
7091: } else {
7092: my @responses = split(/:/,$reply);
7093: my $outcome = shift(@responses);
7094: foreach my $item (@responses) {
7095: my ($key,$value) = split(/=/,$item);
7096: $$photo{$key} = $value;
7097: }
7098: return $outcome;
7099: }
7100: return 'error';
7101: }
7102:
1.521 raeburn 7103: sub auto_instcode_format {
1.793 albertel 7104: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
7105: $cat_order) = @_;
1.521 raeburn 7106: my $courses = '';
1.772 raeburn 7107: my @homeservers;
1.521 raeburn 7108: if ($caller eq 'global') {
1.841 albertel 7109: my %servers = &get_servers($codedom,'library');
7110: foreach my $tryserver (keys(%servers)) {
7111: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7112: push(@homeservers,$tryserver);
7113: }
1.584 raeburn 7114: }
1.1022 raeburn 7115: } elsif ($caller eq 'requests') {
7116: if ($codedom =~ /^$match_domain$/) {
7117: my $chome = &domain($codedom,'primary');
7118: unless ($chome eq 'no_host') {
7119: push(@homeservers,$chome);
7120: }
7121: }
1.521 raeburn 7122: } else {
1.772 raeburn 7123: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 7124: }
1.793 albertel 7125: foreach my $code (keys(%{$instcodes})) {
7126: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 7127: }
7128: chop($courses);
1.772 raeburn 7129: my $ok_response = 0;
7130: my $response;
7131: while (@homeservers > 0 && $ok_response == 0) {
7132: my $server = shift(@homeservers);
7133: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
7134: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
7135: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 7136: split(/:/,$response);
1.772 raeburn 7137: %{$codes} = (%{$codes},&str2hash($codes_str));
7138: push(@{$codetitles},&str2array($codetitles_str));
7139: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
7140: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
7141: $ok_response = 1;
7142: }
7143: }
7144: if ($ok_response) {
1.521 raeburn 7145: return 'ok';
1.772 raeburn 7146: } else {
7147: return $response;
1.521 raeburn 7148: }
7149: }
7150:
1.792 raeburn 7151: sub auto_instcode_defaults {
7152: my ($domain,$returnhash,$code_order) = @_;
7153: my @homeservers;
1.841 albertel 7154:
7155: my %servers = &get_servers($domain,'library');
7156: foreach my $tryserver (keys(%servers)) {
7157: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7158: push(@homeservers,$tryserver);
7159: }
1.792 raeburn 7160: }
1.841 albertel 7161:
1.792 raeburn 7162: my $response;
1.841 albertel 7163: foreach my $server (@homeservers) {
1.792 raeburn 7164: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 7165: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
7166:
7167: foreach my $pair (split(/\&/,$response)) {
7168: my ($name,$value)=split(/\=/,$pair);
7169: if ($name eq 'code_order') {
7170: @{$code_order} = split(/\&/,&unescape($value));
7171: } else {
7172: $returnhash->{&unescape($name)}=&unescape($value);
7173: }
7174: }
7175: return 'ok';
1.792 raeburn 7176: }
1.841 albertel 7177:
7178: return $response;
1.1003 raeburn 7179: }
7180:
7181: sub auto_possible_instcodes {
1.1007 raeburn 7182: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
7183: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
7184: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
7185: return;
7186: }
1.1003 raeburn 7187: my (@homeservers,$uhome);
7188: if (defined(&domain($domain,'primary'))) {
7189: $uhome=&domain($domain,'primary');
7190: push(@homeservers,&domain($domain,'primary'));
7191: } else {
7192: my %servers = &get_servers($domain,'library');
7193: foreach my $tryserver (keys(%servers)) {
7194: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7195: push(@homeservers,$tryserver);
7196: }
7197: }
7198: }
7199: my $response;
7200: foreach my $server (@homeservers) {
7201: $response=&reply('autopossibleinstcodes:'.$domain,$server);
7202: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 7203: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
7204: split(':',$response);
7205: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
7206: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 7207: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 7208: my ($name,$value)=split('=',$item);
7209: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 7210: }
7211: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 7212: my ($name,$value)=split('=',$item);
7213: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 7214: }
7215: return 'ok';
7216: }
7217: return $response;
7218: }
1.792 raeburn 7219:
1.1010 raeburn 7220: sub auto_courserequest_checks {
7221: my ($dom) = @_;
1.1020 raeburn 7222: my ($homeserver,%validations);
7223: if ($dom =~ /^$match_domain$/) {
7224: $homeserver = &domain($dom,'primary');
7225: }
7226: unless ($homeserver eq 'no_host') {
7227: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
7228: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
7229: my @items = split(/&/,$response);
7230: foreach my $item (@items) {
7231: my ($key,$value) = split('=',$item);
7232: $validations{&unescape($key)} = &thaw_unescape($value);
7233: }
7234: }
7235: }
1.1010 raeburn 7236: return %validations;
7237: }
7238:
1.1020 raeburn 7239: sub auto_courserequest_validation {
7240: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
7241: my ($homeserver,$response);
7242: if ($dom =~ /^$match_domain$/) {
7243: $homeserver = &domain($dom,'primary');
7244: }
7245: unless ($homeserver eq 'no_host') {
1.1021 raeburn 7246:
1.1020 raeburn 7247: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 7248: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020 raeburn 7249: ':'.&escape($instcode).':'.&escape($instseclist),
7250: $homeserver));
7251: }
7252: return $response;
7253: }
7254:
1.777 albertel 7255: sub auto_validate_class_sec {
1.918 raeburn 7256: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 7257: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 7258: my $ownerlist;
7259: if (ref($owners) eq 'ARRAY') {
7260: $ownerlist = join(',',@{$owners});
7261: } else {
7262: $ownerlist = $owners;
7263: }
1.773 raeburn 7264: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 7265: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 7266: return $response;
7267: }
7268:
1.679 raeburn 7269: # ------------------------------------------------------- Course Group routines
7270:
7271: sub get_coursegroups {
1.809 raeburn 7272: my ($cdom,$cnum,$group,$namespace) = @_;
7273: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 7274: }
7275:
1.679 raeburn 7276: sub modify_coursegroup {
7277: my ($cdom,$cnum,$groupsettings) = @_;
7278: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
7279: }
7280:
1.809 raeburn 7281: sub toggle_coursegroup_status {
7282: my ($cdom,$cnum,$group,$action) = @_;
7283: my ($from_namespace,$to_namespace);
7284: if ($action eq 'delete') {
7285: $from_namespace = 'coursegroups';
7286: $to_namespace = 'deleted_groups';
7287: } else {
7288: $from_namespace = 'deleted_groups';
7289: $to_namespace = 'coursegroups';
7290: }
7291: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 7292: if (my $tmp = &error(%curr_group)) {
7293: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
7294: return ('read error',$tmp);
7295: } else {
7296: my %savedsettings = %curr_group;
1.809 raeburn 7297: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 7298: my $deloutcome;
7299: if ($result eq 'ok') {
1.809 raeburn 7300: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 7301: } else {
7302: return ('write error',$result);
7303: }
7304: if ($deloutcome eq 'ok') {
7305: return 'ok';
7306: } else {
7307: return ('delete error',$deloutcome);
7308: }
7309: }
7310: }
7311:
1.679 raeburn 7312: sub modify_group_roles {
1.957 raeburn 7313: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 7314: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
7315: my $role = 'gr/'.&escape($userprivs);
7316: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 7317: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 7318: if ($result eq 'ok') {
7319: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
7320: }
1.679 raeburn 7321: return $result;
7322: }
7323:
7324: sub modify_coursegroup_membership {
7325: my ($cdom,$cnum,$membership) = @_;
7326: my $result = &put('groupmembership',$membership,$cdom,$cnum);
7327: return $result;
7328: }
7329:
1.682 raeburn 7330: sub get_active_groups {
7331: my ($udom,$uname,$cdom,$cnum) = @_;
7332: my $now = time;
7333: my %groups = ();
7334: foreach my $key (keys(%env)) {
1.811 albertel 7335: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 7336: my ($start,$end) = split(/\./,$env{$key});
7337: if (($end!=0) && ($end<$now)) { next; }
7338: if (($start!=0) && ($start>$now)) { next; }
7339: if ($1 eq $cdom && $2 eq $cnum) {
7340: $groups{$3} = $env{$key} ;
7341: }
7342: }
7343: }
7344: return %groups;
7345: }
7346:
1.683 raeburn 7347: sub get_group_membership {
7348: my ($cdom,$cnum,$group) = @_;
7349: return(&dump('groupmembership',$cdom,$cnum,$group));
7350: }
7351:
7352: sub get_users_groups {
7353: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 7354: my @usersgroups;
1.683 raeburn 7355: my $cachetime=1800;
7356:
7357: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 7358: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
7359: if (defined($cached)) {
1.734 albertel 7360: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 7361: } else {
7362: $grouplist = '';
1.816 raeburn 7363: my $courseurl = &courseid_to_courseurl($courseid);
1.1166 raeburn 7364: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 7365: my $access_end = $env{'course.'.$courseid.
7366: '.default_enrollment_end_date'};
7367: my $now = time;
7368: foreach my $key (keys(%roleshash)) {
7369: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
7370: my $group = $1;
7371: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
7372: my $start = $2;
7373: my $end = $1;
7374: if ($start == -1) { next; } # deleted from group
7375: if (($start!=0) && ($start>$now)) { next; }
7376: if (($end!=0) && ($end<$now)) {
7377: if ($access_end && $access_end < $now) {
7378: if ($access_end - $end < 86400) {
7379: push(@usersgroups,$group);
1.733 raeburn 7380: }
7381: }
1.817 raeburn 7382: next;
1.733 raeburn 7383: }
1.817 raeburn 7384: push(@usersgroups,$group);
1.683 raeburn 7385: }
7386: }
7387: }
1.817 raeburn 7388: @usersgroups = &sort_course_groups($courseid,@usersgroups);
7389: $grouplist = join(':',@usersgroups);
7390: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 7391: }
1.733 raeburn 7392: return @usersgroups;
1.683 raeburn 7393: }
7394:
7395: sub devalidate_getgroups_cache {
7396: my ($udom,$uname,$cdom,$cnum)=@_;
7397: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 7398:
1.683 raeburn 7399: my $hashid="$udom:$uname:$courseid";
7400: &devalidate_cache_new('getgroups',$hashid);
7401: }
7402:
1.12 www 7403: # ------------------------------------------------------------------ Plain Text
7404:
7405: sub plaintext {
1.988 raeburn 7406: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 7407: if ($short =~ m{^cr/}) {
1.758 albertel 7408: return (split('/',$short))[-1];
7409: }
1.742 raeburn 7410: if (!defined($cid)) {
7411: $cid = $env{'request.course.id'};
7412: }
7413: my %rolenames = (
1.1008 raeburn 7414: Course => 'std',
7415: Community => 'alt1',
1.742 raeburn 7416: );
1.1037 raeburn 7417: if ($cid ne '') {
7418: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
7419: unless ($forcedefault) {
7420: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
7421: &Apache::lonlocal::mt_escape(\$roletext);
7422: return &Apache::lonlocal::mt($roletext);
7423: }
7424: }
7425: }
7426: if ((defined($type)) && (defined($rolenames{$type})) &&
7427: (defined($rolenames{$type})) &&
7428: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 7429: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 7430: } elsif ($cid ne '') {
7431: my $crstype = $env{'course.'.$cid.'.type'};
7432: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
7433: (defined($prp{$short}{$rolenames{$crstype}}))) {
7434: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
7435: }
1.742 raeburn 7436: }
1.1037 raeburn 7437: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 7438: }
7439:
7440: # ----------------------------------------------------------------- Assign Role
7441:
7442: sub assignrole {
1.957 raeburn 7443: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
7444: $context)=@_;
1.21 www 7445: my $mrole;
7446: if ($role =~ /^cr\//) {
1.393 www 7447: my $cwosec=$url;
1.811 albertel 7448: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 7449: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 7450: my $refused = 1;
7451: if ($context eq 'requestcourses') {
7452: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
7453: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
7454: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
7455: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
7456: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
7457: if ($crsenv{'internal.courseowner'} eq
7458: $env{'user.name'}.':'.$env{'user.domain'}) {
7459: $refused = '';
7460: }
7461: }
7462: }
7463: }
7464: }
7465: if ($refused) {
7466: &logthis('Refused custom assignrole: '.
7467: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
7468: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
7469: return 'refused';
7470: }
1.104 www 7471: }
1.21 www 7472: $mrole='cr';
1.678 raeburn 7473: } elsif ($role =~ /^gr\//) {
7474: my $cwogrp=$url;
1.811 albertel 7475: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 7476: unless (&allowed('mdg',$cwogrp)) {
7477: &logthis('Refused group assignrole: '.
7478: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
7479: $env{'user.name'}.' at '.$env{'user.domain'});
7480: return 'refused';
7481: }
7482: $mrole='gr';
1.21 www 7483: } else {
1.82 www 7484: my $cwosec=$url;
1.811 albertel 7485: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 7486: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
7487: my $refused;
7488: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
7489: if (!(&allowed('c'.$role,$url))) {
7490: $refused = 1;
7491: }
7492: } else {
7493: $refused = 1;
7494: }
1.947 raeburn 7495: if ($refused) {
1.1045 raeburn 7496: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
7497: if (!$selfenroll && $context eq 'course') {
7498: my %crsenv;
7499: if ($role eq 'cc' || $role eq 'co') {
7500: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
7501: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
7502: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
7503: if ($crsenv{'internal.courseowner'} eq
7504: $env{'user.name'}.':'.$env{'user.domain'}) {
7505: $refused = '';
7506: }
7507: }
7508: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
7509: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
7510: if ($crsenv{'internal.courseowner'} eq
7511: $env{'user.name'}.':'.$env{'user.domain'}) {
7512: $refused = '';
7513: }
7514: }
7515: }
7516: }
7517: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 7518: $refused = '';
1.1017 raeburn 7519: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 7520: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 7521: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 7522: my $wrongcc;
7523: if ($cnum =~ /^$match_community$/) {
7524: $wrongcc = 1 if ($role eq 'cc');
7525: } else {
7526: $wrongcc = 1 if ($role eq 'co');
7527: }
7528: unless ($wrongcc) {
7529: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
7530: if ($crsenv{'internal.courseowner'} eq
7531: $env{'user.name'}.':'.$env{'user.domain'}) {
7532: $refused = '';
7533: }
1.1017 raeburn 7534: }
7535: }
1.1172.2.9 raeburn 7536: } elsif ($context eq 'requestauthor') {
7537: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
7538: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
7539: if ($env{'environment.requestauthor'} eq 'automatic') {
7540: $refused = '';
7541: } else {
7542: my %domdefaults = &get_domain_defaults($udom);
7543: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
7544: my $checkbystatus;
7545: if ($env{'user.adv'}) {
7546: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
7547: if ($disposition eq 'automatic') {
7548: $refused = '';
7549: } elsif ($disposition eq '') {
7550: $checkbystatus = 1;
7551: }
7552: } else {
7553: $checkbystatus = 1;
7554: }
7555: if ($checkbystatus) {
7556: if ($env{'environment.inststatus'}) {
7557: my @inststatuses = split(/,/,$env{'environment.inststatus'});
7558: foreach my $type (@inststatuses) {
7559: if (($type ne '') &&
7560: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
7561: $refused = '';
7562: }
7563: }
7564: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
7565: $refused = '';
7566: }
7567: }
7568: }
7569: }
7570: }
1.1017 raeburn 7571: }
7572: if ($refused) {
1.947 raeburn 7573: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
7574: ' '.$role.' '.$end.' '.$start.' by '.
7575: $env{'user.name'}.' at '.$env{'user.domain'});
7576: return 'refused';
7577: }
1.932 raeburn 7578: }
1.1131 raeburn 7579: } elsif ($role eq 'au') {
7580: if ($url ne '/'.$udom.'/') {
7581: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
7582: ' to assign author role for '.$uname.':'.$udom.
7583: ' in domain: '.$url.' refused (wrong domain).');
7584: return 'refused';
7585: }
1.104 www 7586: }
1.21 www 7587: $mrole=$role;
7588: }
1.620 albertel 7589: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 7590: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 7591: if ($end) { $command.='_'.$end; }
1.21 www 7592: if ($start) {
7593: if ($end) {
1.81 www 7594: $command.='_'.$start;
1.21 www 7595: } else {
1.81 www 7596: $command.='_0_'.$start;
1.21 www 7597: }
7598: }
1.739 raeburn 7599: my $origstart = $start;
7600: my $origend = $end;
1.957 raeburn 7601: my $delflag;
1.357 www 7602: # actually delete
7603: if ($deleteflag) {
1.373 www 7604: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 7605: # modify command to delete the role
1.620 albertel 7606: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 7607: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 7608: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 7609: # set start and finish to negative values for userrolelog
7610: $start=-1;
7611: $end=-1;
1.957 raeburn 7612: $delflag = 1;
1.357 www 7613: }
7614: }
7615: # send command
1.349 www 7616: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 7617: # log new user role if status is ok
1.349 www 7618: if ($answer eq 'ok') {
1.663 raeburn 7619: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.739 raeburn 7620: # for course roles, perform group memberships changes triggered by role change.
7621: unless ($role =~ /^gr/) {
7622: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957 raeburn 7623: $origstart,$selfenroll,$context);
1.739 raeburn 7624: }
1.1172.2.9 raeburn 7625: if (($role eq 'cc') || ($role eq 'in') ||
7626: ($role eq 'ep') || ($role eq 'ad') ||
7627: ($role eq 'ta') || ($role eq 'st') ||
7628: ($role=~/^cr/) || ($role eq 'gr') ||
7629: ($role eq 'co')) {
7630: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
7631: $selfenroll,$context);
7632: } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
7633: ($role eq 'au') || ($role eq 'dc')) {
7634: &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
7635: $context);
7636: } elsif (($role eq 'ca') || ($role eq 'aa')) {
7637: &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
7638: $context);
7639: }
1.1053 raeburn 7640: if ($role eq 'cc') {
7641: &autoupdate_coowners($url,$end,$start,$uname,$udom);
7642: }
1.349 www 7643: }
7644: return $answer;
1.169 harris41 7645: }
7646:
1.1053 raeburn 7647: sub autoupdate_coowners {
7648: my ($url,$end,$start,$uname,$udom) = @_;
7649: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
7650: if (($cdom ne '') && ($cnum ne '')) {
7651: my $now = time;
7652: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
7653: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
7654: my %coursehash = &coursedescription($cdom.'_'.$cnum);
7655: my $instcode = $coursehash{'internal.coursecode'};
7656: if ($instcode ne '') {
1.1056 raeburn 7657: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
7658: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 7659: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 7660: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
7661: if ($result eq 'valid') {
7662: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 7663: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
7664: push(@newcoowners,$coowner);
7665: }
7666: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
7667: push(@newcoowners,$uname.':'.$udom);
7668: }
7669: @newcoowners = sort(@newcoowners);
7670: } else {
7671: push(@newcoowners,$uname.':'.$udom);
7672: }
7673: } else {
7674: if ($coursehash{'internal.co-owners'}) {
7675: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
7676: unless ($coowner eq $uname.':'.$udom) {
7677: push(@newcoowners,$coowner);
7678: }
7679: }
7680: unless (@newcoowners > 0) {
7681: $delcoowners = 1;
7682: $coowners = '';
7683: }
7684: }
7685: }
7686: if (@newcoowners || $delcoowners) {
7687: &store_coowners($cdom,$cnum,$coursehash{'home'},
7688: $delcoowners,@newcoowners);
7689: }
7690: }
7691: }
7692: }
7693: }
7694: }
7695: }
7696:
7697: sub store_coowners {
7698: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
7699: my $cid = $cdom.'_'.$cnum;
7700: my ($coowners,$delresult,$putresult);
7701: if (@newcoowners) {
7702: $coowners = join(',',@newcoowners);
7703: my %coownershash = (
7704: 'internal.co-owners' => $coowners,
7705: );
7706: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
7707: if ($putresult eq 'ok') {
7708: if ($env{'course.'.$cid.'.num'} eq $cnum) {
7709: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
7710: }
7711: }
7712: }
7713: if ($delcoowners) {
7714: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
7715: if ($delresult eq 'ok') {
7716: if ($env{'course.'.$cid.'.internal.co-owners'}) {
7717: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
7718: }
7719: }
7720: }
7721: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
7722: my %crsinfo =
7723: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
7724: if (ref($crsinfo{$cid}) eq 'HASH') {
7725: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
7726: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
7727: }
7728: }
7729: }
7730:
1.169 harris41 7731: # -------------------------------------------------- Modify user authentication
1.197 www 7732: # Overrides without validation
7733:
1.169 harris41 7734: sub modifyuserauth {
7735: my ($udom,$uname,$umode,$upass)=@_;
7736: my $uhome=&homeserver($uname,$udom);
1.197 www 7737: unless (&allowed('mau',$udom)) { return 'refused'; }
7738: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 7739: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
7740: ' in domain '.$env{'request.role.domain'});
1.169 harris41 7741: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
7742: &escape($upass),$uhome);
1.620 albertel 7743: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 7744: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
7745: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
7746: &log($udom,,$uname,$uhome,
1.620 albertel 7747: 'Authentication changed by '.$env{'user.domain'}.', '.
7748: $env{'user.name'}.', '.$umode.
1.197 www 7749: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 7750: unless ($reply eq 'ok') {
1.197 www 7751: &logthis('Authentication mode error: '.$reply);
1.169 harris41 7752: return 'error: '.$reply;
7753: }
1.170 harris41 7754: return 'ok';
1.80 www 7755: }
7756:
1.81 www 7757: # --------------------------------------------------------------- Modify a user
1.80 www 7758:
1.81 www 7759: sub modifyuser {
1.206 matthew 7760: my ($udom, $uname, $uid,
7761: $umode, $upass, $first,
7762: $middle, $last, $gene,
1.1058 raeburn 7763: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 7764: $udom= &LONCAPA::clean_domain($udom);
7765: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 7766: my $showcandelete = 'none';
7767: if (ref($candelete) eq 'ARRAY') {
7768: if (@{$candelete} > 0) {
7769: $showcandelete = join(', ',@{$candelete});
7770: }
7771: }
1.81 www 7772: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 7773: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 7774: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 7775: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
7776: ' desiredhome not specified').
1.620 albertel 7777: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
7778: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 7779: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 7780: my $newuser;
7781: if ($uhome eq 'no_host') {
7782: $newuser = 1;
7783: }
1.80 www 7784: # ----------------------------------------------------------------- Create User
1.406 albertel 7785: if (($uhome eq 'no_host') &&
7786: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 7787: my $unhome='';
1.844 albertel 7788: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 7789: $unhome = $desiredhome;
1.620 albertel 7790: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
7791: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 7792: } else { # load balancing routine for determining $unhome
1.81 www 7793: my $loadm=10000000;
1.841 albertel 7794: my %servers = &get_servers($udom,'library');
7795: foreach my $tryserver (keys(%servers)) {
7796: my $answer=reply('load',$tryserver);
7797: if (($answer=~/\d+/) && ($answer<$loadm)) {
7798: $loadm=$answer;
7799: $unhome=$tryserver;
7800: }
1.80 www 7801: }
7802: }
7803: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 7804: return 'error: unable to find a home server for '.$uname.
7805: ' in domain '.$udom;
1.80 www 7806: }
7807: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
7808: &escape($upass),$unhome);
7809: unless ($reply eq 'ok') {
7810: return 'error: '.$reply;
7811: }
1.230 stredwic 7812: $uhome=&homeserver($uname,$udom,'true');
1.80 www 7813: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 7814: return 'error: unable verify users home machine.';
1.80 www 7815: }
1.209 matthew 7816: } # End of creation of new user
1.80 www 7817: # ---------------------------------------------------------------------- Add ID
7818: if ($uid) {
7819: $uid=~tr/A-Z/a-z/;
7820: my %uidhash=&idrget($udom,$uname);
1.196 www 7821: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
7822: && (!$forceid)) {
1.80 www 7823: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 7824: return 'error: user id "'.$uid.'" does not match '.
7825: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 7826: }
7827: } else {
7828: &idput($udom,($uname => $uid));
7829: }
7830: }
7831: # -------------------------------------------------------------- Add names, etc
1.313 matthew 7832: my @tmp=&get('environment',
1.899 raeburn 7833: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 7834: 'permanentemail','inststatus'],
1.134 albertel 7835: $udom,$uname);
1.1075 raeburn 7836: my (%names,%oldnames);
1.313 matthew 7837: if ($tmp[0] =~ m/^error:.*/) {
7838: %names=();
7839: } else {
7840: %names = @tmp;
1.1075 raeburn 7841: %oldnames = %names;
1.313 matthew 7842: }
1.388 www 7843: #
1.1058 raeburn 7844: # If name, email and/or uid are blank (e.g., because an uploaded file
7845: # of users did not contain them), do not overwrite existing values
7846: # unless field is in $candelete array ref.
7847: #
7848:
7849: my @fields = ('firstname','middlename','lastname','generation',
7850: 'permanentemail','id');
7851: my %newvalues;
7852: if (ref($candelete) eq 'ARRAY') {
7853: foreach my $field (@fields) {
7854: if (grep(/^\Q$field\E$/,@{$candelete})) {
7855: if ($field eq 'firstname') {
7856: $names{$field} = $first;
7857: } elsif ($field eq 'middlename') {
7858: $names{$field} = $middle;
7859: } elsif ($field eq 'lastname') {
7860: $names{$field} = $last;
7861: } elsif ($field eq 'generation') {
7862: $names{$field} = $gene;
7863: } elsif ($field eq 'permanentemail') {
7864: $names{$field} = $email;
7865: } elsif ($field eq 'id') {
7866: $names{$field} = $uid;
7867: }
7868: }
7869: }
7870: }
1.388 www 7871: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 7872: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 7873: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 7874: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 7875: if ($email) {
7876: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 7877: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 7878: }
1.899 raeburn 7879: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 7880: if (defined($inststatus)) {
7881: $names{'inststatus'} = '';
7882: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
7883: if (ref($usertypes) eq 'HASH') {
7884: my @okstatuses;
7885: foreach my $item (split(/:/,$inststatus)) {
7886: if (defined($usertypes->{$item})) {
7887: push(@okstatuses,$item);
7888: }
7889: }
7890: if (@okstatuses) {
7891: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
7892: }
7893: }
7894: }
1.1075 raeburn 7895: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 7896: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 7897: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 7898: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
7899: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
7900: } else {
7901: $logmsg .= ' during self creation';
7902: }
1.1075 raeburn 7903: my $changed;
7904: if ($newuser) {
7905: $changed = 1;
7906: } else {
7907: foreach my $field (@fields) {
7908: if ($names{$field} ne $oldnames{$field}) {
7909: $changed = 1;
7910: last;
7911: }
7912: }
7913: }
7914: unless ($changed) {
7915: $logmsg = 'No changes in user information needed for: '.$logmsg;
7916: &logthis($logmsg);
7917: return 'ok';
7918: }
7919: my $reply = &put('environment', \%names, $udom,$uname);
7920: if ($reply ne 'ok') {
7921: return 'error: '.$reply;
7922: }
1.1087 raeburn 7923: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
7924: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
7925: }
1.1075 raeburn 7926: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
7927: &devalidate_cache_new('namescache',$uname.':'.$udom);
7928: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 7929: &logthis($logmsg);
1.134 albertel 7930: return 'ok';
1.80 www 7931: }
7932:
1.81 www 7933: # -------------------------------------------------------------- Modify student
1.80 www 7934:
1.81 www 7935: sub modifystudent {
7936: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 7937: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.990 raeburn 7938: $selfenroll,$context,$inststatus)=@_;
1.455 albertel 7939: if (!$cid) {
1.620 albertel 7940: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 7941: return 'not_in_class';
7942: }
1.80 www 7943: }
7944: # --------------------------------------------------------------- Make the user
1.81 www 7945: my $reply=&modifyuser
1.209 matthew 7946: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 7947: $desiredhome,$email,$inststatus);
1.80 www 7948: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 7949: # This will cause &modify_student_enrollment to get the uid from the
7950: # students environment
7951: $uid = undef if (!$forceid);
1.455 albertel 7952: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957 raeburn 7953: $gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297 matthew 7954: return $reply;
7955: }
7956:
7957: sub modify_student_enrollment {
1.957 raeburn 7958: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455 albertel 7959: my ($cdom,$cnum,$chome);
7960: if (!$cid) {
1.620 albertel 7961: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 7962: return 'not_in_class';
7963: }
1.620 albertel 7964: $cdom=$env{'course.'.$cid.'.domain'};
7965: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 7966: } else {
7967: ($cdom,$cnum)=split(/_/,$cid);
7968: }
1.620 albertel 7969: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 7970: if (!$chome) {
1.457 raeburn 7971: $chome=&homeserver($cnum,$cdom);
1.297 matthew 7972: }
1.455 albertel 7973: if (!$chome) { return 'unknown_course'; }
1.297 matthew 7974: # Make sure the user exists
1.81 www 7975: my $uhome=&homeserver($uname,$udom);
7976: if (($uhome eq '') || ($uhome eq 'no_host')) {
7977: return 'error: no such user';
7978: }
1.297 matthew 7979: # Get student data if we were not given enough information
7980: if (!defined($first) || $first eq '' ||
7981: !defined($last) || $last eq '' ||
7982: !defined($uid) || $uid eq '' ||
7983: !defined($middle) || $middle eq '' ||
7984: !defined($gene) || $gene eq '') {
1.294 matthew 7985: # They did not supply us with enough data to enroll the student, so
7986: # we need to pick up more information.
1.297 matthew 7987: my %tmp = &get('environment',
1.294 matthew 7988: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 7989: ,$udom,$uname);
7990:
1.800 albertel 7991: #foreach my $key (keys(%tmp)) {
7992: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 7993: #}
1.294 matthew 7994: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
7995: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
7996: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 7997: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 7998: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
7999: }
1.556 albertel 8000: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148 raeburn 8001: my $user = "$uname:$udom";
8002: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487 albertel 8003: my $reply=cput('classlist',
1.1148 raeburn 8004: {$user =>
1.515 raeburn 8005: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487 albertel 8006: $cdom,$cnum);
1.1148 raeburn 8007: if (($reply eq 'ok') || ($reply eq 'delayed')) {
8008: &devalidate_getsection_cache($udom,$uname,$cid);
8009: } else {
1.81 www 8010: return 'error: '.$reply;
8011: }
1.297 matthew 8012: # Add student role to user
1.83 www 8013: my $uurl='/'.$cid;
1.81 www 8014: $uurl=~s/\_/\//g;
8015: if ($usec) {
8016: $uurl.='/'.$usec;
8017: }
1.1148 raeburn 8018: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
8019: $selfenroll,$context);
8020: if ($result ne 'ok') {
8021: if ($old_entry{$user} ne '') {
8022: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
8023: } else {
8024: $reply = &del('classlist',[$user],$cdom,$cnum);
8025: }
8026: }
8027: return $result;
1.21 www 8028: }
8029:
1.556 albertel 8030: sub format_name {
8031: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
8032: my $name;
8033: if ($first ne 'lastname') {
8034: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
8035: } else {
8036: if ($lastname=~/\S/) {
8037: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
8038: $name=~s/\s+,/,/;
8039: } else {
8040: $name.= $firstname.' '.$middlename.' '.$generation;
8041: }
8042: }
8043: $name=~s/^\s+//;
8044: $name=~s/\s+$//;
8045: $name=~s/\s+/ /g;
8046: return $name;
8047: }
8048:
1.84 www 8049: # ------------------------------------------------- Write to course preferences
8050:
8051: sub writecoursepref {
8052: my ($courseid,%prefs)=@_;
8053: $courseid=~s/^\///;
8054: $courseid=~s/\_/\//g;
8055: my ($cdomain,$cnum)=split(/\//,$courseid);
8056: my $chome=homeserver($cnum,$cdomain);
8057: if (($chome eq '') || ($chome eq 'no_host')) {
8058: return 'error: no such course';
8059: }
8060: my $cstring='';
1.800 albertel 8061: foreach my $pref (keys(%prefs)) {
8062: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 8063: }
1.84 www 8064: $cstring=~s/\&$//;
8065: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
8066: }
8067:
8068: # ---------------------------------------------------------- Make/modify course
8069:
8070: sub createcourse {
1.741 raeburn 8071: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 8072: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 8073: $url=&declutter($url);
8074: my $cid='';
1.1028 raeburn 8075: if ($context eq 'requestcourses') {
8076: my $can_create = 0;
8077: my ($ownername,$ownerdom) = split(':',$course_owner);
8078: if ($udom eq $ownerdom) {
8079: if (&usertools_access($ownername,$ownerdom,$category,undef,
8080: $context)) {
8081: $can_create = 1;
8082: }
8083: } else {
8084: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
8085: $category);
8086: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
8087: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
8088: if (@curr > 0) {
8089: my @options = qw(approval validate autolimit);
8090: my $optregex = join('|',@options);
8091: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
8092: $can_create = 1;
8093: }
8094: }
8095: }
8096: }
8097: if ($can_create) {
8098: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
8099: unless (&allowed('ccc',$udom)) {
8100: return 'refused';
8101: }
1.1017 raeburn 8102: }
8103: } else {
8104: return 'refused';
8105: }
1.1028 raeburn 8106: } elsif (!&allowed('ccc',$udom)) {
8107: return 'refused';
1.84 www 8108: }
1.1011 raeburn 8109: # --------------------------------------------------------------- Get Unique ID
8110: my $uname;
8111: if ($cnum =~ /^$match_courseid$/) {
8112: my $chome=&homeserver($cnum,$udom,'true');
8113: if (($chome eq '') || ($chome eq 'no_host')) {
8114: $uname = $cnum;
8115: } else {
1.1038 raeburn 8116: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 8117: }
8118: } else {
1.1038 raeburn 8119: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 8120: }
8121: return $uname if ($uname =~ /^error/);
8122: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 8123: if (!defined($course_server)) {
8124: if (defined(&domain($udom,'primary'))) {
8125: $course_server = &domain($udom,'primary');
8126: } else {
8127: $course_server = $env{'user.home'};
8128: }
8129: }
8130: my %host_servers =
8131: &Apache::lonnet::get_servers($udom,'library');
8132: unless ($host_servers{$course_server}) {
8133: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 8134: }
1.84 www 8135: # ------------------------------------------------------------- Make the course
8136: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 8137: $course_server);
1.84 www 8138: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 8139: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 8140: if (($uhome eq '') || ($uhome eq 'no_host')) {
8141: return 'error: no such course';
8142: }
1.271 www 8143: # ----------------------------------------------------------------- Course made
1.516 raeburn 8144: # log existence
1.1029 raeburn 8145: my $now = time;
1.918 raeburn 8146: my $newcourse = {
8147: $udom.'_'.$uname => {
1.921 raeburn 8148: description => $description,
8149: inst_code => $inst_code,
8150: owner => $course_owner,
8151: type => $crstype,
1.1029 raeburn 8152: creator => $env{'user.name'}.':'.
8153: $env{'user.domain'},
8154: created => $now,
8155: context => $context,
1.918 raeburn 8156: },
8157: };
1.921 raeburn 8158: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 8159: # set toplevel url
1.271 www 8160: my $topurl=$url;
8161: unless ($nonstandard) {
8162: # ------------------------------------------ For standard courses, make top url
8163: my $mapurl=&clutter($url);
1.278 www 8164: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 8165: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 8166: <map>
8167: <resource id="1" type="start"></resource>
8168: <resource id="2" src="$mapurl"></resource>
8169: <resource id="3" type="finish"></resource>
8170: <link index="1" from="1" to="2"></link>
8171: <link index="2" from="2" to="3"></link>
8172: </map>
8173: ENDINITMAP
8174: $topurl=&declutter(
1.638 albertel 8175: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 8176: );
8177: }
8178: # ----------------------------------------------------------- Write preferences
1.84 www 8179: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 8180: ('description' => $description,
8181: 'url' => $topurl,
8182: 'internal.creator' => $env{'user.name'}.':'.
8183: $env{'user.domain'},
8184: 'internal.created' => $now,
8185: 'internal.creationcontext' => $context)
8186: );
1.84 www 8187: return '/'.$udom.'/'.$uname;
8188: }
8189:
1.1011 raeburn 8190: # ------------------------------------------------------------------- Create ID
8191: sub generate_coursenum {
1.1038 raeburn 8192: my ($udom,$crstype) = @_;
1.1011 raeburn 8193: my $domdesc = &domain($udom);
8194: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 8195: my $first;
8196: if ($crstype eq 'Community') {
8197: $first = '0';
8198: } else {
8199: $first = int(1+rand(9));
8200: }
8201: my $uname=$first.
1.1011 raeburn 8202: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
8203: substr($$.time,0,5).unpack("H8",pack("I32",time)).
8204: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
8205: # ----------------------------------------------- Make sure that does not exist
8206: my $uhome=&homeserver($uname,$udom,'true');
8207: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 8208: if ($crstype eq 'Community') {
8209: $first = '0';
8210: } else {
8211: $first = int(1+rand(9));
8212: }
8213: $uname=$first.
1.1011 raeburn 8214: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
8215: substr($$.time,0,5).unpack("H8",pack("I32",time)).
8216: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
8217: $uhome=&homeserver($uname,$udom,'true');
8218: unless (($uhome eq '') || ($uhome eq 'no_host')) {
8219: return 'error: unable to generate unique course-ID';
8220: }
8221: }
8222: return $uname;
8223: }
8224:
1.813 albertel 8225: sub is_course {
1.1167 droeschl 8226: my ($cdom, $cnum) = scalar(@_) == 1 ?
8227: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
8228:
8229: return unless $cdom and $cnum;
8230:
8231: my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
8232: '.');
8233:
8234: return unless exists($courses{$cdom.'_'.$cnum});
8235: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813 albertel 8236: }
8237:
1.1015 raeburn 8238: sub store_userdata {
8239: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 8240: my $result;
1.1016 raeburn 8241: if ($datakey ne '') {
1.1013 raeburn 8242: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 8243: if ($udom eq '' || $uname eq '') {
8244: $udom = $env{'user.domain'};
8245: $uname = $env{'user.name'};
8246: }
8247: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 8248: if (($uhome eq '') || ($uhome eq 'no_host')) {
8249: $result = 'error: no_host';
8250: } else {
8251: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
8252: $storehash->{'host'} = $perlvar{'lonHostID'};
8253:
8254: my $namevalue='';
8255: foreach my $key (keys(%{$storehash})) {
8256: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
8257: }
8258: $namevalue=~s/\&$//;
1.1105 raeburn 8259: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
8260: $namevalue,$uhome);
1.1013 raeburn 8261: }
8262: } else {
8263: $result = 'error: data to store was not a hash reference';
8264: }
8265: } else {
8266: $result= 'error: invalid requestkey';
8267: }
8268: return $result;
8269: }
8270:
1.21 www 8271: # ---------------------------------------------------------- Assign Custom Role
8272:
8273: sub assigncustomrole {
1.957 raeburn 8274: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 8275: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 8276: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 8277: }
8278:
8279: # ----------------------------------------------------------------- Revoke Role
8280:
8281: sub revokerole {
1.957 raeburn 8282: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 8283: my $now=time;
1.965 raeburn 8284: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 8285: }
8286:
8287: # ---------------------------------------------------------- Revoke Custom Role
8288:
8289: sub revokecustomrole {
1.957 raeburn 8290: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 8291: my $now=time;
1.357 www 8292: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 8293: $deleteflag,$selfenroll,$context);
1.17 www 8294: }
8295:
1.533 banghart 8296: # ------------------------------------------------------------ Disk usage
1.535 albertel 8297: sub diskusage {
1.955 raeburn 8298: my ($udom,$uname,$directorypath,$getpropath)=@_;
8299: $directorypath =~ s/\/$//;
8300: my $listing=&reply('du2:'.&escape($directorypath).':'
8301: .&escape($getpropath).':'.&escape($uname).':'
8302: .&escape($udom),homeserver($uname,$udom));
8303: if ($listing eq 'unknown_cmd') {
8304: if ($getpropath) {
8305: $directorypath = &propath($udom,$uname).'/'.$directorypath;
8306: }
8307: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
8308: }
1.514 albertel 8309: return $listing;
1.512 banghart 8310: }
8311:
1.566 banghart 8312: sub is_locked {
1.1096 raeburn 8313: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 8314: my @check;
8315: my $is_locked;
1.1093 raeburn 8316: push (@check,$file_name);
1.613 albertel 8317: my %locked = &get('file_permissions',\@check,
1.620 albertel 8318: $env{'user.domain'},$env{'user.name'});
1.615 albertel 8319: my ($tmp)=keys(%locked);
8320: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 8321:
1.566 banghart 8322: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 8323: $is_locked = 'false';
8324: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 8325: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 8326: $is_locked = 'true';
1.1096 raeburn 8327: if (ref($which) eq 'ARRAY') {
8328: push(@{$which},$entry);
8329: } else {
8330: last;
8331: }
1.745 raeburn 8332: }
8333: }
1.566 banghart 8334: } else {
8335: $is_locked = 'false';
8336: }
1.1093 raeburn 8337: return $is_locked;
1.566 banghart 8338: }
8339:
1.759 albertel 8340: sub declutter_portfile {
8341: my ($file) = @_;
1.833 albertel 8342: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 8343: return $file;
8344: }
8345:
1.559 banghart 8346: # ------------------------------------------------------------- Mark as Read Only
8347:
8348: sub mark_as_readonly {
8349: my ($domain,$user,$files,$what) = @_;
1.613 albertel 8350: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 8351: my ($tmp)=keys(%current_permissions);
8352: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 8353: foreach my $file (@{$files}) {
1.759 albertel 8354: $file = &declutter_portfile($file);
1.561 banghart 8355: push(@{$current_permissions{$file}},$what);
1.559 banghart 8356: }
1.613 albertel 8357: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 8358: return;
8359: }
8360:
1.572 banghart 8361: # ------------------------------------------------------------Save Selected Files
8362:
8363: sub save_selected_files {
8364: my ($user, $path, @files) = @_;
8365: my $filename = $user."savedfiles";
1.573 banghart 8366: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 8367: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 8368: foreach my $file (@files) {
1.620 albertel 8369: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 8370: }
8371: foreach my $file (@other_files) {
1.574 banghart 8372: print (OUT $file."\n");
1.572 banghart 8373: }
1.574 banghart 8374: close (OUT);
1.572 banghart 8375: return 'ok';
8376: }
8377:
1.574 banghart 8378: sub clear_selected_files {
8379: my ($user) = @_;
8380: my $filename = $user."savedfiles";
1.1117 foxr 8381: open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574 banghart 8382: print (OUT undef);
8383: close (OUT);
8384: return ("ok");
8385: }
8386:
1.572 banghart 8387: sub files_in_path {
8388: my ($user, $path) = @_;
8389: my $filename = $user."savedfiles";
8390: my %return_files;
1.1117 foxr 8391: open (IN, '<'.LONCAPA::tempdir().$filename);
1.573 banghart 8392: while (my $line_in = <IN>) {
1.574 banghart 8393: chomp ($line_in);
8394: my @paths_and_file = split (m!/!, $line_in);
8395: my $file_part = pop (@paths_and_file);
8396: my $path_part = join ('/', @paths_and_file);
1.573 banghart 8397: $path_part.='/';
8398: my $path_and_file = $path_part.$file_part;
8399: if ($path_part eq $path) {
8400: $return_files{$file_part}= 'selected';
8401: }
8402: }
1.574 banghart 8403: close (IN);
8404: return (\%return_files);
1.572 banghart 8405: }
8406:
8407: # called in portfolio select mode, to show files selected NOT in current directory
8408: sub files_not_in_path {
8409: my ($user, $path) = @_;
8410: my $filename = $user."savedfiles";
8411: my @return_files;
8412: my $path_part;
1.1117 foxr 8413: open(IN, '<'.LONCAPA::.$filename);
1.800 albertel 8414: while (my $line = <IN>) {
1.572 banghart 8415: #ok, I know it's clunky, but I want it to work
1.800 albertel 8416: my @paths_and_file = split(m|/|, $line);
8417: my $file_part = pop(@paths_and_file);
8418: chomp($file_part);
8419: my $path_part = join('/', @paths_and_file);
1.572 banghart 8420: $path_part .= '/';
8421: my $path_and_file = $path_part.$file_part;
8422: if ($path_part ne $path) {
1.800 albertel 8423: push(@return_files, ($path_and_file));
1.572 banghart 8424: }
8425: }
1.800 albertel 8426: close(OUT);
1.574 banghart 8427: return (@return_files);
1.572 banghart 8428: }
8429:
1.745 raeburn 8430: #----------------------------------------------Get portfolio file permissions
1.629 banghart 8431:
1.745 raeburn 8432: sub get_portfile_permissions {
8433: my ($domain,$user) = @_;
1.613 albertel 8434: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 8435: my ($tmp)=keys(%current_permissions);
8436: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 8437: return \%current_permissions;
8438: }
8439:
8440: #---------------------------------------------Get portfolio file access controls
8441:
1.749 raeburn 8442: sub get_access_controls {
1.745 raeburn 8443: my ($current_permissions,$group,$file) = @_;
1.769 albertel 8444: my %access;
8445: my $real_file = $file;
8446: $file =~ s/\.meta$//;
1.745 raeburn 8447: if (defined($file)) {
1.749 raeburn 8448: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
8449: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 8450: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 8451: }
8452: }
1.745 raeburn 8453: } else {
1.749 raeburn 8454: foreach my $key (keys(%{$current_permissions})) {
8455: if ($key =~ /\0accesscontrol$/) {
8456: if (defined($group)) {
8457: if ($key !~ m-^\Q$group\E/-) {
8458: next;
8459: }
8460: }
8461: my ($fullpath) = split(/\0/,$key);
8462: if (ref($$current_permissions{$key}) eq 'HASH') {
8463: foreach my $control (keys(%{$$current_permissions{$key}})) {
8464: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
8465: }
8466: }
8467: }
8468: }
8469: }
8470: return %access;
8471: }
8472:
8473: sub modify_access_controls {
8474: my ($file_name,$changes,$domain,$user)=@_;
8475: my ($outcome,$deloutcome);
8476: my %store_permissions;
8477: my %new_values;
8478: my %new_control;
8479: my %translation;
8480: my @deletions = ();
8481: my $now = time;
8482: if (exists($$changes{'activate'})) {
8483: if (ref($$changes{'activate'}) eq 'HASH') {
8484: my @newitems = sort(keys(%{$$changes{'activate'}}));
8485: my $numnew = scalar(@newitems);
8486: for (my $i=0; $i<$numnew; $i++) {
8487: my $newkey = $newitems[$i];
8488: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 8489: if ($newkey =~ /^\d+:/) {
8490: $newkey =~ s/^(\d+)/$newid/;
8491: $translation{$1} = $newid;
8492: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
8493: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
8494: $translation{$1} = $newid;
8495: }
1.749 raeburn 8496: $new_values{$file_name."\0".$newkey} =
8497: $$changes{'activate'}{$newitems[$i]};
8498: $new_control{$newkey} = $now;
8499: }
8500: }
8501: }
8502: my %todelete;
8503: my %changed_items;
8504: foreach my $action ('delete','update') {
8505: if (exists($$changes{$action})) {
8506: if (ref($$changes{$action}) eq 'HASH') {
8507: foreach my $key (keys(%{$$changes{$action}})) {
8508: my ($itemnum) = ($key =~ /^([^:]+):/);
8509: if ($action eq 'delete') {
8510: $todelete{$itemnum} = 1;
8511: } else {
8512: $changed_items{$itemnum} = $key;
8513: }
8514: }
1.745 raeburn 8515: }
8516: }
1.749 raeburn 8517: }
8518: # get lock on access controls for file.
8519: my $lockhash = {
8520: $file_name."\0".'locked_access_records' => $env{'user.name'}.
8521: ':'.$env{'user.domain'},
8522: };
8523: my $tries = 0;
8524: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
8525:
8526: while (($gotlock ne 'ok') && $tries <3) {
8527: $tries ++;
8528: sleep 1;
8529: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
8530: }
8531: if ($gotlock eq 'ok') {
8532: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
8533: my ($tmp)=keys(%curr_permissions);
8534: if ($tmp=~/^error:/) { undef(%curr_permissions); }
8535: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
8536: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
8537: if (ref($curr_controls) eq 'HASH') {
8538: foreach my $control_item (keys(%{$curr_controls})) {
8539: my ($itemnum) = ($control_item =~ /^([^:]+):/);
8540: if (defined($todelete{$itemnum})) {
8541: push(@deletions,$file_name."\0".$control_item);
8542: } else {
8543: if (defined($changed_items{$itemnum})) {
8544: $new_control{$changed_items{$itemnum}} = $now;
8545: push(@deletions,$file_name."\0".$control_item);
8546: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
8547: } else {
8548: $new_control{$control_item} = $$curr_controls{$control_item};
8549: }
8550: }
1.745 raeburn 8551: }
8552: }
8553: }
1.970 raeburn 8554: my ($group);
8555: if (&is_course($domain,$user)) {
8556: ($group,my $file) = split(/\//,$file_name,2);
8557: }
1.749 raeburn 8558: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
8559: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
8560: $outcome = &put('file_permissions',\%new_values,$domain,$user);
8561: # remove lock
8562: my @del_lock = ($file_name."\0".'locked_access_records');
8563: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 8564: my $sqlresult =
1.970 raeburn 8565: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 8566: $group);
1.749 raeburn 8567: } else {
8568: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 8569: }
1.749 raeburn 8570: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 8571: }
8572:
1.827 raeburn 8573: sub make_public_indefinitely {
8574: my ($requrl) = @_;
8575: my $now = time;
8576: my $action = 'activate';
8577: my $aclnum = 0;
8578: if (&is_portfolio_url($requrl)) {
8579: my (undef,$udom,$unum,$file_name,$group) =
8580: &parse_portfolio_url($requrl);
8581: my $current_perms = &get_portfile_permissions($udom,$unum);
8582: my %access_controls = &get_access_controls($current_perms,
8583: $group,$file_name);
8584: foreach my $key (keys(%{$access_controls{$file_name}})) {
8585: my ($num,$scope,$end,$start) =
8586: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
8587: if ($scope eq 'public') {
8588: if ($start <= $now && $end == 0) {
8589: $action = 'none';
8590: } else {
8591: $action = 'update';
8592: $aclnum = $num;
8593: }
8594: last;
8595: }
8596: }
8597: if ($action eq 'none') {
8598: return 'ok';
8599: } else {
8600: my %changes;
8601: my $newend = 0;
8602: my $newstart = $now;
8603: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
8604: $changes{$action}{$newkey} = {
8605: type => 'public',
8606: time => {
8607: start => $newstart,
8608: end => $newend,
8609: },
8610: };
8611: my ($outcome,$deloutcome,$new_values,$translation) =
8612: &modify_access_controls($file_name,\%changes,$udom,$unum);
8613: return $outcome;
8614: }
8615: } else {
8616: return 'invalid';
8617: }
8618: }
8619:
1.745 raeburn 8620: #------------------------------------------------------Get Marked as Read Only
8621:
8622: sub get_marked_as_readonly {
8623: my ($domain,$user,$what,$group) = @_;
8624: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 8625: my @readonly_files;
1.629 banghart 8626: my $cmp1=$what;
8627: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 8628: while (my ($file_name,$value) = each(%{$current_permissions})) {
8629: if (defined($group)) {
8630: if ($file_name !~ m-^\Q$group\E/-) {
8631: next;
8632: }
8633: }
1.561 banghart 8634: if (ref($value) eq "ARRAY"){
8635: foreach my $stored_what (@{$value}) {
1.629 banghart 8636: my $cmp2=$stored_what;
1.759 albertel 8637: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 8638: $cmp2=join('',@{$stored_what});
1.745 raeburn 8639: }
1.629 banghart 8640: if ($cmp1 eq $cmp2) {
1.561 banghart 8641: push(@readonly_files, $file_name);
1.745 raeburn 8642: last;
1.563 banghart 8643: } elsif (!defined($what)) {
8644: push(@readonly_files, $file_name);
1.745 raeburn 8645: last;
1.561 banghart 8646: }
8647: }
1.745 raeburn 8648: }
1.561 banghart 8649: }
8650: return @readonly_files;
8651: }
1.577 banghart 8652: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 8653:
1.577 banghart 8654: sub get_marked_as_readonly_hash {
1.745 raeburn 8655: my ($current_permissions,$group,$what) = @_;
1.577 banghart 8656: my %readonly_files;
1.745 raeburn 8657: while (my ($file_name,$value) = each(%{$current_permissions})) {
8658: if (defined($group)) {
8659: if ($file_name !~ m-^\Q$group\E/-) {
8660: next;
8661: }
8662: }
1.577 banghart 8663: if (ref($value) eq "ARRAY"){
8664: foreach my $stored_what (@{$value}) {
1.745 raeburn 8665: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 8666: foreach my $lock_descriptor(@{$stored_what}) {
8667: if ($lock_descriptor eq 'graded') {
8668: $readonly_files{$file_name} = 'graded';
8669: } elsif ($lock_descriptor eq 'handback') {
8670: $readonly_files{$file_name} = 'handback';
8671: } else {
8672: if (!exists($readonly_files{$file_name})) {
8673: $readonly_files{$file_name} = 'locked';
8674: }
8675: }
1.745 raeburn 8676: }
1.750 banghart 8677: }
1.577 banghart 8678: }
8679: }
8680: }
8681: return %readonly_files;
8682: }
1.559 banghart 8683: # ------------------------------------------------------------ Unmark as Read Only
8684:
8685: sub unmark_as_readonly {
1.629 banghart 8686: # unmarks $file_name (if $file_name is defined), or all files locked by $what
8687: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 8688: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 8689: $file_name = &declutter_portfile($file_name);
1.634 albertel 8690: my $symb_crs = $what;
8691: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 8692: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 8693: my ($tmp)=keys(%current_permissions);
8694: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 8695: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 8696: foreach my $file (@readonly_files) {
1.759 albertel 8697: my $clean_file = &declutter_portfile($file);
8698: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 8699: my $current_locks = $current_permissions{$file};
1.563 banghart 8700: my @new_locks;
8701: my @del_keys;
8702: if (ref($current_locks) eq "ARRAY"){
8703: foreach my $locker (@{$current_locks}) {
1.632 albertel 8704: my $compare=$locker;
1.749 raeburn 8705: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 8706: $compare=join('',@{$locker});
1.746 raeburn 8707: if ($compare ne $symb_crs) {
8708: push(@new_locks, $locker);
8709: }
1.563 banghart 8710: }
8711: }
1.650 albertel 8712: if (scalar(@new_locks) > 0) {
1.563 banghart 8713: $current_permissions{$file} = \@new_locks;
8714: } else {
8715: push(@del_keys, $file);
1.613 albertel 8716: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 8717: delete($current_permissions{$file});
1.563 banghart 8718: }
8719: }
1.561 banghart 8720: }
1.613 albertel 8721: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 8722: return;
8723: }
1.512 banghart 8724:
1.17 www 8725: # ------------------------------------------------------------ Directory lister
8726:
8727: sub dirlist {
1.955 raeburn 8728: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 8729: $uri=~s/^\///;
8730: $uri=~s/\/$//;
1.253 stredwic 8731: my ($udom, $uname);
1.955 raeburn 8732: if ($getuserdir) {
1.253 stredwic 8733: $udom = $userdomain;
8734: $uname = $username;
1.955 raeburn 8735: } else {
8736: (undef,$udom,$uname)=split(/\//,$uri);
8737: if(defined($userdomain)) {
8738: $udom = $userdomain;
8739: }
8740: if(defined($username)) {
8741: $uname = $username;
8742: }
1.253 stredwic 8743: }
1.955 raeburn 8744: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 8745:
1.955 raeburn 8746: $dirRoot = $perlvar{'lonDocRoot'};
8747: if (defined($getpropath)) {
8748: $dirRoot = &propath($udom,$uname);
1.253 stredwic 8749: $dirRoot =~ s/\/$//;
1.955 raeburn 8750: } elsif (defined($getuserdir)) {
8751: my $subdir=$uname.'__';
8752: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
8753: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
8754: ."/$udom/$subdir/$uname";
8755: } elsif (defined($alternateRoot)) {
8756: $dirRoot = $alternateRoot;
1.751 banghart 8757: }
1.253 stredwic 8758:
8759: if($udom) {
8760: if($uname) {
1.1135 raeburn 8761: my $uhome = &homeserver($uname,$udom);
1.1136 raeburn 8762: if ($uhome eq 'no_host') {
8763: return ([],'no_host');
8764: }
1.955 raeburn 8765: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 8766: .$getuserdir.':'.&escape($dirRoot)
1.1135 raeburn 8767: .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955 raeburn 8768: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 8769: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955 raeburn 8770: } else {
8771: @listing_results = map { &unescape($_); } split(/:/,$listing);
8772: }
1.605 matthew 8773: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 8774: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605 matthew 8775: @listing_results = split(/:/,$listing);
8776: } else {
8777: @listing_results = map { &unescape($_); } split(/:/,$listing);
8778: }
1.1135 raeburn 8779: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
1.1136 raeburn 8780: ($listing eq 'rejected') || ($listing eq 'refused') ||
8781: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
8782: return ([],$listing);
8783: } else {
8784: return (\@listing_results);
1.1135 raeburn 8785: }
1.955 raeburn 8786: } elsif(!$alternateRoot) {
1.1136 raeburn 8787: my (%allusers,%listerror);
1.841 albertel 8788: my %servers = &get_servers($udom,'library');
1.955 raeburn 8789: foreach my $tryserver (keys(%servers)) {
8790: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
8791: &escape($udom),$tryserver);
8792: if ($listing eq 'unknown_cmd') {
8793: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
8794: $udom, $tryserver);
8795: } else {
8796: @listing_results = map { &unescape($_); } split(/:/,$listing);
8797: }
1.841 albertel 8798: if ($listing eq 'unknown_cmd') {
8799: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
8800: $udom, $tryserver);
8801: @listing_results = split(/:/,$listing);
8802: } else {
8803: @listing_results =
8804: map { &unescape($_); } split(/:/,$listing);
8805: }
1.1136 raeburn 8806: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
8807: ($listing eq 'rejected') || ($listing eq 'refused') ||
8808: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
8809: $listerror{$tryserver} = $listing;
8810: } else {
1.841 albertel 8811: foreach my $line (@listing_results) {
8812: my ($entry) = split(/&/,$line,2);
8813: $allusers{$entry} = 1;
8814: }
8815: }
1.253 stredwic 8816: }
1.1136 raeburn 8817: my @alluserslist=();
1.800 albertel 8818: foreach my $user (sort(keys(%allusers))) {
1.1136 raeburn 8819: push(@alluserslist,$user.'&user');
1.253 stredwic 8820: }
1.1136 raeburn 8821: return (\@alluserslist);
1.253 stredwic 8822: } else {
1.1136 raeburn 8823: return ([],'missing username');
1.253 stredwic 8824: }
1.955 raeburn 8825: } elsif(!defined($getpropath)) {
1.1136 raeburn 8826: my $path = $perlvar{'lonDocRoot'}.'/res/';
8827: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
8828: return (\@all_domains);
1.955 raeburn 8829: } else {
1.1136 raeburn 8830: return ([],'missing domain');
1.275 stredwic 8831: }
8832: }
8833:
8834: # --------------------------------------------- GetFileTimestamp
8835: # This function utilizes dirlist and returns the date stamp for
8836: # when it was last modified. It will also return an error of -1
8837: # if an error occurs
8838:
8839: sub GetFileTimestamp {
1.955 raeburn 8840: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 8841: $studentDomain = &LONCAPA::clean_domain($studentDomain);
8842: $studentName = &LONCAPA::clean_username($studentName);
1.1136 raeburn 8843: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
8844: undef,$getuserdir);
8845: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
8846: return -1;
8847: }
8848: if (ref($fileref) eq 'ARRAY') {
8849: my @stats = split('&',$fileref->[0]);
1.375 matthew 8850: # @stats contains first the filename, then the stat output
8851: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 8852: } else {
8853: return -1;
1.253 stredwic 8854: }
1.26 www 8855: }
8856:
1.712 albertel 8857: sub stat_file {
8858: my ($uri) = @_;
1.787 albertel 8859: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 8860:
1.955 raeburn 8861: my ($udom,$uname,$file);
1.712 albertel 8862: if ($uri =~ m-^/(uploaded|editupload)/-) {
8863: ($udom,$uname,$file) =
1.811 albertel 8864: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 8865: $file = 'userfiles/'.$file;
8866: }
8867: if ($uri =~ m-^/res/-) {
8868: ($udom,$uname) =
1.807 albertel 8869: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 8870: $file = $uri;
8871: }
8872:
8873: if (!$udom || !$uname || !$file) {
8874: # unable to handle the uri
8875: return ();
8876: }
1.956 raeburn 8877: my $getpropath;
8878: if ($file =~ /^userfiles\//) {
8879: $getpropath = 1;
8880: }
1.1136 raeburn 8881: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
8882: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
8883: return ();
8884: } else {
8885: if (ref($listref) eq 'ARRAY') {
8886: my @stats = split('&',$listref->[0]);
8887: shift(@stats); #filename is first
8888: return @stats;
8889: }
1.712 albertel 8890: }
8891: return ();
8892: }
8893:
1.26 www 8894: # -------------------------------------------------------- Value of a Condition
8895:
1.713 albertel 8896: # gets the value of a specific preevaluated condition
8897: # stored in the string $env{user.state.<cid>}
8898: # or looks up a condition reference in the bighash and if if hasn't
8899: # already been evaluated recurses into docondval to get the value of
8900: # the condition, then memoizing it to
8901: # $env{user.state.<cid>.<condition>}
1.40 www 8902: sub directcondval {
8903: my $number=shift;
1.620 albertel 8904: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 8905: &Apache::lonuserstate::evalstate();
8906: }
1.713 albertel 8907: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
8908: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
8909: } elsif ($number =~ /^_/) {
8910: my $sub_condition;
8911: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
8912: &GDBM_READER(),0640)) {
8913: $sub_condition=$bighash{'conditions'.$number};
8914: untie(%bighash);
8915: }
8916: my $value = &docondval($sub_condition);
1.949 raeburn 8917: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 8918: return $value;
8919: }
1.620 albertel 8920: if ($env{'user.state.'.$env{'request.course.id'}}) {
8921: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 8922: } else {
8923: return 2;
8924: }
8925: }
8926:
1.713 albertel 8927: # get the collection of conditions for this resource
1.26 www 8928: sub condval {
8929: my $condidx=shift;
1.54 www 8930: my $allpathcond='';
1.713 albertel 8931: foreach my $cond (split(/\|/,$condidx)) {
8932: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
8933: $allpathcond.=
8934: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
8935: }
1.191 harris41 8936: }
1.54 www 8937: $allpathcond=~s/\|$//;
1.713 albertel 8938: return &docondval($allpathcond);
8939: }
8940:
8941: #evaluates an expression of conditions
8942: sub docondval {
8943: my ($allpathcond) = @_;
8944: my $result=0;
8945: if ($env{'request.course.id'}
8946: && defined($allpathcond)) {
8947: my $operand='|';
8948: my @stack;
8949: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
8950: if ($chunk eq '(') {
8951: push @stack,($operand,$result);
8952: } elsif ($chunk eq ')') {
8953: my $before=pop @stack;
8954: if (pop @stack eq '&') {
8955: $result=$result>$before?$before:$result;
8956: } else {
8957: $result=$result>$before?$result:$before;
8958: }
8959: } elsif (($chunk eq '&') || ($chunk eq '|')) {
8960: $operand=$chunk;
8961: } else {
8962: my $new=directcondval($chunk);
8963: if ($operand eq '&') {
8964: $result=$result>$new?$new:$result;
8965: } else {
8966: $result=$result>$new?$result:$new;
8967: }
8968: }
8969: }
1.26 www 8970: }
8971: return $result;
1.421 albertel 8972: }
8973:
8974: # ---------------------------------------------------- Devalidate courseresdata
8975:
8976: sub devalidatecourseresdata {
8977: my ($coursenum,$coursedomain)=@_;
8978: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 8979: &devalidate_cache_new('courseres',$hashid);
1.28 www 8980: }
8981:
1.763 www 8982:
1.200 www 8983: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 8984: #
8985: # Parameters:
8986: # $coursenum - Number of the course.
8987: # $coursedomain - Domain at which the course was created.
8988: # Returns:
8989: # A hash of the course parameters along (I think) with timestamps
8990: # and version info.
1.877 foxr 8991:
1.624 albertel 8992: sub get_courseresdata {
8993: my ($coursenum,$coursedomain)=@_;
1.200 www 8994: my $coursehom=&homeserver($coursenum,$coursedomain);
8995: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 8996: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 8997: my %dumpreply;
1.417 albertel 8998: unless (defined($cached)) {
1.624 albertel 8999: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 9000: $result=\%dumpreply;
1.251 albertel 9001: my ($tmp) = keys(%dumpreply);
9002: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 9003: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 9004: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
9005: return $tmp;
1.416 albertel 9006: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 9007: $result=undef;
1.599 albertel 9008: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 9009: }
9010: }
1.624 albertel 9011: return $result;
9012: }
9013:
1.633 albertel 9014: sub devalidateuserresdata {
9015: my ($uname,$udom)=@_;
9016: my $hashid="$udom:$uname";
9017: &devalidate_cache_new('userres',$hashid);
9018: }
9019:
1.624 albertel 9020: sub get_userresdata {
9021: my ($uname,$udom)=@_;
9022: #most student don\'t have any data set, check if there is some data
9023: if (&EXT_cache_status($udom,$uname)) { return undef; }
9024:
9025: my $hashid="$udom:$uname";
9026: my ($result,$cached)=&is_cached_new('userres',$hashid);
9027: if (!defined($cached)) {
9028: my %resourcedata=&dump('resourcedata',$udom,$uname);
9029: $result=\%resourcedata;
9030: &do_cache_new('userres',$hashid,$result,600);
9031: }
9032: my ($tmp)=keys(%$result);
9033: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
9034: return $result;
9035: }
9036: #error 2 occurs when the .db doesn't exist
9037: if ($tmp!~/error: 2 /) {
1.672 albertel 9038: &logthis("<font color=\"blue\">WARNING:".
1.624 albertel 9039: " Trying to get resource data for ".
9040: $uname." at ".$udom.": ".
9041: $tmp."</font>");
9042: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 9043: #&EXT_cache_set($udom,$uname);
9044: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 9045: undef($tmp); # not really an error so don't send it back
1.624 albertel 9046: }
9047: return $tmp;
9048: }
1.879 foxr 9049: #----------------------------------------------- resdata - return resource data
9050: # Purpose:
9051: # Return resource data for either users or for a course.
9052: # Parameters:
9053: # $name - Course/user name.
9054: # $domain - Name of the domain the user/course is registered on.
9055: # $type - Type of thing $name is (must be 'course' or 'user'
9056: # @which - Array of names of resources desired.
9057: # Returns:
9058: # The value of the first reasource in @which that is found in the
9059: # resource hash.
9060: # Exceptional Conditions:
9061: # If the $type passed in is not valid (not the string 'course' or
9062: # 'user', an undefined reference is returned.
9063: # If none of the resources are found, an undef is returned
1.624 albertel 9064: sub resdata {
9065: my ($name,$domain,$type,@which)=@_;
9066: my $result;
9067: if ($type eq 'course') {
9068: $result=&get_courseresdata($name,$domain);
9069: } elsif ($type eq 'user') {
9070: $result=&get_userresdata($name,$domain);
9071: }
9072: if (!ref($result)) { return $result; }
1.251 albertel 9073: foreach my $item (@which) {
1.927 albertel 9074: if (defined($result->{$item->[0]})) {
9075: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 9076: }
1.250 albertel 9077: }
1.291 albertel 9078: return undef;
1.200 www 9079: }
9080:
1.379 matthew 9081: #
9082: # EXT resource caching routines
9083: #
9084:
9085: sub clear_EXT_cache_status {
1.383 albertel 9086: &delenv('cache.EXT.');
1.379 matthew 9087: }
9088:
9089: sub EXT_cache_status {
9090: my ($target_domain,$target_user) = @_;
1.383 albertel 9091: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 9092: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 9093: # We know already the user has no data
9094: return 1;
9095: } else {
9096: return 0;
9097: }
9098: }
9099:
9100: sub EXT_cache_set {
9101: my ($target_domain,$target_user) = @_;
1.383 albertel 9102: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 9103: #&appenv({$cachename => time});
1.379 matthew 9104: }
9105:
1.28 www 9106: # --------------------------------------------------------- Value of a Variable
1.58 www 9107: sub EXT {
1.715 albertel 9108:
1.395 albertel 9109: my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68 www 9110: unless ($varname) { return ''; }
1.218 albertel 9111: #get real user name/domain, courseid and symb
9112: my $courseid;
1.359 albertel 9113: my $publicuser;
1.427 www 9114: if ($symbparm) {
9115: $symbparm=&get_symb_from_alias($symbparm);
9116: }
1.218 albertel 9117: if (!($uname && $udom)) {
1.790 albertel 9118: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 9119: if (!$symbparm) { $symbparm=$cursymb; }
9120: } else {
1.620 albertel 9121: $courseid=$env{'request.course.id'};
1.218 albertel 9122: }
1.48 www 9123: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
9124: my $rest;
1.320 albertel 9125: if (defined($therest[0])) {
1.48 www 9126: $rest=join('.',@therest);
9127: } else {
9128: $rest='';
9129: }
1.320 albertel 9130:
1.57 www 9131: my $qualifierrest=$qualifier;
9132: if ($rest) { $qualifierrest.='.'.$rest; }
9133: my $spacequalifierrest=$space;
9134: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 9135: if ($realm eq 'user') {
1.48 www 9136: # --------------------------------------------------------------- user.resource
9137: if ($space eq 'resource') {
1.651 albertel 9138: if ( (defined($Apache::lonhomework::parsing_a_problem)
9139: || defined($Apache::lonhomework::parsing_a_task))
9140: &&
1.744 albertel 9141: ($symbparm eq &symbread()) ) {
9142: # if we are in the middle of processing the resource the
9143: # get the value we are planning on committing
9144: if (defined($Apache::lonhomework::results{$qualifierrest})) {
9145: return $Apache::lonhomework::results{$qualifierrest};
9146: } else {
9147: return $Apache::lonhomework::history{$qualifierrest};
9148: }
1.335 albertel 9149: } else {
1.359 albertel 9150: my %restored;
1.620 albertel 9151: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 9152: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
9153: } else {
9154: %restored=&restore($symbparm,$courseid,$udom,$uname);
9155: }
1.335 albertel 9156: return $restored{$qualifierrest};
9157: }
1.48 www 9158: # ----------------------------------------------------------------- user.access
9159: } elsif ($space eq 'access') {
1.218 albertel 9160: # FIXME - not supporting calls for a specific user
1.48 www 9161: return &allowed($qualifier,$rest);
9162: # ------------------------------------------ user.preferences, user.environment
9163: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 9164: if (($uname eq $env{'user.name'}) &&
9165: ($udom eq $env{'user.domain'})) {
9166: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 9167: } else {
1.359 albertel 9168: my %returnhash;
9169: if (!$publicuser) {
9170: %returnhash=&userenvironment($udom,$uname,
9171: $qualifierrest);
9172: }
1.218 albertel 9173: return $returnhash{$qualifierrest};
9174: }
1.48 www 9175: # ----------------------------------------------------------------- user.course
9176: } elsif ($space eq 'course') {
1.218 albertel 9177: # FIXME - not supporting calls for a specific user
1.620 albertel 9178: return $env{join('.',('request.course',$qualifier))};
1.48 www 9179: # ------------------------------------------------------------------- user.role
9180: } elsif ($space eq 'role') {
1.218 albertel 9181: # FIXME - not supporting calls for a specific user
1.620 albertel 9182: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 9183: if ($qualifier eq 'value') {
9184: return $role;
9185: } elsif ($qualifier eq 'extent') {
9186: return $where;
9187: }
9188: # ----------------------------------------------------------------- user.domain
9189: } elsif ($space eq 'domain') {
1.218 albertel 9190: return $udom;
1.48 www 9191: # ------------------------------------------------------------------- user.name
9192: } elsif ($space eq 'name') {
1.218 albertel 9193: return $uname;
1.48 www 9194: # ---------------------------------------------------- Any other user namespace
1.29 www 9195: } else {
1.359 albertel 9196: my %reply;
9197: if (!$publicuser) {
9198: %reply=&get($space,[$qualifierrest],$udom,$uname);
9199: }
9200: return $reply{$qualifierrest};
1.48 www 9201: }
1.236 www 9202: } elsif ($realm eq 'query') {
9203: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 9204: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
9205: [$spacequalifierrest]);
1.620 albertel 9206: return $env{'form.'.$spacequalifierrest};
1.236 www 9207: } elsif ($realm eq 'request') {
1.48 www 9208: # ------------------------------------------------------------- request.browser
9209: if ($space eq 'browser') {
1.1145 bisitz 9210: return $env{'browser.'.$qualifier};
1.57 www 9211: # ------------------------------------------------------------ request.filename
9212: } else {
1.620 albertel 9213: return $env{'request.'.$spacequalifierrest};
1.29 www 9214: }
1.28 www 9215: } elsif ($realm eq 'course') {
1.48 www 9216: # ---------------------------------------------------------- course.description
1.620 albertel 9217: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 9218: } elsif ($realm eq 'resource') {
1.165 www 9219:
1.620 albertel 9220: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 9221: if (!$symbparm) { $symbparm=&symbread(); }
9222: }
1.693 albertel 9223:
9224: if ($space eq 'title') {
9225: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
9226: return &gettitle($symbparm);
9227: }
9228:
9229: if ($space eq 'map') {
9230: my ($map) = &decode_symb($symbparm);
9231: return &symbread($map);
9232: }
1.905 albertel 9233: if ($space eq 'filename') {
9234: if ($symbparm) {
9235: return &clutter((&decode_symb($symbparm))[2]);
9236: }
9237: return &hreflocation('',$env{'request.filename'});
9238: }
1.693 albertel 9239:
9240: my ($section, $group, @groups);
1.593 albertel 9241: my ($courselevelm,$courselevel);
1.539 albertel 9242: if ($symbparm && defined($courseid) &&
1.620 albertel 9243: $courseid eq $env{'request.course.id'}) {
1.165 www 9244:
1.218 albertel 9245: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 9246:
1.60 www 9247: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 9248: my $symbp=$symbparm;
1.735 albertel 9249: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 9250:
9251: my $symbparm=$symbp.'.'.$spacequalifierrest;
9252: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
9253:
1.620 albertel 9254: if (($env{'user.name'} eq $uname) &&
9255: ($env{'user.domain'} eq $udom)) {
9256: $section=$env{'request.course.sec'};
1.733 raeburn 9257: @groups = split(/:/,$env{'request.course.groups'});
9258: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 9259: } else {
1.539 albertel 9260: if (! defined($usection)) {
1.551 albertel 9261: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 9262: } else {
9263: $section = $usection;
9264: }
1.733 raeburn 9265: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 9266: }
9267:
9268: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
9269: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
9270: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
9271:
1.593 albertel 9272: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 9273: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 9274: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 9275:
1.60 www 9276: # ----------------------------------------------------------- first, check user
1.624 albertel 9277:
9278: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 9279: ([$courselevelr,'resource'],
9280: [$courselevelm,'map' ],
9281: [$courselevel, 'course' ]));
1.931 albertel 9282: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 9283:
1.594 albertel 9284: # ------------------------------------------------ second, check some of course
1.684 raeburn 9285: my $coursereply;
1.691 raeburn 9286: if (@groups > 0) {
9287: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
9288: $mapparm,$spacequalifierrest);
1.927 albertel 9289: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 9290: }
1.96 www 9291:
1.684 raeburn 9292: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 9293: $env{'course.'.$courseid.'.domain'},
9294: 'course',
9295: ([$seclevelr, 'resource'],
9296: [$seclevelm, 'map' ],
9297: [$seclevel, 'course' ],
9298: [$courselevelr,'resource']));
9299: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 9300:
1.60 www 9301: # ------------------------------------------------------ third, check map parms
1.218 albertel 9302: my %parmhash=();
9303: my $thisparm='';
9304: if (tie(%parmhash,'GDBM_File',
1.620 albertel 9305: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 9306: &GDBM_READER(),0640)) {
1.218 albertel 9307: $thisparm=$parmhash{$symbparm};
9308: untie(%parmhash);
9309: }
1.927 albertel 9310: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 9311: }
1.594 albertel 9312: # ------------------------------------------ fourth, look in resource metadata
1.71 www 9313:
1.218 albertel 9314: $spacequalifierrest=~s/\./\_/;
1.282 albertel 9315: my $filename;
9316: if (!$symbparm) { $symbparm=&symbread(); }
9317: if ($symbparm) {
1.409 www 9318: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 9319: } else {
1.620 albertel 9320: $filename=$env{'request.filename'};
1.282 albertel 9321: }
9322: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 9323: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 9324: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 9325: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 9326:
1.927 albertel 9327: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 9328: if ($symbparm && defined($courseid) &&
1.620 albertel 9329: $courseid eq $env{'request.course.id'}) {
1.624 albertel 9330: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
9331: $env{'course.'.$courseid.'.domain'},
9332: 'course',
1.927 albertel 9333: ([$courselevelm,'map' ],
9334: [$courselevel, 'course']));
9335: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 9336: }
1.145 www 9337: # ------------------------------------------------------------------ Cascade up
1.218 albertel 9338: unless ($space eq '0') {
1.336 albertel 9339: my @parts=split(/_/,$space);
9340: my $id=pop(@parts);
9341: my $part=join('_',@parts);
9342: if ($part eq '') { $part='0'; }
1.927 albertel 9343: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 9344: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 9345: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 9346: }
1.395 albertel 9347: if ($recurse) { return undef; }
9348: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 9349: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 9350: # ---------------------------------------------------- Any other user namespace
9351: } elsif ($realm eq 'environment') {
9352: # ----------------------------------------------------------------- environment
1.620 albertel 9353: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
9354: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 9355: } else {
1.770 albertel 9356: if ($uname eq 'anonymous' && $udom eq '') {
9357: return '';
9358: }
1.219 albertel 9359: my %returnhash=&userenvironment($udom,$uname,
9360: $spacequalifierrest);
9361: return $returnhash{$spacequalifierrest};
9362: }
1.28 www 9363: } elsif ($realm eq 'system') {
1.48 www 9364: # ----------------------------------------------------------------- system.time
9365: if ($space eq 'time') {
9366: return time;
9367: }
1.696 albertel 9368: } elsif ($realm eq 'server') {
9369: # ----------------------------------------------------------------- system.time
9370: if ($space eq 'name') {
9371: return $ENV{'SERVER_NAME'};
9372: }
1.28 www 9373: }
1.48 www 9374: return '';
1.61 www 9375: }
9376:
1.927 albertel 9377: sub get_reply {
9378: my ($reply_value) = @_;
1.940 raeburn 9379: if (ref($reply_value) eq 'ARRAY') {
9380: if (wantarray) {
9381: return @$reply_value;
9382: }
9383: return $reply_value->[0];
9384: } else {
9385: return $reply_value;
1.927 albertel 9386: }
9387: }
9388:
1.691 raeburn 9389: sub check_group_parms {
9390: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
9391: my @groupitems = ();
9392: my $resultitem;
1.927 albertel 9393: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 9394: foreach my $group (@{$groups}) {
9395: foreach my $level (@levels) {
1.927 albertel 9396: my $item = $courseid.'.['.$group.'].'.$level->[0];
9397: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 9398: }
9399: }
9400: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
9401: $env{'course.'.$courseid.'.domain'},
9402: 'course',@groupitems);
9403: return $coursereply;
9404: }
9405:
9406: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 9407: my ($courseid,@groups) = @_;
9408: @groups = sort(@groups);
1.691 raeburn 9409: return @groups;
9410: }
9411:
1.395 albertel 9412: sub packages_tab_default {
9413: my ($uri,$varname)=@_;
9414: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 9415:
9416: my (@extension,@specifics,$do_default);
9417: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 9418: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 9419: if ($pack_type eq 'default') {
9420: $do_default=1;
9421: } elsif ($pack_type eq 'extension') {
9422: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 9423: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 9424: # only look at packages defaults for packages that this id is
1.738 albertel 9425: push(@specifics,[$package,$pack_type,$pack_part]);
9426: }
9427: }
9428: # first look for a package that matches the requested part id
9429: foreach my $package (@specifics) {
9430: my (undef,$pack_type,$pack_part)=@{$package};
9431: next if ($pack_part ne $part);
9432: if (defined($packagetab{"$pack_type&$name&default"})) {
9433: return $packagetab{"$pack_type&$name&default"};
9434: }
9435: }
9436: # look for any possible matching non extension_ package
9437: foreach my $package (@specifics) {
9438: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 9439: if (defined($packagetab{"$pack_type&$name&default"})) {
9440: return $packagetab{"$pack_type&$name&default"};
9441: }
1.585 albertel 9442: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 9443: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
9444: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 9445: }
9446: }
1.738 albertel 9447: # look for any posible extension_ match
9448: foreach my $package (@extension) {
9449: my ($package,$pack_type)=@{$package};
9450: if (defined($packagetab{"$pack_type&$name&default"})) {
9451: return $packagetab{"$pack_type&$name&default"};
9452: }
9453: if (defined($packagetab{$package."&$name&default"})) {
9454: return $packagetab{$package."&$name&default"};
9455: }
9456: }
9457: # look for a global default setting
9458: if ($do_default && defined($packagetab{"default&$name&default"})) {
9459: return $packagetab{"default&$name&default"};
9460: }
1.395 albertel 9461: return undef;
9462: }
9463:
1.334 albertel 9464: sub add_prefix_and_part {
9465: my ($prefix,$part)=@_;
9466: my $keyroot;
9467: if (defined($prefix) && $prefix !~ /^__/) {
9468: # prefix that has a part already
9469: $keyroot=$prefix;
9470: } elsif (defined($prefix)) {
9471: # prefix that is missing a part
9472: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
9473: } else {
9474: # no prefix at all
9475: if (defined($part)) { $keyroot='_'.$part; }
9476: }
9477: return $keyroot;
9478: }
9479:
1.71 www 9480: # ---------------------------------------------------------------- Get metadata
9481:
1.599 albertel 9482: my %metaentry;
1.1070 www 9483: my %importedpartids;
1.71 www 9484: sub metadata {
1.176 www 9485: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 9486: $uri=&declutter($uri);
1.288 albertel 9487: # if it is a non metadata possible uri return quickly
1.529 albertel 9488: if (($uri eq '') ||
9489: (($uri =~ m|^/*adm/|) &&
1.698 albertel 9490: ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.1108 raeburn 9491: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 9492: return undef;
9493: }
1.1140 www 9494: if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/)
1.924 albertel 9495: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 9496: return undef;
1.288 albertel 9497: }
1.73 www 9498: my $filename=$uri;
9499: $uri=~s/\.meta$//;
1.172 www 9500: #
9501: # Is the metadata already cached?
1.177 www 9502: # Look at timestamp of caching
1.172 www 9503: # Everything is cached by the main uri, libraries are never directly cached
9504: #
1.428 albertel 9505: if (!defined($liburi)) {
1.599 albertel 9506: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 9507: if (defined($cached)) { return $result->{':'.$what}; }
9508: }
9509: {
1.1069 www 9510: # Imported parts would go here
1.1070 www 9511: my %importedids=();
9512: my @origfileimportpartids=();
1.1069 www 9513: my $importedparts=0;
1.172 www 9514: #
9515: # Is this a recursive call for a library?
9516: #
1.599 albertel 9517: # if (! exists($metacache{$uri})) {
9518: # $metacache{$uri}={};
9519: # }
1.924 albertel 9520: my $cachetime = 60*60;
1.171 www 9521: if ($liburi) {
9522: $liburi=&declutter($liburi);
9523: $filename=$liburi;
1.401 bowersj2 9524: } else {
1.599 albertel 9525: &devalidate_cache_new('meta',$uri);
9526: undef(%metaentry);
1.401 bowersj2 9527: }
1.140 www 9528: my %metathesekeys=();
1.73 www 9529: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 9530: my $metastring;
1.1140 www 9531: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929 albertel 9532: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 9533: $metastring =
1.929 albertel 9534: &Apache::lonnet::ssi_body($which,
1.924 albertel 9535: ('grade_target' => 'meta'));
9536: $cachetime = 1; # only want this cached in the child not long term
1.1108 raeburn 9537: } elsif (($uri !~ m -^(editupload)/-) &&
9538: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 9539: my $file=&filelocation('',&clutter($filename));
1.599 albertel 9540: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 9541: $metastring=&getfile($file);
1.489 albertel 9542: }
1.208 albertel 9543: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 9544: my $token;
1.140 www 9545: undef %metathesekeys;
1.71 www 9546: while ($token=$parser->get_token) {
1.339 albertel 9547: if ($token->[0] eq 'S') {
9548: if (defined($token->[2]->{'package'})) {
1.172 www 9549: #
9550: # This is a package - get package info
9551: #
1.339 albertel 9552: my $package=$token->[2]->{'package'};
9553: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
9554: if (defined($token->[2]->{'id'})) {
9555: $keyroot.='_'.$token->[2]->{'id'};
9556: }
1.599 albertel 9557: if ($metaentry{':packages'}) {
9558: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 9559: } else {
1.599 albertel 9560: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 9561: }
1.736 albertel 9562: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 9563: my $part=$keyroot;
9564: $part=~s/^\_//;
1.736 albertel 9565: if ($pack_entry=~/^\Q$package\E\&/ ||
9566: $pack_entry=~/^\Q$package\E_0\&/) {
9567: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 9568: # ignore package.tab specified default values
9569: # here &package_tab_default() will fetch those
9570: if ($subp eq 'default') { next; }
1.736 albertel 9571: my $value=$packagetab{$pack_entry};
1.432 albertel 9572: my $unikey;
9573: if ($pack =~ /_0$/) {
9574: $unikey='parameter_0_'.$name;
9575: $part=0;
9576: } else {
9577: $unikey='parameter'.$keyroot.'_'.$name;
9578: }
1.339 albertel 9579: if ($subp eq 'display') {
9580: $value.=' [Part: '.$part.']';
9581: }
1.599 albertel 9582: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 9583: $metathesekeys{$unikey}=1;
1.599 albertel 9584: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
9585: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 9586: }
1.599 albertel 9587: if (defined($metaentry{':'.$unikey.'.default'})) {
9588: $metaentry{':'.$unikey}=
9589: $metaentry{':'.$unikey.'.default'};
1.356 albertel 9590: }
1.339 albertel 9591: }
9592: }
9593: } else {
1.172 www 9594: #
9595: # This is not a package - some other kind of start tag
1.339 albertel 9596: #
9597: my $entry=$token->[1];
1.1068 www 9598: my $unikey='';
1.175 www 9599:
1.339 albertel 9600: if ($entry eq 'import') {
1.175 www 9601: #
9602: # Importing a library here
1.339 albertel 9603: #
1.1067 www 9604: my $location=$parser->get_text('/import');
9605: my $dir=$filename;
9606: $dir=~s|[^/]*$||;
9607: $location=&filelocation($dir,$location);
1.1069 www 9608:
1.1068 www 9609: my $importmode=$token->[2]->{'importmode'};
9610: if ($importmode eq 'problem') {
1.1069 www 9611: # Import as problem/response
1.1068 www 9612: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
9613: } elsif ($importmode eq 'part') {
9614: # Import as part(s)
1.1069 www 9615: $importedparts=1;
9616: # We need to get the original file and the imported file to get the part order correct
9617: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
9618: # Load and inspect original file
1.1070 www 9619: if ($#origfileimportpartids<0) {
9620: undef(%importedpartids);
9621: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
9622: my $origfile=&getfile($origfilelocation);
9623: @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
9624: }
9625:
1.1069 www 9626: # Load and inspect imported file
9627: my $impfile=&getfile($location);
9628: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
9629: if ($#impfilepartids>=0) {
9630: # This problem had parts
1.1070 www 9631: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 9632: } else {
9633: # Importing by turning a single problem into a problem part
9634: # It gets the import-tags ID as part-ID
9635: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 9636: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 9637: }
1.1068 www 9638: } else {
9639: # Normal import
9640: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
9641: if (defined($token->[2]->{'id'})) {
9642: $unikey.='_'.$token->[2]->{'id'};
9643: }
1.1067 www 9644: }
9645:
1.339 albertel 9646: if ($depthcount<20) {
1.736 albertel 9647: my $metadata =
9648: &metadata($uri,'keys', $location,$unikey,
9649: $depthcount+1);
9650: foreach my $meta (split(',',$metadata)) {
9651: $metaentry{':'.$meta}=$metaentry{':'.$meta};
9652: $metathesekeys{$meta}=1;
1.339 albertel 9653: }
1.1068 www 9654:
9655: }
1.1067 www 9656: } else {
9657: #
9658: # Not importing, some other kind of non-package, non-library start tag
9659: #
9660: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
9661: if (defined($token->[2]->{'id'})) {
9662: $unikey.='_'.$token->[2]->{'id'};
9663: }
1.339 albertel 9664: if (defined($token->[2]->{'name'})) {
9665: $unikey.='_'.$token->[2]->{'name'};
9666: }
9667: $metathesekeys{$unikey}=1;
1.736 albertel 9668: foreach my $param (@{$token->[3]}) {
9669: $metaentry{':'.$unikey.'.'.$param} =
9670: $token->[2]->{$param};
1.339 albertel 9671: }
9672: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 9673: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 9674: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
9675: # only ws inside the tag, and not in default, so use default
9676: # as value
1.599 albertel 9677: $metaentry{':'.$unikey}=$default;
1.908 albertel 9678: } elsif ( $internaltext =~ /\S/ ) {
9679: # something interesting inside the tag
9680: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 9681: } else {
1.908 albertel 9682: # no interesting values, don't set a default
1.339 albertel 9683: }
1.172 www 9684: # end of not-a-package not-a-library import
1.339 albertel 9685: }
1.172 www 9686: # end of not-a-package start tag
1.339 albertel 9687: }
1.172 www 9688: # the next is the end of "start tag"
1.339 albertel 9689: }
9690: }
1.483 albertel 9691: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 9692: $extension = lc($extension);
9693: if ($extension eq 'htm') { $extension='html'; }
9694:
1.737 albertel 9695: foreach my $key (keys(%packagetab)) {
1.483 albertel 9696: #no specific packages #how's our extension
9697: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 9698: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 9699: \%metathesekeys);
9700: }
1.883 albertel 9701:
9702: if (!exists($metaentry{':packages'})
9703: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 9704: foreach my $key (keys(%packagetab)) {
1.483 albertel 9705: #no specific packages well let's get default then
9706: if ($key!~/^default&/) { next; }
1.488 albertel 9707: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 9708: \%metathesekeys);
9709: }
9710: }
1.338 www 9711: # are there custom rights to evaluate
1.599 albertel 9712: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 9713:
1.338 www 9714: #
9715: # Importing a rights file here
1.339 albertel 9716: #
9717: unless ($depthcount) {
1.599 albertel 9718: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 9719: my $dir=$filename;
9720: $dir=~s|[^/]*$||;
9721: $location=&filelocation($dir,$location);
1.736 albertel 9722: my $rights_metadata =
9723: &metadata($uri,'keys',$location,'_rights',
9724: $depthcount+1);
9725: foreach my $rights (split(',',$rights_metadata)) {
9726: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
9727: $metathesekeys{$rights}=1;
1.339 albertel 9728: }
9729: }
9730: }
1.737 albertel 9731: # uniqifiy package listing
9732: my %seen;
9733: my @uniq_packages =
9734: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
9735: $metaentry{':packages'} = join(',',@uniq_packages);
9736:
1.1070 www 9737: if ($importedparts) {
9738: # We had imported parts and need to rebuild partorder
9739: $metaentry{':partorder'}='';
9740: $metathesekeys{'partorder'}=1;
9741: for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
9742: if ($origfileimportpartids[$index] eq 'part') {
9743: # original part, part of the problem
9744: $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
9745: } else {
9746: # we have imported parts at this position
9747: $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
9748: }
9749: }
9750: $metaentry{':partorder'}=~s/^\,//;
9751: }
9752:
1.737 albertel 9753: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 9754: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
9755: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924 albertel 9756: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 9757: # this is the end of "was not already recently cached
1.71 www 9758: }
1.599 albertel 9759: return $metaentry{':'.$what};
1.261 albertel 9760: }
9761:
1.488 albertel 9762: sub metadata_create_package_def {
1.483 albertel 9763: my ($uri,$key,$package,$metathesekeys)=@_;
9764: my ($pack,$name,$subp)=split(/\&/,$key);
9765: if ($subp eq 'default') { next; }
9766:
1.599 albertel 9767: if (defined($metaentry{':packages'})) {
9768: $metaentry{':packages'}.=','.$package;
1.483 albertel 9769: } else {
1.599 albertel 9770: $metaentry{':packages'}=$package;
1.483 albertel 9771: }
9772: my $value=$packagetab{$key};
9773: my $unikey;
9774: $unikey='parameter_0_'.$name;
1.599 albertel 9775: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 9776: $$metathesekeys{$unikey}=1;
1.599 albertel 9777: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
9778: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 9779: }
1.599 albertel 9780: if (defined($metaentry{':'.$unikey.'.default'})) {
9781: $metaentry{':'.$unikey}=
9782: $metaentry{':'.$unikey.'.default'};
1.483 albertel 9783: }
9784: }
9785:
1.261 albertel 9786: sub metadata_generate_part0 {
9787: my ($metadata,$metacache,$uri) = @_;
9788: my %allnames;
1.737 albertel 9789: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 9790: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 9791: my $part=$$metacache{':'.$metakey.'.part'};
9792: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 9793: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 9794: $allnames{$name}=$part;
9795: }
9796: }
9797: }
9798: foreach my $name (keys(%allnames)) {
9799: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 9800: my $key=":parameter_0_$name";
1.261 albertel 9801: $$metacache{"$key.part"}='0';
9802: $$metacache{"$key.name"}=$name;
1.428 albertel 9803: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 9804: $allnames{$name}.'_'.$name.
9805: '.type'};
1.428 albertel 9806: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 9807: '.display'};
1.644 www 9808: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 9809: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 9810: $$metacache{"$key.display"}=$olddis;
9811: }
1.71 www 9812: }
9813:
1.764 albertel 9814: # ------------------------------------------------------ Devalidate title cache
9815:
9816: sub devalidate_title_cache {
9817: my ($url)=@_;
9818: if (!$env{'request.course.id'}) { return; }
9819: my $symb=&symbread($url);
9820: if (!$symb) { return; }
9821: my $key=$env{'request.course.id'}."\0".$symb;
9822: &devalidate_cache_new('title',$key);
9823: }
9824:
1.1014 droeschl 9825: # ------------------------------------------------- Get the title of a course
9826:
9827: sub current_course_title {
9828: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
9829: }
1.301 www 9830: # ------------------------------------------------- Get the title of a resource
9831:
9832: sub gettitle {
9833: my $urlsymb=shift;
9834: my $symb=&symbread($urlsymb);
1.534 albertel 9835: if ($symb) {
1.620 albertel 9836: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 9837: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 9838: if (defined($cached)) {
9839: return $result;
9840: }
1.534 albertel 9841: my ($map,$resid,$url)=&decode_symb($symb);
9842: my $title='';
1.907 albertel 9843: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
9844: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
9845: } else {
9846: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
9847: &GDBM_READER(),0640)) {
9848: my $mapid=$bighash{'map_pc_'.&clutter($map)};
9849: $title=$bighash{'title_'.$mapid.'.'.$resid};
9850: untie(%bighash);
9851: }
1.534 albertel 9852: }
9853: $title=~s/\&colon\;/\:/gs;
9854: if ($title) {
1.1159 www 9855: # Remember both $symb and $title for dynamic metadata
9856: $accesshash{$symb.'___crstitle'}=$title;
1.1161 www 9857: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159 www 9858: # Cache this title and then return it
1.599 albertel 9859: return &do_cache_new('title',$key,$title,600);
1.534 albertel 9860: }
9861: $urlsymb=$url;
9862: }
9863: my $title=&metadata($urlsymb,'title');
9864: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
9865: return $title;
1.301 www 9866: }
1.613 albertel 9867:
1.614 albertel 9868: sub get_slot {
9869: my ($which,$cnum,$cdom)=@_;
9870: if (!$cnum || !$cdom) {
1.790 albertel 9871: (undef,my $courseid)=&whichuser();
1.620 albertel 9872: $cdom=$env{'course.'.$courseid.'.domain'};
9873: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 9874: }
1.703 albertel 9875: my $key=join("\0",'slots',$cdom,$cnum,$which);
9876: my %slotinfo;
9877: if (exists($remembered{$key})) {
9878: $slotinfo{$which} = $remembered{$key};
9879: } else {
9880: %slotinfo=&get('slots',[$which],$cdom,$cnum);
9881: &Apache::lonhomework::showhash(%slotinfo);
9882: my ($tmp)=keys(%slotinfo);
9883: if ($tmp=~/^error:/) { return (); }
9884: $remembered{$key} = $slotinfo{$which};
9885: }
1.616 albertel 9886: if (ref($slotinfo{$which}) eq 'HASH') {
9887: return %{$slotinfo{$which}};
9888: }
9889: return $slotinfo{$which};
1.614 albertel 9890: }
1.1150 raeburn 9891:
9892: sub get_reservable_slots {
9893: my ($cnum,$cdom,$uname,$udom) = @_;
9894: my $now = time;
9895: my $reservable_info;
9896: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
9897: if (exists($remembered{$key})) {
9898: $reservable_info = $remembered{$key};
9899: } else {
9900: my %resv;
9901: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
9902: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
9903: $reservable_info = \%resv;
9904: $remembered{$key} = $reservable_info;
9905: }
9906: return $reservable_info;
9907: }
9908:
9909: sub get_course_slots {
9910: my ($cnum,$cdom) = @_;
9911: my $hashid=$cnum.':'.$cdom;
9912: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
9913: if (defined($cached)) {
9914: if (ref($result) eq 'HASH') {
9915: return %{$result};
9916: }
9917: } else {
9918: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
9919: my ($tmp) = keys(%slots);
9920: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
9921: &Apache::lonnet::do_cache_new('allslots',$hashid,\%slots,600);
9922: return %slots;
9923: }
9924: }
9925: return;
9926: }
9927:
9928: sub devalidate_slots_cache {
9929: my ($cnum,$cdom)=@_;
9930: my $hashid=$cnum.':'.$cdom;
9931: &devalidate_cache_new('allslots',$hashid);
9932: }
9933:
1.1172.2.8 raeburn 9934: sub get_coursechange {
9935: my ($cdom,$cnum) = @_;
9936: if ($cdom eq '' || $cnum eq '') {
9937: return unless ($env{'request.course.id'});
9938: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
9939: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
9940: }
9941: my $hashid=$cdom.'_'.$cnum;
9942: my ($change,$cached)=&is_cached_new('crschange',$hashid);
9943: if ((defined($cached)) && ($change ne '')) {
9944: return $change;
9945: } else {
9946: my %crshash;
9947: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
9948: if ($crshash{'internal.contentchange'} eq '') {
9949: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
9950: if ($change eq '') {
9951: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
9952: $change = $crshash{'internal.created'};
9953: }
9954: } else {
9955: $change = $crshash{'internal.contentchange'};
9956: }
9957: my $cachetime = 600;
9958: &do_cache_new('crschange',$hashid,$change,$cachetime);
9959: }
9960: return $change;
9961: }
9962:
9963: sub devalidate_coursechange_cache {
9964: my ($cnum,$cdom)=@_;
9965: my $hashid=$cnum.':'.$cdom;
9966: &devalidate_cache_new('crschange',$hashid);
9967: }
9968:
1.31 www 9969: # ------------------------------------------------- Update symbolic store links
9970:
9971: sub symblist {
9972: my ($mapname,%newhash)=@_;
1.438 www 9973: $mapname=&deversion(&declutter($mapname));
1.31 www 9974: my %hash;
1.620 albertel 9975: if (($env{'request.course.fn'}) && (%newhash)) {
9976: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 9977: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 9978: foreach my $url (keys(%newhash)) {
1.711 albertel 9979: next if ($url eq 'last_known'
9980: && $env{'form.no_update_last_known'});
9981: $hash{declutter($url)}=&encode_symb($mapname,
9982: $newhash{$url}->[1],
9983: $newhash{$url}->[0]);
1.191 harris41 9984: }
1.31 www 9985: if (untie(%hash)) {
9986: return 'ok';
9987: }
9988: }
9989: }
9990: return 'error';
1.212 www 9991: }
9992:
9993: # --------------------------------------------------------------- Verify a symb
9994:
9995: sub symbverify {
1.1172.2.11 raeburn 9996: my ($symb,$thisurl,$encstate)=@_;
1.510 www 9997: my $thisfn=$thisurl;
1.439 www 9998: $thisfn=&declutter($thisfn);
1.215 www 9999: # direct jump to resource in page or to a sequence - will construct own symbs
10000: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
10001: # check URL part
1.409 www 10002: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 10003:
1.431 www 10004: unless ($url eq $thisfn) { return 0; }
1.213 www 10005:
1.216 www 10006: $symb=&symbclean($symb);
1.510 www 10007: $thisurl=&deversion($thisurl);
1.439 www 10008: $thisfn=&deversion($thisfn);
1.213 www 10009:
10010: my %bighash;
10011: my $okay=0;
1.431 www 10012:
1.620 albertel 10013: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 10014: &GDBM_READER(),0640)) {
1.1032 raeburn 10015: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
10016: $thisurl =~ s/\?.+$//;
10017: }
1.510 www 10018: my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1102 raeburn 10019: unless ($ids) {
10020: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
10021: $ids=$bighash{$idkey};
1.216 www 10022: }
10023: if ($ids) {
10024: # ------------------------------------------------------------------- Has ID(s)
1.800 albertel 10025: foreach my $id (split(/\,/,$ids)) {
10026: my ($mapid,$resid)=split(/\./,$id);
1.1032 raeburn 10027: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
10028: $symb =~ s/\?.+$//;
10029: }
1.216 www 10030: if (
10031: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
10032: eq $symb) {
1.1172.2.11 raeburn 10033: if (ref($encstate)) {
10034: $$encstate = $bighash{'encrypted_'.$id};
10035: }
1.620 albertel 10036: if (($env{'request.role.adv'}) ||
1.1101 raeburn 10037: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
10038: ($thisurl eq '/adm/navmaps')) {
1.582 albertel 10039: $okay=1;
10040: }
10041: }
1.216 www 10042: }
10043: }
1.213 www 10044: untie(%bighash);
10045: }
10046: return $okay;
1.31 www 10047: }
10048:
1.210 www 10049: # --------------------------------------------------------------- Clean-up symb
10050:
10051: sub symbclean {
10052: my $symb=shift;
1.568 albertel 10053: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 10054: # remove version from map
10055: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 10056:
1.210 www 10057: # remove version from URL
10058: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 10059:
1.507 www 10060: # remove wrapper
10061:
1.510 www 10062: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 10063: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 10064: return $symb;
1.409 www 10065: }
10066:
10067: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 10068:
10069: sub encode_symb {
10070: my ($map,$resid,$url)=@_;
10071: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
10072: }
1.409 www 10073:
10074: sub decode_symb {
1.568 albertel 10075: my $symb=shift;
10076: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
10077: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 10078: return (&fixversion($map),$resid,&fixversion($url));
10079: }
10080:
10081: sub fixversion {
10082: my $fn=shift;
1.609 banghart 10083: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 10084: my %bighash;
10085: my $uri=&clutter($fn);
1.620 albertel 10086: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 10087: # is this cached?
1.599 albertel 10088: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 10089: if (defined($cached)) { return $result; }
10090: # unfortunately not cached, or expired
1.620 albertel 10091: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 10092: &GDBM_READER(),0640)) {
10093: if ($bighash{'version_'.$uri}) {
10094: my $version=$bighash{'version_'.$uri};
1.444 www 10095: unless (($version eq 'mostrecent') ||
10096: ($version==&getversion($uri))) {
1.440 www 10097: $uri=~s/\.(\w+)$/\.$version\.$1/;
10098: }
10099: }
10100: untie %bighash;
1.413 www 10101: }
1.599 albertel 10102: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 10103: }
10104:
10105: sub deversion {
10106: my $url=shift;
10107: $url=~s/\.\d+\.(\w+)$/\.$1/;
10108: return $url;
1.210 www 10109: }
10110:
1.31 www 10111: # ------------------------------------------------------ Return symb list entry
10112:
10113: sub symbread {
1.249 www 10114: my ($thisfn,$donotrecurse)=@_;
1.542 albertel 10115: my $cache_str='request.symbread.cached.'.$thisfn;
1.1172.2.8 raeburn 10116: if (defined($env{$cache_str})) {
10117: if (($thisfn) || ($env{$cache_str} ne '')) {
10118: return $env{$cache_str};
10119: }
10120: }
1.242 www 10121: # no filename provided? try from environment
1.44 www 10122: unless ($thisfn) {
1.620 albertel 10123: if ($env{'request.symb'}) {
10124: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 10125: }
1.620 albertel 10126: $thisfn=$env{'request.filename'};
1.44 www 10127: }
1.569 albertel 10128: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 10129: # is that filename actually a symb? Verify, clean, and return
10130: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 10131: if (&symbverify($thisfn,$1)) {
1.620 albertel 10132: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 10133: }
1.242 www 10134: }
1.44 www 10135: $thisfn=declutter($thisfn);
1.31 www 10136: my %hash;
1.37 www 10137: my %bighash;
10138: my $syval='';
1.620 albertel 10139: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 10140: my $targetfn = $thisfn;
1.609 banghart 10141: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 10142: $targetfn = 'adm/wrapper/'.$thisfn;
10143: }
1.687 albertel 10144: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
10145: $targetfn=$1;
10146: }
1.620 albertel 10147: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 10148: &GDBM_READER(),0640)) {
1.481 raeburn 10149: $syval=$hash{$targetfn};
1.37 www 10150: untie(%hash);
10151: }
10152: # ---------------------------------------------------------- There was an entry
10153: if ($syval) {
1.601 albertel 10154: #unless ($syval=~/\_\d+$/) {
1.620 albertel 10155: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 10156: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 10157: #return $env{$cache_str}='';
1.601 albertel 10158: #}
10159: #$syval.=$1;
10160: #}
1.37 www 10161: } else {
10162: # ------------------------------------------------------- Was not in symb table
1.620 albertel 10163: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 10164: &GDBM_READER(),0640)) {
1.37 www 10165: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 10166: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 10167: unless ($ids) {
10168: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 10169: }
10170: unless ($ids) {
10171: # alias?
10172: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 10173: }
1.37 www 10174: if ($ids) {
10175: # ------------------------------------------------------------------- Has ID(s)
10176: my @possibilities=split(/\,/,$ids);
1.39 www 10177: if ($#possibilities==0) {
10178: # ----------------------------------------------- There is only one possibility
1.37 www 10179: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 10180: $syval=&encode_symb($bighash{'map_id_'.$mapid},
10181: $resid,$thisfn);
1.249 www 10182: } elsif (!$donotrecurse) {
1.39 www 10183: # ------------------------------------------ There is more than one possibility
10184: my $realpossible=0;
1.800 albertel 10185: foreach my $id (@possibilities) {
10186: my $file=$bighash{'src_'.$id};
1.39 www 10187: if (&allowed('bre',$file)) {
1.800 albertel 10188: my ($mapid,$resid)=split(/\./,$id);
1.39 www 10189: if ($bighash{'map_type_'.$mapid} ne 'page') {
10190: $realpossible++;
1.626 albertel 10191: $syval=&encode_symb($bighash{'map_id_'.$mapid},
10192: $resid,$thisfn);
1.39 www 10193: }
10194: }
1.191 harris41 10195: }
1.39 www 10196: if ($realpossible!=1) { $syval=''; }
1.249 www 10197: } else {
10198: $syval='';
1.37 www 10199: }
10200: }
10201: untie(%bighash)
1.481 raeburn 10202: }
1.31 www 10203: }
1.62 www 10204: if ($syval) {
1.620 albertel 10205: return $env{$cache_str}=$syval;
1.62 www 10206: }
1.31 www 10207: }
1.949 raeburn 10208: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 10209: return $env{$cache_str}='';
1.31 www 10210: }
10211:
10212: # ---------------------------------------------------------- Return random seed
10213:
1.32 www 10214: sub numval {
10215: my $txt=shift;
10216: $txt=~tr/A-J/0-9/;
10217: $txt=~tr/a-j/0-9/;
10218: $txt=~tr/K-T/0-9/;
10219: $txt=~tr/k-t/0-9/;
10220: $txt=~tr/U-Z/0-5/;
10221: $txt=~tr/u-z/0-5/;
10222: $txt=~s/\D//g;
1.564 albertel 10223: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 10224: return int($txt);
1.368 albertel 10225: }
10226:
1.484 albertel 10227: sub numval2 {
10228: my $txt=shift;
10229: $txt=~tr/A-J/0-9/;
10230: $txt=~tr/a-j/0-9/;
10231: $txt=~tr/K-T/0-9/;
10232: $txt=~tr/k-t/0-9/;
10233: $txt=~tr/U-Z/0-5/;
10234: $txt=~tr/u-z/0-5/;
10235: $txt=~s/\D//g;
10236: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10237: my $total;
10238: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 10239: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 10240: return int($total);
10241: }
10242:
1.575 albertel 10243: sub numval3 {
10244: use integer;
10245: my $txt=shift;
10246: $txt=~tr/A-J/0-9/;
10247: $txt=~tr/a-j/0-9/;
10248: $txt=~tr/K-T/0-9/;
10249: $txt=~tr/k-t/0-9/;
10250: $txt=~tr/U-Z/0-5/;
10251: $txt=~tr/u-z/0-5/;
10252: $txt=~s/\D//g;
10253: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10254: my $total;
10255: foreach my $val (@txts) { $total+=$val; }
10256: if ($_64bit) { $total=(($total<<32)>>32); }
10257: return $total;
10258: }
10259:
1.675 albertel 10260: sub digest {
10261: my ($data)=@_;
10262: my $digest=&Digest::MD5::md5($data);
10263: my ($a,$b,$c,$d)=unpack("iiii",$digest);
10264: my ($e,$f);
10265: {
10266: use integer;
10267: $e=($a+$b);
10268: $f=($c+$d);
10269: if ($_64bit) {
10270: $e=(($e<<32)>>32);
10271: $f=(($f<<32)>>32);
10272: }
10273: }
10274: if (wantarray) {
10275: return ($e,$f);
10276: } else {
10277: my $g;
10278: {
10279: use integer;
10280: $g=($e+$f);
10281: if ($_64bit) {
10282: $g=(($g<<32)>>32);
10283: }
10284: }
10285: return $g;
10286: }
10287: }
10288:
1.368 albertel 10289: sub latest_rnd_algorithm_id {
1.675 albertel 10290: return '64bit5';
1.366 albertel 10291: }
1.32 www 10292:
1.503 albertel 10293: sub get_rand_alg {
10294: my ($courseid)=@_;
1.790 albertel 10295: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 10296: if ($courseid) {
1.620 albertel 10297: return $env{"course.$courseid.rndseed"};
1.503 albertel 10298: }
10299: return &latest_rnd_algorithm_id();
10300: }
10301:
1.562 albertel 10302: sub validCODE {
10303: my ($CODE)=@_;
10304: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
10305: return 0;
10306: }
10307:
1.491 albertel 10308: sub getCODE {
1.620 albertel 10309: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 10310: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
10311: defined($Apache::lonhomework::parsing_a_task) ) &&
10312: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 10313: return $Apache::lonhomework::history{'resource.CODE'};
10314: }
10315: return undef;
10316: }
1.1133 foxr 10317: #
10318: # Determines the random seed for a specific context:
10319: #
10320: # parameters:
10321: # symb - in course context the symb for the seed.
10322: # course_id - The course id of the form domain_coursenum.
10323: # domain - Domain for the user.
10324: # course - Course for the user.
10325: # cenv - environment of the course.
10326: #
10327: # NOTE:
10328: # All parameters are picked out of the environment if missing
10329: # or not defined.
10330: # If a symb cannot be determined the current time is used instead.
10331: #
10332: # For a given well defined symb, courside, domain, username,
10333: # and course environment, the seed is reproducible.
10334: #
1.31 www 10335: sub rndseed {
1.1133 foxr 10336: my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790 albertel 10337: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 10338: if (!defined($symb)) {
1.366 albertel 10339: unless ($symb=$wsymb) { return time; }
10340: }
1.1146 foxr 10341: if (!defined $courseid) {
10342: $courseid=$wcourseid;
10343: }
10344: if (!defined $domain) { $domain=$wdomain; }
10345: if (!defined $username) { $username=$wusername }
1.1133 foxr 10346:
10347: my $which;
10348: if (defined($cenv->{'rndseed'})) {
10349: $which = $cenv->{'rndseed'};
10350: } else {
10351: $which =&get_rand_alg($courseid);
10352: }
1.491 albertel 10353: if (defined(&getCODE())) {
1.1133 foxr 10354:
1.675 albertel 10355: if ($which eq '64bit5') {
10356: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
10357: } elsif ($which eq '64bit4') {
1.575 albertel 10358: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
10359: } else {
10360: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
10361: }
1.675 albertel 10362: } elsif ($which eq '64bit5') {
10363: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 10364: } elsif ($which eq '64bit4') {
10365: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 10366: } elsif ($which eq '64bit3') {
10367: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 10368: } elsif ($which eq '64bit2') {
10369: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 10370: } elsif ($which eq '64bit') {
10371: return &rndseed_64bit($symb,$courseid,$domain,$username);
10372: }
10373: return &rndseed_32bit($symb,$courseid,$domain,$username);
10374: }
10375:
10376: sub rndseed_32bit {
10377: my ($symb,$courseid,$domain,$username)=@_;
10378: {
10379: use integer;
10380: my $symbchck=unpack("%32C*",$symb) << 27;
10381: my $symbseed=numval($symb) << 22;
10382: my $namechck=unpack("%32C*",$username) << 17;
10383: my $nameseed=numval($username) << 12;
10384: my $domainseed=unpack("%32C*",$domain) << 7;
10385: my $courseseed=unpack("%32C*",$courseid);
10386: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 10387: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10388: #&logthis("rndseed :$num:$symb");
1.564 albertel 10389: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 10390: return $num;
10391: }
10392: }
10393:
10394: sub rndseed_64bit {
10395: my ($symb,$courseid,$domain,$username)=@_;
10396: {
10397: use integer;
10398: my $symbchck=unpack("%32S*",$symb) << 21;
10399: my $symbseed=numval($symb) << 10;
10400: my $namechck=unpack("%32S*",$username);
10401:
10402: my $nameseed=numval($username) << 21;
10403: my $domainseed=unpack("%32S*",$domain) << 10;
10404: my $courseseed=unpack("%32S*",$courseid);
10405:
10406: my $num1=$symbchck+$symbseed+$namechck;
10407: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 10408: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10409: #&logthis("rndseed :$num:$symb");
1.564 albertel 10410: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 10411: return "$num1,$num2";
1.155 albertel 10412: }
1.366 albertel 10413: }
10414:
1.443 albertel 10415: sub rndseed_64bit2 {
10416: my ($symb,$courseid,$domain,$username)=@_;
10417: {
10418: use integer;
10419: # strings need to be an even # of cahracters long, it it is odd the
10420: # last characters gets thrown away
10421: my $symbchck=unpack("%32S*",$symb.' ') << 21;
10422: my $symbseed=numval($symb) << 10;
10423: my $namechck=unpack("%32S*",$username.' ');
10424:
10425: my $nameseed=numval($username) << 21;
1.501 albertel 10426: my $domainseed=unpack("%32S*",$domain.' ') << 10;
10427: my $courseseed=unpack("%32S*",$courseid.' ');
10428:
10429: my $num1=$symbchck+$symbseed+$namechck;
10430: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 10431: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10432: #&logthis("rndseed :$num:$symb");
1.803 albertel 10433: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 10434: return "$num1,$num2";
10435: }
10436: }
10437:
10438: sub rndseed_64bit3 {
10439: my ($symb,$courseid,$domain,$username)=@_;
10440: {
10441: use integer;
10442: # strings need to be an even # of cahracters long, it it is odd the
10443: # last characters gets thrown away
10444: my $symbchck=unpack("%32S*",$symb.' ') << 21;
10445: my $symbseed=numval2($symb) << 10;
10446: my $namechck=unpack("%32S*",$username.' ');
10447:
10448: my $nameseed=numval2($username) << 21;
1.443 albertel 10449: my $domainseed=unpack("%32S*",$domain.' ') << 10;
10450: my $courseseed=unpack("%32S*",$courseid.' ');
10451:
10452: my $num1=$symbchck+$symbseed+$namechck;
10453: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 10454: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10455: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 10456: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 10457:
1.503 albertel 10458: return "$num1:$num2";
1.443 albertel 10459: }
10460: }
10461:
1.575 albertel 10462: sub rndseed_64bit4 {
10463: my ($symb,$courseid,$domain,$username)=@_;
10464: {
10465: use integer;
10466: # strings need to be an even # of cahracters long, it it is odd the
10467: # last characters gets thrown away
10468: my $symbchck=unpack("%32S*",$symb.' ') << 21;
10469: my $symbseed=numval3($symb) << 10;
10470: my $namechck=unpack("%32S*",$username.' ');
10471:
10472: my $nameseed=numval3($username) << 21;
10473: my $domainseed=unpack("%32S*",$domain.' ') << 10;
10474: my $courseseed=unpack("%32S*",$courseid.' ');
10475:
10476: my $num1=$symbchck+$symbseed+$namechck;
10477: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 10478: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10479: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 10480: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 10481:
1.575 albertel 10482: return "$num1:$num2";
10483: }
10484: }
10485:
1.675 albertel 10486: sub rndseed_64bit5 {
10487: my ($symb,$courseid,$domain,$username)=@_;
10488: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
10489: return "$num1:$num2";
10490: }
10491:
1.366 albertel 10492: sub rndseed_CODE_64bit {
10493: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 10494: {
1.366 albertel 10495: use integer;
1.443 albertel 10496: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 10497: my $symbseed=numval2($symb);
1.491 albertel 10498: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
10499: my $CODEseed=numval(&getCODE());
1.443 albertel 10500: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 10501: my $num1=$symbseed+$CODEchck;
10502: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 10503: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
10504: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 10505: if ($_64bit) { $num1=(($num1<<32)>>32); }
10506: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 10507: return "$num1:$num2";
1.366 albertel 10508: }
10509: }
10510:
1.575 albertel 10511: sub rndseed_CODE_64bit4 {
10512: my ($symb,$courseid,$domain,$username)=@_;
10513: {
10514: use integer;
10515: my $symbchck=unpack("%32S*",$symb.' ') << 16;
10516: my $symbseed=numval3($symb);
10517: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
10518: my $CODEseed=numval3(&getCODE());
10519: my $courseseed=unpack("%32S*",$courseid.' ');
10520: my $num1=$symbseed+$CODEchck;
10521: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 10522: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
10523: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 10524: if ($_64bit) { $num1=(($num1<<32)>>32); }
10525: if ($_64bit) { $num2=(($num2<<32)>>32); }
10526: return "$num1:$num2";
10527: }
10528: }
10529:
1.675 albertel 10530: sub rndseed_CODE_64bit5 {
10531: my ($symb,$courseid,$domain,$username)=@_;
10532: my $code = &getCODE();
10533: my ($num1,$num2)=&digest("$symb,$courseid,$code");
10534: return "$num1:$num2";
10535: }
10536:
1.366 albertel 10537: sub setup_random_from_rndseed {
10538: my ($rndseed)=@_;
1.503 albertel 10539: if ($rndseed =~/([,:])/) {
10540: my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366 albertel 10541: &Math::Random::random_set_seed(abs($num1),abs($num2));
10542: } else {
10543: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 10544: }
1.36 albertel 10545: }
10546:
1.474 albertel 10547: sub latest_receipt_algorithm_id {
1.835 albertel 10548: return 'receipt3';
1.474 albertel 10549: }
10550:
1.480 www 10551: sub recunique {
10552: my $fucourseid=shift;
10553: my $unique;
1.835 albertel 10554: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
10555: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 10556: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 10557: } else {
10558: $unique=$perlvar{'lonReceipt'};
10559: }
10560: return unpack("%32C*",$unique);
10561: }
10562:
10563: sub recprefix {
10564: my $fucourseid=shift;
10565: my $prefix;
1.835 albertel 10566: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
10567: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 10568: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 10569: } else {
10570: $prefix=$perlvar{'lonHostID'};
10571: }
10572: return unpack("%32C*",$prefix);
10573: }
10574:
1.76 www 10575: sub ireceipt {
1.474 albertel 10576: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 10577:
10578: my $return =&recprefix($fucourseid).'-';
10579:
10580: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
10581: $env{'request.state'} eq 'construct') {
10582: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
10583: return $return;
10584: }
10585:
1.76 www 10586: my $cuname=unpack("%32C*",$funame);
10587: my $cudom=unpack("%32C*",$fudom);
10588: my $cucourseid=unpack("%32C*",$fucourseid);
10589: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 10590: my $cunique=&recunique($fucourseid);
1.474 albertel 10591: my $cpart=unpack("%32S*",$part);
1.835 albertel 10592: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
10593:
1.790 albertel 10594: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 10595:
10596: $return.= ($cunique%$cuname+
10597: $cunique%$cudom+
10598: $cusymb%$cuname+
10599: $cusymb%$cudom+
10600: $cucourseid%$cuname+
10601: $cucourseid%$cudom+
10602: $cpart%$cuname+
10603: $cpart%$cudom);
10604: } else {
10605: $return.= ($cunique%$cuname+
10606: $cunique%$cudom+
10607: $cusymb%$cuname+
10608: $cusymb%$cudom+
10609: $cucourseid%$cuname+
10610: $cucourseid%$cudom);
10611: }
10612: return $return;
1.76 www 10613: }
10614:
10615: sub receipt {
1.474 albertel 10616: my ($part)=@_;
1.790 albertel 10617: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 10618: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 10619: }
1.260 ng 10620:
1.790 albertel 10621: sub whichuser {
10622: my ($passedsymb)=@_;
10623: my ($symb,$courseid,$domain,$name,$publicuser);
10624: if (defined($env{'form.grade_symb'})) {
10625: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
10626: my $allowed=&allowed('vgr',$tmp_courseid);
10627: if (!$allowed &&
10628: exists($env{'request.course.sec'}) &&
10629: $env{'request.course.sec'} !~ /^\s*$/) {
10630: $allowed=&allowed('vgr',$tmp_courseid.
10631: '/'.$env{'request.course.sec'});
10632: }
10633: if ($allowed) {
10634: ($symb)=&get_env_multiple('form.grade_symb');
10635: $courseid=$tmp_courseid;
10636: ($domain)=&get_env_multiple('form.grade_domain');
10637: ($name)=&get_env_multiple('form.grade_username');
10638: return ($symb,$courseid,$domain,$name,$publicuser);
10639: }
10640: }
10641: if (!$passedsymb) {
10642: $symb=&symbread();
10643: } else {
10644: $symb=$passedsymb;
10645: }
10646: $courseid=$env{'request.course.id'};
10647: $domain=$env{'user.domain'};
10648: $name=$env{'user.name'};
10649: if ($name eq 'public' && $domain eq 'public') {
10650: if (!defined($env{'form.username'})) {
10651: $env{'form.username'}.=time.rand(10000000);
10652: }
10653: $name.=$env{'form.username'};
10654: }
10655: return ($symb,$courseid,$domain,$name,$publicuser);
10656:
10657: }
10658:
1.36 albertel 10659: # ------------------------------------------------------------ Serves up a file
1.472 albertel 10660: # returns either the contents of the file or
10661: # -1 if the file doesn't exist
1.481 raeburn 10662: #
10663: # if the target is a file that was uploaded via DOCS,
10664: # a check will be made to see if a current copy exists on the local server,
10665: # if it does this will be served, otherwise a copy will be retrieved from
10666: # the home server for the course and stored in /home/httpd/html/userfiles on
10667: # the local server.
1.472 albertel 10668:
1.36 albertel 10669: sub getfile {
1.538 albertel 10670: my ($file) = @_;
1.609 banghart 10671: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 10672: &repcopy($file);
10673: return &readfile($file);
10674: }
10675:
10676: sub repcopy_userfile {
10677: my ($file)=@_;
1.1142 raeburn 10678: my $londocroot = $perlvar{'lonDocRoot'};
10679: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164 raeburn 10680: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538 albertel 10681: my ($cdom,$cnum,$filename) =
1.811 albertel 10682: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 10683: my $uri="/uploaded/$cdom/$cnum/$filename";
10684: if (-e "$file") {
1.828 www 10685: # we already have a local copy, check it out
1.538 albertel 10686: my @fileinfo = stat($file);
1.828 www 10687: my $rtncode;
10688: my $info;
1.538 albertel 10689: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 10690: if ($lwpresp ne 'ok') {
1.828 www 10691: # there is no such file anymore, even though we had a local copy
1.482 albertel 10692: if ($rtncode eq '404') {
1.538 albertel 10693: unlink($file);
1.482 albertel 10694: }
10695: return -1;
10696: }
10697: if ($info < $fileinfo[9]) {
1.828 www 10698: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 10699: return 'ok';
1.828 www 10700: } else {
10701: # the file is outdated, get rid of it
10702: unlink($file);
1.482 albertel 10703: }
1.828 www 10704: }
10705: # one way or the other, at this point, we don't have the file
10706: # construct the correct path for the file
10707: my @parts = ($cdom,$cnum);
10708: if ($filename =~ m|^(.+)/[^/]+$|) {
10709: push @parts, split(/\//,$1);
10710: }
10711: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
10712: foreach my $part (@parts) {
10713: $path .= '/'.$part;
10714: if (!-e $path) {
10715: mkdir($path,0770);
1.482 albertel 10716: }
10717: }
1.828 www 10718: # now the path exists for sure
10719: # get a user agent
10720: my $ua=new LWP::UserAgent;
10721: my $transferfile=$file.'.in.transfer';
10722: # FIXME: this should flock
10723: if (-e $transferfile) { return 'ok'; }
10724: my $request;
10725: $uri=~s/^\///;
1.980 raeburn 10726: my $homeserver = &homeserver($cnum,$cdom);
10727: my $protocol = $protocol{$homeserver};
10728: $protocol = 'http' if ($protocol ne 'https');
10729: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 10730: my $response=$ua->request($request,$transferfile);
10731: # did it work?
10732: if ($response->is_error()) {
10733: unlink($transferfile);
10734: &logthis("Userfile repcopy failed for $uri");
10735: return -1;
10736: }
10737: # worked, rename the transfer file
10738: rename($transferfile,$file);
1.607 raeburn 10739: return 'ok';
1.481 raeburn 10740: }
10741:
1.517 albertel 10742: sub tokenwrapper {
10743: my $uri=shift;
1.980 raeburn 10744: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 10745: $uri=~s|^/||;
1.620 albertel 10746: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 10747: my $token=$1;
1.552 albertel 10748: my (undef,$udom,$uname,$file)=split('/',$uri,4);
10749: if ($udom && $uname && $file) {
10750: $file=~s|(\?\.*)*$||;
1.949 raeburn 10751: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 10752: my $homeserver = &homeserver($uname,$udom);
10753: my $protocol = $protocol{$homeserver};
10754: $protocol = 'http' if ($protocol ne 'https');
10755: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 10756: (($uri=~/\?/)?'&':'?').'token='.$token.
10757: '&tokenissued='.$perlvar{'lonHostID'};
10758: } else {
10759: return '/adm/notfound.html';
10760: }
10761: }
10762:
1.828 www 10763: # call with reqtype HEAD: get last modification time
10764: # call with reqtype GET: get the file contents
10765: # Do not call this with reqtype GET for large files! It loads everything into memory
10766: #
1.481 raeburn 10767: sub getuploaded {
10768: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
10769: $uri=~s/^\///;
1.980 raeburn 10770: my $homeserver = &homeserver($cnum,$cdom);
10771: my $protocol = $protocol{$homeserver};
10772: $protocol = 'http' if ($protocol ne 'https');
10773: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 10774: my $ua=new LWP::UserAgent;
10775: my $request=new HTTP::Request($reqtype,$uri);
10776: my $response=$ua->request($request);
10777: $$rtncode = $response->code;
1.482 albertel 10778: if (! $response->is_success()) {
10779: return 'failed';
10780: }
10781: if ($reqtype eq 'HEAD') {
1.486 www 10782: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 10783: } elsif ($reqtype eq 'GET') {
10784: $$info = $response->content;
1.472 albertel 10785: }
1.482 albertel 10786: return 'ok';
1.36 albertel 10787: }
10788:
1.481 raeburn 10789: sub readfile {
10790: my $file = shift;
10791: if ( (! -e $file ) || ($file eq '') ) { return -1; };
10792: my $fh;
10793: open($fh,"<$file");
10794: my $a='';
1.800 albertel 10795: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 10796: return $a;
10797: }
10798:
1.36 albertel 10799: sub filelocation {
1.590 banghart 10800: my ($dir,$file) = @_;
10801: my $location;
10802: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 10803:
10804: if ($file =~ m-^/adm/-) {
10805: $file=~s-^/adm/wrapper/-/-;
10806: $file=~s-^/adm/coursedocs/showdoc/-/-;
10807: }
1.882 albertel 10808:
1.1139 www 10809: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956 raeburn 10810: $location = $file;
1.609 banghart 10811: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 10812: my ($udom,$uname,$filename)=
1.811 albertel 10813: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 10814: my $home=&homeserver($uname,$udom);
10815: my $is_me=0;
10816: my @ids=¤t_machine_ids();
10817: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
10818: if ($is_me) {
1.1117 foxr 10819: $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 10820: } else {
10821: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
10822: $udom.'/'.$uname.'/'.$filename;
10823: }
1.882 albertel 10824: } elsif ($file =~ m-^/adm/-) {
10825: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 10826: } else {
10827: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139 www 10828: $file=~s:^/(res|priv)/:/:;
10829: my $space=$1;
1.590 banghart 10830: if ( !( $file =~ m:^/:) ) {
10831: $location = $dir. '/'.$file;
10832: } else {
1.1142 raeburn 10833: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590 banghart 10834: }
1.59 albertel 10835: }
1.590 banghart 10836: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 10837: while ($location=~m{/\.\./}) {
10838: if ($location =~ m{/[^/]+/\.\./}) {
10839: $location=~ s{/[^/]+/\.\./}{/}g;
10840: } else {
10841: $location=~ s{/\.\./}{/}g;
10842: }
10843: } #remove dir/..
1.590 banghart 10844: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
10845: return $location;
1.46 www 10846: }
1.36 albertel 10847:
1.46 www 10848: sub hreflocation {
10849: my ($dir,$file)=@_;
1.980 raeburn 10850: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 10851: $file=filelocation($dir,$file);
1.700 albertel 10852: } elsif ($file=~m-^/adm/-) {
10853: $file=~s-^/adm/wrapper/-/-;
10854: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 10855: }
10856: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
10857: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
10858: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143 raeburn 10859: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
10860: {/uploaded/$1/$2/}x;
1.46 www 10861: }
1.913 albertel 10862: if ($file=~ m{^/userfiles/}) {
10863: $file =~ s{^/userfiles/}{/uploaded/};
10864: }
1.462 albertel 10865: return $file;
1.465 albertel 10866: }
10867:
1.1139 www 10868:
10869:
10870:
10871:
1.465 albertel 10872: sub current_machine_domains {
1.853 albertel 10873: return &machine_domains(&hostname($perlvar{'lonHostID'}));
10874: }
10875:
10876: sub machine_domains {
10877: my ($hostname) = @_;
1.465 albertel 10878: my @domains;
1.838 albertel 10879: my %hostname = &all_hostnames();
1.465 albertel 10880: while( my($id, $name) = each(%hostname)) {
1.467 matthew 10881: # &logthis("-$id-$name-$hostname-");
1.465 albertel 10882: if ($hostname eq $name) {
1.844 albertel 10883: push(@domains,&host_domain($id));
1.465 albertel 10884: }
10885: }
10886: return @domains;
10887: }
10888:
10889: sub current_machine_ids {
1.853 albertel 10890: return &machine_ids(&hostname($perlvar{'lonHostID'}));
10891: }
10892:
10893: sub machine_ids {
10894: my ($hostname) = @_;
10895: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 10896: my @ids;
1.888 albertel 10897: my %name_to_host = &all_names();
1.889 albertel 10898: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
10899: return @{ $name_to_host{$hostname} };
10900: }
10901: return;
1.31 www 10902: }
10903:
1.824 raeburn 10904: sub additional_machine_domains {
10905: my @domains;
10906: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
10907: while( my $line = <$fh>) {
10908: $line =~ s/\s//g;
10909: push(@domains,$line);
10910: }
10911: return @domains;
10912: }
10913:
10914: sub default_login_domain {
10915: my $domain = $perlvar{'lonDefDomain'};
10916: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
10917: foreach my $posdom (¤t_machine_domains(),
10918: &additional_machine_domains()) {
10919: if (lc($posdom) eq lc($testdomain)) {
10920: $domain=$posdom;
10921: last;
10922: }
10923: }
10924: return $domain;
10925: }
10926:
1.31 www 10927: # ------------------------------------------------------------- Declutters URLs
10928:
10929: sub declutter {
10930: my $thisfn=shift;
1.569 albertel 10931: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479 albertel 10932: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31 www 10933: $thisfn=~s/^\///;
1.697 albertel 10934: $thisfn=~s|^adm/wrapper/||;
10935: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 10936: $thisfn=~s/^res\///;
1.1172 bisitz 10937: $thisfn=~s/^priv\///;
1.1032 raeburn 10938: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
10939: $thisfn=~s/\?.+$//;
10940: }
1.268 www 10941: return $thisfn;
10942: }
10943:
10944: # ------------------------------------------------------------- Clutter up URLs
10945:
10946: sub clutter {
10947: my $thisfn='/'.&declutter(shift);
1.887 albertel 10948: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 10949: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 10950: $thisfn='/res'.$thisfn;
10951: }
1.1031 raeburn 10952: if ($thisfn !~m|^/adm|) {
10953: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 10954: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 10955: } else {
10956: my ($ext) = ($thisfn =~ /\.(\w+)$/);
10957: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 10958: if ($embstyle eq 'ssi'
10959: || ($embstyle eq 'hdn')
10960: || ($embstyle eq 'rat')
10961: || ($embstyle eq 'prv')
10962: || ($embstyle eq 'ign')) {
10963: #do nothing with these
10964: } elsif (($embstyle eq 'img')
1.695 albertel 10965: || ($embstyle eq 'emb')
10966: || ($embstyle eq 'wrp')) {
10967: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 10968: } elsif ($embstyle eq 'unk'
10969: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 10970: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 10971: } else {
1.718 www 10972: # &logthis("Got a blank emb style");
1.695 albertel 10973: }
1.694 albertel 10974: }
10975: }
1.31 www 10976: return $thisfn;
1.12 www 10977: }
10978:
1.787 albertel 10979: sub clutter_with_no_wrapper {
10980: my $uri = &clutter(shift);
10981: if ($uri =~ m-^/adm/-) {
10982: $uri =~ s-^/adm/wrapper/-/-;
10983: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
10984: }
10985: return $uri;
10986: }
10987:
1.557 albertel 10988: sub freeze_escape {
10989: my ($value)=@_;
10990: if (ref($value)) {
10991: $value=&nfreeze($value);
10992: return '__FROZEN__'.&escape($value);
10993: }
10994: return &escape($value);
10995: }
10996:
1.11 www 10997:
1.557 albertel 10998: sub thaw_unescape {
10999: my ($value)=@_;
11000: if ($value =~ /^__FROZEN__/) {
11001: substr($value,0,10,undef);
11002: $value=&unescape($value);
11003: return &thaw($value);
11004: }
11005: return &unescape($value);
11006: }
11007:
1.436 albertel 11008: sub correct_line_ends {
11009: my ($result)=@_;
11010: $$result =~s/\r\n/\n/mg;
11011: $$result =~s/\r/\n/mg;
1.415 albertel 11012: }
1.1 albertel 11013: # ================================================================ Main Program
11014:
1.184 www 11015: sub goodbye {
1.204 albertel 11016: &logthis("Starting Shut down");
1.443 albertel 11017: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 11018: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 11019: #converted
1.599 albertel 11020: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 11021: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
11022: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
11023: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 11024: #1.1 only
1.870 albertel 11025: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
11026: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
11027: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
11028: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
11029: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 11030: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
11031: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 11032: &flushcourselogs();
11033: &logthis("Shutting down");
11034: }
11035:
1.852 albertel 11036: sub get_dns {
1.869 albertel 11037: my ($url,$func,$ignore_cache) = @_;
11038: if (!$ignore_cache) {
11039: my ($content,$cached)=
11040: &Apache::lonnet::is_cached_new('dns',$url);
11041: if ($cached) {
11042: &$func($content);
11043: return;
11044: }
11045: }
11046:
11047: my %alldns;
1.852 albertel 11048: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11049: foreach my $dns (<$config>) {
11050: next if ($dns !~ /^\^(\S*)/x);
1.979 raeburn 11051: my $line = $1;
11052: my ($host,$protocol) = split(/:/,$line);
11053: if ($protocol ne 'https') {
11054: $protocol = 'http';
11055: }
11056: $alldns{$host} = $protocol;
1.869 albertel 11057: }
11058: while (%alldns) {
11059: my ($dns) = keys(%alldns);
1.852 albertel 11060: my $ua=new LWP::UserAgent;
1.1134 raeburn 11061: $ua->timeout(30);
1.979 raeburn 11062: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 11063: my $response=$ua->request($request);
1.979 raeburn 11064: delete($alldns{$dns});
1.852 albertel 11065: next if ($response->is_error());
11066: my @content = split("\n",$response->content);
1.869 albertel 11067: &Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852 albertel 11068: &$func(\@content);
1.869 albertel 11069: return;
1.852 albertel 11070: }
11071: close($config);
1.871 albertel 11072: my $which = (split('/',$url))[3];
11073: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
11074: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 11075: my @content = <$config>;
11076: &$func(\@content);
11077: return;
1.852 albertel 11078: }
1.327 albertel 11079: # ------------------------------------------------------------ Read domain file
11080: {
1.852 albertel 11081: my $loaded;
1.846 albertel 11082: my %domain;
11083:
1.852 albertel 11084: sub parse_domain_tab {
11085: my ($lines) = @_;
11086: foreach my $line (@$lines) {
11087: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 11088:
1.846 albertel 11089: chomp($line);
1.852 albertel 11090: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 11091: my %this_domain;
11092: foreach my $field ('description', 'auth_def', 'auth_arg_def',
11093: 'lang_def', 'city', 'longi', 'lati',
11094: 'primary') {
11095: $this_domain{$field} = shift(@elements);
11096: }
11097: $domain{$name} = \%this_domain;
1.852 albertel 11098: }
11099: }
1.864 albertel 11100:
11101: sub reset_domain_info {
11102: undef($loaded);
11103: undef(%domain);
11104: }
11105:
1.852 albertel 11106: sub load_domain_tab {
1.869 albertel 11107: my ($ignore_cache) = @_;
11108: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852 albertel 11109: my $fh;
11110: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
11111: my @lines = <$fh>;
11112: &parse_domain_tab(\@lines);
1.448 albertel 11113: }
1.852 albertel 11114: close($fh);
11115: $loaded = 1;
1.327 albertel 11116: }
1.846 albertel 11117:
11118: sub domain {
1.852 albertel 11119: &load_domain_tab() if (!$loaded);
11120:
1.846 albertel 11121: my ($name,$what) = @_;
11122: return if ( !exists($domain{$name}) );
11123:
11124: if (!$what) {
11125: return $domain{$name}{'description'};
11126: }
11127: return $domain{$name}{$what};
11128: }
1.974 raeburn 11129:
11130: sub domain_info {
11131: &load_domain_tab() if (!$loaded);
11132: return %domain;
11133: }
11134:
1.327 albertel 11135: }
11136:
11137:
1.1 albertel 11138: # ------------------------------------------------------------- Read hosts file
11139: {
1.838 albertel 11140: my %hostname;
1.844 albertel 11141: my %hostdom;
1.845 albertel 11142: my %libserv;
1.852 albertel 11143: my $loaded;
1.888 albertel 11144: my %name_to_host;
1.1074 raeburn 11145: my %internetdom;
1.1107 raeburn 11146: my %LC_dns_serv;
1.852 albertel 11147:
11148: sub parse_hosts_tab {
11149: my ($file) = @_;
11150: foreach my $configline (@$file) {
11151: next if ($configline =~ /^(\#|\s*$ )/x);
1.1107 raeburn 11152: chomp($configline);
11153: if ($configline =~ /^\^/) {
11154: if ($configline =~ /^\^([\w.\-]+)/) {
11155: $LC_dns_serv{$1} = 1;
11156: }
11157: next;
11158: }
1.1074 raeburn 11159: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 11160: $name=~s/\s//g;
11161: if ($id && $domain && $role && $name) {
11162: $hostname{$id}=$name;
1.888 albertel 11163: push(@{$name_to_host{$name}}, $id);
1.852 albertel 11164: $hostdom{$id}=$domain;
11165: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 11166: if (defined($protocol)) {
11167: if ($protocol eq 'https') {
11168: $protocol{$id} = $protocol;
11169: } else {
11170: $protocol{$id} = 'http';
11171: }
1.968 raeburn 11172: } else {
1.969 raeburn 11173: $protocol{$id} = 'http';
1.968 raeburn 11174: }
1.1074 raeburn 11175: if (defined($intdom)) {
11176: $internetdom{$id} = $intdom;
11177: }
1.852 albertel 11178: }
11179: }
11180: }
1.864 albertel 11181:
11182: sub reset_hosts_info {
1.897 albertel 11183: &purge_remembered();
1.864 albertel 11184: &reset_domain_info();
11185: &reset_hosts_ip_info();
1.892 albertel 11186: undef(%name_to_host);
1.864 albertel 11187: undef(%hostname);
11188: undef(%hostdom);
11189: undef(%libserv);
11190: undef($loaded);
11191: }
1.1 albertel 11192:
1.852 albertel 11193: sub load_hosts_tab {
1.869 albertel 11194: my ($ignore_cache) = @_;
11195: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852 albertel 11196: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11197: my @config = <$config>;
11198: &parse_hosts_tab(\@config);
11199: close($config);
11200: $loaded=1;
1.1 albertel 11201: }
1.852 albertel 11202:
1.838 albertel 11203: sub hostname {
1.852 albertel 11204: &load_hosts_tab() if (!$loaded);
11205:
1.838 albertel 11206: my ($lonid) = @_;
11207: return $hostname{$lonid};
11208: }
1.845 albertel 11209:
1.838 albertel 11210: sub all_hostnames {
1.852 albertel 11211: &load_hosts_tab() if (!$loaded);
11212:
1.838 albertel 11213: return %hostname;
11214: }
1.845 albertel 11215:
1.888 albertel 11216: sub all_names {
11217: &load_hosts_tab() if (!$loaded);
11218:
11219: return %name_to_host;
11220: }
11221:
1.974 raeburn 11222: sub all_host_domain {
11223: &load_hosts_tab() if (!$loaded);
11224: return %hostdom;
11225: }
11226:
1.845 albertel 11227: sub is_library {
1.852 albertel 11228: &load_hosts_tab() if (!$loaded);
11229:
1.845 albertel 11230: return exists($libserv{$_[0]});
11231: }
11232:
11233: sub all_library {
1.852 albertel 11234: &load_hosts_tab() if (!$loaded);
11235:
1.845 albertel 11236: return %libserv;
11237: }
11238:
1.1062 droeschl 11239: sub unique_library {
11240: #2x reverse removes all hostnames that appear more than once
11241: my %unique = reverse &all_library();
11242: return reverse %unique;
11243: }
11244:
1.841 albertel 11245: sub get_servers {
1.852 albertel 11246: &load_hosts_tab() if (!$loaded);
11247:
1.841 albertel 11248: my ($domain,$type) = @_;
11249: my %possible_hosts = ($type eq 'library') ? %libserv
11250: : %hostname;
11251: my %result;
1.842 albertel 11252: if (ref($domain) eq 'ARRAY') {
11253: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 11254: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 11255: $result{$host} = $hostname;
11256: }
11257: }
11258: } else {
11259: while ( my ($host,$hostname) = each(%possible_hosts)) {
11260: if ($hostdom{$host} eq $domain) {
11261: $result{$host} = $hostname;
11262: }
1.841 albertel 11263: }
11264: }
11265: return %result;
11266: }
1.845 albertel 11267:
1.1062 droeschl 11268: sub get_unique_servers {
11269: my %unique = reverse &get_servers(@_);
11270: return reverse %unique;
11271: }
11272:
1.844 albertel 11273: sub host_domain {
1.852 albertel 11274: &load_hosts_tab() if (!$loaded);
11275:
1.844 albertel 11276: my ($lonid) = @_;
11277: return $hostdom{$lonid};
11278: }
11279:
1.841 albertel 11280: sub all_domains {
1.852 albertel 11281: &load_hosts_tab() if (!$loaded);
11282:
1.841 albertel 11283: my %seen;
11284: my @uniq = grep(!$seen{$_}++, values(%hostdom));
11285: return @uniq;
11286: }
1.1074 raeburn 11287:
11288: sub internet_dom {
11289: &load_hosts_tab() if (!$loaded);
11290:
11291: my ($lonid) = @_;
11292: return $internetdom{$lonid};
11293: }
1.1107 raeburn 11294:
11295: sub is_LC_dns {
11296: &load_hosts_tab() if (!$loaded);
11297:
11298: my ($hostname) = @_;
11299: return exists($LC_dns_serv{$hostname});
11300: }
11301:
1.1 albertel 11302: }
11303:
1.847 albertel 11304: {
11305: my %iphost;
1.856 albertel 11306: my %name_to_ip;
11307: my %lonid_to_ip;
1.869 albertel 11308:
1.847 albertel 11309: sub get_hosts_from_ip {
11310: my ($ip) = @_;
11311: my %iphosts = &get_iphost();
11312: if (ref($iphosts{$ip})) {
11313: return @{$iphosts{$ip}};
11314: }
11315: return;
1.839 albertel 11316: }
1.864 albertel 11317:
11318: sub reset_hosts_ip_info {
11319: undef(%iphost);
11320: undef(%name_to_ip);
11321: undef(%lonid_to_ip);
11322: }
1.856 albertel 11323:
11324: sub get_host_ip {
11325: my ($lonid) = @_;
11326: if (exists($lonid_to_ip{$lonid})) {
11327: return $lonid_to_ip{$lonid};
11328: }
11329: my $name=&hostname($lonid);
11330: my $ip = gethostbyname($name);
11331: return if (!$ip || length($ip) ne 4);
11332: $ip=inet_ntoa($ip);
11333: $name_to_ip{$name} = $ip;
11334: $lonid_to_ip{$lonid} = $ip;
11335: return $ip;
11336: }
1.847 albertel 11337:
11338: sub get_iphost {
1.869 albertel 11339: my ($ignore_cache) = @_;
1.894 albertel 11340:
1.869 albertel 11341: if (!$ignore_cache) {
11342: if (%iphost) {
11343: return %iphost;
11344: }
11345: my ($ip_info,$cached)=
11346: &Apache::lonnet::is_cached_new('iphost','iphost');
11347: if ($cached) {
11348: %iphost = %{$ip_info->[0]};
11349: %name_to_ip = %{$ip_info->[1]};
11350: %lonid_to_ip = %{$ip_info->[2]};
11351: return %iphost;
11352: }
11353: }
1.894 albertel 11354:
11355: # get yesterday's info for fallback
11356: my %old_name_to_ip;
11357: my ($ip_info,$cached)=
11358: &Apache::lonnet::is_cached_new('iphost','iphost');
11359: if ($cached) {
11360: %old_name_to_ip = %{$ip_info->[1]};
11361: }
11362:
1.888 albertel 11363: my %name_to_host = &all_names();
11364: foreach my $name (keys(%name_to_host)) {
1.847 albertel 11365: my $ip;
11366: if (!exists($name_to_ip{$name})) {
11367: $ip = gethostbyname($name);
11368: if (!$ip || length($ip) ne 4) {
1.894 albertel 11369: if (defined($old_name_to_ip{$name})) {
11370: $ip = $old_name_to_ip{$name};
11371: &logthis("Can't find $name defaulting to old $ip");
11372: } else {
11373: &logthis("Name $name no IP found");
11374: next;
11375: }
11376: } else {
11377: $ip=inet_ntoa($ip);
1.847 albertel 11378: }
11379: $name_to_ip{$name} = $ip;
11380: } else {
11381: $ip = $name_to_ip{$name};
1.653 albertel 11382: }
1.888 albertel 11383: foreach my $id (@{ $name_to_host{$name} }) {
11384: $lonid_to_ip{$id} = $ip;
11385: }
11386: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 11387: }
1.869 albertel 11388: &Apache::lonnet::do_cache_new('iphost','iphost',
11389: [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894 albertel 11390: 48*60*60);
1.869 albertel 11391:
1.847 albertel 11392: return %iphost;
1.598 albertel 11393: }
11394:
1.992 raeburn 11395: #
11396: # Given a DNS returns the loncapa host name for that DNS
11397: #
11398: sub host_from_dns {
11399: my ($dns) = @_;
11400: my @hosts;
11401: my $ip;
11402:
1.993 raeburn 11403: if (exists($name_to_ip{$dns})) {
1.992 raeburn 11404: $ip = $name_to_ip{$dns};
11405: }
11406: if (!$ip) {
11407: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
11408: if (length($ip) == 4) {
11409: $ip = &IO::Socket::inet_ntoa($ip);
11410: }
11411: }
11412: if ($ip) {
11413: @hosts = get_hosts_from_ip($ip);
11414: return $hosts[0];
11415: }
11416: return undef;
1.986 foxr 11417: }
1.992 raeburn 11418:
1.1074 raeburn 11419: sub get_internet_names {
11420: my ($lonid) = @_;
11421: return if ($lonid eq '');
11422: my ($idnref,$cached)=
11423: &Apache::lonnet::is_cached_new('internetnames',$lonid);
11424: if ($cached) {
11425: return $idnref;
11426: }
11427: my $ip = &get_host_ip($lonid);
11428: my @hosts = &get_hosts_from_ip($ip);
11429: my %iphost = &get_iphost();
11430: my (@idns,%seen);
11431: foreach my $id (@hosts) {
11432: my $dom = &host_domain($id);
11433: my $prim_id = &domain($dom,'primary');
11434: my $prim_ip = &get_host_ip($prim_id);
11435: next if ($seen{$prim_ip});
11436: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
11437: foreach my $id (@{$iphost{$prim_ip}}) {
11438: my $intdom = &internet_dom($id);
11439: unless (grep(/^\Q$intdom\E$/,@idns)) {
11440: push(@idns,$intdom);
11441: }
11442: }
11443: }
11444: $seen{$prim_ip} = 1;
11445: }
11446: return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
11447: }
11448:
1.986 foxr 11449: }
11450:
1.1079 raeburn 11451: sub all_loncaparevs {
11452: 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);
11453: }
11454:
1.862 albertel 11455: BEGIN {
11456:
11457: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
11458: unless ($readit) {
11459: {
11460: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
11461: %perlvar = (%perlvar,%{$configvars});
11462: }
11463:
11464:
1.1 albertel 11465: # ------------------------------------------------------ Read spare server file
11466: {
1.448 albertel 11467: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 11468:
11469: while (my $configline=<$config>) {
11470: chomp($configline);
1.284 matthew 11471: if ($configline) {
1.784 albertel 11472: my ($host,$type) = split(':',$configline,2);
1.785 albertel 11473: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 11474: push(@{ $spareid{$type} }, $host);
1.1 albertel 11475: }
11476: }
1.448 albertel 11477: close($config);
1.1 albertel 11478: }
1.11 www 11479: # ------------------------------------------------------------ Read permissions
11480: {
1.448 albertel 11481: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 11482:
11483: while (my $configline=<$config>) {
1.448 albertel 11484: chomp($configline);
11485: if ($configline) {
11486: my ($role,$perm)=split(/ /,$configline);
11487: if ($perm ne '') { $pr{$role}=$perm; }
11488: }
1.11 www 11489: }
1.448 albertel 11490: close($config);
1.11 www 11491: }
11492:
11493: # -------------------------------------------- Read plain texts for permissions
11494: {
1.448 albertel 11495: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 11496:
11497: while (my $configline=<$config>) {
1.448 albertel 11498: chomp($configline);
11499: if ($configline) {
1.742 raeburn 11500: my ($short,@plain)=split(/:/,$configline);
11501: %{$prp{$short}} = ();
11502: if (@plain > 0) {
11503: $prp{$short}{'std'} = $plain[0];
11504: for (my $i=1; $i<@plain; $i++) {
11505: $prp{$short}{'alt'.$i} = $plain[$i];
11506: }
11507: }
1.448 albertel 11508: }
1.135 www 11509: }
1.448 albertel 11510: close($config);
1.135 www 11511: }
11512:
11513: # ---------------------------------------------------------- Read package table
11514: {
1.448 albertel 11515: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 11516:
11517: while (my $configline=<$config>) {
1.483 albertel 11518: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 11519: chomp($configline);
11520: my ($short,$plain)=split(/:/,$configline);
11521: my ($pack,$name)=split(/\&/,$short);
11522: if ($plain ne '') {
11523: $packagetab{$pack.'&'.$name.'&name'}=$name;
11524: $packagetab{$short}=$plain;
11525: }
1.11 www 11526: }
1.448 albertel 11527: close($config);
1.329 matthew 11528: }
11529:
1.1073 raeburn 11530: # ---------------------------------------------------------- Read loncaparev table
11531: {
11532: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
11533: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
11534: while (my $configline=<$config>) {
11535: chomp($configline);
11536: my ($hostid,$loncaparev)=split(/:/,$configline);
11537: $loncaparevs{$hostid}=$loncaparev;
11538: }
11539: close($config);
11540: }
11541: }
11542: }
11543:
1.1074 raeburn 11544: # ---------------------------------------------------------- Read serverhostID table
11545: {
11546: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
11547: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
11548: while (my $configline=<$config>) {
11549: chomp($configline);
11550: my ($name,$id)=split(/:/,$configline);
11551: $serverhomeIDs{$name}=$id;
11552: }
11553: close($config);
11554: }
11555: }
11556: }
11557:
1.1079 raeburn 11558: {
11559: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
11560: if (-e $file) {
11561: my $parser = HTML::LCParser->new($file);
11562: while (my $token = $parser->get_token()) {
11563: if ($token->[0] eq 'S') {
11564: my $item = $token->[1];
11565: my $name = $token->[2]{'name'};
11566: my $value = $token->[2]{'value'};
11567: if ($item ne '' && $name ne '' && $value ne '') {
11568: my $release = $parser->get_text();
11569: $release =~ s/(^\s*|\s*$ )//gx;
11570: $needsrelease{$item.':'.$name.':'.$value} = $release;
11571: }
11572: }
11573: }
11574: }
1.1073 raeburn 11575: }
11576:
1.1138 raeburn 11577: # ---------------------------------------------------------- Read managers table
11578: {
11579: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
11580: if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
11581: while (my $configline=<$config>) {
11582: chomp($configline);
11583: next if ($configline =~ /^\#/);
11584: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
11585: $managerstab{$configline} = 1;
11586: }
11587: }
11588: close($config);
11589: }
11590: }
11591: }
11592:
1.329 matthew 11593: # ------------- set up temporary directory
11594: {
1.1117 foxr 11595: $tmpdir = LONCAPA::tempdir();
1.329 matthew 11596:
1.11 www 11597: }
11598:
1.794 albertel 11599: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
11600: 'compress_threshold'=> 20_000,
11601: });
1.185 www 11602:
1.281 www 11603: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 11604: $dumpcount=0;
1.958 www 11605: $locknum=0;
1.22 www 11606:
1.163 harris41 11607: &logtouch();
1.672 albertel 11608: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 11609: $readit=1;
1.564 albertel 11610: {
11611: use integer;
11612: my $test=(2**32)+1;
1.568 albertel 11613: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 11614: &logthis(" Detected 64bit platform ($_64bit)");
11615: }
1.195 www 11616: }
1.1 albertel 11617: }
1.179 www 11618:
1.1 albertel 11619: 1;
1.191 harris41 11620: __END__
11621:
1.243 albertel 11622: =pod
11623:
1.191 harris41 11624: =head1 NAME
11625:
1.243 albertel 11626: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 11627:
11628: =head1 SYNOPSIS
11629:
1.243 albertel 11630: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 11631:
11632: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
11633:
1.243 albertel 11634: Common parameters:
11635:
11636: =over 4
11637:
11638: =item *
11639:
11640: $uname : an internal username (if $cname expecting a course Id specifically)
11641:
11642: =item *
11643:
11644: $udom : a domain (if $cdom expecting a course's domain specifically)
11645:
11646: =item *
11647:
11648: $symb : a resource instance identifier
11649:
11650: =item *
11651:
11652: $namespace : the name of a .db file that contains the data needed or
11653: being set.
11654:
11655: =back
11656:
1.394 bowersj2 11657: =head1 OVERVIEW
1.191 harris41 11658:
1.394 bowersj2 11659: lonnet provides subroutines which interact with the
11660: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
11661: about classes, users, and resources.
1.243 albertel 11662:
11663: For many of these objects you can also use this to store data about
11664: them or modify them in various ways.
1.191 harris41 11665:
1.394 bowersj2 11666: =head2 Symbs
1.191 harris41 11667:
1.394 bowersj2 11668: To identify a specific instance of a resource, LON-CAPA uses symbols
11669: or "symbs"X<symb>. These identifiers are built from the URL of the
11670: map, the resource number of the resource in the map, and the URL of
11671: the resource itself. The latter is somewhat redundant, but might help
11672: if maps change.
11673:
11674: An example is
11675:
11676: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
11677:
11678: The respective map entry is
11679:
11680: <resource id="19" src="/res/msu/korte/tests/part12.problem"
11681: title="Problem 2">
11682: </resource>
11683:
11684: Symbs are used by the random number generator, as well as to store and
11685: restore data specific to a certain instance of for example a problem.
11686:
11687: =head2 Storing And Retrieving Data
11688:
11689: X<store()>X<cstore()>X<restore()>Three of the most important functions
11690: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
11691: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
11692: is is the non-critical message twin of cstore. These functions are for
11693: handlers to store a perl hash to a user's permanent data space in an
11694: easy manner, and to retrieve it again on another call. It is expected
11695: that a handler would use this once at the beginning to retrieve data,
11696: and then again once at the end to send only the new data back.
11697:
11698: The data is stored in the user's data directory on the user's
11699: homeserver under the ID of the course.
11700:
11701: The hash that is returned by restore will have all of the previous
11702: value for all of the elements of the hash.
11703:
11704: Example:
11705:
11706: #creating a hash
11707: my %hash;
11708: $hash{'foo'}='bar';
11709:
11710: #storing it
11711: &Apache::lonnet::cstore(\%hash);
11712:
11713: #changing a value
11714: $hash{'foo'}='notbar';
11715:
11716: #adding a new value
11717: $hash{'bar'}='foo';
11718: &Apache::lonnet::cstore(\%hash);
11719:
11720: #retrieving the hash
11721: my %history=&Apache::lonnet::restore();
11722:
11723: #print the hash
11724: foreach my $key (sort(keys(%history))) {
11725: print("\%history{$key} = $history{$key}");
11726: }
11727:
11728: Will print out:
1.191 harris41 11729:
1.394 bowersj2 11730: %history{1:foo} = bar
11731: %history{1:keys} = foo:timestamp
11732: %history{1:timestamp} = 990455579
11733: %history{2:bar} = foo
11734: %history{2:foo} = notbar
11735: %history{2:keys} = foo:bar:timestamp
11736: %history{2:timestamp} = 990455580
11737: %history{bar} = foo
11738: %history{foo} = notbar
11739: %history{timestamp} = 990455580
11740: %history{version} = 2
11741:
11742: Note that the special hash entries C<keys>, C<version> and
11743: C<timestamp> were added to the hash. C<version> will be equal to the
11744: total number of versions of the data that have been stored. The
11745: C<timestamp> attribute will be the UNIX time the hash was
11746: stored. C<keys> is available in every historical section to list which
11747: keys were added or changed at a specific historical revision of a
11748: hash.
11749:
11750: B<Warning>: do not store the hash that restore returns directly. This
11751: will cause a mess since it will restore the historical keys as if the
11752: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 11753:
1.394 bowersj2 11754: Calling convention:
1.191 harris41 11755:
1.394 bowersj2 11756: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
11757: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191 harris41 11758:
1.394 bowersj2 11759: For more detailed information, see lonnet specific documentation.
1.191 harris41 11760:
1.394 bowersj2 11761: =head1 RETURN MESSAGES
1.191 harris41 11762:
1.394 bowersj2 11763: =over 4
1.191 harris41 11764:
1.394 bowersj2 11765: =item * B<con_lost>: unable to contact remote host
1.191 harris41 11766:
1.394 bowersj2 11767: =item * B<con_delayed>: unable to contact remote host, message will be delivered
11768: when the connection is brought back up
1.191 harris41 11769:
1.394 bowersj2 11770: =item * B<con_failed>: unable to contact remote host and unable to save message
11771: for later delivery
1.191 harris41 11772:
1.967 bisitz 11773: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 11774:
1.394 bowersj2 11775: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 11776: that was requested
1.191 harris41 11777:
1.243 albertel 11778: =back
1.191 harris41 11779:
1.243 albertel 11780: =head1 PUBLIC SUBROUTINES
1.191 harris41 11781:
1.243 albertel 11782: =head2 Session Environment Functions
1.191 harris41 11783:
1.243 albertel 11784: =over 4
1.191 harris41 11785:
1.394 bowersj2 11786: =item *
11787: X<appenv()>
1.949 raeburn 11788: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 11789: the user envirnoment file, and will be restored for each access this
1.620 albertel 11790: user makes during this session, also modifies the %env for the current
1.949 raeburn 11791: process. Optional rolesarrayref - if defined contains a reference to an array
11792: of roles which are exempt from the restriction on modifying user.role entries
11793: in the user's environment.db and in %env.
1.191 harris41 11794:
11795: =item *
1.394 bowersj2 11796: X<delenv()>
1.987 raeburn 11797: B<delenv($delthis,$regexp)>: removes all items from the session
11798: environment file that begin with $delthis. If the
11799: optional second arg - $regexp - is true, $delthis is treated as a
11800: regular expression, otherwise \Q$delthis\E is used.
11801: The values are also deleted from the current processes %env.
1.191 harris41 11802:
1.795 albertel 11803: =item * get_env_multiple($name)
11804:
11805: gets $name from the %env hash, it seemlessly handles the cases where multiple
11806: values may be defined and end up as an array ref.
11807:
11808: returns an array of values
11809:
1.243 albertel 11810: =back
11811:
11812: =head2 User Information
1.191 harris41 11813:
1.243 albertel 11814: =over 4
1.191 harris41 11815:
11816: =item *
1.394 bowersj2 11817: X<queryauthenticate()>
11818: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 11819: authentication scheme
11820:
11821: =item *
1.394 bowersj2 11822: X<authenticate()>
1.1073 raeburn 11823: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 11824: authenticate user from domain's lib servers (first use the current
11825: one). C<$upass> should be the users password.
1.1073 raeburn 11826: $checkdefauth is optional (value is 1 if a check should be made to
11827: authenticate user using default authentication method, and allow
11828: account creation if username does not have account in the domain).
11829: $clientcancheckhost is optional (value is 1 if checking whether the
11830: server can host will occur on the client side in lonauth.pm).
1.191 harris41 11831:
11832: =item *
1.394 bowersj2 11833: X<homeserver()>
11834: B<homeserver($uname,$udom)>: find the server which has
11835: the user's directory and files (there must be only one), this caches
11836: the answer, and also caches if there is a borken connection.
1.191 harris41 11837:
11838: =item *
1.394 bowersj2 11839: X<idget()>
11840: B<idget($udom,@ids)>: find the usernames behind a list of IDs
11841: (IDs are a unique resource in a domain, there must be only 1 ID per
11842: username, and only 1 username per ID in a specific domain) (returns
11843: hash: id=>name,id=>name)
1.191 harris41 11844:
11845: =item *
1.394 bowersj2 11846: X<idrget()>
11847: B<idrget($udom,@unames)>: find the IDs behind a list of
11848: usernames (returns hash: name=>id,name=>id)
1.191 harris41 11849:
11850: =item *
1.394 bowersj2 11851: X<idput()>
11852: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 11853:
11854: =item *
1.394 bowersj2 11855: X<rolesinit()>
1.1169 droeschl 11856: B<rolesinit($udom,$username)>: get user privileges.
11857: returns user role, first access and timer interval hashes
1.243 albertel 11858:
11859: =item *
1.1171 droeschl 11860: X<privileged()>
11861: B<privileged($username,$domain)>: returns a true if user has a
11862: privileged and active role (i.e. su or dc), false otherwise.
11863:
11864: =item *
1.551 albertel 11865: X<getsection()>
11866: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 11867: course $cname, return section name/number or '' for "not in course"
11868: and '-1' for "no section"
11869:
11870: =item *
1.394 bowersj2 11871: X<userenvironment()>
11872: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 11873: passed in @what from the requested user's environment, returns a hash
11874:
1.858 raeburn 11875: =item *
11876: X<userlog_query()>
1.859 albertel 11877: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
11878: activity.log file. %filters defines filters applied when parsing the
11879: log file. These can be start or end timestamps, or the type of action
11880: - log to look for Login or Logout events, check for Checkin or
11881: Checkout, role for role selection. The response is in the form
11882: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
11883: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 11884:
1.243 albertel 11885: =back
11886:
11887: =head2 User Roles
11888:
11889: =over 4
11890:
11891: =item *
11892:
1.810 raeburn 11893: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243 albertel 11894: F: full access
11895: U,I,K: authentication modes (cxx only)
11896: '': forbidden
11897: 1: user needs to choose course
11898: 2: browse allowed
1.766 albertel 11899: A: passphrase authentication needed
1.243 albertel 11900:
11901: =item *
11902:
11903: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
11904: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
11905: and course level
11906:
11907: =item *
11908:
1.988 raeburn 11909: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
11910: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 11911: $type is Course (default) or Community.
1.988 raeburn 11912: If $forcedefault evaluates to true, text returned will be default
11913: text for $type. Otherwise, if this is a course, the text returned
11914: will be a custom name for the role (if defined in the course's
11915: environment). If no custom name is defined the default is returned.
11916:
1.832 raeburn 11917: =item *
11918:
1.935 raeburn 11919: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858 raeburn 11920: All arguments are optional. Returns a hash of a roles, either for
11921: co-author/assistant author roles for a user's Construction Space
1.906 albertel 11922: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 11923: In the hash, keys are set to colon-separated $uname,$udom,$role, and
11924: (optionally) if $withsec is true, a fourth colon-separated item - $section.
11925: For each key, value is set to colon-separated start and end times for
11926: the role. If no username and domain are specified, will default to
1.934 raeburn 11927: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 11928: of role statuses (active, future or previous), roles
11929: (e.g., cc,in, st etc.) and domains of the roles which can be used
11930: to restrict the list of roles reported. If no array ref is
11931: provided for types, will default to return only active roles.
1.834 albertel 11932:
1.243 albertel 11933: =back
11934:
11935: =head2 User Modification
11936:
11937: =over 4
11938:
11939: =item *
11940:
1.957 raeburn 11941: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 11942: user for the level given by URL. Optional start and end dates (leave empty
11943: string or zero for "no date")
1.191 harris41 11944:
11945: =item *
11946:
1.243 albertel 11947: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
11948: change a users, password, possible return values are: ok,
11949: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
11950: refused
1.191 harris41 11951:
11952: =item *
11953:
1.243 albertel 11954: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 11955:
11956: =item *
11957:
1.1058 raeburn 11958: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
11959: $forceid,$desiredhome,$email,$inststatus,$candelete) :
11960:
11961: will update user information (firstname,middlename,lastname,generation,
11962: permanentemail), and if forceid is true, student/employee ID also.
11963: A user's institutional affiliation(s) can also be updated.
11964: User information fields will not be overwritten with empty entries
11965: unless the field is included in the $candelete array reference.
11966: This array is included when a single user is modified via "Manage Users",
11967: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 11968:
11969: =item *
11970:
1.286 matthew 11971: modifystudent
11972:
1.957 raeburn 11973: modify a student's enrollment and identification information.
1.286 matthew 11974: The course id is resolved based on the current users environment.
11975: This means the envoking user must be a course coordinator or otherwise
11976: associated with a course.
11977:
1.297 matthew 11978: This call is essentially a wrapper for lonnet::modifyuser and
11979: lonnet::modify_student_enrollment
1.286 matthew 11980:
11981: Inputs:
11982:
11983: =over 4
11984:
1.957 raeburn 11985: =item B<$udom> Student's loncapa domain
1.286 matthew 11986:
1.957 raeburn 11987: =item B<$uname> Student's loncapa login name
1.286 matthew 11988:
1.964 bisitz 11989: =item B<$uid> Student/Employee ID
1.286 matthew 11990:
1.957 raeburn 11991: =item B<$umode> Student's authentication mode
1.286 matthew 11992:
1.957 raeburn 11993: =item B<$upass> Student's password
1.286 matthew 11994:
1.957 raeburn 11995: =item B<$first> Student's first name
1.286 matthew 11996:
1.957 raeburn 11997: =item B<$middle> Student's middle name
1.286 matthew 11998:
1.957 raeburn 11999: =item B<$last> Student's last name
1.286 matthew 12000:
1.957 raeburn 12001: =item B<$gene> Student's generation
1.286 matthew 12002:
1.957 raeburn 12003: =item B<$usec> Student's section in course
1.286 matthew 12004:
12005: =item B<$end> Unix time of the roles expiration
12006:
12007: =item B<$start> Unix time of the roles start date
12008:
12009: =item B<$forceid> If defined, allow $uid to be changed
12010:
12011: =item B<$desiredhome> server to use as home server for student
12012:
1.957 raeburn 12013: =item B<$email> Student's permanent e-mail address
12014:
12015: =item B<$type> Type of enrollment (auto or manual)
12016:
1.963 raeburn 12017: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
12018:
12019: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 12020:
1.963 raeburn 12021: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 12022:
1.963 raeburn 12023: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 12024:
1.963 raeburn 12025: =item B<$inststatus> institutional status of user - : separated string of escaped status types
1.957 raeburn 12026:
1.286 matthew 12027: =back
1.297 matthew 12028:
12029: =item *
12030:
12031: modify_student_enrollment
12032:
12033: Change a students enrollment status in a class. The environment variable
12034: 'role.request.course' must be defined for this function to proceed.
12035:
12036: Inputs:
12037:
12038: =over 4
12039:
12040: =item $udom, students domain
12041:
12042: =item $uname, students name
12043:
12044: =item $uid, students user id
12045:
12046: =item $first, students first name
12047:
12048: =item $middle
12049:
12050: =item $last
12051:
12052: =item $gene
12053:
12054: =item $usec
12055:
12056: =item $end
12057:
12058: =item $start
12059:
1.957 raeburn 12060: =item $type
12061:
12062: =item $locktype
12063:
12064: =item $cid
12065:
12066: =item $selfenroll
12067:
12068: =item $context
12069:
1.297 matthew 12070: =back
12071:
1.191 harris41 12072:
12073: =item *
12074:
1.243 albertel 12075: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
12076: custom role; give a custom role to a user for the level given by URL. Specify
12077: name and domain of role author, and role name
1.191 harris41 12078:
12079: =item *
12080:
1.243 albertel 12081: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 12082:
12083: =item *
12084:
1.243 albertel 12085: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
12086:
12087: =back
12088:
12089: =head2 Course Infomation
12090:
12091: =over 4
1.191 harris41 12092:
12093: =item *
12094:
1.1118 foxr 12095: coursedescription($courseid,$options) : returns a hash of information about the
1.631 albertel 12096: specified course id, including all environment settings for the
12097: course, the description of the course will be in the hash under the
12098: key 'description'
1.191 harris41 12099:
1.1118 foxr 12100: $options is an optional parameter that if supplied is a hash reference that controls
12101: what how this function works. It has the following key/values:
12102:
12103: =over 4
12104:
12105: =item freshen_cache
12106:
12107: If defined, and the environment cache for the course is valid, it is
12108: returned in the returned hash.
12109:
12110: =item one_time
12111:
12112: If defined, the last cache time is set to _now_
12113:
12114: =item user
12115:
12116: If defined, the supplied username is used instead of the current user.
12117:
12118:
12119: =back
12120:
1.191 harris41 12121: =item *
12122:
1.624 albertel 12123: resdata($name,$domain,$type,@which) : request for current parameter
12124: setting for a specific $type, where $type is either 'course' or 'user',
12125: @what should be a list of parameters to ask about. This routine caches
12126: answers for 5 minutes.
1.243 albertel 12127:
1.877 foxr 12128: =item *
12129:
12130: get_courseresdata($courseid, $domain) : dump the entire course resource
12131: data base, returning a hash that is keyed by the resource name and has
12132: values that are the resource value. I believe that the timestamps and
12133: versions are also returned.
12134:
12135:
1.243 albertel 12136: =back
12137:
12138: =head2 Course Modification
12139:
12140: =over 4
1.191 harris41 12141:
12142: =item *
12143:
1.243 albertel 12144: writecoursepref($courseid,%prefs) : write preferences (environment
12145: database) for a course
1.191 harris41 12146:
12147: =item *
12148:
1.1011 raeburn 12149: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
12150:
12151: =item *
12152:
1.1038 raeburn 12153: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 12154:
1.1167 droeschl 12155: =item *
12156:
12157: is_course($courseid), is_course($cdom, $cnum)
12158:
12159: Accepts either a combined $courseid (in the form of domain_courseid) or the
12160: two component version $cdom, $cnum. It checks if the specified course exists.
12161:
12162: Returns:
12163: undef if the course doesn't exist, otherwise
12164: in scalar context the combined courseid.
12165: in list context the two components of the course identifier, domain and
12166: courseid.
12167:
1.243 albertel 12168: =back
12169:
12170: =head2 Resource Subroutines
12171:
12172: =over 4
1.191 harris41 12173:
12174: =item *
12175:
1.243 albertel 12176: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 12177:
12178: =item *
12179:
1.243 albertel 12180: repcopy($filename) : subscribes to the requested file, and attempts to
12181: replicate from the owning library server, Might return
1.607 raeburn 12182: 'unavailable', 'not_found', 'forbidden', 'ok', or
12183: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 12184: resource. Expects the local filesystem pathname
12185: (/home/httpd/html/res/....)
12186:
12187: =back
12188:
12189: =head2 Resource Information
12190:
12191: =over 4
1.191 harris41 12192:
12193: =item *
12194:
1.243 albertel 12195: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
12196: a vairety of different possible values, $varname should be a request
12197: string, and the other parameters can be used to specify who and what
12198: one is asking about.
12199:
12200: Possible values for $varname are environment.lastname (or other item
12201: from the envirnment hash), user.name (or someother aspect about the
12202: user), resource.0.maxtries (or some other part and parameter of a
12203: resource)
1.204 albertel 12204:
12205: =item *
12206:
1.243 albertel 12207: directcondval($number) : get current value of a condition; reads from a state
12208: string
1.204 albertel 12209:
12210: =item *
12211:
1.243 albertel 12212: condval($condidx) : value of condition index based on state
1.204 albertel 12213:
12214: =item *
12215:
1.243 albertel 12216: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
12217: resource's metadata, $what should be either a specific key, or either
12218: 'keys' (to get a list of possible keys) or 'packages' to get a list of
12219: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
12220:
12221: this function automatically caches all requests
1.191 harris41 12222:
12223: =item *
12224:
1.243 albertel 12225: metadata_query($query,$custom,$customshow) : make a metadata query against the
12226: network of library servers; returns file handle of where SQL and regex results
12227: will be stored for query
1.191 harris41 12228:
12229: =item *
12230:
1.243 albertel 12231: symbread($filename) : return symbolic list entry (filename argument optional);
12232: returns the data handle
1.191 harris41 12233:
12234: =item *
12235:
1.1172.2.11 raeburn 12236: symbverify($symb,$thisfn,$ecstate) : verifies that $symb actually exists
12237: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582 albertel 12238: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11 raeburn 12239: on failure, user must be in a course, as it assumes the existence of
12240: the course initial hash, and uses $env('request.course.id'}. The third
12241: arg is an optional reference to a scalar. If this arg is passed in the
12242: call to symbverify, it will be set to 1 if the symb has been set to be
12243: encrypted; otherwise it will be null.
1.243 albertel 12244:
1.191 harris41 12245:
12246: =item *
12247:
1.243 albertel 12248: symbclean($symb) : removes versions numbers from a symb, returns the
12249: cleaned symb
1.191 harris41 12250:
12251: =item *
12252:
1.243 albertel 12253: is_on_map($uri) : checks if the $uri is somewhere on the current
12254: course map, user must be in a course for it to work.
1.191 harris41 12255:
12256: =item *
12257:
1.243 albertel 12258: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 12259:
12260: =item *
12261:
1.243 albertel 12262: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
12263: a random seed, all arguments are optional, if they aren't sent it uses the
12264: environment to derive them. Note: if symb isn't sent and it can't get one
12265: from &symbread it will use the current time as its return value
1.191 harris41 12266:
12267: =item *
12268:
1.243 albertel 12269: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
12270: unfakeable, receipt
1.191 harris41 12271:
12272: =item *
12273:
1.620 albertel 12274: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 12275:
12276: =item *
12277:
1.243 albertel 12278: countacc($url) : count the number of accesses to a given URL
1.191 harris41 12279:
12280: =item *
12281:
1.243 albertel 12282: 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 12283:
12284: =item *
12285:
1.243 albertel 12286: 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 12287:
12288: =item *
12289:
1.243 albertel 12290: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 12291:
12292: =item *
12293:
1.243 albertel 12294: devalidate($symb) : devalidate temporary spreadsheet calculations,
12295: forcing spreadsheet to reevaluate the resource scores next time.
12296:
12297: =back
12298:
12299: =head2 Storing/Retreiving Data
12300:
12301: =over 4
1.191 harris41 12302:
12303: =item *
12304:
1.243 albertel 12305: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
12306: for this url; hashref needs to be given and should be a \%hashname; the
12307: remaining args aren't required and if they aren't passed or are '' they will
1.620 albertel 12308: be derived from the env
1.191 harris41 12309:
12310: =item *
12311:
1.243 albertel 12312: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
12313: uses critical subroutine
1.191 harris41 12314:
12315: =item *
12316:
1.243 albertel 12317: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
12318: all args are optional
1.191 harris41 12319:
12320: =item *
12321:
1.717 albertel 12322: dumpstore($namespace,$udom,$uname,$regexp,$range) :
12323: dumps the complete (or key matching regexp) namespace into a hash
12324: ($udom, $uname, $regexp, $range are optional) for a namespace that is
12325: normally &store()ed into
12326:
12327: $range should be either an integer '100' (give me the first 100
12328: matching records)
12329: or be two integers sperated by a - with no spaces
12330: '30-50' (give me the 30th through the 50th matching
12331: records)
12332:
12333:
12334: =item *
12335:
12336: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
12337: replaces a &store() version of data with a replacement set of data
12338: for a particular resource in a namespace passed in the $storehash hash
12339: reference
12340:
12341: =item *
12342:
1.243 albertel 12343: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
12344: works very similar to store/cstore, but all data is stored in a
12345: temporary location and can be reset using tmpreset, $storehash should
12346: be a hash reference, returns nothing on success
1.191 harris41 12347:
12348: =item *
12349:
1.243 albertel 12350: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
12351: similar to restore, but all data is stored in a temporary location and
12352: can be reset using tmpreset. Returns a hash of values on success,
12353: error string otherwise.
1.191 harris41 12354:
12355: =item *
12356:
1.243 albertel 12357: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
12358: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 12359:
12360: =item *
12361:
1.243 albertel 12362: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
12363: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 12364:
12365: =item *
12366:
1.243 albertel 12367: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
12368: namesp ($udom and $uname are optional)
1.191 harris41 12369:
12370: =item *
12371:
1.702 albertel 12372: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 12373: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 12374: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 12375:
1.702 albertel 12376: $range should be either an integer '100' (give me the first 100
12377: matching records)
12378: or be two integers sperated by a - with no spaces
12379: '30-50' (give me the 30th through the 50th matching
12380: records)
1.449 matthew 12381: =item *
12382:
12383: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
12384: $store can be a scalar, an array reference, or if the amount to be
12385: incremented is > 1, a hash reference.
12386:
12387: ($udom and $uname are optional)
1.191 harris41 12388:
12389: =item *
12390:
1.243 albertel 12391: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
12392: ($udom and $uname are optional)
1.191 harris41 12393:
12394: =item *
12395:
1.243 albertel 12396: cput($namespace,$storehash,$udom,$uname) : critical put
12397: ($udom and $uname are optional)
1.191 harris41 12398:
12399: =item *
12400:
1.748 albertel 12401: newput($namespace,$storehash,$udom,$uname) :
12402:
12403: Attempts to store the items in the $storehash, but only if they don't
12404: currently exist, if this succeeds you can be certain that you have
12405: successfully created a new key value pair in the $namespace db.
12406:
12407:
12408: Args:
12409: $namespace: name of database to store values to
12410: $storehash: hashref to store to the db
12411: $udom: (optional) domain of user containing the db
12412: $uname: (optional) name of user caontaining the db
12413:
12414: Returns:
12415: 'ok' -> succeeded in storing all keys of $storehash
12416: 'key_exists: <key>' -> failed to anything out of $storehash, as at
12417: least <key> already existed in the db (other
12418: requested keys may also already exist)
1.967 bisitz 12419: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 12420: 'con_lost' -> unable to contact request server
12421: 'refused' -> action was not allowed by remote machine
12422:
12423:
12424: =item *
12425:
1.243 albertel 12426: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
12427: reference filled in from namesp (encrypts the return communication)
12428: ($udom and $uname are optional)
1.191 harris41 12429:
12430: =item *
12431:
1.243 albertel 12432: log($udom,$name,$home,$message) : write to permanent log for user; use
12433: critical subroutine
12434:
1.806 raeburn 12435: =item *
12436:
1.860 raeburn 12437: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
12438: array reference filled in from namespace found in domain level on either
12439: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 12440:
12441: =item *
12442:
1.860 raeburn 12443: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
12444: domain level either on specified domain server ($uhome) or primary domain
12445: server ($udom and $uhome are optional)
1.806 raeburn 12446:
1.943 raeburn 12447: =item *
12448:
12449: get_domain_defaults($target_domain) : returns hash with defaults for
12450: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
12451: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
12452: or localauth), initial password or a kerberos realm, language (e.g., en-us).
12453: Values are retrieved from cache (if current), or from domain's configuration.db
12454: (if available), or lastly from values in lonTabs/dns_domain,tab,
12455: or lonTabs/domain.tab.
12456:
12457: %domdefaults = &get_auth_defaults($target_domain);
12458:
1.243 albertel 12459: =back
12460:
12461: =head2 Network Status Functions
12462:
12463: =over 4
1.191 harris41 12464:
12465: =item *
12466:
1.1137 raeburn 12467: dirlist() : return directory list based on URI (first arg).
12468:
12469: Inputs: 1 required, 5 optional.
12470:
12471: =over
12472:
12473: =item
12474: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
12475:
12476: =item
12477: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
12478:
12479: =item
12480: $username - username of user/course to be listed. Extracted from $uri if absent.
12481:
12482: =item
12483: $getpropath - boolean: 1 if prepend path using &propath().
12484:
12485: =item
12486: $getuserdir - boolean: 1 if prepend path for "userfiles".
12487:
12488: =item
12489: $alternateRoot - path to prepend in place of path from $uri.
12490:
12491: =back
12492:
12493: Returns: Array of up to two items.
12494:
12495: =over
12496:
12497: a reference to an array of files/subdirectories
12498:
12499: =over
12500:
12501: Each element in the array of files/subdirectories is a & separated list of
12502: item name and the result of running stat on the item. If dirlist was requested
12503: for a file instead of a directory, the item name will be ''. For a directory
12504: listing, if the item is a metadata file, the element will end &N&M
12505: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
12506: default copyright set (1).
12507:
12508: =back
12509:
12510: a scalar containing error condition (if encountered).
12511:
12512: =over
12513:
12514: =item
12515: no_host (no homeserver identified for $username:$domain).
12516:
12517: =item
12518: no_such_host (server contacted for listing not identified as valid host).
12519:
12520: =item
12521: con_lost (connection to remote server failed).
12522:
12523: =item
12524: refused (invalid $username:$domain received on lond side).
12525:
12526: =item
12527: no_such_dir (directory at specified path on lond side does not exist).
12528:
12529: =item
12530: empty (directory at specified path on lond side is empty).
12531:
12532: =over
12533:
12534: This is currently not encountered because the &ls3, &ls2,
12535: &ls (_handler) routines on the lond side do not filter out
12536: . and .. from a directory listing.
12537:
12538: =back
12539:
12540: =back
12541:
12542: =back
1.191 harris41 12543:
12544: =item *
12545:
1.243 albertel 12546: spareserver() : find server with least workload from spare.tab
12547:
1.986 foxr 12548:
12549: =item *
12550:
12551: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
12552: if there is no corresponding loncapa host.
12553:
1.243 albertel 12554: =back
12555:
1.986 foxr 12556:
1.243 albertel 12557: =head2 Apache Request
12558:
12559: =over 4
1.191 harris41 12560:
12561: =item *
12562:
1.243 albertel 12563: ssi($url,%hash) : server side include, does a complete request cycle on url to
12564: localhost, posts hash
12565:
12566: =back
12567:
12568: =head2 Data to String to Data
12569:
12570: =over 4
1.191 harris41 12571:
12572: =item *
12573:
1.243 albertel 12574: hash2str(%hash) : convert a hash into a string complete with escaping and '='
12575: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 12576:
12577: =item *
12578:
1.243 albertel 12579: hashref2str($hashref) : convert a hashref into a string complete with
12580: escaping and '=' and '&' separators, supports elements that are
12581: arrayrefs and hashrefs
1.191 harris41 12582:
12583: =item *
12584:
1.243 albertel 12585: arrayref2str($arrayref) : convert an arrayref into a string complete
12586: with escaping and '&' separators, supports elements that are arrayrefs
12587: and hashrefs
1.191 harris41 12588:
12589: =item *
12590:
1.243 albertel 12591: str2hash($string) : convert string to hash using unescaping and
12592: splitting on '=' and '&', supports elements that are arrayrefs and
12593: hashrefs
1.191 harris41 12594:
12595: =item *
12596:
1.243 albertel 12597: str2array($string) : convert string to hash using unescaping and
12598: splitting on '&', supports elements that are arrayrefs and hashrefs
12599:
12600: =back
12601:
12602: =head2 Logging Routines
12603:
12604:
12605: These routines allow one to make log messages in the lonnet.log and
12606: lonnet.perm logfiles.
1.191 harris41 12607:
1.1119 foxr 12608: =over 4
12609:
1.191 harris41 12610: =item *
12611:
1.243 albertel 12612: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 12613:
12614: =item *
12615:
1.243 albertel 12616: logthis() : append message to the normal lonnet.log file, it gets
12617: preiodically rolled over and deleted.
1.191 harris41 12618:
12619: =item *
12620:
1.243 albertel 12621: logperm() : append a permanent message to lonnet.perm.log, this log
12622: file never gets deleted by any automated portion of the system, only
12623: messages of critical importance should go in here.
12624:
1.1119 foxr 12625:
1.243 albertel 12626: =back
12627:
12628: =head2 General File Helper Routines
12629:
12630: =over 4
1.191 harris41 12631:
12632: =item *
12633:
1.481 raeburn 12634: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
12635: (a) files in /uploaded
12636: (i) If a local copy of the file exists -
12637: compares modification date of local copy with last-modified date for
12638: definitive version stored on home server for course. If local copy is
12639: stale, requests a new version from the home server and stores it.
12640: If the original has been removed from the home server, then local copy
12641: is unlinked.
12642: (ii) If local copy does not exist -
12643: requests the file from the home server and stores it.
12644:
12645: If $caller is 'uploadrep':
12646: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
12647: for request for files originally uploaded via DOCS.
12648: - returns 'ok' if fresh local copy now available, -1 otherwise.
12649:
12650: Otherwise:
12651: This indicates a call from the content generation phase of the request.
12652: - returns the entire contents of the file or -1.
12653:
12654: (b) files in /res
12655: - returns the entire contents of a file or -1;
12656: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 12657:
1.712 albertel 12658:
12659: =item *
12660:
12661: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
12662: reference
12663:
12664: returns either a stat() list of data about the file or an empty list
12665: if the file doesn't exist or couldn't find out about it (connection
12666: problems or user unknown)
12667:
1.191 harris41 12668: =item *
12669:
1.243 albertel 12670: filelocation($dir,$file) : returns file system location of a file
12671: based on URI; meant to be "fairly clean" absolute reference, $dir is a
12672: directory that relative $file lookups are to looked in ($dir of /a/dir
12673: and a file of ../bob will become /a/bob)
1.191 harris41 12674:
12675: =item *
12676:
12677: hreflocation($dir,$file) : returns file system location or a URL; same as
12678: filelocation except for hrefs
12679:
12680: =item *
12681:
12682: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
12683:
1.243 albertel 12684: =back
12685:
1.608 albertel 12686: =head2 Usererfile file routines (/uploaded*)
12687:
12688: =over 4
12689:
12690: =item *
12691:
12692: userfileupload(): main rotine for putting a file in a user or course's
12693: filespace, arguments are,
12694:
1.620 albertel 12695: formname - required - this is the name of the element in $env where the
1.608 albertel 12696: filename, and the contents of the file to create/modifed exist
1.620 albertel 12697: the filename is in $env{'form.'.$formname.'.filename'} and the
12698: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 12699: context - if coursedoc, store the file in the course of the active role
12700: of the current user;
12701: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
12702: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 12703: subdir - required - subdirectory to put the file in under ../userfiles/
12704: if undefined, it will be placed in "unknown"
12705:
12706: (This routine calls clean_filename() to remove any dangerous
12707: characters from the filename, and then calls finuserfileupload() to
12708: complete the transaction)
12709:
12710: returns either the url of the uploaded file (/uploaded/....) if successful
12711: and /adm/notfound.html if unsuccessful
12712:
12713: =item *
12714:
12715: clean_filename(): routine for cleaing a filename up for storage in
12716: userfile space, argument is:
12717:
12718: filename - proposed filename
12719:
12720: returns: the new clean filename
12721:
12722: =item *
12723:
1.1090 raeburn 12724: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 12725: userspace, probably shouldn't be called directly
12726:
12727: docuname: username or courseid of destination for the file
12728: docudom: domain of user/course of destination for the file
12729: formname: same as for userfileupload()
1.1090 raeburn 12730: fname: filename (including subdirectories) for the file
12731: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
12732: allfiles: reference to hash used to store objects found by parser
12733: codebase: reference to hash used for codebases of java objects found by parser
12734: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
12735: thumbheight: height (pixels) of thumbnail to be created for uploaded image
12736: resizewidth: width to be used to resize image using resizeImage from ImageMagick
12737: resizeheight: height to be used to resize image using resizeImage from ImageMagick
12738: context: if 'overwrite', will move the uploaded file from its temporary location to
12739: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 12740: mimetype: reference to scalar to accommodate mime type determined
12741: from File::MMagic if $parser = parse.
1.608 albertel 12742:
12743: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 12744: and /adm/notfound.html if unsuccessful (or an error message if context
12745: was 'overwrite').
12746:
1.608 albertel 12747:
12748: =item *
12749:
12750: renameuserfile(): renames an existing userfile to a new name
12751:
12752: Args:
12753: docuname: username or courseid of destination for the file
12754: docudom: domain of user/course of destination for the file
12755: old: current file name (including any subdirs under userfiles)
12756: new: desired file name (including any subdirs under userfiles)
12757:
12758: =item *
12759:
12760: mkdiruserfile(): creates a directory is a userfiles dir
12761:
12762: Args:
12763: docuname: username or courseid of destination for the file
12764: docudom: domain of user/course of destination for the file
12765: dir: dir to create (including any subdirs under userfiles)
12766:
12767: =item *
12768:
12769: removeuserfile(): removes a file that exists in userfiles
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: fname: filname to delete (including any subdirs under userfiles)
12775:
12776: =item *
12777:
12778: removeuploadedurl(): convience function for removeuserfile()
12779:
12780: Args:
12781: url: a full /uploaded/... url to delete
12782:
1.747 albertel 12783: =item *
12784:
12785: get_portfile_permissions():
12786: Args:
12787: domain: domain of user or course contain the portfolio files
12788: user: name of user or num of course contain the portfolio files
12789: Returns:
12790: hashref of a dump of the proper file_permissions.db
12791:
12792:
12793: =item *
12794:
12795: get_access_controls():
12796:
12797: Args:
12798: current_permissions: the hash ref returned from get_portfile_permissions()
12799: group: (optional) the group you want the files associated with
12800: file: (optional) the file you want access info on
12801:
12802: Returns:
1.749 raeburn 12803: a hash (keys are file names) of hashes containing
12804: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
12805: values are XML containing access control settings (see below)
1.747 albertel 12806:
12807: Internal notes:
12808:
1.749 raeburn 12809: access controls are stored in file_permissions.db as key=value pairs.
12810: key -> path to file/file_name\0uniqueID:scope_end_start
12811: where scope -> public,guest,course,group,domains or users.
12812: end -> UNIX time for end of access (0 -> no end date)
12813: start -> UNIX time for start of access
12814:
12815: value -> XML description of access control
12816: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
12817: <start></start>
12818: <end></end>
12819:
12820: <password></password> for scope type = guest
12821:
12822: <domain></domain> for scope type = course or group
12823: <number></number>
12824: <roles id="">
12825: <role></role>
12826: <access></access>
12827: <section></section>
12828: <group></group>
12829: </roles>
12830:
12831: <dom></dom> for scope type = domains
12832:
12833: <users> for scope type = users
12834: <user>
12835: <uname></uname>
12836: <udom></udom>
12837: </user>
12838: </users>
12839: </scope>
12840:
12841: Access data is also aggregated for each file in an additional key=value pair:
12842: key -> path to file/file_name\0accesscontrol
12843: value -> reference to hash
12844: hash contains key = value pairs
12845: where key = uniqueID:scope_end_start
12846: value = UNIX time record was last updated
12847:
12848: Used to improve speed of look-ups of access controls for each file.
12849:
12850: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
12851:
12852: modify_access_controls():
12853:
12854: Modifies access controls for a portfolio file
12855: Args
12856: 1. file name
12857: 2. reference to hash of required changes,
12858: 3. domain
12859: 4. username
12860: where domain,username are the domain of the portfolio owner
12861: (either a user or a course)
12862:
12863: Returns:
12864: 1. result of additions or updates ('ok' or 'error', with error message).
12865: 2. result of deletions ('ok' or 'error', with error message).
12866: 3. reference to hash of any new or updated access controls.
12867: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
12868: key = integer (inbound ID)
12869: value = uniqueID
1.747 albertel 12870:
1.608 albertel 12871: =back
12872:
1.243 albertel 12873: =head2 HTTP Helper Routines
12874:
12875: =over 4
12876:
1.191 harris41 12877: =item *
12878:
12879: escape() : unpack non-word characters into CGI-compatible hex codes
12880:
12881: =item *
12882:
12883: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
12884:
1.243 albertel 12885: =back
12886:
12887: =head1 PRIVATE SUBROUTINES
12888:
12889: =head2 Underlying communication routines (Shouldn't call)
12890:
12891: =over 4
12892:
12893: =item *
12894:
12895: subreply() : tries to pass a message to lonc, returns con_lost if incapable
12896:
12897: =item *
12898:
12899: reply() : uses subreply to send a message to remote machine, logs all failures
12900:
12901: =item *
12902:
12903: critical() : passes a critical message to another server; if cannot
12904: get through then place message in connection buffer directory and
12905: returns con_delayed, if incapable of saving message, returns
12906: con_failed
12907:
12908: =item *
12909:
12910: reconlonc() : tries to reconnect lonc client processes.
12911:
12912: =back
12913:
12914: =head2 Resource Access Logging
12915:
12916: =over 4
12917:
12918: =item *
12919:
12920: flushcourselogs() : flush (save) buffer logs and access logs
12921:
12922: =item *
12923:
12924: courselog($what) : save message for course in hash
12925:
12926: =item *
12927:
12928: courseacclog($what) : save message for course using &courselog(). Perform
12929: special processing for specific resource types (problems, exams, quizzes, etc).
12930:
1.191 harris41 12931: =item *
12932:
12933: goodbye() : flush course logs and log shutting down; it is called in srm.conf
12934: as a PerlChildExitHandler
1.243 albertel 12935:
12936: =back
12937:
12938: =head2 Other
12939:
12940: =over 4
12941:
12942: =item *
12943:
12944: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 12945:
12946: =back
12947:
12948: =cut
1.877 foxr 12949:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>