Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1172.2.5
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1172.2.5! raeburn 4: # $Id: lonnet.pm,v 1.1172.2.4 2012/05/30 16:57:06 raeburn Exp $
1.178 www 5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27: #
1.169 harris41 28: ###
29:
1.971 jms 30: =pod
31:
1.972 jms 32: =head1 NAME
33:
34: Apache::lonnet.pm
35:
36: =head1 SYNOPSIS
37:
38: This file is an interface to the lonc processes of
39: the LON-CAPA network as well as set of elaborated functions for handling information
40: necessary for navigating through a given cluster of LON-CAPA machines within a
41: domain. There are over 40 specialized functions in this module which handle the
42: reading and transmission of metadata, user information (ids, names, environments, roles,
43: logs), file information (storage, reading, directories, extensions, replication, embedded
44: styles and descriptors), educational resources (course descriptions, section names and
45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
46: and from more descriptive phrases or explanations.
47:
48: This is part of the LearningOnline Network with CAPA project
49: described at http://www.lon-capa.org.
50:
1.971 jms 51: =head1 Package Variables
52:
53: These are largely undocumented, so if you decipher one please note it here.
54:
55: =over 4
56:
57: =item $processmarker
58:
59: Contains the time this process was started and this servers host id.
60:
61: =item $dumpcount
62:
63: Counts the number of times a message log flush has been attempted (regardless
64: of success) by this process. Used as part of the filename when messages are
65: delayed.
66:
67: =back
68:
69: =cut
70:
1.1 albertel 71: package Apache::lonnet;
72:
73: use strict;
1.8 www 74: use LWP::UserAgent();
1.486 www 75: use HTTP::Date;
1.977 amueller 76: use Image::Magick;
77:
1.871 albertel 78: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.1138 raeburn 79: $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
80: %managerstab);
1.871 albertel 81:
82: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
83: %userrolehash, $processmarker, $dumpcount, %coursedombuf,
84: %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958 www 85: %courseownerbuf, %coursetypebuf,$locknum);
1.403 www 86:
1.1 albertel 87: use IO::Socket;
1.31 www 88: use GDBM_File;
1.208 albertel 89: use HTML::LCParser;
1.88 www 90: use Fcntl qw(:flock);
1.870 albertel 91: use Storable qw(thaw nfreeze);
1.539 albertel 92: use Time::HiRes qw( gettimeofday tv_interval );
1.599 albertel 93: use Cache::Memcached;
1.676 albertel 94: use Digest::MD5;
1.790 albertel 95: use Math::Random;
1.1024 raeburn 96: use File::MMagic;
1.807 albertel 97: use LONCAPA qw(:DEFAULT :match);
1.740 www 98: use LONCAPA::Configuration;
1.1160 www 99: use LONCAPA::lonmetadata;
1.1117 foxr 100:
1.1090 raeburn 101: use File::Copy;
1.676 albertel 102:
1.195 www 103: my $readit;
1.550 foxr 104: my $max_connection_retries = 10; # Or some such value.
1.1 albertel 105:
1.619 albertel 106: require Exporter;
107:
108: our @ISA = qw (Exporter);
109: our @EXPORT = qw(%env);
110:
1.449 matthew 111:
1.1 albertel 112: # --------------------------------------------------------------------- Logging
1.729 www 113: {
114: my $logid;
115: sub instructor_log {
1.957 raeburn 116: my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
117: if (($cnum eq '') || ($cdom eq '')) {
118: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
119: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
120: }
1.729 www 121: $logid++;
1.957 raeburn 122: my $now = time();
123: my $id=$now.'00000'.$$.'00000'.$logid;
1.729 www 124: return &Apache::lonnet::put('nohist_'.$hash_name,
1.730 www 125: { $id => {
126: 'exe_uname' => $env{'user.name'},
127: 'exe_udom' => $env{'user.domain'},
1.957 raeburn 128: 'exe_time' => $now,
1.730 www 129: 'exe_ip' => $ENV{'REMOTE_ADDR'},
130: 'delflag' => $delflag,
131: 'logentry' => $storehash,
132: 'uname' => $uname,
133: 'udom' => $udom,
134: }
1.957 raeburn 135: },$cdom,$cnum);
1.729 www 136: }
137: }
1.1 albertel 138:
1.163 harris41 139: sub logtouch {
140: my $execdir=$perlvar{'lonDaemons'};
1.448 albertel 141: unless (-e "$execdir/logs/lonnet.log") {
142: open(my $fh,">>$execdir/logs/lonnet.log");
1.163 harris41 143: close $fh;
144: }
145: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
146: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
147: }
148:
1.1 albertel 149: sub logthis {
150: my $message=shift;
151: my $execdir=$perlvar{'lonDaemons'};
152: my $now=time;
153: my $local=localtime($now);
1.448 albertel 154: if (open(my $fh,">>$execdir/logs/lonnet.log")) {
1.986 foxr 155: my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
156: print $fh $logstring;
1.448 albertel 157: close($fh);
158: }
1.1 albertel 159: return 1;
160: }
161:
162: sub logperm {
163: my $message=shift;
164: my $execdir=$perlvar{'lonDaemons'};
165: my $now=time;
166: my $local=localtime($now);
1.448 albertel 167: if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
168: print $fh "$now:$message:$local\n";
169: close($fh);
170: }
1.1 albertel 171: return 1;
172: }
173:
1.850 albertel 174: sub create_connection {
1.853 albertel 175: my ($hostname,$lonid) = @_;
1.851 albertel 176: my $client=IO::Socket::UNIX->new(Peer => $perlvar{'lonSockCreate'},
1.850 albertel 177: Type => SOCK_STREAM,
178: Timeout => 10);
179: return 0 if (!$client);
1.890 albertel 180: print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850 albertel 181: my $result = <$client>;
182: chomp($result);
183: return 1 if ($result eq 'done');
184: return 0;
185: }
186:
1.983 raeburn 187: sub get_server_timezone {
188: my ($cnum,$cdom) = @_;
189: my $home=&homeserver($cnum,$cdom);
190: if ($home ne 'no_host') {
191: my $cachetime = 24*3600;
192: my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
193: if (defined($cached)) {
194: return $timezone;
195: } else {
196: my $timezone = &reply('servertimezone',$home);
197: return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
198: }
199: }
200: }
1.850 albertel 201:
1.1106 raeburn 202: sub get_server_distarch {
203: my ($lonhost,$ignore_cache) = @_;
204: if (defined($lonhost)) {
205: if (!defined(&hostname($lonhost))) {
206: return;
207: }
208: my $cachetime = 12*3600;
209: if (!$ignore_cache) {
210: my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
211: if (defined($cached)) {
212: return $distarch;
213: }
214: }
215: my $rep = &reply('serverdistarch',$lonhost);
216: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
217: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
218: $rep eq '') {
219: return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
220: }
221: }
222: return;
223: }
224:
1.993 raeburn 225: sub get_server_loncaparev {
1.1073 raeburn 226: my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993 raeburn 227: if (defined($lonhost)) {
228: if (!defined(&hostname($lonhost))) {
229: undef($lonhost);
230: }
231: }
232: if (!defined($lonhost)) {
233: if (defined(&domain($dom,'primary'))) {
234: $lonhost=&domain($dom,'primary');
235: if ($lonhost eq 'no_host') {
236: undef($lonhost);
237: }
238: }
239: }
240: if (defined($lonhost)) {
1.1073 raeburn 241: my $cachetime = 12*3600;
242: if (!$ignore_cache) {
243: my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
244: if (defined($cached)) {
245: return $loncaparev;
246: }
247: }
248: my ($answer,$loncaparev);
249: my @ids=¤t_machine_ids();
250: if (grep(/^\Q$lonhost\E$/,@ids)) {
251: $answer = $perlvar{'lonVersion'};
1.1081 raeburn 252: if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 253: $loncaparev = $1;
254: }
255: } else {
256: $answer = &reply('serverloncaparev',$lonhost);
257: if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
258: if ($caller eq 'loncron') {
259: my $ua=new LWP::UserAgent;
1.1082 raeburn 260: $ua->timeout(4);
1.1073 raeburn 261: my $protocol = $protocol{$lonhost};
262: $protocol = 'http' if ($protocol ne 'https');
263: my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
264: my $request=new HTTP::Request('GET',$url);
265: my $response=$ua->request($request);
266: unless ($response->is_error()) {
267: my $content = $response->content;
1.1081 raeburn 268: if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073 raeburn 269: $loncaparev = $1;
270: }
271: }
272: } else {
273: $loncaparev = $loncaparevs{$lonhost};
274: }
1.1081 raeburn 275: } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 276: $loncaparev = $1;
277: }
1.993 raeburn 278: }
1.1073 raeburn 279: return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993 raeburn 280: }
281: }
282:
1.1074 raeburn 283: sub get_server_homeID {
284: my ($hostname,$ignore_cache,$caller) = @_;
285: unless ($ignore_cache) {
286: my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
287: if (defined($cached)) {
288: return $serverhomeID;
289: }
290: }
291: my $cachetime = 12*3600;
292: my $serverhomeID;
293: if ($caller eq 'loncron') {
294: my @machine_ids = &machine_ids($hostname);
295: foreach my $id (@machine_ids) {
296: my $response = &reply('serverhomeID',$id);
297: unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
298: $serverhomeID = $response;
299: last;
300: }
301: }
302: if ($serverhomeID eq '') {
303: $serverhomeID = $machine_ids[-1];
304: }
305: } else {
306: $serverhomeID = $serverhomeIDs{$hostname};
307: }
308: return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
309: }
310:
1.1121 raeburn 311: sub get_remote_globals {
312: my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125 raeburn 313: my ($result,%returnhash,%whatneeded);
314: if (ref($whathash) eq 'HASH') {
1.1121 raeburn 315: foreach my $what (sort(keys(%{$whathash}))) {
316: my $hashid = $lonhost.'-'.$what;
1.1125 raeburn 317: my ($response,$cached);
1.1121 raeburn 318: unless ($ignore_cache) {
1.1125 raeburn 319: ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121 raeburn 320: }
321: if (defined($cached)) {
1.1125 raeburn 322: $returnhash{$what} = $response;
1.1121 raeburn 323: } else {
1.1125 raeburn 324: $whatneeded{$what} = 1;
1.1121 raeburn 325: }
326: }
1.1125 raeburn 327: if (keys(%whatneeded) == 0) {
328: $result = 'ok';
329: } else {
1.1121 raeburn 330: my $requested = &freeze_escape(\%whatneeded);
331: my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125 raeburn 332: if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
333: ($rep eq 'unknown_cmd')) {
334: $result = $rep;
335: } else {
336: $result = 'ok';
1.1121 raeburn 337: my @pairs=split(/\&/,$rep);
1.1125 raeburn 338: foreach my $item (@pairs) {
339: my ($key,$value)=split(/=/,$item,2);
340: my $what = &unescape($key);
341: my $hashid = $lonhost.'-'.$what;
342: $returnhash{$what}=&thaw_unescape($value);
343: &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121 raeburn 344: }
345: }
346: }
347: }
1.1125 raeburn 348: return ($result,\%returnhash);
1.1121 raeburn 349: }
350:
1.1124 raeburn 351: sub remote_devalidate_cache {
352: my ($lonhost,$name,$id) = @_;
1.1130 raeburn 353: my $response = &reply('devalidatecache:'.&escape($name).':'.&escape($id),$lonhost);
1.1124 raeburn 354: return $response;
355: }
356:
1.1 albertel 357: # -------------------------------------------------- Non-critical communication
358: sub subreply {
359: my ($cmd,$server)=@_;
1.838 albertel 360: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549 foxr 361: #
362: # With loncnew process trimming, there's a timing hole between lonc server
363: # process exit and the master server picking up the listen on the AF_UNIX
364: # socket. In that time interval, a lock file will exist:
365:
366: my $lockfile=$peerfile.".lock";
367: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
368: sleep(1);
369: }
370: # At this point, either a loncnew parent is listening or an old lonc
1.550 foxr 371: # or loncnew child is listening so we can connect or everything's dead.
1.549 foxr 372: #
1.550 foxr 373: # We'll give the connection a few tries before abandoning it. If
374: # connection is not possible, we'll con_lost back to the client.
375: #
376: my $client;
377: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
378: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
379: Type => SOCK_STREAM,
380: Timeout => 10);
1.869 albertel 381: if ($client) {
1.550 foxr 382: last; # Connected!
1.850 albertel 383: } else {
1.853 albertel 384: &create_connection(&hostname($server),$server);
1.550 foxr 385: }
1.850 albertel 386: sleep(1); # Try again later if failed connection.
1.550 foxr 387: }
388: my $answer;
389: if ($client) {
1.704 albertel 390: print $client "sethost:$server:$cmd\n";
1.550 foxr 391: $answer=<$client>;
392: if (!$answer) { $answer="con_lost"; }
393: chomp($answer);
394: } else {
395: $answer = 'con_lost'; # Failed connection.
396: }
1.1 albertel 397: return $answer;
398: }
399:
400: sub reply {
401: my ($cmd,$server)=@_;
1.838 albertel 402: unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1 albertel 403: my $answer=subreply($cmd,$server);
1.65 www 404: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672 albertel 405: &logthis("<font color=\"blue\">WARNING:".
1.12 www 406: " $cmd to $server returned $answer</font>");
407: }
1.1 albertel 408: return $answer;
409: }
410:
411: # ----------------------------------------------------------- Send USR1 to lonc
412:
413: sub reconlonc {
1.891 albertel 414: my ($lonid) = @_;
415: my $hostname = &hostname($lonid);
416: if ($lonid) {
417: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
418: if ($hostname && -e $peerfile) {
419: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
420: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
421: Type => SOCK_STREAM,
422: Timeout => 10);
423: if ($client) {
424: print $client ("reset_retries\n");
425: my $answer=<$client>;
426: #reset just this one.
427: }
428: }
429: return;
430: }
431:
1.836 www 432: &logthis("Trying to reconnect lonc");
1.1 albertel 433: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448 albertel 434: if (open(my $fh,"<$loncfile")) {
1.1 albertel 435: my $loncpid=<$fh>;
436: chomp($loncpid);
437: if (kill 0 => $loncpid) {
438: &logthis("lonc at pid $loncpid responding, sending USR1");
439: kill USR1 => $loncpid;
440: sleep 1;
1.836 www 441: } else {
1.12 www 442: &logthis(
1.672 albertel 443: "<font color=\"blue\">WARNING:".
1.12 www 444: " lonc at pid $loncpid not responding, giving up</font>");
1.1 albertel 445: }
446: } else {
1.836 www 447: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1 albertel 448: }
449: }
450:
451: # ------------------------------------------------------ Critical communication
1.12 www 452:
1.1 albertel 453: sub critical {
454: my ($cmd,$server)=@_;
1.838 albertel 455: unless (&hostname($server)) {
1.672 albertel 456: &logthis("<font color=\"blue\">WARNING:".
1.89 www 457: " Critical message to unknown server ($server)</font>");
458: return 'no_such_host';
459: }
1.1 albertel 460: my $answer=reply($cmd,$server);
461: if ($answer eq 'con_lost') {
462: &reconlonc("$perlvar{'lonSockDir'}/$server");
1.589 albertel 463: my $answer=reply($cmd,$server);
1.1 albertel 464: if ($answer eq 'con_lost') {
465: my $now=time;
466: my $middlename=$cmd;
1.5 www 467: $middlename=substr($middlename,0,16);
1.1 albertel 468: $middlename=~s/\W//g;
469: my $dfilename=
1.305 www 470: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
471: $dumpcount++;
1.1 albertel 472: {
1.448 albertel 473: my $dfh;
474: if (open($dfh,">$dfilename")) {
475: print $dfh "$cmd\n";
476: close($dfh);
477: }
1.1 albertel 478: }
479: sleep 2;
480: my $wcmd='';
481: {
1.448 albertel 482: my $dfh;
483: if (open($dfh,"<$dfilename")) {
484: $wcmd=<$dfh>;
485: close($dfh);
486: }
1.1 albertel 487: }
488: chomp($wcmd);
1.7 www 489: if ($wcmd eq $cmd) {
1.672 albertel 490: &logthis("<font color=\"blue\">WARNING: ".
1.12 www 491: "Connection buffer $dfilename: $cmd</font>");
1.1 albertel 492: &logperm("D:$server:$cmd");
493: return 'con_delayed';
494: } else {
1.672 albertel 495: &logthis("<font color=\"red\">CRITICAL:"
1.12 www 496: ." Critical connection failed: $server $cmd</font>");
1.1 albertel 497: &logperm("F:$server:$cmd");
498: return 'con_failed';
499: }
500: }
501: }
502: return $answer;
1.405 albertel 503: }
504:
1.755 albertel 505: # ------------------------------------------- check if return value is an error
506:
507: sub error {
508: my ($result) = @_;
1.756 albertel 509: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755 albertel 510: if ($2 == 2) { return undef; }
511: return $1;
512: }
513: return undef;
514: }
515:
1.783 albertel 516: sub convert_and_load_session_env {
517: my ($lonidsdir,$handle)=@_;
518: my @profile;
519: {
1.917 albertel 520: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
521: if (!$opened) {
1.915 albertel 522: return 0;
523: }
1.783 albertel 524: flock($idf,LOCK_SH);
525: @profile=<$idf>;
526: close($idf);
527: }
528: my %temp_env;
529: foreach my $line (@profile) {
1.786 albertel 530: if ($line !~ m/=/) {
531: return 0;
532: }
1.783 albertel 533: chomp($line);
534: my ($envname,$envvalue)=split(/=/,$line,2);
535: $temp_env{&unescape($envname)} = &unescape($envvalue);
536: }
537: unlink("$lonidsdir/$handle.id");
538: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
539: 0640)) {
540: %disk_env = %temp_env;
541: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
542: untie(%disk_env);
543: }
1.786 albertel 544: return 1;
1.783 albertel 545: }
546:
1.374 www 547: # ------------------------------------------- Transfer profile into environment
1.780 albertel 548: my $env_loaded;
549: sub transfer_profile_to_env {
1.788 albertel 550: my ($lonidsdir,$handle,$force_transfer) = @_;
551: if (!$force_transfer && $env_loaded) { return; }
1.374 www 552:
1.720 albertel 553: if (!defined($lonidsdir)) {
554: $lonidsdir = $perlvar{'lonIDsDir'};
555: }
556: if (!defined($handle)) {
557: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
558: }
559:
1.786 albertel 560: my $convert;
561: {
1.917 albertel 562: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
563: if (!$opened) {
1.915 albertel 564: return;
565: }
1.786 albertel 566: flock($idf,LOCK_SH);
567: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
568: &GDBM_READER(),0640)) {
569: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
570: untie(%disk_env);
571: } else {
572: $convert = 1;
573: }
574: }
575: if ($convert) {
576: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
577: &logthis("Failed to load session, or convert session.");
578: }
1.374 www 579: }
1.783 albertel 580:
1.786 albertel 581: my %remove;
1.783 albertel 582: while ( my $envname = each(%env) ) {
1.433 matthew 583: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
584: if ($time < time-300) {
1.783 albertel 585: $remove{$key}++;
1.433 matthew 586: }
587: }
588: }
1.783 albertel 589:
1.619 albertel 590: $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780 albertel 591: $env_loaded=1;
1.783 albertel 592: foreach my $expired_key (keys(%remove)) {
1.433 matthew 593: &delenv($expired_key);
1.374 www 594: }
1.1 albertel 595: }
596:
1.916 albertel 597: # ---------------------------------------------------- Check for valid session
598: sub check_for_valid_session {
1.1155 raeburn 599: my ($r,$name) = @_;
1.916 albertel 600: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1155 raeburn 601: if ($name eq '') {
602: $name = 'lonID';
603: }
604: my $lonid=$cookies{$name};
1.916 albertel 605: return undef if (!$lonid);
606:
607: my $handle=&LONCAPA::clean_handle($lonid->value);
1.1155 raeburn 608: my $lonidsdir;
609: if ($name eq 'lonDAV') {
610: $lonidsdir=$r->dir_config('lonDAVsessDir');
611: } else {
612: $lonidsdir=$r->dir_config('lonIDsDir');
613: }
1.916 albertel 614: return undef if (!-e "$lonidsdir/$handle.id");
615:
1.917 albertel 616: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
617: return undef if (!$opened);
1.916 albertel 618:
619: flock($idf,LOCK_SH);
620: my %disk_env;
621: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
622: &GDBM_READER(),0640)) {
623: return undef;
624: }
625:
626: if (!defined($disk_env{'user.name'})
627: || !defined($disk_env{'user.domain'})) {
628: return undef;
629: }
630: return $handle;
631: }
632:
1.830 albertel 633: sub timed_flock {
634: my ($file,$lock_type) = @_;
635: my $failed=0;
636: eval {
637: local $SIG{__DIE__}='DEFAULT';
638: local $SIG{ALRM}=sub {
639: $failed=1;
640: die("failed lock");
641: };
642: alarm(13);
643: flock($file,$lock_type);
644: alarm(0);
645: };
646: if ($failed) {
647: return undef;
648: } else {
649: return 1;
650: }
651: }
652:
1.5 www 653: # ---------------------------------------------------------- Append Environment
654:
655: sub appenv {
1.949 raeburn 656: my ($newenv,$roles) = @_;
657: if (ref($newenv) eq 'HASH') {
658: foreach my $key (keys(%{$newenv})) {
659: my $refused = 0;
660: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
661: $refused = 1;
662: if (ref($roles) eq 'ARRAY') {
663: my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
664: if (grep(/^\Q$role\E$/,@{$roles})) {
665: $refused = 0;
666: }
667: }
668: }
669: if ($refused) {
670: &logthis("<font color=\"blue\">WARNING: ".
671: "Attempt to modify environment ".$key." to ".$newenv->{$key}
672: .'</font>');
673: delete($newenv->{$key});
674: } else {
675: $env{$key}=$newenv->{$key};
676: }
677: }
678: my $opened = open(my $env_file,'+<',$env{'user.environment'});
679: if ($opened
680: && &timed_flock($env_file,LOCK_EX)
681: &&
682: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
683: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
684: while (my ($key,$value) = each(%{$newenv})) {
685: $disk_env{$key} = $value;
686: }
687: untie(%disk_env);
1.35 www 688: }
1.191 harris41 689: }
1.56 www 690: return 'ok';
691: }
692: # ----------------------------------------------------- Delete from Environment
693:
694: sub delenv {
1.1104 raeburn 695: my ($delthis,$regexp,$roles) = @_;
696: if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
697: my $refused = 1;
698: if (ref($roles) eq 'ARRAY') {
699: my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
700: if (grep(/^\Q$role\E$/,@{$roles})) {
701: $refused = 0;
702: }
703: }
704: if ($refused) {
705: &logthis("<font color=\"blue\">WARNING: ".
706: "Attempt to delete from environment ".$delthis);
707: return 'error';
708: }
1.56 www 709: }
1.917 albertel 710: my $opened = open(my $env_file,'+<',$env{'user.environment'});
711: if ($opened
1.915 albertel 712: && &timed_flock($env_file,LOCK_EX)
1.830 albertel 713: &&
714: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
715: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 716: foreach my $key (keys(%disk_env)) {
1.987 raeburn 717: if ($regexp) {
718: if ($key=~/^$delthis/) {
719: delete($env{$key});
720: delete($disk_env{$key});
721: }
722: } else {
723: if ($key=~/^\Q$delthis\E/) {
724: delete($env{$key});
725: delete($disk_env{$key});
726: }
727: }
1.448 albertel 728: }
1.783 albertel 729: untie(%disk_env);
1.5 www 730: }
731: return 'ok';
1.369 albertel 732: }
733:
1.790 albertel 734: sub get_env_multiple {
735: my ($name) = @_;
736: my @values;
737: if (defined($env{$name})) {
738: # exists is it an array
739: if (ref($env{$name})) {
740: @values=@{ $env{$name} };
741: } else {
742: $values[0]=$env{$name};
743: }
744: }
745: return(@values);
746: }
747:
1.958 www 748: # ------------------------------------------------------------------- Locking
749:
750: sub set_lock {
751: my ($text)=@_;
752: $locknum++;
753: my $id=$$.'-'.$locknum;
754: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
755: 'session.lock.'.$id => $text});
756: return $id;
757: }
758:
759: sub get_locks {
760: my $num=0;
761: my %texts=();
762: foreach my $lock (split(/\,/,$env{'session.locks'})) {
763: if ($lock=~/\w/) {
764: $num++;
765: $texts{$lock}=$env{'session.lock.'.$lock};
766: }
767: }
768: return ($num,%texts);
769: }
770:
771: sub remove_lock {
772: my ($id)=@_;
773: my $newlocks='';
774: foreach my $lock (split(/\,/,$env{'session.locks'})) {
775: if (($lock=~/\w/) && ($lock ne $id)) {
776: $newlocks.=','.$lock;
777: }
778: }
779: &appenv({'session.locks' => $newlocks});
780: &delenv('session.lock.'.$id);
781: }
782:
783: sub remove_all_locks {
784: my $activelocks=$env{'session.locks'};
785: foreach my $lock (split(/\,/,$env{'session.locks'})) {
786: if ($lock=~/\w/) {
787: &remove_lock($lock);
788: }
789: }
790: }
791:
792:
1.369 albertel 793: # ------------------------------------------ Find out current server userload
794: sub userload {
795: my $numusers=0;
796: {
797: opendir(LONIDS,$perlvar{'lonIDsDir'});
798: my $filename;
799: my $curtime=time;
800: while ($filename=readdir(LONIDS)) {
1.925 albertel 801: next if ($filename eq '.' || $filename eq '..');
802: next if ($filename =~ /publicuser_\d+\.id/);
1.404 albertel 803: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437 albertel 804: if ($curtime-$mtime < 1800) { $numusers++; }
1.369 albertel 805: }
806: closedir(LONIDS);
807: }
808: my $userloadpercent=0;
809: my $maxuserload=$perlvar{'lonUserLoadLim'};
810: if ($maxuserload) {
1.371 albertel 811: $userloadpercent=100*$numusers/$maxuserload;
1.369 albertel 812: }
1.372 albertel 813: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369 albertel 814: return $userloadpercent;
1.283 www 815: }
816:
1.1 albertel 817: # ------------------------------ Find server with least workload from spare.tab
1.11 www 818:
1.1 albertel 819: sub spareserver {
1.1083 raeburn 820: my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784 albertel 821: my $spare_server;
1.370 albertel 822: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784 albertel 823: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
824: : $userloadpercent;
1.1083 raeburn 825: my ($uint_dom,$remotesessions);
826: if (($udom ne '') && (&domain($udom) ne '')) {
827: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
828: $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
829: my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
830: $remotesessions = $udomdefaults{'remotesessions'};
831: }
1.1123 raeburn 832: my $spareshash = &this_host_spares($udom);
833: if (ref($spareshash) eq 'HASH') {
834: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
835: foreach my $try_server (@{ $spareshash->{'primary'} }) {
836: if ($uint_dom) {
837: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
838: $try_server));
839: }
840: ($spare_server, $lowest_load) =
841: &compare_server_load($try_server, $spare_server, $lowest_load);
842: }
1.1083 raeburn 843: }
1.784 albertel 844:
1.1123 raeburn 845: my $found_server = ($spare_server ne '' && $lowest_load < 100);
846:
847: if (!$found_server) {
848: if (ref($spareshash->{'default'}) eq 'ARRAY') {
849: foreach my $try_server (@{ $spareshash->{'default'} }) {
850: if ($uint_dom) {
851: next unless (&spare_can_host($udom,$uint_dom,
852: $remotesessions,$try_server));
853: }
854: ($spare_server, $lowest_load) =
855: &compare_server_load($try_server, $spare_server, $lowest_load);
856: }
857: }
858: }
1.784 albertel 859: }
860:
861: if (!$want_server_name) {
1.968 raeburn 862: my $protocol = 'http';
863: if ($protocol{$spare_server} eq 'https') {
864: $protocol = $protocol{$spare_server};
865: }
1.1001 raeburn 866: if (defined($spare_server)) {
867: my $hostname = &hostname($spare_server);
1.1083 raeburn 868: if (defined($hostname)) {
1.1001 raeburn 869: $spare_server = $protocol.'://'.$hostname;
870: }
871: }
1.784 albertel 872: }
873: return $spare_server;
874: }
875:
876: sub compare_server_load {
877: my ($try_server, $spare_server, $lowest_load) = @_;
878:
879: my $loadans = &reply('load', $try_server);
880: my $userloadans = &reply('userload',$try_server);
881:
882: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114 raeburn 883: return ($spare_server, $lowest_load); #didn't get a number from the server
1.784 albertel 884: }
885:
886: my $load;
887: if ($loadans =~ /\d/) {
888: if ($userloadans =~ /\d/) {
889: #both are numbers, pick the bigger one
890: $load = ($loadans > $userloadans) ? $loadans
891: : $userloadans;
1.411 albertel 892: } else {
1.784 albertel 893: $load = $loadans;
1.411 albertel 894: }
1.784 albertel 895: } else {
896: $load = $userloadans;
897: }
898:
899: if (($load =~ /\d/) && ($load < $lowest_load)) {
900: $spare_server = $try_server;
901: $lowest_load = $load;
1.370 albertel 902: }
1.784 albertel 903: return ($spare_server,$lowest_load);
1.202 matthew 904: }
1.914 albertel 905:
906: # --------------------------- ask offload servers if user already has a session
907: sub find_existing_session {
908: my ($udom,$uname) = @_;
1.1123 raeburn 909: my $spareshash = &this_host_spares($udom);
910: if (ref($spareshash) eq 'HASH') {
911: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
912: foreach my $try_server (@{ $spareshash->{'primary'} }) {
913: return $try_server if (&has_user_session($try_server, $udom, $uname));
914: }
915: }
916: if (ref($spareshash->{'default'}) eq 'ARRAY') {
917: foreach my $try_server (@{ $spareshash->{'default'} }) {
918: return $try_server if (&has_user_session($try_server, $udom, $uname));
919: }
920: }
1.914 albertel 921: }
922: return;
923: }
924:
925: # -------------------------------- ask if server already has a session for user
926: sub has_user_session {
927: my ($lonid,$udom,$uname) = @_;
928: my $result = &reply(join(':','userhassession',
929: map {&escape($_)} ($udom,$uname)),$lonid);
930: return 1 if ($result eq 'ok');
931:
932: return 0;
933: }
934:
1.1076 raeburn 935: # --------- determine least loaded server in a user's domain which allows login
936:
937: sub choose_server {
1.1115 raeburn 938: my ($udom,$checkloginvia) = @_;
1.1076 raeburn 939: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077 raeburn 940: my %servers = &get_servers($udom);
1.1076 raeburn 941: my $lowest_load = 30000;
1.1151 raeburn 942: my ($login_host,$hostname,$portal_path,$isredirect);
1.1076 raeburn 943: foreach my $lonhost (keys(%servers)) {
1.1115 raeburn 944: my $loginvia;
945: if ($checkloginvia) {
946: $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116 raeburn 947: if ($loginvia) {
948: my ($server,$path) = split(/:/,$loginvia);
949: ($login_host, $lowest_load) =
950: &compare_server_load($server, $login_host, $lowest_load);
951: if ($login_host eq $server) {
952: $portal_path = $path;
1.1151 raeburn 953: $isredirect = 1;
1.1116 raeburn 954: }
955: } else {
956: ($login_host, $lowest_load) =
957: &compare_server_load($lonhost, $login_host, $lowest_load);
958: if ($login_host eq $lonhost) {
959: $portal_path = '';
1.1151 raeburn 960: $isredirect = '';
1.1116 raeburn 961: }
962: }
963: } else {
1.1076 raeburn 964: ($login_host, $lowest_load) =
1.1116 raeburn 965: &compare_server_load($lonhost, $login_host, $lowest_load);
1.1076 raeburn 966: }
967: }
968: if ($login_host ne '') {
1.1116 raeburn 969: $hostname = &hostname($login_host);
1.1076 raeburn 970: }
1.1151 raeburn 971: return ($login_host,$hostname,$portal_path,$isredirect);
1.1076 raeburn 972: }
973:
1.202 matthew 974: # --------------------------------------------- Try to change a user's password
975:
976: sub changepass {
1.799 raeburn 977: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 978: $currentpass = &escape($currentpass);
979: $newpass = &escape($newpass);
1.1030 raeburn 980: my $lonhost = $perlvar{'lonHostID'};
981: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202 matthew 982: $server);
983: if (! $answer) {
984: &logthis("No reply on password change request to $server ".
985: "by $uname in domain $udom.");
986: } elsif ($answer =~ "^ok") {
987: &logthis("$uname in $udom successfully changed their password ".
988: "on $server.");
989: } elsif ($answer =~ "^pwchange_failure") {
990: &logthis("$uname in $udom was unable to change their password ".
991: "on $server. The action was blocked by either lcpasswd ".
992: "or pwchange");
993: } elsif ($answer =~ "^non_authorized") {
994: &logthis("$uname in $udom did not get their password correct when ".
995: "attempting to change it on $server.");
996: } elsif ($answer =~ "^auth_mode_error") {
997: &logthis("$uname in $udom attempted to change their password despite ".
998: "not being locally or internally authenticated on $server.");
999: } elsif ($answer =~ "^unknown_user") {
1000: &logthis("$uname in $udom attempted to change their password ".
1001: "on $server but were unable to because $server is not ".
1002: "their home server.");
1003: } elsif ($answer =~ "^refused") {
1004: &logthis("$server refused to change $uname in $udom password because ".
1005: "it was sent an unencrypted request to change the password.");
1.1030 raeburn 1006: } elsif ($answer =~ "invalid_client") {
1007: &logthis("$server refused to change $uname in $udom password because ".
1008: "it was a reset by e-mail originating from an invalid server.");
1.202 matthew 1009: }
1010: return $answer;
1.1 albertel 1011: }
1012:
1.169 harris41 1013: # ----------------------- Try to determine user's current authentication scheme
1014:
1015: sub queryauthenticate {
1016: my ($uname,$udom)=@_;
1.456 albertel 1017: my $uhome=&homeserver($uname,$udom);
1018: if (!$uhome) {
1019: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
1020: return 'no_host';
1021: }
1022: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
1023: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
1024: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 1025: }
1.456 albertel 1026: return $answer;
1.169 harris41 1027: }
1028:
1.1 albertel 1029: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 1030:
1.1 albertel 1031: sub authenticate {
1.1073 raeburn 1032: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807 albertel 1033: $upass=&escape($upass);
1034: $uname= &LONCAPA::clean_username($uname);
1.836 www 1035: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 1036: my $newhome;
1.836 www 1037: if ((!$uhome) || ($uhome eq 'no_host')) {
1038: # Maybe the machine was offline and only re-appeared again recently?
1039: &reconlonc();
1040: # One more
1.952 raeburn 1041: $uhome=&homeserver($uname,$udom,1);
1042: if (($uhome eq 'no_host') && $checkdefauth) {
1043: if (defined(&domain($udom,'primary'))) {
1044: $newhome=&domain($udom,'primary');
1045: }
1046: if ($newhome ne '') {
1047: $uhome = $newhome;
1048: }
1049: }
1.836 www 1050: if ((!$uhome) || ($uhome eq 'no_host')) {
1051: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 1052: return 'no_host';
1053: }
1.1 albertel 1054: }
1.1073 raeburn 1055: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471 albertel 1056: if ($answer eq 'authorized') {
1.952 raeburn 1057: if ($newhome) {
1058: &logthis("User $uname at $udom authorized by $uhome, but needs account");
1059: return 'no_account_on_host';
1060: } else {
1061: &logthis("User $uname at $udom authorized by $uhome");
1062: return $uhome;
1063: }
1.471 albertel 1064: }
1065: if ($answer eq 'non_authorized') {
1066: &logthis("User $uname at $udom rejected by $uhome");
1067: return 'no_host';
1.9 www 1068: }
1.471 albertel 1069: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 1070: return 'no_host';
1071: }
1072:
1.1073 raeburn 1073: sub can_host_session {
1.1074 raeburn 1074: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073 raeburn 1075: my $canhost = 1;
1.1074 raeburn 1076: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073 raeburn 1077: if (ref($remotesessions) eq 'HASH') {
1078: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074 raeburn 1079: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073 raeburn 1080: $canhost = 0;
1081: } else {
1082: $canhost = 1;
1083: }
1084: }
1085: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074 raeburn 1086: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073 raeburn 1087: $canhost = 1;
1088: } else {
1089: $canhost = 0;
1090: }
1091: }
1092: if ($canhost) {
1093: if ($remotesessions->{'version'} ne '') {
1094: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1095: if ($reqmajor ne '' && $reqminor ne '') {
1096: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1097: my $major = $1;
1098: my $minor = $2;
1099: if (($major < $reqmajor ) ||
1100: (($major == $reqmajor) && ($minor < $reqminor))) {
1101: $canhost = 0;
1102: }
1103: } else {
1104: $canhost = 0;
1105: }
1106: }
1107: }
1108: }
1109: }
1110: if ($canhost) {
1111: if (ref($hostedsessions) eq 'HASH') {
1.1120 raeburn 1112: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1113: my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073 raeburn 1114: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120 raeburn 1115: if (($uint_dom ne '') &&
1116: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073 raeburn 1117: $canhost = 0;
1118: } else {
1119: $canhost = 1;
1120: }
1121: }
1122: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120 raeburn 1123: if (($uint_dom ne '') &&
1124: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073 raeburn 1125: $canhost = 1;
1126: } else {
1127: $canhost = 0;
1128: }
1129: }
1130: }
1131: }
1132: return $canhost;
1133: }
1134:
1.1083 raeburn 1135: sub spare_can_host {
1136: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1137: my $canhost=1;
1138: my @intdoms;
1139: my $internet_names = &Apache::lonnet::get_internet_names($try_server);
1140: if (ref($internet_names) eq 'ARRAY') {
1141: @intdoms = @{$internet_names};
1142: }
1143: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1144: my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
1145: my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
1146: my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
1147: my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
1148: $canhost = &can_host_session($udom,$try_server,$remoterev,
1149: $remotesessions,
1150: $defdomdefaults{'hostedsessions'});
1151: }
1152: return $canhost;
1153: }
1154:
1.1123 raeburn 1155: sub this_host_spares {
1156: my ($dom) = @_;
1.1126 raeburn 1157: my ($dom_in_use,$lonhost_in_use,$result);
1.1123 raeburn 1158: my @hosts = ¤t_machine_ids();
1159: foreach my $lonhost (@hosts) {
1160: if (&host_domain($lonhost) eq $dom) {
1.1126 raeburn 1161: $dom_in_use = $dom;
1162: $lonhost_in_use = $lonhost;
1.1123 raeburn 1163: last;
1164: }
1165: }
1.1126 raeburn 1166: if ($dom_in_use ne '') {
1167: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1168: }
1169: if (ref($result) ne 'HASH') {
1170: $lonhost_in_use = $perlvar{'lonHostID'};
1171: $dom_in_use = &host_domain($lonhost_in_use);
1172: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1173: if (ref($result) ne 'HASH') {
1174: $result = \%spareid;
1175: }
1176: }
1177: return $result;
1178: }
1179:
1180: sub spares_for_offload {
1181: my ($dom_in_use,$lonhost_in_use) = @_;
1182: my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123 raeburn 1183: if (defined($cached)) {
1184: return $result;
1185: } else {
1.1126 raeburn 1186: my $cachetime = 60*60*24;
1187: my %domconfig =
1188: &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
1189: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1190: if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
1191: if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
1192: return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123 raeburn 1193: }
1194: }
1195: }
1196: }
1.1126 raeburn 1197: return;
1.1123 raeburn 1198: }
1199:
1.1129 raeburn 1200: sub get_lonbalancer_config {
1201: my ($servers) = @_;
1202: my ($currbalancer,$currtargets);
1203: if (ref($servers) eq 'HASH') {
1204: foreach my $server (keys(%{$servers})) {
1205: my %what = (
1206: spareid => 1,
1207: perlvar => 1,
1208: );
1209: my ($result,$returnhash) = &get_remote_globals($server,\%what);
1210: if ($result eq 'ok') {
1211: if (ref($returnhash) eq 'HASH') {
1212: if (ref($returnhash->{'perlvar'}) eq 'HASH') {
1213: if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
1214: $currbalancer = $server;
1215: $currtargets = {};
1216: if (ref($returnhash->{'spareid'}) eq 'HASH') {
1217: if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
1218: $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
1219: }
1220: if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
1221: $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
1222: }
1223: }
1224: last;
1225: }
1226: }
1227: }
1228: }
1229: }
1230: }
1231: return ($currbalancer,$currtargets);
1232: }
1233:
1234: sub check_loadbalancing {
1235: my ($uname,$udom) = @_;
1236: my ($is_balancer,$dom_in_use,$homeintdom,$rule_in_effect,
1237: $offloadto,$otherserver);
1238: my $lonhost = $perlvar{'lonHostID'};
1.1172.2.4 raeburn 1239: my @hosts = ¤t_machine_ids();
1.1129 raeburn 1240: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1241: my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
1242: my $intdom = &Apache::lonnet::internet_dom($lonhost);
1243: my $serverhomedom = &host_domain($lonhost);
1244:
1245: my $cachetime = 60*60*24;
1246:
1247: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1248: $dom_in_use = $udom;
1249: $homeintdom = 1;
1250: } else {
1251: $dom_in_use = $serverhomedom;
1252: }
1253: my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
1254: unless (defined($cached)) {
1255: my %domconfig =
1256: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
1257: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1258: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129 raeburn 1259: }
1260: }
1261: if (ref($result) eq 'HASH') {
1262: my $currbalancer = $result->{'lonhost'};
1263: my $currtargets = $result->{'targets'};
1264: my $currrules = $result->{'rules'};
1265: if ($currbalancer ne '') {
1266: if (grep(/^\Q$currbalancer\E$/,@hosts)) {
1267: $is_balancer = 1;
1268: }
1269: }
1270: if ($is_balancer) {
1271: if (ref($currrules) eq 'HASH') {
1272: if ($homeintdom) {
1273: if ($uname ne '') {
1274: if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
1275: my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
1276: if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
1277: $rule_in_effect = $currrules->{'_LC_author'};
1278: } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
1279: $rule_in_effect = $currrules->{'_LC_adv'}
1280: }
1281: }
1282: if ($rule_in_effect eq '') {
1283: my %userenv = &userenvironment($udom,$uname,'inststatus');
1284: if ($userenv{'inststatus'} ne '') {
1285: my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
1286: my ($othertitle,$usertypes,$types) =
1287: &Apache::loncommon::sorted_inst_types($udom);
1288: if (ref($types) eq 'ARRAY') {
1289: foreach my $type (@{$types}) {
1290: if (grep(/^\Q$type\E$/,@statuses)) {
1291: if (exists($currrules->{$type})) {
1292: $rule_in_effect = $currrules->{$type};
1293: }
1294: }
1295: }
1296: }
1297: } else {
1298: if (exists($currrules->{'default'})) {
1299: $rule_in_effect = $currrules->{'default'};
1300: }
1301: }
1302: }
1303: } else {
1304: if (exists($currrules->{'default'})) {
1305: $rule_in_effect = $currrules->{'default'};
1306: }
1307: }
1308: } else {
1309: if ($currrules->{'_LC_external'} ne '') {
1310: $rule_in_effect = $currrules->{'_LC_external'};
1311: }
1312: }
1313: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1314: $uname,$udom);
1315: }
1316: }
1317: } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1318: my ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1319: unless (defined($cached)) {
1320: my %domconfig =
1321: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
1322: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1323: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129 raeburn 1324: }
1325: }
1326: if (ref($result) eq 'HASH') {
1327: my $currbalancer = $result->{'lonhost'};
1328: my $currtargets = $result->{'targets'};
1329: my $currrules = $result->{'rules'};
1330:
1331: if ($currbalancer eq $lonhost) {
1332: $is_balancer = 1;
1333: if (ref($currrules) eq 'HASH') {
1334: if ($currrules->{'_LC_internetdom'} ne '') {
1335: $rule_in_effect = $currrules->{'_LC_internetdom'};
1336: }
1337: }
1338: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1339: $uname,$udom);
1340: }
1341: } else {
1342: if ($perlvar{'lonBalancer'} eq 'yes') {
1343: $is_balancer = 1;
1344: $offloadto = &this_host_spares($dom_in_use);
1345: }
1346: }
1347: } else {
1348: if ($perlvar{'lonBalancer'} eq 'yes') {
1349: $is_balancer = 1;
1350: $offloadto = &this_host_spares($dom_in_use);
1351: }
1352: }
1.1172.2.5! raeburn 1353: if ($is_balancer) {
! 1354: my $lowest_load = 30000;
! 1355: if (ref($offloadto) eq 'HASH') {
! 1356: if (ref($offloadto->{'primary'}) eq 'ARRAY') {
! 1357: foreach my $try_server (@{$offloadto->{'primary'}}) {
! 1358: ($otherserver,$lowest_load) =
! 1359: &compare_server_load($try_server,$otherserver,$lowest_load);
! 1360: }
1.1129 raeburn 1361: }
1.1172.2.5! raeburn 1362: my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129 raeburn 1363:
1.1172.2.5! raeburn 1364: if (!$found_server) {
! 1365: if (ref($offloadto->{'default'}) eq 'ARRAY') {
! 1366: foreach my $try_server (@{$offloadto->{'default'}}) {
! 1367: ($otherserver,$lowest_load) =
! 1368: &compare_server_load($try_server,$otherserver,$lowest_load);
! 1369: }
! 1370: }
! 1371: }
! 1372: } elsif (ref($offloadto) eq 'ARRAY') {
! 1373: if (@{$offloadto} == 1) {
! 1374: $otherserver = $offloadto->[0];
! 1375: } elsif (@{$offloadto} > 1) {
! 1376: foreach my $try_server (@{$offloadto}) {
1.1129 raeburn 1377: ($otherserver,$lowest_load) =
1378: &compare_server_load($try_server,$otherserver,$lowest_load);
1379: }
1380: }
1381: }
1.1172.2.5! raeburn 1382: if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
! 1383: $is_balancer = 0;
! 1384: if ($uname ne '' && $udom ne '') {
! 1385: if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
! 1386:
! 1387: &appenv({'user.loadbalexempt' => $lonhost,
! 1388: 'user.loadbalcheck.time' => time});
! 1389: }
1.1129 raeburn 1390: }
1391: }
1392: }
1393: return ($is_balancer,$otherserver);
1394: }
1395:
1396: sub get_loadbalancer_targets {
1397: my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
1398: my $offloadto;
1.1172.2.4 raeburn 1399: if ($rule_in_effect eq 'none') {
1400: return [$perlvar{'lonHostID'}];
1401: } elsif ($rule_in_effect eq '') {
1.1129 raeburn 1402: $offloadto = $currtargets;
1403: } else {
1404: if ($rule_in_effect eq 'homeserver') {
1405: my $homeserver = &homeserver($uname,$udom);
1406: if ($homeserver ne 'no_host') {
1407: $offloadto = [$homeserver];
1408: }
1409: } elsif ($rule_in_effect eq 'externalbalancer') {
1410: my %domconfig =
1411: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1412: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1413: if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
1414: if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
1415: $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
1416: }
1417: }
1418: } else {
1419: my %servers = &dom_servers($udom);
1420: my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
1421: if (&hostname($remotebalancer) ne '') {
1422: $offloadto = [$remotebalancer];
1423: }
1424: }
1425: } elsif (&hostname($rule_in_effect) ne '') {
1426: $offloadto = [$rule_in_effect];
1427: }
1428: }
1429: return $offloadto;
1430: }
1431:
1.1127 raeburn 1432: sub internet_dom_servers {
1433: my ($dom) = @_;
1434: my (%uniqservers,%servers);
1435: my $primaryserver = &hostname(&domain($dom,'primary'));
1436: my @machinedoms = &machine_domains($primaryserver);
1437: foreach my $mdom (@machinedoms) {
1438: my %currservers = %servers;
1439: my %server = &get_servers($mdom);
1440: %servers = (%currservers,%server);
1441: }
1442: my %by_hostname;
1443: foreach my $id (keys(%servers)) {
1444: push(@{$by_hostname{$servers{$id}}},$id);
1445: }
1446: foreach my $hostname (sort(keys(%by_hostname))) {
1447: if (@{$by_hostname{$hostname}} > 1) {
1448: my $match = 0;
1449: foreach my $id (@{$by_hostname{$hostname}}) {
1450: if (&host_domain($id) eq $dom) {
1451: $uniqservers{$id} = $hostname;
1452: $match = 1;
1453: }
1454: }
1455: unless ($match) {
1456: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1457: }
1458: } else {
1459: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1460: }
1461: }
1462: return %uniqservers;
1463: }
1464:
1.1 albertel 1465: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 1466:
1.599 albertel 1467: my %homecache;
1.1 albertel 1468: sub homeserver {
1.230 stredwic 1469: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 1470: my $index="$uname:$udom";
1.426 albertel 1471:
1.599 albertel 1472: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 1473:
1474: my %servers = &get_servers($udom,'library');
1475: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 1476: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 1477: exists($badServerCache{$tryserver}));
1.841 albertel 1478:
1479: my $answer=reply("home:$udom:$uname",$tryserver);
1480: if ($answer eq 'found') {
1481: delete($badServerCache{$tryserver});
1482: return $homecache{$index}=$tryserver;
1483: } elsif ($answer eq 'no_host') {
1484: $badServerCache{$tryserver}=1;
1485: }
1.1 albertel 1486: }
1487: return 'no_host';
1.70 www 1488: }
1489:
1490: # ------------------------------------- Find the usernames behind a list of IDs
1491:
1492: sub idget {
1493: my ($udom,@ids)=@_;
1494: my %returnhash=();
1495:
1.841 albertel 1496: my %servers = &get_servers($udom,'library');
1497: foreach my $tryserver (keys(%servers)) {
1498: my $idlist=join('&',@ids);
1499: $idlist=~tr/A-Z/a-z/;
1500: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
1501: my @answer=();
1502: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1503: @answer=split(/\&/,$reply);
1504: } ;
1505: my $i;
1506: for ($i=0;$i<=$#ids;$i++) {
1507: if ($answer[$i]) {
1508: $returnhash{$ids[$i]}=$answer[$i];
1509: }
1510: }
1511: }
1.70 www 1512: return %returnhash;
1513: }
1514:
1515: # ------------------------------------- Find the IDs behind a list of usernames
1516:
1517: sub idrget {
1518: my ($udom,@unames)=@_;
1519: my %returnhash=();
1.800 albertel 1520: foreach my $uname (@unames) {
1521: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 1522: }
1.70 www 1523: return %returnhash;
1524: }
1525:
1526: # ------------------------------- Store away a list of names and associated IDs
1527:
1528: sub idput {
1529: my ($udom,%ids)=@_;
1530: my %servers=();
1.800 albertel 1531: foreach my $uname (keys(%ids)) {
1532: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1533: my $uhom=&homeserver($uname,$udom);
1.70 www 1534: if ($uhom ne 'no_host') {
1.800 albertel 1535: my $id=&escape($ids{$uname});
1.70 www 1536: $id=~tr/A-Z/a-z/;
1.800 albertel 1537: my $esc_unam=&escape($uname);
1.70 www 1538: if ($servers{$uhom}) {
1.800 albertel 1539: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70 www 1540: } else {
1.800 albertel 1541: $servers{$uhom}=$id.'='.$esc_unam;
1.70 www 1542: }
1543: }
1.191 harris41 1544: }
1.800 albertel 1545: foreach my $server (keys(%servers)) {
1546: &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191 harris41 1547: }
1.344 www 1548: }
1549:
1.1023 raeburn 1550: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 1551: sub dump_dom {
1.1165 droeschl 1552: my ($namespace, $udom, $regexp) = @_;
1553:
1554: $udom ||= $env{'user.domain'};
1555:
1556: return () unless $udom;
1557:
1558: return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012 raeburn 1559: }
1560:
1.1023 raeburn 1561: # ------------------------------------------ get items from domain db files
1.806 raeburn 1562:
1563: sub get_dom {
1.860 raeburn 1564: my ($namespace,$storearr,$udom,$uhome)=@_;
1.806 raeburn 1565: my $items='';
1566: foreach my $item (@$storearr) {
1567: $items.=&escape($item).'&';
1568: }
1569: $items=~s/\&$//;
1.860 raeburn 1570: if (!$udom) {
1571: $udom=$env{'user.domain'};
1572: if (defined(&domain($udom,'primary'))) {
1573: $uhome=&domain($udom,'primary');
1574: } else {
1.874 albertel 1575: undef($uhome);
1.860 raeburn 1576: }
1577: } else {
1578: if (!$uhome) {
1579: if (defined(&domain($udom,'primary'))) {
1580: $uhome=&domain($udom,'primary');
1581: }
1582: }
1583: }
1584: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1585: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866 raeburn 1586: my %returnhash;
1.875 albertel 1587: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 1588: return %returnhash;
1589: }
1.806 raeburn 1590: my @pairs=split(/\&/,$rep);
1591: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1592: return @pairs;
1593: }
1594: my $i=0;
1595: foreach my $item (@$storearr) {
1596: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1597: $i++;
1598: }
1599: return %returnhash;
1600: } else {
1.880 banghart 1601: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 1602: }
1603: }
1604:
1605: # -------------------------------------------- put items in domain db files
1606:
1607: sub put_dom {
1.860 raeburn 1608: my ($namespace,$storehash,$udom,$uhome)=@_;
1609: if (!$udom) {
1610: $udom=$env{'user.domain'};
1611: if (defined(&domain($udom,'primary'))) {
1612: $uhome=&domain($udom,'primary');
1613: } else {
1.874 albertel 1614: undef($uhome);
1.860 raeburn 1615: }
1616: } else {
1617: if (!$uhome) {
1618: if (defined(&domain($udom,'primary'))) {
1619: $uhome=&domain($udom,'primary');
1620: }
1621: }
1622: }
1623: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1624: my $items='';
1625: foreach my $item (keys(%$storehash)) {
1626: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1627: }
1628: $items=~s/\&$//;
1629: return &reply("putdom:$udom:$namespace:$items",$uhome);
1630: } else {
1.860 raeburn 1631: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 1632: }
1633: }
1634:
1.1023 raeburn 1635: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 1636: sub newput_dom {
1.1023 raeburn 1637: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 1638: my $result;
1639: if (!$udom) {
1640: $udom=$env{'user.domain'};
1641: }
1.1023 raeburn 1642: if ($udom) {
1643: my $uname = &get_domainconfiguser($udom);
1644: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 1645: }
1646: return $result;
1647: }
1648:
1.1023 raeburn 1649: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 1650: sub del_dom {
1.1023 raeburn 1651: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 1652: if (ref($storearr) eq 'ARRAY') {
1653: if (!$udom) {
1654: $udom=$env{'user.domain'};
1655: }
1.1023 raeburn 1656: if ($udom) {
1657: my $uname = &get_domainconfiguser($udom);
1658: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 1659: }
1660: }
1661: }
1662:
1.1023 raeburn 1663: # ----------------------------------construct domainconfig user for a domain
1664: sub get_domainconfiguser {
1665: my ($udom) = @_;
1666: return $udom.'-domainconfig';
1667: }
1668:
1.837 raeburn 1669: sub retrieve_inst_usertypes {
1670: my ($udom) = @_;
1671: my (%returnhash,@order);
1.989 raeburn 1672: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1673: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1674: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1675: %returnhash = %{$domdefs{'inststatustypes'}};
1676: @order = @{$domdefs{'inststatusorder'}};
1677: } else {
1678: if (defined(&domain($udom,'primary'))) {
1679: my $uhome=&domain($udom,'primary');
1680: my $rep=&reply("inst_usertypes:$udom",$uhome);
1681: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1682: &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
1683: return (\%returnhash,\@order);
1684: }
1685: my ($hashitems,$orderitems) = split(/:/,$rep);
1686: my @pairs=split(/\&/,$hashitems);
1687: foreach my $item (@pairs) {
1688: my ($key,$value)=split(/=/,$item,2);
1689: $key = &unescape($key);
1690: next if ($key =~ /^error: 2 /);
1691: $returnhash{$key}=&thaw_unescape($value);
1692: }
1693: my @esc_order = split(/\&/,$orderitems);
1694: foreach my $item (@esc_order) {
1695: push(@order,&unescape($item));
1696: }
1697: } else {
1698: &logthis("get_dom failed - no primary domain server for $udom");
1.837 raeburn 1699: }
1700: }
1701: return (\%returnhash,\@order);
1702: }
1703:
1.868 raeburn 1704: sub is_domainimage {
1705: my ($url) = @_;
1706: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
1707: if (&domain($1) ne '') {
1708: return '1';
1709: }
1710: }
1711: return;
1712: }
1713:
1.899 raeburn 1714: sub inst_directory_query {
1715: my ($srch) = @_;
1716: my $udom = $srch->{'srchdomain'};
1717: my %results;
1718: my $homeserver = &domain($udom,'primary');
1.909 raeburn 1719: my $outcome;
1.899 raeburn 1720: if ($homeserver ne '') {
1.904 albertel 1721: my $queryid=&reply("querysend:instdirsearch:".
1722: &escape($srch->{'srchby'}).':'.
1723: &escape($srch->{'srchterm'}).':'.
1724: &escape($srch->{'srchtype'}),$homeserver);
1725: my $host=&hostname($homeserver);
1726: if ($queryid !~/^\Q$host\E\_/) {
1727: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1728: return;
1729: }
1730: my $response = &get_query_reply($queryid);
1731: my $maxtries = 5;
1732: my $tries = 1;
1733: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1734: $response = &get_query_reply($queryid);
1735: $tries ++;
1736: }
1737:
1738: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 1739: if ($response eq 'unavailable') {
1740: $outcome = $response;
1741: } else {
1742: $outcome = 'ok';
1743: my @matches = split(/\n/,$response);
1744: foreach my $match (@matches) {
1745: my ($key,$value) = split(/=/,$match);
1746: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1747: }
1.899 raeburn 1748: }
1749: }
1750: }
1.909 raeburn 1751: return ($outcome,%results);
1.899 raeburn 1752: }
1753:
1754: sub usersearch {
1755: my ($srch) = @_;
1756: my $dom = $srch->{'srchdomain'};
1757: my %results;
1758: my %libserv = &all_library();
1759: my $query = 'usersearch';
1760: foreach my $tryserver (keys(%libserv)) {
1761: if (&host_domain($tryserver) eq $dom) {
1762: my $host=&hostname($tryserver);
1763: my $queryid=
1.911 raeburn 1764: &reply("querysend:".&escape($query).':'.
1765: &escape($srch->{'srchby'}).':'.
1.899 raeburn 1766: &escape($srch->{'srchtype'}).':'.
1767: &escape($srch->{'srchterm'}),$tryserver);
1768: if ($queryid !~/^\Q$host\E\_/) {
1769: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 1770: next;
1.899 raeburn 1771: }
1772: my $reply = &get_query_reply($queryid);
1773: my $maxtries = 1;
1774: my $tries = 1;
1775: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1776: $reply = &get_query_reply($queryid);
1777: $tries ++;
1778: }
1779: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1780: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1781: } else {
1.911 raeburn 1782: my @matches;
1783: if ($reply =~ /\n/) {
1784: @matches = split(/\n/,$reply);
1785: } else {
1786: @matches = split(/\&/,$reply);
1787: }
1.899 raeburn 1788: foreach my $match (@matches) {
1789: my ($uname,$udom,%userhash);
1.911 raeburn 1790: foreach my $entry (split(/:/,$match)) {
1791: my ($key,$value) =
1792: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 1793: $userhash{$key} = $value;
1794: if ($key eq 'username') {
1795: $uname = $value;
1796: } elsif ($key eq 'domain') {
1797: $udom = $value;
1.911 raeburn 1798: }
1.899 raeburn 1799: }
1800: $results{$uname.':'.$udom} = \%userhash;
1801: }
1802: }
1803: }
1804: }
1805: return %results;
1806: }
1807:
1.912 raeburn 1808: sub get_instuser {
1809: my ($udom,$uname,$id) = @_;
1810: my $homeserver = &domain($udom,'primary');
1811: my ($outcome,%results);
1812: if ($homeserver ne '') {
1813: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1814: &escape($id).':'.&escape($udom),$homeserver);
1815: my $host=&hostname($homeserver);
1816: if ($queryid !~/^\Q$host\E\_/) {
1817: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1818: return;
1819: }
1820: my $response = &get_query_reply($queryid);
1821: my $maxtries = 5;
1822: my $tries = 1;
1823: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1824: $response = &get_query_reply($queryid);
1825: $tries ++;
1826: }
1827: if (!&error($response) && $response ne 'refused') {
1828: if ($response eq 'unavailable') {
1829: $outcome = $response;
1830: } else {
1831: $outcome = 'ok';
1832: my @matches = split(/\n/,$response);
1833: foreach my $match (@matches) {
1834: my ($key,$value) = split(/=/,$match);
1835: $results{&unescape($key)} = &thaw_unescape($value);
1836: }
1837: }
1838: }
1839: }
1840: my %userinfo;
1841: if (ref($results{$uname}) eq 'HASH') {
1842: %userinfo = %{$results{$uname}};
1843: }
1844: return ($outcome,%userinfo);
1845: }
1846:
1847: sub inst_rulecheck {
1.923 raeburn 1848: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 1849: my %returnhash;
1850: if ($udom ne '') {
1851: if (ref($rules) eq 'ARRAY') {
1852: @{$rules} = map {&escape($_);} (@{$rules});
1853: my $rulestr = join(':',@{$rules});
1854: my $homeserver=&domain($udom,'primary');
1855: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1856: my $response;
1857: if ($item eq 'username') {
1858: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
1859: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 1860: $homeserver));
1.923 raeburn 1861: } elsif ($item eq 'id') {
1862: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
1863: ':'.&escape($id).':'.$rulestr,
1864: $homeserver));
1.945 raeburn 1865: } elsif ($item eq 'selfcreate') {
1866: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 1867: &escape($udom).':'.&escape($uname).
1868: ':'.$rulestr,$homeserver));
1.923 raeburn 1869: }
1.912 raeburn 1870: if ($response ne 'refused') {
1871: my @pairs=split(/\&/,$response);
1872: foreach my $item (@pairs) {
1873: my ($key,$value)=split(/=/,$item,2);
1874: $key = &unescape($key);
1875: next if ($key =~ /^error: 2 /);
1876: $returnhash{$key}=&thaw_unescape($value);
1877: }
1878: }
1879: }
1880: }
1881: }
1882: return %returnhash;
1883: }
1884:
1885: sub inst_userrules {
1.923 raeburn 1886: my ($udom,$check) = @_;
1.912 raeburn 1887: my (%ruleshash,@ruleorder);
1888: if ($udom ne '') {
1889: my $homeserver=&domain($udom,'primary');
1890: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1891: my $response;
1892: if ($check eq 'id') {
1893: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 1894: $homeserver);
1.943 raeburn 1895: } elsif ($check eq 'email') {
1896: $response=&reply('instemailrules:'.&escape($udom),
1897: $homeserver);
1.923 raeburn 1898: } else {
1899: $response=&reply('instuserrules:'.&escape($udom),
1900: $homeserver);
1901: }
1.912 raeburn 1902: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 1903: ($response ne 'unknown_cmd') &&
1.912 raeburn 1904: ($response ne 'no_such_host')) {
1905: my ($hashitems,$orderitems) = split(/:/,$response);
1906: my @pairs=split(/\&/,$hashitems);
1907: foreach my $item (@pairs) {
1908: my ($key,$value)=split(/=/,$item,2);
1909: $key = &unescape($key);
1910: next if ($key =~ /^error: 2 /);
1911: $ruleshash{$key}=&thaw_unescape($value);
1912: }
1913: my @esc_order = split(/\&/,$orderitems);
1914: foreach my $item (@esc_order) {
1915: push(@ruleorder,&unescape($item));
1916: }
1917: }
1918: }
1919: }
1920: return (\%ruleshash,\@ruleorder);
1921: }
1922:
1.976 raeburn 1923: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 1924:
1925: sub get_domain_defaults {
1926: my ($domain) = @_;
1927: my $cachetime = 60*60*24;
1928: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
1929: if (defined($cached)) {
1930: if (ref($result) eq 'HASH') {
1931: return %{$result};
1932: }
1933: }
1934: my %domdefaults;
1935: my %domconfig =
1.989 raeburn 1936: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 1937: 'requestcourses','inststatus',
1.1073 raeburn 1938: 'coursedefaults','usersessions'],$domain);
1.943 raeburn 1939: if (ref($domconfig{'defaults'}) eq 'HASH') {
1940: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
1941: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
1942: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 1943: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 1944: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147 raeburn 1945: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943 raeburn 1946: } else {
1947: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
1948: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
1949: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
1950: }
1.976 raeburn 1951: if (ref($domconfig{'quotas'}) eq 'HASH') {
1952: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
1953: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
1954: } else {
1955: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1956: }
1957: my @usertools = ('aboutme','blog','portfolio');
1958: foreach my $item (@usertools) {
1959: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
1960: $domdefaults{$item} = $domconfig{'quotas'}{$item};
1961: }
1962: }
1963: }
1.985 raeburn 1964: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006 raeburn 1965: foreach my $item ('official','unofficial','community') {
1.985 raeburn 1966: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
1967: }
1968: }
1.989 raeburn 1969: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1970: foreach my $item ('inststatustypes','inststatusorder') {
1971: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
1972: }
1973: }
1.1047 raeburn 1974: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1975: foreach my $item ('canuse_pdfforms') {
1976: $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
1977: }
1978: }
1.1073 raeburn 1979: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1980: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
1981: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
1982: }
1983: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
1984: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
1985: }
1986: }
1.943 raeburn 1987: &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
1988: $cachetime);
1989: return %domdefaults;
1990: }
1991:
1.344 www 1992: # --------------------------------------------------- Assign a key to a student
1993:
1994: sub assign_access_key {
1.364 www 1995: #
1996: # a valid key looks like uname:udom#comments
1997: # comments are being appended
1998: #
1.498 www 1999: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
2000: $kdom=
1.620 albertel 2001: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 2002: $knum=
1.620 albertel 2003: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 2004: $cdom=
1.620 albertel 2005: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2006: $cnum=
1.620 albertel 2007: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2008: $udom=$env{'user.name'} unless (defined($udom));
2009: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 2010: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 2011: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 2012: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 2013: # assigned to this person
2014: # - this should not happen,
1.345 www 2015: # unless something went wrong
2016: # the first time around
2017: # ready to assign
1.364 www 2018: $logentry=$1.'; '.$logentry;
1.496 www 2019: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 2020: $kdom,$knum) eq 'ok') {
1.345 www 2021: # key now belongs to user
1.346 www 2022: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 2023: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 2024: &appenv({'environment.'.$envkey => $ckey});
1.345 www 2025: return 'ok';
2026: } else {
2027: return
2028: 'error: Count not permanently assign key, will need to be re-entered later.';
2029: }
2030: } else {
2031: return 'error: Could not assign key, try again later.';
2032: }
1.364 www 2033: } elsif (!$existing{$ckey}) {
1.345 www 2034: # the key does not exist
2035: return 'error: The key does not exist';
2036: } else {
2037: # the key is somebody else's
2038: return 'error: The key is already in use';
2039: }
1.344 www 2040: }
2041:
1.364 www 2042: # ------------------------------------------ put an additional comment on a key
2043:
2044: sub comment_access_key {
2045: #
2046: # a valid key looks like uname:udom#comments
2047: # comments are being appended
2048: #
2049: my ($ckey,$cdom,$cnum,$logentry)=@_;
2050: $cdom=
1.620 albertel 2051: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 2052: $cnum=
1.620 albertel 2053: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 2054: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2055: if ($existing{$ckey}) {
2056: $existing{$ckey}.='; '.$logentry;
2057: # ready to assign
1.367 www 2058: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 2059: $cdom,$cnum) eq 'ok') {
2060: return 'ok';
2061: } else {
2062: return 'error: Count not store comment.';
2063: }
2064: } else {
2065: # the key does not exist
2066: return 'error: The key does not exist';
2067: }
2068: }
2069:
1.344 www 2070: # ------------------------------------------------------ Generate a set of keys
2071:
2072: sub generate_access_keys {
1.364 www 2073: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 2074: $cdom=
1.620 albertel 2075: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2076: $cnum=
1.620 albertel 2077: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 2078: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 2079: unless (($cdom) && ($cnum)) { return 0; }
2080: if ($number>10000) { return 0; }
2081: sleep(2); # make sure don't get same seed twice
2082: srand(time()^($$+($$<<15))); # from "Programming Perl"
2083: my $total=0;
2084: for (my $i=1;$i<=$number;$i++) {
2085: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
2086: sprintf("%lx",int(100000*rand)).'-'.
2087: sprintf("%lx",int(100000*rand));
2088: $newkey=~s/1/g/g; # folks mix up 1 and l
2089: $newkey=~s/0/h/g; # and also 0 and O
2090: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
2091: if ($existing{$newkey}) {
2092: $i--;
2093: } else {
1.364 www 2094: if (&put('accesskeys',
2095: { $newkey => '# generated '.localtime().
1.620 albertel 2096: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 2097: '; '.$logentry },
2098: $cdom,$cnum) eq 'ok') {
1.344 www 2099: $total++;
2100: }
2101: }
2102: }
1.620 albertel 2103: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 2104: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
2105: return $total;
2106: }
2107:
2108: # ------------------------------------------------------- Validate an accesskey
2109:
2110: sub validate_access_key {
2111: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
2112: $cdom=
1.620 albertel 2113: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2114: $cnum=
1.620 albertel 2115: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2116: $udom=$env{'user.domain'} unless (defined($udom));
2117: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 2118: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 2119: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 2120: }
2121:
2122: # ------------------------------------- Find the section of student in a course
1.652 albertel 2123: sub devalidate_getsection_cache {
2124: my ($udom,$unam,$courseid)=@_;
2125: my $hashid="$udom:$unam:$courseid";
2126: &devalidate_cache_new('getsection',$hashid);
2127: }
1.298 matthew 2128:
1.815 albertel 2129: sub courseid_to_courseurl {
2130: my ($courseid) = @_;
2131: #already url style courseid
2132: return $courseid if ($courseid =~ m{^/});
2133:
2134: if (exists($env{'course.'.$courseid.'.num'})) {
2135: my $cnum = $env{'course.'.$courseid.'.num'};
2136: my $cdom = $env{'course.'.$courseid.'.domain'};
2137: return "/$cdom/$cnum";
2138: }
2139:
2140: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
2141: if (exists($courseinfo{'num'})) {
2142: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
2143: }
2144:
2145: return undef;
2146: }
2147:
1.298 matthew 2148: sub getsection {
2149: my ($udom,$unam,$courseid)=@_;
1.599 albertel 2150: my $cachetime=1800;
1.551 albertel 2151:
2152: my $hashid="$udom:$unam:$courseid";
1.599 albertel 2153: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 2154: if (defined($cached)) { return $result; }
2155:
1.298 matthew 2156: my %Pending;
2157: my %Expired;
2158: #
2159: # Each role can either have not started yet (pending), be active,
2160: # or have expired.
2161: #
2162: # If there is an active role, we are done.
2163: #
2164: # If there is more than one role which has not started yet,
2165: # choose the one which will start sooner
2166: # If there is one role which has not started yet, return it.
2167: #
2168: # If there is more than one expired role, choose the one which ended last.
2169: # If there is a role which has expired, return it.
2170: #
1.815 albertel 2171: $courseid = &courseid_to_courseurl($courseid);
1.1166 raeburn 2172: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817 raeburn 2173: foreach my $key (keys(%roleshash)) {
1.479 albertel 2174: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 2175: my $section=$1;
2176: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 2177: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 2178: my $now=time;
1.548 albertel 2179: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 2180: $Expired{$end}=$section;
2181: next;
2182: }
1.548 albertel 2183: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 2184: $Pending{$start}=$section;
2185: next;
2186: }
1.599 albertel 2187: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 2188: }
2189: #
2190: # Presumedly there will be few matching roles from the above
2191: # loop and the sorting time will be negligible.
2192: if (scalar(keys(%Pending))) {
2193: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 2194: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 2195: }
2196: if (scalar(keys(%Expired))) {
2197: my @sorted = sort {$a <=> $b} keys(%Expired);
2198: my $time = pop(@sorted);
1.599 albertel 2199: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 2200: }
1.599 albertel 2201: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 2202: }
1.70 www 2203:
1.599 albertel 2204: sub save_cache {
2205: &purge_remembered();
1.722 albertel 2206: #&Apache::loncommon::validate_page();
1.620 albertel 2207: undef(%env);
1.780 albertel 2208: undef($env_loaded);
1.599 albertel 2209: }
1.452 albertel 2210:
1.599 albertel 2211: my $to_remember=-1;
2212: my %remembered;
2213: my %accessed;
2214: my $kicks=0;
2215: my $hits=0;
1.849 albertel 2216: sub make_key {
2217: my ($name,$id) = @_;
1.872 albertel 2218: if (length($id) > 65
2219: && length(&escape($id)) > 200) {
2220: $id=length($id).':'.&Digest::MD5::md5_hex($id);
2221: }
1.849 albertel 2222: return &escape($name.':'.$id);
2223: }
2224:
1.599 albertel 2225: sub devalidate_cache_new {
2226: my ($name,$id,$debug) = @_;
2227: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849 albertel 2228: $id=&make_key($name,$id);
1.599 albertel 2229: $memcache->delete($id);
2230: delete($remembered{$id});
2231: delete($accessed{$id});
2232: }
2233:
2234: sub is_cached_new {
2235: my ($name,$id,$debug) = @_;
1.849 albertel 2236: $id=&make_key($name,$id);
1.599 albertel 2237: if (exists($remembered{$id})) {
1.1133 foxr 2238: if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
1.599 albertel 2239: $accessed{$id}=[&gettimeofday()];
2240: $hits++;
2241: return ($remembered{$id},1);
2242: }
2243: my $value = $memcache->get($id);
2244: if (!(defined($value))) {
2245: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 2246: return (undef,undef);
1.416 albertel 2247: }
1.599 albertel 2248: if ($value eq '__undef__') {
2249: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
2250: $value=undef;
2251: }
2252: &make_room($id,$value,$debug);
2253: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
2254: return ($value,1);
2255: }
2256:
2257: sub do_cache_new {
2258: my ($name,$id,$value,$time,$debug) = @_;
1.849 albertel 2259: $id=&make_key($name,$id);
1.599 albertel 2260: my $setvalue=$value;
2261: if (!defined($setvalue)) {
2262: $setvalue='__undef__';
2263: }
1.623 albertel 2264: if (!defined($time) ) {
2265: $time=600;
2266: }
1.599 albertel 2267: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 2268: my $result = $memcache->set($id,$setvalue,$time);
2269: if (! $result) {
1.872 albertel 2270: &logthis("caching of id -> $id failed");
1.910 albertel 2271: $memcache->disconnect_all();
1.872 albertel 2272: }
1.600 albertel 2273: # need to make a copy of $value
1.919 albertel 2274: &make_room($id,$value,$debug);
1.599 albertel 2275: return $value;
2276: }
2277:
2278: sub make_room {
2279: my ($id,$value,$debug)=@_;
1.919 albertel 2280:
2281: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
2282: : $value;
1.599 albertel 2283: if ($to_remember<0) { return; }
2284: $accessed{$id}=[&gettimeofday()];
2285: if (scalar(keys(%remembered)) <= $to_remember) { return; }
2286: my $to_kick;
2287: my $max_time=0;
2288: foreach my $other (keys(%accessed)) {
2289: if (&tv_interval($accessed{$other}) > $max_time) {
2290: $to_kick=$other;
2291: $max_time=&tv_interval($accessed{$other});
2292: }
2293: }
2294: delete($remembered{$to_kick});
2295: delete($accessed{$to_kick});
2296: $kicks++;
2297: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 2298: return;
2299: }
2300:
1.599 albertel 2301: sub purge_remembered {
1.604 albertel 2302: #&logthis("Tossing ".scalar(keys(%remembered)));
2303: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 2304: undef(%remembered);
2305: undef(%accessed);
1.428 albertel 2306: }
1.70 www 2307: # ------------------------------------- Read an entry from a user's environment
2308:
2309: sub userenvironment {
2310: my ($udom,$unam,@what)=@_;
1.976 raeburn 2311: my $items;
2312: foreach my $item (@what) {
2313: $items.=&escape($item).'&';
2314: }
2315: $items=~s/\&$//;
1.70 www 2316: my %returnhash=();
1.1009 raeburn 2317: my $uhome = &homeserver($unam,$udom);
2318: unless ($uhome eq 'no_host') {
2319: my @answer=split(/\&/,
2320: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 2321: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
2322: return %returnhash;
2323: }
1.1009 raeburn 2324: my $i;
2325: for ($i=0;$i<=$#what;$i++) {
2326: $returnhash{$what[$i]}=&unescape($answer[$i]);
2327: }
1.70 www 2328: }
2329: return %returnhash;
1.1 albertel 2330: }
2331:
1.617 albertel 2332: # ---------------------------------------------------------- Get a studentphoto
2333: sub studentphoto {
2334: my ($udom,$unam,$ext) = @_;
2335: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 2336: if (defined($env{'request.course.id'})) {
1.708 raeburn 2337: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 2338: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
2339: return(&retrievestudentphoto($udom,$unam,$ext));
2340: } else {
2341: my ($result,$perm_reqd)=
1.707 albertel 2342: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2343: if ($result eq 'ok') {
2344: if (!($perm_reqd eq 'yes')) {
2345: return(&retrievestudentphoto($udom,$unam,$ext));
2346: }
2347: }
2348: }
2349: }
2350: } else {
2351: my ($result,$perm_reqd) =
1.707 albertel 2352: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2353: if ($result eq 'ok') {
2354: if (!($perm_reqd eq 'yes')) {
2355: return(&retrievestudentphoto($udom,$unam,$ext));
2356: }
2357: }
2358: }
2359: return '/adm/lonKaputt/lonlogo_broken.gif';
2360: }
2361:
2362: sub retrievestudentphoto {
2363: my ($udom,$unam,$ext,$type) = @_;
2364: my $home=&Apache::lonnet::homeserver($unam,$udom);
2365: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
2366: if ($ret eq 'ok') {
2367: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
2368: if ($type eq 'thumbnail') {
2369: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
2370: }
2371: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
2372: return $tokenurl;
2373: } else {
2374: if ($type eq 'thumbnail') {
2375: return '/adm/lonKaputt/genericstudent_tn.gif';
2376: } else {
2377: return '/adm/lonKaputt/lonlogo_broken.gif';
2378: }
1.617 albertel 2379: }
2380: }
2381:
1.263 www 2382: # -------------------------------------------------------------------- New chat
2383:
2384: sub chatsend {
1.724 raeburn 2385: my ($newentry,$anon,$group)=@_;
1.620 albertel 2386: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
2387: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2388: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 2389: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 2390: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 2391: &escape($newentry)).':'.$group,$chome);
1.292 www 2392: }
2393:
2394: # ------------------------------------------ Find current version of a resource
2395:
2396: sub getversion {
2397: my $fname=&clutter(shift);
2398: unless ($fname=~/^\/res\//) { return -1; }
2399: return ¤tversion(&filelocation('',$fname));
2400: }
2401:
2402: sub currentversion {
2403: my $fname=shift;
2404: my $author=$fname;
2405: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2406: my ($udom,$uname)=split(/\//,$author);
1.1112 www 2407: my $home=&homeserver($uname,$udom);
1.292 www 2408: if ($home eq 'no_host') {
2409: return -1;
2410: }
1.1112 www 2411: my $answer=&reply("currentversion:$fname",$home);
1.292 www 2412: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2413: return -1;
2414: }
1.1112 www 2415: return $answer;
1.263 www 2416: }
2417:
1.1111 www 2418: #
2419: # Return special version number of resource if set by override, empty otherwise
2420: #
2421: sub usedversion {
2422: my $fname=shift;
2423: unless ($fname) { $fname=$env{'request.uri'}; }
2424: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
2425: if ($urlversion) { return $urlversion; }
2426: return '';
2427: }
2428:
1.1 albertel 2429: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 2430:
1.1 albertel 2431: sub subscribe {
2432: my $fname=shift;
1.761 raeburn 2433: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 2434: $fname=~s/[\n\r]//g;
1.1 albertel 2435: my $author=$fname;
2436: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2437: my ($udom,$uname)=split(/\//,$author);
2438: my $home=homeserver($uname,$udom);
1.335 albertel 2439: if ($home eq 'no_host') {
2440: return 'not_found';
1.1 albertel 2441: }
2442: my $answer=reply("sub:$fname",$home);
1.64 www 2443: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2444: $answer.=' by '.$home;
2445: }
1.1 albertel 2446: return $answer;
2447: }
2448:
1.8 www 2449: # -------------------------------------------------------------- Replicate file
2450:
2451: sub repcopy {
2452: my $filename=shift;
1.23 www 2453: $filename=~s/\/+/\//g;
1.1142 raeburn 2454: my $londocroot = $perlvar{'lonDocRoot'};
2455: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164 raeburn 2456: if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142 raeburn 2457: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
2458: $filename=~m{^/*(uploaded|editupload)/}) {
1.538 albertel 2459: return &repcopy_userfile($filename);
2460: }
1.532 albertel 2461: $filename=~s/[\n\r]//g;
1.8 www 2462: my $transname="$filename.in.transfer";
1.828 www 2463: # FIXME: this should flock
1.607 raeburn 2464: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 2465: my $remoteurl=subscribe($filename);
1.64 www 2466: if ($remoteurl =~ /^con_lost by/) {
2467: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2468: return 'unavailable';
1.8 www 2469: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 2470: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 2471: return 'not_found';
1.64 www 2472: } elsif ($remoteurl =~ /^rejected by/) {
2473: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2474: return 'forbidden';
1.20 www 2475: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 2476: return 'ok';
1.8 www 2477: } else {
1.290 www 2478: my $author=$filename;
2479: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2480: my ($udom,$uname)=split(/\//,$author);
2481: my $home=homeserver($uname,$udom);
2482: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 2483: my @parts=split(/\//,$filename);
2484: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142 raeburn 2485: if ($path ne "$londocroot/res") {
1.8 www 2486: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 2487: return 'bad_request';
1.8 www 2488: }
2489: my $count;
2490: for ($count=5;$count<$#parts;$count++) {
2491: $path.="/$parts[$count]";
2492: if ((-e $path)!=1) {
2493: mkdir($path,0777);
2494: }
2495: }
2496: my $ua=new LWP::UserAgent;
2497: my $request=new HTTP::Request('GET',"$remoteurl");
2498: my $response=$ua->request($request,$transname);
2499: if ($response->is_error()) {
2500: unlink($transname);
2501: my $message=$response->status_line;
1.672 albertel 2502: &logthis("<font color=\"blue\">WARNING:"
1.12 www 2503: ." LWP get: $message: $filename</font>");
1.607 raeburn 2504: return 'unavailable';
1.8 www 2505: } else {
1.16 www 2506: if ($remoteurl!~/\.meta$/) {
2507: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2508: my $mresponse=$ua->request($mrequest,$filename.'.meta');
2509: if ($mresponse->is_error()) {
2510: unlink($filename.'.meta');
2511: &logthis(
1.672 albertel 2512: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 2513: }
2514: }
1.8 www 2515: rename($transname,$filename);
1.607 raeburn 2516: return 'ok';
1.8 www 2517: }
1.290 www 2518: }
1.8 www 2519: }
1.330 www 2520: }
2521:
2522: # ------------------------------------------------ Get server side include body
2523: sub ssi_body {
1.381 albertel 2524: my ($filelink,%form)=@_;
1.606 matthew 2525: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
2526: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
2527: }
1.953 www 2528: my $output='';
2529: my $response;
1.980 raeburn 2530: if ($filelink=~/^https?\:/) {
1.954 raeburn 2531: ($output,$response)=&externalssi($filelink);
1.953 www 2532: } else {
1.1004 droeschl 2533: $filelink .= $filelink=~/\?/ ? '&' : '?';
2534: $filelink .= 'inhibitmenu=yes';
1.953 www 2535: ($output,$response)=&ssi($filelink,%form);
2536: }
1.778 albertel 2537: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 2538: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 2539: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 2540: if (wantarray) {
2541: return ($output, $response);
2542: } else {
2543: return $output;
2544: }
1.8 www 2545: }
2546:
1.15 www 2547: # --------------------------------------------------------- Server Side Include
2548:
1.782 albertel 2549: sub absolute_url {
2550: my ($host_name) = @_;
2551: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
2552: if ($host_name eq '') {
2553: $host_name = $ENV{'SERVER_NAME'};
2554: }
2555: return $protocol.$host_name;
2556: }
2557:
1.942 foxr 2558: #
2559: # Server side include.
2560: # Parameters:
2561: # fn Possibly encrypted resource name/id.
2562: # form Hash that describes how the rendering should be done
2563: # and other things.
1.944 foxr 2564: # Returns:
1.950 raeburn 2565: # Scalar context: The content of the response.
2566: # Array context: 2 element list of the content and the full response object.
1.942 foxr 2567: #
1.15 www 2568: sub ssi {
2569:
1.944 foxr 2570: my ($fn,%form)=@_;
1.15 www 2571: my $ua=new LWP::UserAgent;
1.23 www 2572: my $request;
1.711 albertel 2573:
2574: $form{'no_update_last_known'}=1;
1.895 albertel 2575: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 2576: if (%form) {
1.782 albertel 2577: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000 raeburn 2578: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23 www 2579: } else {
1.782 albertel 2580: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 2581: }
2582:
1.15 www 2583: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.2 raeburn 2584: my $response= $ua->request($request);
1.944 foxr 2585: if (wantarray) {
1.1172.2.3 raeburn 2586: return ($response->content, $response);
1.944 foxr 2587: } else {
1.1172.2.3 raeburn 2588: return $response->content;
1.942 foxr 2589: }
1.324 www 2590: }
2591:
2592: sub externalssi {
2593: my ($url)=@_;
2594: my $ua=new LWP::UserAgent;
2595: my $request=new HTTP::Request('GET',$url);
2596: my $response=$ua->request($request);
1.954 raeburn 2597: if (wantarray) {
2598: return ($response->content, $response);
2599: } else {
2600: return $response->content;
2601: }
1.15 www 2602: }
1.254 www 2603:
1.492 albertel 2604: # -------------------------------- Allow a /uploaded/ URI to be vouched for
2605:
2606: sub allowuploaded {
2607: my ($srcurl,$url)=@_;
2608: $url=&clutter(&declutter($url));
2609: my $dir=$url;
2610: $dir=~s/\/[^\/]+$//;
2611: my %httpref=();
2612: my $httpurl=&hreflocation('',$url);
2613: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 2614: &Apache::lonnet::appenv(\%httpref);
1.254 www 2615: }
1.477 raeburn 2616:
1.478 albertel 2617: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 2618: # input: action, courseID, current domain, intended
1.637 raeburn 2619: # path to file, source of file, instruction to parse file for objects,
2620: # ref to hash for embedded objects,
2621: # ref to hash for codebase of java objects.
1.1095 raeburn 2622: # reference to scalar to accommodate mime type determined
2623: # from File::MMagic if $parser = parse.
1.637 raeburn 2624: #
1.485 raeburn 2625: # output: url to file (if action was uploaddoc),
2626: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 2627: #
1.478 albertel 2628: # Allows directory structure to be used within lonUsers/../userfiles/ for a
2629: # course.
1.477 raeburn 2630: #
1.478 albertel 2631: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2632: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
2633: # course's home server.
1.477 raeburn 2634: #
1.478 albertel 2635: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
2636: # be copied from $source (current location) to
2637: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2638: # and will then be copied to
2639: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
2640: # course's home server.
1.485 raeburn 2641: #
1.481 raeburn 2642: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 2643: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 2644: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2645: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
2646: # in course's home server.
1.637 raeburn 2647: #
1.477 raeburn 2648:
2649: sub process_coursefile {
1.1095 raeburn 2650: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
2651: $mimetype)=@_;
1.477 raeburn 2652: my $fetchresult;
1.638 albertel 2653: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 2654: if ($action eq 'propagate') {
1.638 albertel 2655: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2656: $home);
1.481 raeburn 2657: } else {
1.477 raeburn 2658: my $fpath = '';
2659: my $fname = $file;
1.478 albertel 2660: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 2661: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 2662: my $filepath = &build_filepath($fpath);
1.481 raeburn 2663: if ($action eq 'copy') {
2664: if ($source eq '') {
2665: $fetchresult = 'no source file';
2666: return $fetchresult;
2667: } else {
2668: my $destination = $filepath.'/'.$fname;
2669: rename($source,$destination);
2670: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2671: $home);
1.481 raeburn 2672: }
2673: } elsif ($action eq 'uploaddoc') {
2674: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 2675: print $fh $env{'form.'.$source};
1.481 raeburn 2676: close($fh);
1.637 raeburn 2677: if ($parser eq 'parse') {
1.1024 raeburn 2678: my $mm = new File::MMagic;
1.1095 raeburn 2679: my $type = $mm->checktype_filename($filepath.'/'.$fname);
2680: if ($type eq 'text/html') {
1.1024 raeburn 2681: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
2682: unless ($parse_result eq 'ok') {
2683: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
2684: }
1.637 raeburn 2685: }
1.1095 raeburn 2686: if (ref($mimetype)) {
2687: $$mimetype = $type;
2688: }
1.637 raeburn 2689: }
1.477 raeburn 2690: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2691: $home);
1.481 raeburn 2692: if ($fetchresult eq 'ok') {
2693: return '/uploaded/'.$fpath.'/'.$fname;
2694: } else {
2695: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 2696: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 2697: return '/adm/notfound.html';
2698: }
1.477 raeburn 2699: }
2700: }
1.485 raeburn 2701: unless ( $fetchresult eq 'ok') {
1.477 raeburn 2702: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 2703: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 2704: }
2705: return $fetchresult;
2706: }
2707:
1.637 raeburn 2708: sub build_filepath {
2709: my ($fpath) = @_;
2710: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
2711: unless ($fpath eq '') {
2712: my @parts=split('/',$fpath);
2713: foreach my $part (@parts) {
2714: $filepath.= '/'.$part;
2715: if ((-e $filepath)!=1) {
2716: mkdir($filepath,0777);
2717: }
2718: }
2719: }
2720: return $filepath;
2721: }
2722:
2723: sub store_edited_file {
1.638 albertel 2724: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 2725: my $file = $primary_url;
2726: $file =~ s#^/uploaded/$docudom/$docuname/##;
2727: my $fpath = '';
2728: my $fname = $file;
2729: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
2730: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
2731: my $filepath = &build_filepath($fpath);
2732: open(my $fh,'>'.$filepath.'/'.$fname);
2733: print $fh $content;
2734: close($fh);
1.638 albertel 2735: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 2736: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2737: $home);
1.637 raeburn 2738: if ($$fetchresult eq 'ok') {
2739: return '/uploaded/'.$fpath.'/'.$fname;
2740: } else {
1.638 albertel 2741: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
2742: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 2743: return '/adm/notfound.html';
2744: }
2745: }
2746:
1.531 albertel 2747: sub clean_filename {
1.831 albertel 2748: my ($fname,$args)=@_;
1.315 www 2749: # Replace Windows backslashes by forward slashes
1.257 www 2750: $fname=~s/\\/\//g;
1.831 albertel 2751: if (!$args->{'keep_path'}) {
2752: # Get rid of everything but the actual filename
2753: $fname=~s/^.*\/([^\/]+)$/$1/;
2754: }
1.315 www 2755: # Replace spaces by underscores
2756: $fname=~s/\s+/\_/g;
2757: # Replace all other weird characters by nothing
1.831 albertel 2758: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 2759: # Replace all .\d. sequences with _\d. so they no longer look like version
2760: # numbers
2761: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 2762: return $fname;
2763: }
1.1051 raeburn 2764: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
2765: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
2766: # image with the same aspect ratio as the original, but with dimensions which do
2767: # not exceed $resizewidth and $resizeheight.
2768:
1.984 neumanie 2769: sub resizeImage {
1.1051 raeburn 2770: my ($img_path,$resizewidth,$resizeheight) = @_;
2771: my $ima = Image::Magick->new;
2772: my $resized;
2773: if (-e $img_path) {
2774: $ima->Read($img_path);
2775: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
2776: my $width = $ima->Get('width');
2777: my $height = $ima->Get('height');
2778: if ($width > $resizewidth) {
2779: my $factor = $width/$resizewidth;
2780: my $newheight = $height/$factor;
2781: $ima->Scale(width=>$resizewidth,height=>$newheight);
2782: $resized = 1;
2783: }
2784: }
2785: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
2786: my $width = $ima->Get('width');
2787: my $height = $ima->Get('height');
2788: if ($height > $resizeheight) {
2789: my $factor = $height/$resizeheight;
2790: my $newwidth = $width/$factor;
2791: $ima->Scale(width=>$newwidth,height=>$resizeheight);
2792: $resized = 1;
2793: }
2794: }
2795: if ($resized) {
2796: $ima->Write($img_path);
2797: }
2798: }
2799: return;
1.977 amueller 2800: }
2801:
1.608 albertel 2802: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 2803: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093 raeburn 2804: # the desired filename is in $env{"form.$formname.filename"}
1.1090 raeburn 2805: # $context - possible values: coursedoc, existingfile, overwrite,
2806: # canceloverwrite, or ''.
2807: # if 'coursedoc': upload to the current course
2808: # if 'existingfile': write file to tmp/overwrites directory
2809: # if 'canceloverwrite': delete file written to tmp/overwrites directory
2810: # $context is passed as argument to &finishuserfileupload
1.686 albertel 2811: # $subdir - directory in userfile to store the file into
1.858 raeburn 2812: # $parser - instruction to parse file for objects ($parser = parse)
2813: # $allfiles - reference to hash for embedded objects
2814: # $codebase - reference to hash for codebase of java objects
2815: # $desuname - username for permanent storage of uploaded file
2816: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 2817: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
2818: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 2819: # $resizewidth - width (pixels) to which to resize uploaded image
2820: # $resizeheight - height (pixels) to which to resize uploaded image
1.1095 raeburn 2821: # $mimetype - reference to scalar to accommodate mime type determined
1.1152 raeburn 2822: # from File::MMagic.
1.858 raeburn 2823: #
1.686 albertel 2824: # output: url of file in userspace, or error: <message>
2825: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 2826:
1.531 albertel 2827: sub userfileupload {
1.1090 raeburn 2828: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095 raeburn 2829: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531 albertel 2830: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 2831: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 2832: $fname=&clean_filename($fname);
1.1090 raeburn 2833: # See if there is anything left
1.257 www 2834: unless ($fname) { return 'error: no uploaded file'; }
1.1090 raeburn 2835: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
2836: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
2837: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
2838: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523 raeburn 2839: my $now = time;
1.1090 raeburn 2840: my $filepath;
1.1095 raeburn 2841: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090 raeburn 2842: $filepath = 'tmp/helprequests/'.$now;
2843: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
2844: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
2845: '_'.$env{'user.domain'}.'/pending';
2846: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
2847: my ($docuname,$docudom);
2848: if ($destudom) {
2849: $docudom = $destudom;
2850: } else {
2851: $docudom = $env{'user.domain'};
2852: }
2853: if ($destuname) {
2854: $docuname = $destuname;
2855: } else {
2856: $docuname = $env{'user.name'};
2857: }
2858: if (exists($env{'form.group'})) {
2859: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2860: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2861: }
2862: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
2863: if ($context eq 'canceloverwrite') {
2864: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
2865: if (-e $tempfile) {
2866: my @info = stat($tempfile);
2867: if ($info[9] eq $env{'form.timestamp'}) {
2868: unlink($tempfile);
2869: }
2870: }
2871: return;
1.523 raeburn 2872: }
2873: }
1.1090 raeburn 2874: # Create the directory if not present
1.741 raeburn 2875: my @parts=split(/\//,$filepath);
2876: my $fullpath = $perlvar{'lonDaemons'};
2877: for (my $i=0;$i<@parts;$i++) {
2878: $fullpath .= '/'.$parts[$i];
2879: if ((-e $fullpath)!=1) {
2880: mkdir($fullpath,0777);
2881: }
2882: }
2883: open(my $fh,'>'.$fullpath.'/'.$fname);
2884: print $fh $env{'form.'.$formname};
2885: close($fh);
1.1090 raeburn 2886: if ($context eq 'existingfile') {
2887: my @info = stat($fullpath.'/'.$fname);
2888: return ($fullpath.'/'.$fname,$info[9]);
2889: } else {
2890: return $fullpath.'/'.$fname;
2891: }
1.523 raeburn 2892: }
1.995 raeburn 2893: if ($subdir eq 'scantron') {
2894: $fname = 'scantron_orig_'.$fname;
1.1093 raeburn 2895: } else {
1.995 raeburn 2896: $fname="$subdir/$fname";
2897: }
1.1090 raeburn 2898: if ($context eq 'coursedoc') {
1.638 albertel 2899: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2900: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 2901: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 2902: return &finishuserfileupload($docuname,$docudom,
2903: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 2904: $codebase,$thumbwidth,$thumbheight,
1.1095 raeburn 2905: $resizewidth,$resizeheight,$context,$mimetype);
1.481 raeburn 2906: } else {
1.620 albertel 2907: $fname=$env{'form.folder'}.'/'.$fname;
1.638 albertel 2908: return &process_coursefile('uploaddoc',$docuname,$docudom,
2909: $fname,$formname,$parser,
1.1095 raeburn 2910: $allfiles,$codebase,$mimetype);
1.481 raeburn 2911: }
1.719 banghart 2912: } elsif (defined($destuname)) {
2913: my $docuname=$destuname;
2914: my $docudom=$destudom;
1.860 raeburn 2915: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2916: $parser,$allfiles,$codebase,
1.1051 raeburn 2917: $thumbwidth,$thumbheight,
1.1095 raeburn 2918: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 2919: } else {
1.638 albertel 2920: my $docuname=$env{'user.name'};
2921: my $docudom=$env{'user.domain'};
1.714 raeburn 2922: if (exists($env{'form.group'})) {
2923: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2924: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2925: }
1.860 raeburn 2926: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2927: $parser,$allfiles,$codebase,
1.1051 raeburn 2928: $thumbwidth,$thumbheight,
1.1095 raeburn 2929: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 2930: }
1.271 www 2931: }
2932:
2933: sub finishuserfileupload {
1.860 raeburn 2934: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095 raeburn 2935: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477 raeburn 2936: my $path=$docudom.'/'.$docuname.'/';
1.258 www 2937: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 2938:
1.860 raeburn 2939: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 2940: $file=$fname;
2941: if ($fname=~m|/|) {
2942: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
2943: $path.=$fnamepath.'/';
2944: }
1.259 www 2945: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 2946: my $count;
2947: for ($count=4;$count<=$#parts;$count++) {
2948: $filepath.="/$parts[$count]";
2949: if ((-e $filepath)!=1) {
2950: mkdir($filepath,0777);
2951: }
2952: }
1.984 neumanie 2953:
1.258 www 2954: # Save the file
2955: {
1.701 albertel 2956: if (!open(FH,'>'.$filepath.'/'.$file)) {
2957: &logthis('Failed to create '.$filepath.'/'.$file);
2958: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
2959: return '/adm/notfound.html';
2960: }
1.1090 raeburn 2961: if ($context eq 'overwrite') {
1.1117 foxr 2962: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090 raeburn 2963: my $target = $filepath.'/'.$file;
2964: if (-e $source) {
2965: my @info = stat($source);
2966: if ($info[9] eq $env{'form.timestamp'}) {
2967: unless (&File::Copy::move($source,$target)) {
2968: &logthis('Failed to overwrite '.$filepath.'/'.$file);
2969: return "Moving from $source failed";
2970: }
2971: } else {
2972: return "Temporary file: $source had unexpected date/time for last modification";
2973: }
2974: } else {
2975: return "Temporary file: $source missing";
2976: }
2977: } elsif (!print FH ($env{'form.'.$formname})) {
1.701 albertel 2978: &logthis('Failed to write to '.$filepath.'/'.$file);
2979: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
2980: return '/adm/notfound.html';
2981: }
1.570 albertel 2982: close(FH);
1.1051 raeburn 2983: if ($resizewidth && $resizeheight) {
2984: my $mm = new File::MMagic;
2985: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
2986: if ($mime_type =~ m{^image/}) {
2987: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
2988: }
1.977 amueller 2989: }
1.258 www 2990: }
1.1152 raeburn 2991: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
2992: if (ref($mimetype)) {
2993: if ($$mimetype eq '') {
2994: my $mm = new File::MMagic;
2995: my $type = $mm->checktype_filename($filepath.'/'.$file);
2996: $$mimetype = $type;
2997: }
2998: }
2999: }
1.637 raeburn 3000: if ($parser eq 'parse') {
1.1152 raeburn 3001: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024 raeburn 3002: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
3003: $allfiles,$codebase);
3004: unless ($parse_result eq 'ok') {
3005: &logthis('Failed to parse '.$filepath.$file.
3006: ' for embedded media: '.$parse_result);
3007: }
1.637 raeburn 3008: }
3009: }
1.860 raeburn 3010: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
3011: my $input = $filepath.'/'.$file;
3012: my $output = $filepath.'/'.'tn-'.$file;
3013: my $thumbsize = $thumbwidth.'x'.$thumbheight;
3014: system("convert -sample $thumbsize $input $output");
3015: if (-e $filepath.'/'.'tn-'.$file) {
3016: $fetchthumb = 1;
3017: }
3018: }
1.858 raeburn 3019:
1.259 www 3020: # Notify homeserver to grep it
3021: #
1.984 neumanie 3022: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 3023: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 3024: if ($fetchresult eq 'ok') {
1.860 raeburn 3025: if ($fetchthumb) {
3026: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
3027: if ($thumbresult ne 'ok') {
3028: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
3029: $docuhome.': '.$thumbresult);
3030: }
3031: }
1.259 www 3032: #
1.258 www 3033: # Return the URL to it
1.494 albertel 3034: return '/uploaded/'.$path.$file;
1.263 www 3035: } else {
1.494 albertel 3036: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
3037: ': '.$fetchresult);
1.263 www 3038: return '/adm/notfound.html';
1.858 raeburn 3039: }
1.493 albertel 3040: }
3041:
1.637 raeburn 3042: sub extract_embedded_items {
1.961 raeburn 3043: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 3044: my @state = ();
1.1164 raeburn 3045: my (%lastids,%related,%shockwave,%flashvars);
1.637 raeburn 3046: my %javafiles = (
3047: codebase => '',
3048: code => '',
3049: archive => ''
3050: );
3051: my %mediafiles = (
3052: src => '',
3053: movie => '',
3054: );
1.648 raeburn 3055: my $p;
3056: if ($content) {
3057: $p = HTML::LCParser->new($content);
3058: } else {
1.961 raeburn 3059: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 3060: }
1.641 albertel 3061: while (my $t=$p->get_token()) {
1.640 albertel 3062: if ($t->[0] eq 'S') {
3063: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 3064: push(@state, $tagname);
1.648 raeburn 3065: if (lc($tagname) eq 'allow') {
3066: &add_filetype($allfiles,$attr->{'src'},'src');
3067: }
1.640 albertel 3068: if (lc($tagname) eq 'img') {
3069: &add_filetype($allfiles,$attr->{'src'},'src');
3070: }
1.886 albertel 3071: if (lc($tagname) eq 'a') {
3072: &add_filetype($allfiles,$attr->{'href'},'href');
3073: }
1.645 raeburn 3074: if (lc($tagname) eq 'script') {
1.1164 raeburn 3075: my $src;
1.645 raeburn 3076: if ($attr->{'archive'} =~ /\.jar$/i) {
3077: &add_filetype($allfiles,$attr->{'archive'},'archive');
3078: } else {
1.1164 raeburn 3079: if ($attr->{'src'} ne '') {
3080: $src = $attr->{'src'};
3081: &add_filetype($allfiles,$src,'src');
3082: }
3083: }
3084: my $text = $p->get_trimmed_text();
3085: if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
3086: my @swfargs = split(/,/,$1);
3087: foreach my $item (@swfargs) {
3088: $item =~ s/["']//g;
3089: $item =~ s/^\s+//;
3090: $item =~ s/\s+$//;
3091: }
3092: if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
3093: if (ref($related{$swfargs[0]}) eq 'ARRAY') {
3094: push(@{$related{$swfargs[0]}},$swfargs[2]);
3095: } else {
3096: $related{$swfargs[0]} = [$swfargs[2]];
3097: }
3098: }
1.645 raeburn 3099: }
3100: }
3101: if (lc($tagname) eq 'link') {
3102: if (lc($attr->{'rel'}) eq 'stylesheet') {
3103: &add_filetype($allfiles,$attr->{'href'},'href');
3104: }
3105: }
1.640 albertel 3106: if (lc($tagname) eq 'object' ||
3107: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
3108: foreach my $item (keys(%javafiles)) {
3109: $javafiles{$item} = '';
3110: }
1.1164 raeburn 3111: if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
3112: $lastids{lc($tagname)} = $attr->{'id'};
3113: }
1.640 albertel 3114: }
3115: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
3116: my $name = lc($attr->{'name'});
3117: foreach my $item (keys(%javafiles)) {
3118: if ($name eq $item) {
3119: $javafiles{$item} = $attr->{'value'};
3120: last;
3121: }
3122: }
1.1164 raeburn 3123: my $pathfrom;
1.640 albertel 3124: foreach my $item (keys(%mediafiles)) {
3125: if ($name eq $item) {
1.1164 raeburn 3126: $pathfrom = $attr->{'value'};
3127: $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
3128: &add_filetype($allfiles,$pathfrom,$name);
1.640 albertel 3129: last;
3130: }
3131: }
1.1164 raeburn 3132: if ($name eq 'flashvars') {
3133: $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
3134: }
3135: if ($pathfrom ne '') {
3136: &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
3137: $pathfrom);
3138: }
1.640 albertel 3139: }
3140: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
3141: foreach my $item (keys(%javafiles)) {
3142: if ($attr->{$item}) {
3143: $javafiles{$item} = $attr->{$item};
3144: last;
3145: }
3146: }
3147: foreach my $item (keys(%mediafiles)) {
3148: if ($attr->{$item}) {
3149: &add_filetype($allfiles,$attr->{$item},$item);
3150: last;
3151: }
3152: }
1.1164 raeburn 3153: if (lc($tagname) eq 'embed') {
3154: if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
3155: &embedded_dependency($allfiles,\%related,$attr->{'name'},
3156: $attr->{'src'});
3157: }
3158: }
1.640 albertel 3159: }
1.1164 raeburn 3160: if ($t->[4] =~ m{/>$}) {
3161: pop(@state);
3162: }
1.640 albertel 3163: } elsif ($t->[0] eq 'E') {
3164: my ($tagname) = ($t->[1]);
3165: if ($javafiles{'codebase'} ne '') {
3166: $javafiles{'codebase'} .= '/';
3167: }
3168: if (lc($tagname) eq 'applet' ||
3169: lc($tagname) eq 'object' ||
3170: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
3171: ) {
3172: foreach my $item (keys(%javafiles)) {
3173: if ($item ne 'codebase' && $javafiles{$item} ne '') {
3174: my $file=$javafiles{'codebase'}.$javafiles{$item};
3175: &add_filetype($allfiles,$file,$item);
3176: }
3177: }
3178: }
3179: pop @state;
3180: }
3181: }
1.1164 raeburn 3182: foreach my $id (sort(keys(%flashvars))) {
3183: if ($shockwave{$id} ne '') {
3184: my @pairs = split(/\&/,$flashvars{$id});
3185: foreach my $pair (@pairs) {
3186: my ($key,$value) = split(/\=/,$pair);
3187: if ($key eq 'thumb') {
3188: &add_filetype($allfiles,$value,$key);
3189: } elsif ($key eq 'content') {
3190: my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
3191: my ($ext) = ($value =~ /\.([^.]+)$/);
3192: if ($ext ne '') {
3193: &add_filetype($allfiles,$path.$value,$ext);
3194: }
3195: }
3196: }
3197: }
3198: }
1.637 raeburn 3199: return 'ok';
3200: }
3201:
1.639 albertel 3202: sub add_filetype {
3203: my ($allfiles,$file,$type)=@_;
3204: if (exists($allfiles->{$file})) {
3205: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
3206: push(@{$allfiles->{$file}}, &escape($type));
3207: }
3208: } else {
3209: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 3210: }
3211: }
3212:
1.1164 raeburn 3213: sub embedded_dependency {
3214: my ($allfiles,$related,$identifier,$pathfrom) = @_;
3215: if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
3216: if (($identifier ne '') &&
3217: (ref($related->{$identifier}) eq 'ARRAY') &&
3218: ($pathfrom ne '')) {
3219: my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
3220: foreach my $dep (@{$related->{$identifier}}) {
3221: &add_filetype($allfiles,$path.$dep,'object');
3222: }
3223: }
3224: }
3225: return;
3226: }
3227:
1.493 albertel 3228: sub removeuploadedurl {
1.984 neumanie 3229: my ($url)=@_;
3230: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 3231: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 3232: }
3233:
3234: sub removeuserfile {
3235: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 3236: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3237: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 3238: if ($result eq 'ok') {
1.798 raeburn 3239: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
3240: my $metafile = $fname.'.meta';
3241: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 3242: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 3243: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3244: my $sqlresult =
1.823 albertel 3245: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3246: 'portfolio_metadata',$group,
3247: 'delete');
1.798 raeburn 3248: }
3249: }
3250: return $result;
1.257 www 3251: }
1.15 www 3252:
1.530 albertel 3253: sub mkdiruserfile {
3254: my ($docuname,$docudom,$dir)=@_;
3255: my $home=&homeserver($docuname,$docudom);
3256: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
3257: }
3258:
1.531 albertel 3259: sub renameuserfile {
3260: my ($docuname,$docudom,$old,$new)=@_;
3261: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3262: my $result = &reply("renameuserfile:$docudom:$docuname:".
3263: &escape("$old").':'.&escape("$new"),$home);
3264: if ($result eq 'ok') {
3265: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
3266: my $oldmeta = $old.'.meta';
3267: my $newmeta = $new.'.meta';
3268: my $metaresult =
3269: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 3270: my $url = "/uploaded/$docudom/$docuname/$old";
3271: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3272: my $sqlresult =
1.823 albertel 3273: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3274: 'portfolio_metadata',$group,
3275: 'delete');
1.798 raeburn 3276: }
3277: }
3278: return $result;
1.531 albertel 3279: }
3280:
1.14 www 3281: # ------------------------------------------------------------------------- Log
3282:
3283: sub log {
3284: my ($dom,$nam,$hom,$what)=@_;
1.47 www 3285: return critical("log:$dom:$nam:$what",$hom);
1.157 www 3286: }
3287:
3288: # ------------------------------------------------------------------ Course Log
1.352 www 3289: #
3290: # This routine flushes several buffers of non-mission-critical nature
3291: #
1.157 www 3292:
3293: sub flushcourselogs {
1.352 www 3294: &logthis('Flushing log buffers');
3295: #
3296: # course logs
3297: # This is a log of all transactions in a course, which can be used
3298: # for data mining purposes
3299: #
3300: # It also collects the courseid database, which lists last transaction
3301: # times and course titles for all courseids
3302: #
3303: my %courseidbuffer=();
1.921 raeburn 3304: foreach my $crsid (keys(%courselogs)) {
1.352 www 3305: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 3306: &escape($courselogs{$crsid}),
3307: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 3308: delete $courselogs{$crsid};
3309: } else {
3310: &logthis('Failed to flush log buffer for '.$crsid);
3311: if (length($courselogs{$crsid})>40000) {
1.672 albertel 3312: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 3313: " exceeded maximum size, deleting.</font>");
3314: delete $courselogs{$crsid};
3315: }
1.352 www 3316: }
1.920 raeburn 3317: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 3318: 'description' => $coursedescrbuf{$crsid},
3319: 'inst_code' => $courseinstcodebuf{$crsid},
3320: 'type' => $coursetypebuf{$crsid},
3321: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 3322: };
1.191 harris41 3323: }
1.352 www 3324: #
3325: # Write course id database (reverse lookup) to homeserver of courses
3326: # Is used in pickcourse
3327: #
1.840 albertel 3328: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 3329: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 3330: $courseidbuffer{$crs_home},
3331: $crs_home,'timeonly');
1.352 www 3332: }
3333: #
3334: # File accesses
3335: # Writes to the dynamic metadata of resources to get hit counts, etc.
3336: #
1.449 matthew 3337: foreach my $entry (keys(%accesshash)) {
1.458 matthew 3338: if ($entry =~ /___count$/) {
3339: my ($dom,$name);
1.807 albertel 3340: ($dom,$name,undef)=
1.811 albertel 3341: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 3342: if (! defined($dom) || $dom eq '' ||
3343: ! defined($name) || $name eq '') {
1.620 albertel 3344: my $cid = $env{'request.course.id'};
3345: $dom = $env{'request.'.$cid.'.domain'};
3346: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 3347: }
1.450 matthew 3348: my $value = $accesshash{$entry};
3349: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
3350: my %temphash=($url => $value);
1.449 matthew 3351: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
3352: if ($result eq 'ok') {
3353: delete $accesshash{$entry};
3354: }
3355: } else {
1.811 albertel 3356: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159 www 3357: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450 matthew 3358: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 3359: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
3360: delete $accesshash{$entry};
3361: }
1.185 www 3362: }
1.191 harris41 3363: }
1.352 www 3364: #
3365: # Roles
3366: # Reverse lookup of user roles for course faculty/staff and co-authorship
3367: #
1.800 albertel 3368: foreach my $entry (keys(%userrolehash)) {
1.351 www 3369: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 3370: split(/\:/,$entry);
3371: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 3372: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 3373: $rudom,$runame) eq 'ok') {
3374: delete $userrolehash{$entry};
3375: }
3376: }
1.662 raeburn 3377: #
3378: # Reverse lookup of domain roles (dc, ad, li, sc, au)
3379: #
3380: my %domrolebuffer = ();
1.1000 raeburn 3381: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 3382: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 3383: if ($domrolebuffer{$rudom}) {
3384: $domrolebuffer{$rudom}.='&'.&escape($entry).
3385: '='.&escape($domainrolehash{$entry});
3386: } else {
3387: $domrolebuffer{$rudom}.=&escape($entry).
3388: '='.&escape($domainrolehash{$entry});
3389: }
3390: delete $domainrolehash{$entry};
3391: }
3392: foreach my $dom (keys(%domrolebuffer)) {
1.841 albertel 3393: my %servers = &get_servers($dom,'library');
3394: foreach my $tryserver (keys(%servers)) {
3395: unless (&reply('domroleput:'.$dom.':'.
3396: $domrolebuffer{$dom},$tryserver) eq 'ok') {
3397: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
3398: }
1.662 raeburn 3399: }
3400: }
1.186 www 3401: $dumpcount++;
1.157 www 3402: }
3403:
3404: sub courselog {
3405: my $what=shift;
1.158 www 3406: $what=time.':'.$what;
1.620 albertel 3407: unless ($env{'request.course.id'}) { return ''; }
3408: $coursedombuf{$env{'request.course.id'}}=
3409: $env{'course.'.$env{'request.course.id'}.'.domain'};
3410: $coursenumbuf{$env{'request.course.id'}}=
3411: $env{'course.'.$env{'request.course.id'}.'.num'};
3412: $coursehombuf{$env{'request.course.id'}}=
3413: $env{'course.'.$env{'request.course.id'}.'.home'};
3414: $coursedescrbuf{$env{'request.course.id'}}=
3415: $env{'course.'.$env{'request.course.id'}.'.description'};
3416: $courseinstcodebuf{$env{'request.course.id'}}=
3417: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
3418: $courseownerbuf{$env{'request.course.id'}}=
3419: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 3420: $coursetypebuf{$env{'request.course.id'}}=
3421: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 3422: if (defined $courselogs{$env{'request.course.id'}}) {
3423: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 3424: } else {
1.620 albertel 3425: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 3426: }
1.620 albertel 3427: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 3428: &flushcourselogs();
3429: }
1.158 www 3430: }
3431:
3432: sub courseacclog {
3433: my $fnsymb=shift;
1.620 albertel 3434: unless ($env{'request.course.id'}) { return ''; }
3435: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144 www 3436: if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187 www 3437: $what.=':POST';
1.583 matthew 3438: # FIXME: Probably ought to escape things....
1.800 albertel 3439: foreach my $key (keys(%env)) {
3440: if ($key=~/^form\.(.*)/) {
1.975 raeburn 3441: my $formitem = $1;
3442: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
3443: $what.=':'.$formitem.'='.$env{$key};
3444: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
3445: $what.=':'.$formitem.'='.$env{$key};
3446: }
1.158 www 3447: }
1.191 harris41 3448: }
1.583 matthew 3449: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
3450: # FIXME: We should not be depending on a form parameter that someone
3451: # editing lonsearchcat.pm might change in the future.
1.620 albertel 3452: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 3453: $what.= ':POST';
3454: # FIXME: Probably ought to escape things....
3455: foreach my $element ('courseexp','crsfulltext','crsrelated',
3456: 'crsdiscuss') {
1.620 albertel 3457: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 3458: }
3459: }
1.158 www 3460: }
3461: &courselog($what);
1.149 www 3462: }
3463:
1.185 www 3464: sub countacc {
3465: my $url=&declutter(shift);
1.458 matthew 3466: return if (! defined($url) || $url eq '');
1.620 albertel 3467: unless ($env{'request.course.id'}) { return ''; }
1.1158 www 3468: #
3469: # Mark that this url was used in this course
3470: #
1.620 albertel 3471: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158 www 3472: #
3473: # Increase the access count for this resource in this child process
3474: #
1.281 www 3475: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 3476: $accesshash{$key}++;
1.185 www 3477: }
1.349 www 3478:
1.361 www 3479: sub linklog {
3480: my ($from,$to)=@_;
3481: $from=&declutter($from);
3482: $to=&declutter($to);
3483: $accesshash{$from.'___'.$to.'___comefrom'}=1;
3484: $accesshash{$to.'___'.$from.'___goto'}=1;
3485: }
1.1160 www 3486:
3487: sub statslog {
3488: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
3489: if ($users<2) { return; }
3490: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
3491: 'course' => $env{'request.course.id'},
3492: 'sections' => '"all"',
3493: 'num_students' => $users,
3494: 'part' => $part,
3495: 'symb' => $symb,
3496: 'mean_tries' => $av_attempts,
3497: 'deg_of_diff' => $degdiff});
3498: foreach my $key (keys(%dynstore)) {
3499: $accesshash{$key}=$dynstore{$key};
3500: }
3501: }
1.361 www 3502:
1.349 www 3503: sub userrolelog {
3504: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169 droeschl 3505: if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350 www 3506: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3507: $userrolehash
3508: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 3509: =$tend.':'.$tstart;
1.662 raeburn 3510: }
1.1169 droeschl 3511: if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898 albertel 3512: $userrolehash
3513: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
3514: =$tend.':'.$tstart;
3515: }
1.1169 droeschl 3516: if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
1.662 raeburn 3517: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3518: $domainrolehash
3519: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
3520: = $tend.':'.$tstart;
3521: }
1.351 www 3522: }
3523:
1.957 raeburn 3524: sub courserolelog {
3525: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
3526: if (($trole eq 'cc') || ($trole eq 'in') ||
3527: ($trole eq 'ep') || ($trole eq 'ad') ||
3528: ($trole eq 'ta') || ($trole eq 'st') ||
1.1044 raeburn 3529: ($trole=~/^cr/) || ($trole eq 'gr') ||
3530: ($trole eq 'co')) {
1.957 raeburn 3531: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
3532: my $cdom = $1;
3533: my $cnum = $2;
3534: my $sec = $3;
3535: my $namespace = 'rolelog';
3536: my %storehash = (
3537: role => $trole,
3538: start => $tstart,
3539: end => $tend,
3540: selfenroll => $selfenroll,
3541: context => $context,
3542: );
3543: if ($trole eq 'gr') {
3544: $namespace = 'groupslog';
3545: $storehash{'group'} = $sec;
3546: } else {
3547: $storehash{'section'} = $sec;
3548: }
3549: &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
1.996 raeburn 3550: if (($trole ne 'st') || ($sec ne '')) {
3551: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
3552: }
1.957 raeburn 3553: }
3554: }
3555: return;
3556: }
3557:
1.351 www 3558: sub get_course_adv_roles {
1.948 raeburn 3559: my ($cid,$codes) = @_;
1.620 albertel 3560: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 3561: my %coursehash=&coursedescription($cid);
1.988 raeburn 3562: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 3563: my %nothide=();
1.800 albertel 3564: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 3565: if ($user !~ /:/) {
3566: $nothide{join(':',split(/[\@]/,$user))}=1;
3567: } else {
3568: $nothide{$user}=1;
3569: }
1.470 www 3570: }
1.351 www 3571: my %returnhash=();
3572: my %dumphash=
3573: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
3574: my $now=time;
1.997 raeburn 3575: my %privileged;
1.1000 raeburn 3576: foreach my $entry (keys(%dumphash)) {
1.800 albertel 3577: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 3578: if (($tstart) && ($tstart<0)) { next; }
3579: if (($tend) && ($tend<$now)) { next; }
3580: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 3581: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 3582: if ($username eq '' || $domain eq '') { next; }
1.997 raeburn 3583: unless (ref($privileged{$domain}) eq 'HASH') {
3584: my %dompersonnel =
1.998 raeburn 3585: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
1.997 raeburn 3586: $privileged{$domain} = {};
3587: foreach my $server (keys(%dompersonnel)) {
1.999 raeburn 3588: if (ref($dompersonnel{$server}) eq 'HASH') {
1.997 raeburn 3589: foreach my $user (keys(%{$dompersonnel{$server}})) {
3590: my ($trole,$uname,$udom) = split(/:/,$user);
3591: $privileged{$udom}{$uname} = 1;
3592: }
3593: }
3594: }
3595: }
3596: if ((exists($privileged{$domain}{$username})) &&
3597: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 3598: if ($role eq 'cr') { next; }
1.948 raeburn 3599: if ($codes) {
3600: if ($section) { $role .= ':'.$section; }
3601: if ($returnhash{$role}) {
3602: $returnhash{$role}.=','.$username.':'.$domain;
3603: } else {
3604: $returnhash{$role}=$username.':'.$domain;
3605: }
1.351 www 3606: } else {
1.988 raeburn 3607: my $key=&plaintext($role,$crstype);
1.973 bisitz 3608: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 3609: if ($returnhash{$key}) {
3610: $returnhash{$key}.=','.$username.':'.$domain;
3611: } else {
3612: $returnhash{$key}=$username.':'.$domain;
3613: }
1.351 www 3614: }
1.948 raeburn 3615: }
1.400 www 3616: return %returnhash;
3617: }
3618:
3619: sub get_my_roles {
1.937 raeburn 3620: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 3621: unless (defined($uname)) { $uname=$env{'user.name'}; }
3622: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 3623: my (%dumphash,%nothide);
1.1086 raeburn 3624: if ($context eq 'userroles') {
1.1166 raeburn 3625: %dumphash = &dump('roles',$udom,$uname);
1.858 raeburn 3626: } else {
3627: %dumphash=
1.400 www 3628: &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 3629: if ($hidepriv) {
3630: my %coursehash=&coursedescription($udom.'_'.$uname);
3631: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3632: if ($user !~ /:/) {
3633: $nothide{join(':',split(/[\@]/,$user))} = 1;
3634: } else {
3635: $nothide{$user} = 1;
3636: }
3637: }
3638: }
1.858 raeburn 3639: }
1.400 www 3640: my %returnhash=();
3641: my $now=time;
1.999 raeburn 3642: my %privileged;
1.800 albertel 3643: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 3644: my ($role,$tend,$tstart);
3645: if ($context eq 'userroles') {
1.1149 raeburn 3646: next if ($entry =~ /^rolesdef/);
1.867 raeburn 3647: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
3648: } else {
3649: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
3650: }
1.400 www 3651: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 3652: my $status = 'active';
1.939 raeburn 3653: if (($tend) && ($tend<=$now)) {
1.832 raeburn 3654: $status = 'previous';
3655: }
3656: if (($tstart) && ($now<$tstart)) {
3657: $status = 'future';
3658: }
3659: if (ref($types) eq 'ARRAY') {
3660: if (!grep(/^\Q$status\E$/,@{$types})) {
3661: next;
3662: }
3663: } else {
3664: if ($status ne 'active') {
3665: next;
3666: }
3667: }
1.867 raeburn 3668: my ($rolecode,$username,$domain,$section,$area);
3669: if ($context eq 'userroles') {
3670: ($area,$rolecode) = split(/_/,$entry);
3671: (undef,$domain,$username,$section) = split(/\//,$area);
3672: } else {
3673: ($role,$username,$domain,$section) = split(/\:/,$entry);
3674: }
1.832 raeburn 3675: if (ref($roledoms) eq 'ARRAY') {
3676: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
3677: next;
3678: }
3679: }
3680: if (ref($roles) eq 'ARRAY') {
3681: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 3682: if ($role =~ /^cr\//) {
3683: if (!grep(/^cr$/,@{$roles})) {
3684: next;
3685: }
1.1104 raeburn 3686: } elsif ($role =~ /^gr\//) {
3687: if (!grep(/^gr$/,@{$roles})) {
3688: next;
3689: }
1.922 raeburn 3690: } else {
3691: next;
3692: }
1.832 raeburn 3693: }
1.867 raeburn 3694: }
1.937 raeburn 3695: if ($hidepriv) {
1.999 raeburn 3696: if ($context eq 'userroles') {
3697: if ((&privileged($username,$domain)) &&
3698: (!$nothide{$username.':'.$domain})) {
3699: next;
3700: }
3701: } else {
3702: unless (ref($privileged{$domain}) eq 'HASH') {
3703: my %dompersonnel =
3704: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
3705: $privileged{$domain} = {};
3706: if (keys(%dompersonnel)) {
3707: foreach my $server (keys(%dompersonnel)) {
3708: if (ref($dompersonnel{$server}) eq 'HASH') {
3709: foreach my $user (keys(%{$dompersonnel{$server}})) {
3710: my ($trole,$uname,$udom) = split(/:/,$user);
3711: $privileged{$udom}{$uname} = $trole;
3712: }
3713: }
3714: }
3715: }
3716: }
3717: if (exists($privileged{$domain}{$username})) {
3718: if (!$nothide{$username.':'.$domain}) {
3719: next;
3720: }
3721: }
1.937 raeburn 3722: }
3723: }
1.933 raeburn 3724: if ($withsec) {
3725: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
3726: $tstart.':'.$tend;
3727: } else {
3728: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
3729: }
1.832 raeburn 3730: }
1.373 www 3731: return %returnhash;
1.399 www 3732: }
3733:
3734: # ----------------------------------------------------- Frontpage Announcements
3735: #
3736: #
3737:
3738: sub postannounce {
3739: my ($server,$text)=@_;
1.844 albertel 3740: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 3741: unless ($text=~/\w/) { $text=''; }
3742: return &reply('setannounce:'.&escape($text),$server);
3743: }
3744:
3745: sub getannounce {
1.448 albertel 3746:
3747: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 3748: my $announcement='';
1.800 albertel 3749: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 3750: close($fh);
1.399 www 3751: if ($announcement=~/\w/) {
3752: return
3753: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 3754: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 3755: } else {
3756: return '';
3757: }
3758: } else {
3759: return '';
3760: }
1.351 www 3761: }
1.353 www 3762:
3763: # ---------------------------------------------------------- Course ID routines
3764: # Deal with domain's nohist_courseid.db files
3765: #
3766:
3767: sub courseidput {
1.921 raeburn 3768: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 3769: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 3770: my $outcome;
3771: if ($caller eq 'timeonly') {
3772: my $cids = '';
3773: foreach my $item (keys(%$storehash)) {
3774: $cids.=&escape($item).'&';
3775: }
3776: $cids=~s/\&$//;
3777: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
3778: $coursehome);
3779: } else {
3780: my $items = '';
3781: foreach my $item (keys(%$storehash)) {
3782: $items.= &escape($item).'='.
3783: &freeze_escape($$storehash{$item}).'&';
3784: }
3785: $items=~s/\&$//;
3786: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
3787: $coursehome);
1.918 raeburn 3788: }
3789: if ($outcome eq 'unknown_cmd') {
3790: my $what;
3791: foreach my $cid (keys(%$storehash)) {
3792: $what .= &escape($cid).'=';
1.921 raeburn 3793: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 3794: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 3795: }
3796: $what =~ s/\:$/&/;
3797: }
3798: $what =~ s/\&$//;
3799: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
3800: } else {
3801: return $outcome;
3802: }
1.353 www 3803: }
3804:
3805: sub courseiddump {
1.921 raeburn 3806: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 3807: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 3808: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1071 raeburn 3809: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918 raeburn 3810: my $as_hash = 1;
3811: my %returnhash;
3812: if (!$domfilter) { $domfilter=''; }
1.845 albertel 3813: my %libserv = &all_library();
3814: foreach my $tryserver (keys(%libserv)) {
3815: if ( ( $hostidflag == 1
3816: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
3817: || (!defined($hostidflag)) ) {
3818:
1.918 raeburn 3819: if (($domfilter eq '') ||
3820: (&host_domain($tryserver) eq $domfilter)) {
3821: my $rep =
3822: &reply('courseiddump:'.&host_domain($tryserver).':'.
3823: $sincefilter.':'.&escape($descfilter).':'.
3824: &escape($instcodefilter).':'.&escape($ownerfilter).
3825: ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947 raeburn 3826: ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962 raeburn 3827: &escape($selfenrollonly).':'.&escape($catfilter).':'.
1.1008 raeburn 3828: $showhidden.':'.$caller.':'.&escape($cloner).':'.
1.1029 raeburn 3829: &escape($cc_clone).':'.$cloneonly.':'.
3830: &escape($createdbefore).':'.&escape($createdafter).':'.
1.1071 raeburn 3831: &escape($creationcontext).':'.$domcloner,
3832: $tryserver);
1.918 raeburn 3833: my @pairs=split(/\&/,$rep);
3834: foreach my $item (@pairs) {
3835: my ($key,$value)=split(/\=/,$item,2);
3836: $key = &unescape($key);
3837: next if ($key =~ /^error: 2 /);
3838: my $result = &thaw_unescape($value);
3839: if (ref($result) eq 'HASH') {
3840: $returnhash{$key}=$result;
3841: } else {
1.921 raeburn 3842: my @responses = split(/:/,$value);
3843: my @items = ('description','inst_code','owner','type');
1.918 raeburn 3844: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 3845: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 3846: }
1.1008 raeburn 3847: }
1.353 www 3848: }
3849: }
3850: }
3851: }
3852: return %returnhash;
3853: }
3854:
1.1055 raeburn 3855: sub courselastaccess {
3856: my ($cdom,$cnum,$hostidref) = @_;
3857: my %returnhash;
3858: if ($cdom && $cnum) {
3859: my $chome = &homeserver($cnum,$cdom);
3860: if ($chome ne 'no_host') {
3861: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
3862: &extract_lastaccess(\%returnhash,$rep);
3863: }
3864: } else {
3865: if (!$cdom) { $cdom=''; }
3866: my %libserv = &all_library();
3867: foreach my $tryserver (keys(%libserv)) {
3868: if (ref($hostidref) eq 'ARRAY') {
3869: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
3870: }
3871: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
3872: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
3873: &extract_lastaccess(\%returnhash,$rep);
3874: }
3875: }
3876: }
3877: return %returnhash;
3878: }
3879:
3880: sub extract_lastaccess {
3881: my ($returnhash,$rep) = @_;
3882: if (ref($returnhash) eq 'HASH') {
3883: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
3884: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
3885: $rep eq '') {
3886: my @pairs=split(/\&/,$rep);
3887: foreach my $item (@pairs) {
3888: my ($key,$value)=split(/\=/,$item,2);
3889: $key = &unescape($key);
3890: next if ($key =~ /^error: 2 /);
3891: $returnhash->{$key} = &thaw_unescape($value);
3892: }
3893: }
3894: }
3895: return;
3896: }
3897:
1.658 raeburn 3898: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 3899:
3900: sub dcmailput {
1.685 raeburn 3901: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 3902: my $status = &Apache::lonnet::critical(
1.740 www 3903: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
3904: &escape($message),$server);
1.662 raeburn 3905: return $status;
3906: }
3907:
1.658 raeburn 3908: sub dcmaildump {
3909: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 3910: my %returnhash=();
1.846 albertel 3911:
3912: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 3913: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
3914: &escape($enddate).':';
3915: my @esc_senders=map { &escape($_)} @$senders;
3916: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 3917: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 3918: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 3919: if (($key) && ($value)) {
3920: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 3921: }
3922: }
3923: }
3924: return %returnhash;
3925: }
1.662 raeburn 3926: # ---------------------------------------------------------- Domain roles
3927:
3928: sub get_domain_roles {
3929: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 3930: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 3931: $startdate = '.';
3932: }
1.1018 raeburn 3933: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 3934: $enddate = '.';
3935: }
1.922 raeburn 3936: my $rolelist;
3937: if (ref($roles) eq 'ARRAY') {
3938: $rolelist = join(':',@{$roles});
3939: }
1.662 raeburn 3940: my %personnel = ();
1.841 albertel 3941:
3942: my %servers = &get_servers($dom,'library');
3943: foreach my $tryserver (keys(%servers)) {
3944: %{$personnel{$tryserver}}=();
3945: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
3946: &escape($startdate).':'.
3947: &escape($enddate).':'.
3948: &escape($rolelist), $tryserver))) {
3949: my ($key,$value) = split(/\=/,$line,2);
3950: if (($key) && ($value)) {
3951: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
3952: }
3953: }
1.662 raeburn 3954: }
3955: return %personnel;
3956: }
1.658 raeburn 3957:
1.1057 www 3958: # ----------------------------------------------------------- Interval timing
1.149 www 3959:
1.1153 www 3960: {
3961: # Caches needed for speedup of navmaps
3962: # We don't want to cache this for very long at all (5 seconds at most)
3963: #
3964: # The user for whom we cache
3965: my $cachedkey='';
3966: # The cached times for this user
3967: my %cachedtimes=();
3968: # When this was last done
3969: my $cachedtime=();
3970:
3971: sub load_all_first_access {
1.1154 raeburn 3972: my ($uname,$udom)=@_;
1.1156 www 3973: if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.2 raeburn 3974: (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154 raeburn 3975: return;
3976: }
3977: $cachedtime=time;
3978: $cachedkey=$uname.':'.$udom;
3979: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153 www 3980: }
3981:
1.504 albertel 3982: sub get_first_access {
1.1162 raeburn 3983: my ($type,$argsymb,$argmap)=@_;
1.790 albertel 3984: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 3985: if ($argsymb) { $symb=$argsymb; }
3986: my ($map,$id,$res)=&decode_symb($symb);
1.1162 raeburn 3987: if ($argmap) { $map = $argmap; }
1.926 albertel 3988: if ($type eq 'course') {
3989: $res='course';
3990: } elsif ($type eq 'map') {
1.588 albertel 3991: $res=&symbread($map);
3992: } else {
3993: $res=$symb;
3994: }
1.1153 www 3995: &load_all_first_access($uname,$udom);
3996: return $cachedtimes{"$courseid\0$res"};
1.504 albertel 3997: }
3998:
3999: sub set_first_access {
1.1162 raeburn 4000: my ($type,$interval)=@_;
1.790 albertel 4001: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4002: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 4003: if ($type eq 'course') {
4004: $res='course';
4005: } elsif ($type eq 'map') {
1.588 albertel 4006: $res=&symbread($map);
4007: } else {
4008: $res=$symb;
4009: }
1.1153 www 4010: $cachedkey='';
1.1162 raeburn 4011: my $firstaccess=&get_first_access($type,$symb,$map);
1.505 albertel 4012: if (!$firstaccess) {
1.1162 raeburn 4013: my $start = time;
4014: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
4015: $udom,$uname);
4016: if ($putres eq 'ok') {
4017: &put('timerinterval',{"$courseid\0$res"=>$interval},
4018: $udom,$uname);
4019: &appenv(
4020: {
4021: 'course.'.$courseid.'.firstaccess.'.$res => $start,
4022: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
4023: }
4024: );
4025: }
4026: return $putres;
1.505 albertel 4027: }
4028: return 'already_set';
1.504 albertel 4029: }
1.1153 www 4030: }
1.110 www 4031: # --------------------------------------------- Set Expire Date for Spreadsheet
4032:
4033: sub expirespread {
4034: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 4035: my $cid=$env{'request.course.id'};
1.110 www 4036: if ($cid) {
4037: my $now=time;
4038: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 4039: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
4040: $env{'course.'.$cid.'.num'}.
1.110 www 4041: ':nohist_expirationdates:'.
4042: &escape($key).'='.$now,
1.620 albertel 4043: $env{'course.'.$cid.'.home'})
1.110 www 4044: }
4045: return 'ok';
1.14 www 4046: }
4047:
1.109 www 4048: # ----------------------------------------------------- Devalidate Spreadsheets
4049:
4050: sub devalidate {
1.325 www 4051: my ($symb,$uname,$udom)=@_;
1.620 albertel 4052: my $cid=$env{'request.course.id'};
1.109 www 4053: if ($cid) {
1.391 matthew 4054: # delete the stored spreadsheets for
4055: # - the student level sheet of this user in course's homespace
4056: # - the assessment level sheet for this resource
4057: # for this user in user's homespace
1.553 albertel 4058: # - current conditional state info
1.325 www 4059: my $key=$uname.':'.$udom.':';
1.109 www 4060: my $status=
1.299 matthew 4061: &del('nohist_calculatedsheets',
1.391 matthew 4062: [$key.'studentcalc:'],
1.620 albertel 4063: $env{'course.'.$cid.'.domain'},
4064: $env{'course.'.$cid.'.num'})
1.133 albertel 4065: .' '.
4066: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 4067: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 4068: unless ($status eq 'ok ok') {
4069: &logthis('Could not devalidate spreadsheet '.
1.325 www 4070: $uname.' at '.$udom.' for '.
1.109 www 4071: $symb.': '.$status);
1.133 albertel 4072: }
1.553 albertel 4073: &delenv('user.state.'.$cid);
1.109 www 4074: }
4075: }
4076:
1.265 albertel 4077: sub get_scalar {
4078: my ($string,$end) = @_;
4079: my $value;
4080: if ($$string =~ s/^([^&]*?)($end)/$2/) {
4081: $value = $1;
4082: } elsif ($$string =~ s/^([^&]*?)&//) {
4083: $value = $1;
4084: }
4085: return &unescape($value);
4086: }
4087:
4088: sub array2str {
4089: my (@array) = @_;
4090: my $result=&arrayref2str(\@array);
4091: $result=~s/^__ARRAY_REF__//;
4092: $result=~s/__END_ARRAY_REF__$//;
4093: return $result;
4094: }
4095:
1.204 albertel 4096: sub arrayref2str {
4097: my ($arrayref) = @_;
1.265 albertel 4098: my $result='__ARRAY_REF__';
1.204 albertel 4099: foreach my $elem (@$arrayref) {
1.265 albertel 4100: if(ref($elem) eq 'ARRAY') {
4101: $result.=&arrayref2str($elem).'&';
4102: } elsif(ref($elem) eq 'HASH') {
4103: $result.=&hashref2str($elem).'&';
4104: } elsif(ref($elem)) {
4105: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 4106: } else {
4107: $result.=&escape($elem).'&';
4108: }
4109: }
4110: $result=~s/\&$//;
1.265 albertel 4111: $result .= '__END_ARRAY_REF__';
1.204 albertel 4112: return $result;
4113: }
4114:
1.168 albertel 4115: sub hash2str {
1.204 albertel 4116: my (%hash) = @_;
4117: my $result=&hashref2str(\%hash);
1.265 albertel 4118: $result=~s/^__HASH_REF__//;
4119: $result=~s/__END_HASH_REF__$//;
1.204 albertel 4120: return $result;
4121: }
4122:
4123: sub hashref2str {
4124: my ($hashref)=@_;
1.265 albertel 4125: my $result='__HASH_REF__';
1.800 albertel 4126: foreach my $key (sort(keys(%$hashref))) {
4127: if (ref($key) eq 'ARRAY') {
4128: $result.=&arrayref2str($key).'=';
4129: } elsif (ref($key) eq 'HASH') {
4130: $result.=&hashref2str($key).'=';
4131: } elsif (ref($key)) {
1.265 albertel 4132: $result.='=';
1.800 albertel 4133: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 4134: } else {
1.1132 raeburn 4135: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 4136: }
4137:
1.800 albertel 4138: if(ref($hashref->{$key}) eq 'ARRAY') {
4139: $result.=&arrayref2str($hashref->{$key}).'&';
4140: } elsif(ref($hashref->{$key}) eq 'HASH') {
4141: $result.=&hashref2str($hashref->{$key}).'&';
4142: } elsif(ref($hashref->{$key})) {
1.265 albertel 4143: $result.='&';
1.800 albertel 4144: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 4145: } else {
1.800 albertel 4146: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 4147: }
4148: }
1.168 albertel 4149: $result=~s/\&$//;
1.265 albertel 4150: $result .= '__END_HASH_REF__';
1.168 albertel 4151: return $result;
4152: }
4153:
4154: sub str2hash {
1.265 albertel 4155: my ($string)=@_;
4156: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
4157: return %$hash;
4158: }
4159:
4160: sub str2hashref {
1.168 albertel 4161: my ($string) = @_;
1.265 albertel 4162:
4163: my %hash;
4164:
4165: if($string !~ /^__HASH_REF__/) {
4166: if (! ($string eq '' || !defined($string))) {
4167: $hash{'error'}='Not hash reference';
4168: }
4169: return (\%hash, $string);
4170: }
4171:
4172: $string =~ s/^__HASH_REF__//;
4173:
4174: while($string !~ /^__END_HASH_REF__/) {
4175: #key
4176: my $key='';
4177: if($string =~ /^__HASH_REF__/) {
4178: ($key, $string)=&str2hashref($string);
4179: if(defined($key->{'error'})) {
4180: $hash{'error'}='Bad data';
4181: return (\%hash, $string);
4182: }
4183: } elsif($string =~ /^__ARRAY_REF__/) {
4184: ($key, $string)=&str2arrayref($string);
4185: if($key->[0] eq 'Array reference error') {
4186: $hash{'error'}='Bad data';
4187: return (\%hash, $string);
4188: }
4189: } else {
4190: $string =~ s/^(.*?)=//;
1.267 albertel 4191: $key=&unescape($1);
1.265 albertel 4192: }
4193: $string =~ s/^=//;
4194:
4195: #value
4196: my $value='';
4197: if($string =~ /^__HASH_REF__/) {
4198: ($value, $string)=&str2hashref($string);
4199: if(defined($value->{'error'})) {
4200: $hash{'error'}='Bad data';
4201: return (\%hash, $string);
4202: }
4203: } elsif($string =~ /^__ARRAY_REF__/) {
4204: ($value, $string)=&str2arrayref($string);
4205: if($value->[0] eq 'Array reference error') {
4206: $hash{'error'}='Bad data';
4207: return (\%hash, $string);
4208: }
4209: } else {
4210: $value=&get_scalar(\$string,'__END_HASH_REF__');
4211: }
4212: $string =~ s/^&//;
4213:
4214: $hash{$key}=$value;
1.204 albertel 4215: }
1.265 albertel 4216:
4217: $string =~ s/^__END_HASH_REF__//;
4218:
4219: return (\%hash, $string);
1.204 albertel 4220: }
4221:
4222: sub str2array {
1.265 albertel 4223: my ($string)=@_;
4224: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
4225: return @$array;
4226: }
4227:
4228: sub str2arrayref {
1.204 albertel 4229: my ($string) = @_;
1.265 albertel 4230: my @array;
4231:
4232: if($string !~ /^__ARRAY_REF__/) {
4233: if (! ($string eq '' || !defined($string))) {
4234: $array[0]='Array reference error';
4235: }
4236: return (\@array, $string);
4237: }
4238:
4239: $string =~ s/^__ARRAY_REF__//;
4240:
4241: while($string !~ /^__END_ARRAY_REF__/) {
4242: my $value='';
4243: if($string =~ /^__HASH_REF__/) {
4244: ($value, $string)=&str2hashref($string);
4245: if(defined($value->{'error'})) {
4246: $array[0] ='Array reference error';
4247: return (\@array, $string);
4248: }
4249: } elsif($string =~ /^__ARRAY_REF__/) {
4250: ($value, $string)=&str2arrayref($string);
4251: if($value->[0] eq 'Array reference error') {
4252: $array[0] ='Array reference error';
4253: return (\@array, $string);
4254: }
4255: } else {
4256: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
4257: }
4258: $string =~ s/^&//;
4259:
4260: push(@array, $value);
1.191 harris41 4261: }
1.265 albertel 4262:
4263: $string =~ s/^__END_ARRAY_REF__//;
4264:
4265: return (\@array, $string);
1.168 albertel 4266: }
4267:
1.167 albertel 4268: # -------------------------------------------------------------------Temp Store
4269:
1.168 albertel 4270: sub tmpreset {
4271: my ($symb,$namespace,$domain,$stuname) = @_;
4272: if (!$symb) {
4273: $symb=&symbread();
1.620 albertel 4274: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4275: }
4276: $symb=escape($symb);
4277:
1.620 albertel 4278: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 4279: $namespace=~s/\//\_/g;
4280: $namespace=~s/\W//g;
4281:
1.620 albertel 4282: if (!$domain) { $domain=$env{'user.domain'}; }
4283: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4284: if ($domain eq 'public' && $stuname eq 'public') {
4285: $stuname=$ENV{'REMOTE_ADDR'};
4286: }
1.1117 foxr 4287: my $path=LONCAPA::tempdir();
1.168 albertel 4288: my %hash;
4289: if (tie(%hash,'GDBM_File',
4290: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4291: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 4292: foreach my $key (keys(%hash)) {
1.180 albertel 4293: if ($key=~ /:$symb/) {
1.168 albertel 4294: delete($hash{$key});
4295: }
4296: }
4297: }
4298: }
4299:
1.167 albertel 4300: sub tmpstore {
1.168 albertel 4301: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4302:
4303: if (!$symb) {
4304: $symb=&symbread();
1.620 albertel 4305: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4306: }
4307: $symb=escape($symb);
4308:
4309: if (!$namespace) {
4310: # I don't think we would ever want to store this for a course.
4311: # it seems this will only be used if we don't have a course.
1.620 albertel 4312: #$namespace=$env{'request.course.id'};
1.168 albertel 4313: #if (!$namespace) {
1.620 albertel 4314: $namespace=$env{'request.state'};
1.168 albertel 4315: #}
4316: }
4317: $namespace=~s/\//\_/g;
4318: $namespace=~s/\W//g;
1.620 albertel 4319: if (!$domain) { $domain=$env{'user.domain'}; }
4320: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4321: if ($domain eq 'public' && $stuname eq 'public') {
4322: $stuname=$ENV{'REMOTE_ADDR'};
4323: }
1.168 albertel 4324: my $now=time;
4325: my %hash;
1.1117 foxr 4326: my $path=LONCAPA::tempdir();
1.168 albertel 4327: if (tie(%hash,'GDBM_File',
4328: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4329: &GDBM_WRCREAT(),0640)) {
1.168 albertel 4330: $hash{"version:$symb"}++;
4331: my $version=$hash{"version:$symb"};
4332: my $allkeys='';
4333: foreach my $key (keys(%$storehash)) {
4334: $allkeys.=$key.':';
1.591 albertel 4335: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 4336: }
4337: $hash{"$version:$symb:timestamp"}=$now;
4338: $allkeys.='timestamp';
4339: $hash{"$version:keys:$symb"}=$allkeys;
4340: if (untie(%hash)) {
4341: return 'ok';
4342: } else {
4343: return "error:$!";
4344: }
4345: } else {
4346: return "error:$!";
4347: }
4348: }
1.167 albertel 4349:
1.168 albertel 4350: # -----------------------------------------------------------------Temp Restore
1.167 albertel 4351:
1.168 albertel 4352: sub tmprestore {
4353: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 4354:
1.168 albertel 4355: if (!$symb) {
4356: $symb=&symbread();
1.620 albertel 4357: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4358: }
4359: $symb=escape($symb);
4360:
1.620 albertel 4361: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 4362:
1.620 albertel 4363: if (!$domain) { $domain=$env{'user.domain'}; }
4364: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4365: if ($domain eq 'public' && $stuname eq 'public') {
4366: $stuname=$ENV{'REMOTE_ADDR'};
4367: }
1.168 albertel 4368: my %returnhash;
4369: $namespace=~s/\//\_/g;
4370: $namespace=~s/\W//g;
4371: my %hash;
1.1117 foxr 4372: my $path=LONCAPA::tempdir();
1.168 albertel 4373: if (tie(%hash,'GDBM_File',
4374: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4375: &GDBM_READER(),0640)) {
1.168 albertel 4376: my $version=$hash{"version:$symb"};
4377: $returnhash{'version'}=$version;
4378: my $scope;
4379: for ($scope=1;$scope<=$version;$scope++) {
4380: my $vkeys=$hash{"$scope:keys:$symb"};
4381: my @keys=split(/:/,$vkeys);
4382: my $key;
4383: $returnhash{"$scope:keys"}=$vkeys;
4384: foreach $key (@keys) {
1.591 albertel 4385: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
4386: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 4387: }
4388: }
1.168 albertel 4389: if (!(untie(%hash))) {
4390: return "error:$!";
4391: }
4392: } else {
4393: return "error:$!";
4394: }
4395: return %returnhash;
1.167 albertel 4396: }
4397:
1.9 www 4398: # ----------------------------------------------------------------------- Store
4399:
4400: sub store {
1.124 www 4401: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4402: my $home='';
4403:
1.168 albertel 4404: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4405:
1.213 www 4406: $symb=&symbclean($symb);
1.122 albertel 4407: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 4408:
1.620 albertel 4409: if (!$domain) { $domain=$env{'user.domain'}; }
4410: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 4411:
4412: &devalidate($symb,$stuname,$domain);
1.109 www 4413:
4414: $symb=escape($symb);
1.187 www 4415: if (!$namespace) {
1.620 albertel 4416: unless ($namespace=$env{'request.course.id'}) {
1.187 www 4417: return '';
4418: }
4419: }
1.620 albertel 4420: if (!$home) { $home=$env{'user.home'}; }
1.447 www 4421:
4422: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4423: $$storehash{'host'}=$perlvar{'lonHostID'};
4424:
1.12 www 4425: my $namevalue='';
1.800 albertel 4426: foreach my $key (keys(%$storehash)) {
4427: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 4428: }
1.12 www 4429: $namevalue=~s/\&$//;
1.187 www 4430: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124 www 4431: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9 www 4432: }
4433:
1.47 www 4434: # -------------------------------------------------------------- Critical Store
4435:
4436: sub cstore {
1.124 www 4437: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4438: my $home='';
4439:
1.168 albertel 4440: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4441:
1.213 www 4442: $symb=&symbclean($symb);
1.122 albertel 4443: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 4444:
1.620 albertel 4445: if (!$domain) { $domain=$env{'user.domain'}; }
4446: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 4447:
4448: &devalidate($symb,$stuname,$domain);
1.109 www 4449:
4450: $symb=escape($symb);
1.187 www 4451: if (!$namespace) {
1.620 albertel 4452: unless ($namespace=$env{'request.course.id'}) {
1.187 www 4453: return '';
4454: }
4455: }
1.620 albertel 4456: if (!$home) { $home=$env{'user.home'}; }
1.447 www 4457:
4458: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4459: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 4460:
1.47 www 4461: my $namevalue='';
1.800 albertel 4462: foreach my $key (keys(%$storehash)) {
4463: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 4464: }
1.47 www 4465: $namevalue=~s/\&$//;
1.187 www 4466: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 4467: return critical
4468: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47 www 4469: }
4470:
1.9 www 4471: # --------------------------------------------------------------------- Restore
4472:
4473: sub restore {
1.124 www 4474: my ($symb,$namespace,$domain,$stuname) = @_;
4475: my $home='';
4476:
1.168 albertel 4477: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4478:
1.122 albertel 4479: if (!$symb) {
4480: unless ($symb=escape(&symbread())) { return ''; }
4481: } else {
1.213 www 4482: $symb=&escape(&symbclean($symb));
1.122 albertel 4483: }
1.188 www 4484: if (!$namespace) {
1.620 albertel 4485: unless ($namespace=$env{'request.course.id'}) {
1.188 www 4486: return '';
4487: }
4488: }
1.620 albertel 4489: if (!$domain) { $domain=$env{'user.domain'}; }
4490: if (!$stuname) { $stuname=$env{'user.name'}; }
4491: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 4492: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
4493:
1.12 www 4494: my %returnhash=();
1.800 albertel 4495: foreach my $line (split(/\&/,$answer)) {
4496: my ($name,$value)=split(/\=/,$line);
1.591 albertel 4497: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 4498: }
1.75 www 4499: my $version;
4500: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 4501: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
4502: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 4503: }
1.75 www 4504: }
1.13 www 4505: return %returnhash;
1.34 www 4506: }
4507:
4508: # ---------------------------------------------------------- Course Description
1.1118 foxr 4509: #
4510: #
1.34 www 4511:
4512: sub coursedescription {
1.731 albertel 4513: my ($courseid,$args)=@_;
1.34 www 4514: $courseid=~s/^\///;
1.49 www 4515: $courseid=~s/\_/\//g;
1.34 www 4516: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 4517: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 4518: my $normalid=$cdomain.'_'.$cnum;
4519: # need to always cache even if we get errors otherwise we keep
4520: # trying and trying and trying to get the course description.
4521: my %envhash=();
4522: my %returnhash=();
1.731 albertel 4523:
4524: my $expiretime=600;
4525: if ($env{'request.course.id'} eq $normalid) {
4526: $expiretime=120;
4527: }
4528:
4529: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
4530: if (!$args->{'freshen_cache'}
4531: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
4532: foreach my $key (keys(%env)) {
4533: next if ($key !~ /^\Q$prefix\E(.*)/);
4534: my ($setting) = $1;
4535: $returnhash{$setting} = $env{$key};
4536: }
4537: return %returnhash;
4538: }
4539:
1.1118 foxr 4540: # get the data again
4541:
1.731 albertel 4542: if (!$args->{'one_time'}) {
4543: $envhash{'course.'.$normalid.'.last_cache'}=time;
4544: }
1.811 albertel 4545:
1.34 www 4546: if ($chome ne 'no_host') {
1.302 albertel 4547: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 4548: if (!exists($returnhash{'con_lost'})) {
1.1118 foxr 4549: my $username = $env{'user.name'}; # Defult username
4550: if(defined $args->{'user'}) {
4551: $username = $args->{'user'};
4552: }
1.129 albertel 4553: $returnhash{'home'}= $chome;
4554: $returnhash{'domain'} = $cdomain;
4555: $returnhash{'num'} = $cnum;
1.741 raeburn 4556: if (!defined($returnhash{'type'})) {
4557: $returnhash{'type'} = 'Course';
4558: }
1.130 albertel 4559: while (my ($name,$value) = each %returnhash) {
1.53 www 4560: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 4561: }
1.270 www 4562: $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117 foxr 4563: $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118 foxr 4564: $username.'_'.$cdomain.'_'.$cnum;
1.60 www 4565: $envhash{'course.'.$normalid.'.home'}=$chome;
4566: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
4567: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 4568: }
4569: }
1.731 albertel 4570: if (!$args->{'one_time'}) {
1.949 raeburn 4571: &appenv(\%envhash);
1.731 albertel 4572: }
1.302 albertel 4573: return %returnhash;
1.461 www 4574: }
4575:
1.1080 raeburn 4576: sub update_released_required {
4577: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
4578: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
4579: $cid = $env{'request.course.id'};
4580: $cdom = $env{'course.'.$cid.'.domain'};
4581: $cnum = $env{'course.'.$cid.'.num'};
4582: $chome = $env{'course.'.$cid.'.home'};
4583: }
4584: if ($needsrelease) {
4585: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
4586: my $needsupdate;
4587: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
4588: $needsupdate = 1;
4589: } else {
4590: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
4591: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
4592: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
4593: $needsupdate = 1;
4594: }
4595: }
4596: if ($needsupdate) {
4597: my %needshash = (
4598: 'internal.releaserequired' => $needsrelease,
4599: );
4600: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
4601: if ($putresult eq 'ok') {
4602: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
4603: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
4604: if (ref($crsinfo{$cid}) eq 'HASH') {
4605: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
4606: &courseidput($cdom,\%crsinfo,$chome,'notime');
4607: }
4608: }
4609: }
4610: }
4611: return;
4612: }
4613:
1.461 www 4614: # -------------------------------------------------See if a user is privileged
4615:
4616: sub privileged {
4617: my ($username,$domain)=@_;
1.1170 droeschl 4618:
4619: my %rolesdump = &dump("roles", $domain, $username) or return 0;
4620: my $now = time;
4621:
4622: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys %rolesdump}) {
4623: my ($trole, $tend, $tstart) = split(/_/, $role);
4624: if (($trole eq 'dc') || ($trole eq 'su')) {
4625: return 1 unless ($tend && $tend < $now)
4626: or ($tstart && $tstart > $now);
4627: }
1.461 www 4628: }
1.1170 droeschl 4629:
1.461 www 4630: return 0;
1.9 www 4631: }
1.1 albertel 4632:
1.103 harris41 4633: # -------------------------------------------------------- Get user privileges
1.11 www 4634:
4635: sub rolesinit {
1.1169 droeschl 4636: my ($domain, $username) = @_;
4637: my %userroles = ('user.login.time' => time);
4638: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
4639:
4640: # firstaccess and timerinterval are related to timed maps/resources.
4641: # also, blocking can be triggered by an activating timer
4642: # it's saved in the user's %env.
4643: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
4644: my %timerinterval = &dump('timerinterval', $domain, $username);
4645: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
4646: %timerintchk, %timerintenv);
4647:
1.1162 raeburn 4648: foreach my $key (keys(%firstaccess)) {
1.1169 droeschl 4649: my ($cid, $rest) = split(/\0/, $key);
1.1162 raeburn 4650: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
4651: }
1.1169 droeschl 4652:
1.1162 raeburn 4653: foreach my $key (keys(%timerinterval)) {
4654: my ($cid,$rest) = split(/\0/,$key);
4655: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
4656: }
1.1169 droeschl 4657:
1.11 www 4658: my %allroles=();
1.1162 raeburn 4659: my %allgroups=();
1.11 www 4660:
1.1169 droeschl 4661: for my $area (grep { ! /^rolesdef_/ } keys %rolesdump) {
4662: my $role = $rolesdump{$area};
4663: $area =~ s/\_\w\w$//;
4664:
4665: my ($trole, $tend, $tstart, $group_privs);
4666:
4667: if ($role =~ /^cr/) {
4668: # Custom role, defined by a user
4669: # e.g., user.role.cr/msu/smith/mynewrole
4670: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
4671: $trole = $1;
4672: ($tend, $tstart) = split('_', $2);
4673: } else {
4674: $trole = $role;
4675: }
4676: } elsif ($role =~ m|^gr/|) {
4677: # Role of member in a group, defined within a course/community
4678: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
4679: ($trole, $tend, $tstart) = split(/_/, $role);
4680: next if $tstart eq '-1';
4681: ($trole, $group_privs) = split(/\//, $trole);
4682: $group_privs = &unescape($group_privs);
4683: } else {
4684: # Just a normal role, defined in roles.tab
4685: ($trole, $tend, $tstart) = split(/_/,$role);
4686: }
4687:
4688: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
4689: $username);
4690: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
4691:
4692: # role expired or not available yet?
4693: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
4694: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
4695:
4696: next if $area eq '' or $trole eq '';
4697:
4698: my $spec = "$trole.$area";
4699: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
4700:
4701: if ($trole =~ /^cr\//) {
4702: # Custom role, defined by a user
4703: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
4704: } elsif ($trole eq 'gr') {
4705: # Role of a member in a group, defined within a course/community
4706: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
4707: next;
4708: } else {
4709: # Normal role, defined in roles.tab
4710: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
4711: }
4712:
4713: my $cid = $tdomain.'_'.$trest;
4714: unless ($firstaccchk{$cid}) {
4715: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
4716: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
4717: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
4718: $coursetimerstarts{$cid}{$item};
4719: }
4720: }
4721: $firstaccchk{$cid} = 1;
4722: }
4723: unless ($timerintchk{$cid}) {
4724: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
4725: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
4726: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
4727: $coursetimerintervals{$cid}{$item};
1.1162 raeburn 4728: }
1.12 www 4729: }
1.1169 droeschl 4730: $timerintchk{$cid} = 1;
1.191 harris41 4731: }
1.11 www 4732: }
1.1169 droeschl 4733:
4734: @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
4735: \%allroles, \%allgroups);
4736: $env{'user.adv'} = $userroles{'user.adv'};
4737:
1.1162 raeburn 4738: return (\%userroles,\%firstaccenv,\%timerintenv);
1.11 www 4739: }
4740:
1.567 raeburn 4741: sub set_arearole {
4742: my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
4743: # log the associated role with the area
4744: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743 albertel 4745: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 4746: }
4747:
4748: sub custom_roleprivs {
4749: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
4750: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
4751: my $homsvr=homeserver($rauthor,$rdomain);
1.838 albertel 4752: if (&hostname($homsvr) ne '') {
1.567 raeburn 4753: my ($rdummy,$roledef)=
4754: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
4755: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
4756: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
4757: if (defined($syspriv)) {
1.1043 raeburn 4758: if ($trest =~ /^$match_community$/) {
4759: $syspriv =~ s/bre\&S//;
4760: }
1.567 raeburn 4761: $$allroles{'cm./'}.=':'.$syspriv;
4762: $$allroles{$spec.'./'}.=':'.$syspriv;
4763: }
4764: if ($tdomain ne '') {
4765: if (defined($dompriv)) {
4766: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
4767: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
4768: }
4769: if (($trest ne '') && (defined($coursepriv))) {
4770: $$allroles{'cm.'.$area}.=':'.$coursepriv;
4771: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
4772: }
4773: }
4774: }
4775: }
4776: }
4777:
1.678 raeburn 4778: sub group_roleprivs {
4779: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
4780: my $access = 1;
4781: my $now = time;
4782: if (($tend!=0) && ($tend<$now)) { $access = 0; }
4783: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
4784: if ($access) {
1.811 albertel 4785: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 4786: $$allgroups{$course}{$group} .=':'.$group_privs;
4787: }
4788: }
1.567 raeburn 4789:
4790: sub standard_roleprivs {
4791: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
4792: if (defined($pr{$trole.':s'})) {
4793: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
4794: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
4795: }
4796: if ($tdomain ne '') {
4797: if (defined($pr{$trole.':d'})) {
4798: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
4799: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
4800: }
4801: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
4802: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
4803: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
4804: }
4805: }
4806: }
4807:
4808: sub set_userprivs {
1.1064 raeburn 4809: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 4810: my $author=0;
4811: my $adv=0;
1.678 raeburn 4812: my %grouproles = ();
4813: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 4814: my @groupkeys;
1.1000 raeburn 4815: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 4816: push(@groupkeys,$role);
4817: }
4818: if (ref($groups_roles) eq 'HASH') {
4819: foreach my $key (keys(%{$groups_roles})) {
4820: unless (grep(/^\Q$key\E$/,@groupkeys)) {
4821: push(@groupkeys,$key);
4822: }
4823: }
4824: }
4825: if (@groupkeys > 0) {
4826: foreach my $role (@groupkeys) {
4827: my ($trole,$area,$sec,$extendedarea);
4828: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
4829: $trole = $1;
4830: $area = $2;
4831: $sec = $3;
4832: $extendedarea = $area.$sec;
4833: if (exists($$allgroups{$area})) {
4834: foreach my $group (keys(%{$$allgroups{$area}})) {
4835: my $spec = $trole.'.'.$extendedarea;
4836: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 4837: $$allgroups{$area}{$group};
1.1064 raeburn 4838: }
1.678 raeburn 4839: }
4840: }
4841: }
4842: }
4843: }
1.800 albertel 4844: foreach my $group (keys(%grouproles)) {
4845: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 4846: }
1.800 albertel 4847: foreach my $role (keys(%{$allroles})) {
4848: my %thesepriv;
1.941 raeburn 4849: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 4850: foreach my $item (split(/:/,$$allroles{$role})) {
4851: if ($item ne '') {
4852: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 4853: if ($restrictions eq '') {
4854: $thesepriv{$privilege}='F';
4855: } elsif ($thesepriv{$privilege} ne 'F') {
4856: $thesepriv{$privilege}.=$restrictions;
4857: }
4858: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
4859: }
4860: }
4861: my $thesestr='';
1.1104 raeburn 4862: foreach my $priv (sort(keys(%thesepriv))) {
1.800 albertel 4863: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
4864: }
4865: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 4866: }
4867: return ($author,$adv);
4868: }
4869:
1.994 raeburn 4870: sub role_status {
1.1104 raeburn 4871: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 4872: my @pwhere = ();
4873: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
4874: (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
4875: unless (!defined($$role) || $$role eq '') {
4876: $$where=join('.',@pwhere);
4877: $$trolecode=$$role.'.'.$$where;
4878: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
4879: $$tstatus='is';
1.1104 raeburn 4880: if ($$tstart && $$tstart>$update) {
1.994 raeburn 4881: $$tstatus='future';
1.1034 raeburn 4882: if ($$tstart<$now) {
4883: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 4884: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 4885: my (%allroles,%allgroups,$group_privs,
4886: %groups_roles,@rolecodes);
1.1002 raeburn 4887: my %userroles = (
4888: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
4889: );
1.1064 raeburn 4890: @rolecodes = ('cm');
1.1002 raeburn 4891: my $spec=$$role.'.'.$$where;
4892: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
4893: if ($$role =~ /^cr\//) {
4894: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 4895: push(@rolecodes,'cr');
1.1002 raeburn 4896: } elsif ($$role eq 'gr') {
1.1064 raeburn 4897: push(@rolecodes,$$role);
1.1002 raeburn 4898: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
4899: $env{'user.name'});
1.1064 raeburn 4900: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 4901: (undef,my $group_privs) = split(/\//,$trole);
4902: $group_privs = &unescape($group_privs);
4903: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 4904: my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
1.1104 raeburn 4905: &get_groups_roles($tdomain,$trest,
4906: \%course_roles,\@rolecodes,
4907: \%groups_roles);
1.1002 raeburn 4908: } else {
1.1064 raeburn 4909: push(@rolecodes,$$role);
1.1002 raeburn 4910: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
4911: }
1.1064 raeburn 4912: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
4913: &appenv(\%userroles,\@rolecodes);
1.1002 raeburn 4914: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
4915: }
4916: }
1.1034 raeburn 4917: $$tstatus = 'is';
1.1002 raeburn 4918: }
1.994 raeburn 4919: }
4920: if ($$tend) {
1.1104 raeburn 4921: if ($$tend<$update) {
1.994 raeburn 4922: $$tstatus='expired';
4923: } elsif ($$tend<$now) {
4924: $$tstatus='will_not';
4925: }
4926: }
4927: }
4928: }
4929: }
4930:
1.1104 raeburn 4931: sub get_groups_roles {
4932: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
4933: return unless((ref($cdom_courseroles) eq 'HASH') &&
4934: (ref($rolecodes) eq 'ARRAY') &&
4935: (ref($groups_roles) eq 'HASH'));
4936: if (keys(%{$cdom_courseroles}) > 0) {
4937: my ($cnum) = ($rest =~ /^($match_courseid)/);
4938: if ($cdom ne '' && $cnum ne '') {
4939: foreach my $key (keys(%{$cdom_courseroles})) {
4940: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
4941: my $crsrole = $1;
4942: my $crssec = $2;
4943: if ($crsrole =~ /^cr/) {
4944: unless (grep(/^cr$/,@{$rolecodes})) {
4945: push(@{$rolecodes},'cr');
4946: }
4947: } else {
4948: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
4949: push(@{$rolecodes},$crsrole);
4950: }
4951: }
4952: my $rolekey = "$crsrole./$cdom/$cnum";
4953: if ($crssec ne '') {
4954: $rolekey .= "/$crssec";
4955: }
4956: $rolekey .= './';
4957: $groups_roles->{$rolekey} = $rolecodes;
4958: }
4959: }
4960: }
4961: }
4962: return;
4963: }
4964:
4965: sub delete_env_groupprivs {
4966: my ($where,$courseroles,$possroles) = @_;
4967: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
4968: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
4969: unless (ref($courseroles->{$udom}) eq 'HASH') {
4970: %{$courseroles->{$udom}} =
4971: &get_my_roles('','','userroles',['active'],
4972: $possroles,[$udom],1);
4973: }
4974: if (ref($courseroles->{$udom}) eq 'HASH') {
4975: foreach my $item (keys(%{$courseroles->{$udom}})) {
4976: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
4977: my $area = '/'.$cdom.'/'.$cnum;
4978: my $privkey = "user.priv.$crsrole.$area";
4979: if ($crssec ne '') {
4980: $privkey .= '/'.$crssec;
4981: }
4982: $privkey .= ".$area/$group";
4983: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
4984: }
4985: }
4986: return;
4987: }
4988:
1.994 raeburn 4989: sub check_adhoc_privs {
1.1104 raeburn 4990: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994 raeburn 4991: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
4992: if ($env{$cckey}) {
4993: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104 raeburn 4994: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 4995: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088 raeburn 4996: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994 raeburn 4997: }
4998: } else {
1.1088 raeburn 4999: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994 raeburn 5000: }
5001: }
5002:
5003: sub set_adhoc_privileges {
5004: # role can be cc or ca
1.1088 raeburn 5005: my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994 raeburn 5006: my $area = '/'.$dcdom.'/'.$pickedcourse;
5007: my $spec = $role.'.'.$area;
5008: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
5009: $env{'user.name'});
5010: my %ccrole = ();
5011: &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
5012: my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
5013: &appenv(\%userroles,[$role,'cm']);
5014: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088 raeburn 5015: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
5016: &appenv( {'request.role' => $spec,
5017: 'request.role.domain' => $dcdom,
5018: 'request.course.sec' => ''
5019: }
5020: );
5021: my $tadv=0;
5022: if (&allowed('adv') eq 'F') { $tadv=1; }
5023: &appenv({'request.role.adv' => $tadv});
5024: }
1.994 raeburn 5025: }
5026:
1.12 www 5027: # --------------------------------------------------------------- get interface
5028:
5029: sub get {
1.131 albertel 5030: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 5031: my $items='';
1.800 albertel 5032: foreach my $item (@$storearr) {
5033: $items.=&escape($item).'&';
1.191 harris41 5034: }
1.12 www 5035: $items=~s/\&$//;
1.620 albertel 5036: if (!$udomain) { $udomain=$env{'user.domain'}; }
5037: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 5038: my $uhome=&homeserver($uname,$udomain);
5039:
1.133 albertel 5040: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 5041: my @pairs=split(/\&/,$rep);
1.273 albertel 5042: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
5043: return @pairs;
5044: }
1.15 www 5045: my %returnhash=();
1.42 www 5046: my $i=0;
1.800 albertel 5047: foreach my $item (@$storearr) {
5048: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 5049: $i++;
1.191 harris41 5050: }
1.15 www 5051: return %returnhash;
1.27 www 5052: }
5053:
5054: # --------------------------------------------------------------- del interface
5055:
5056: sub del {
1.133 albertel 5057: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 5058: my $items='';
1.800 albertel 5059: foreach my $item (@$storearr) {
5060: $items.=&escape($item).'&';
1.191 harris41 5061: }
1.984 neumanie 5062:
1.27 www 5063: $items=~s/\&$//;
1.620 albertel 5064: if (!$udomain) { $udomain=$env{'user.domain'}; }
5065: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 5066: my $uhome=&homeserver($uname,$udomain);
5067: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 5068: }
5069:
5070: # -------------------------------------------------------------- dump interface
5071:
5072: sub dump {
1.1166 raeburn 5073: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.755 albertel 5074: if (!$udomain) { $udomain=$env{'user.domain'}; }
5075: if (!$uname) { $uname=$env{'user.name'}; }
5076: my $uhome=&homeserver($uname,$udomain);
1.1167 droeschl 5077:
1.755 albertel 5078: if ($regexp) {
5079: $regexp=&escape($regexp);
5080: } else {
5081: $regexp='.';
5082: }
1.1166 raeburn 5083: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755 albertel 5084: my @pairs=split(/\&/,$rep);
5085: my %returnhash=();
1.1098 foxr 5086: if (!($rep =~ /^error/ )) {
5087: foreach my $item (@pairs) {
5088: my ($key,$value)=split(/=/,$item,2);
5089: $key = &unescape($key);
5090: next if ($key =~ /^error: 2 /);
5091: $returnhash{$key}=&thaw_unescape($value);
5092: }
1.755 albertel 5093: }
5094: return %returnhash;
1.407 www 5095: }
5096:
1.1098 foxr 5097:
1.717 albertel 5098: # --------------------------------------------------------- dumpstore interface
5099:
5100: sub dumpstore {
5101: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822 albertel 5102: if (!$udomain) { $udomain=$env{'user.domain'}; }
5103: if (!$uname) { $uname=$env{'user.name'}; }
5104: my $uhome=&homeserver($uname,$udomain);
5105: if ($regexp) {
5106: $regexp=&escape($regexp);
5107: } else {
5108: $regexp='.';
5109: }
5110: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
5111: my @pairs=split(/\&/,$rep);
5112: my %returnhash=();
5113: foreach my $item (@pairs) {
5114: my ($key,$value)=split(/=/,$item,2);
5115: next if ($key =~ /^error: 2 /);
5116: $returnhash{$key}=&thaw_unescape($value);
5117: }
5118: return %returnhash;
1.717 albertel 5119: }
5120:
1.407 www 5121: # -------------------------------------------------------------- keys interface
5122:
5123: sub getkeys {
5124: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 5125: if (!$udomain) { $udomain=$env{'user.domain'}; }
5126: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 5127: my $uhome=&homeserver($uname,$udomain);
5128: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
5129: my @keyarray=();
1.800 albertel 5130: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 5131: next if ($key =~ /^error: 2 /);
1.800 albertel 5132: push(@keyarray,&unescape($key));
1.407 www 5133: }
5134: return @keyarray;
1.318 matthew 5135: }
5136:
1.319 matthew 5137: # --------------------------------------------------------------- currentdump
5138: sub currentdump {
1.328 matthew 5139: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 5140: $courseid = $env{'request.course.id'} if (! defined($courseid));
5141: $sdom = $env{'user.domain'} if (! defined($sdom));
5142: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 5143: my $uhome = &homeserver($sname,$sdom);
5144: my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318 matthew 5145: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 5146: #
1.318 matthew 5147: my %returnhash=();
1.319 matthew 5148: #
5149: if ($rep eq "unknown_cmd") {
5150: # an old lond will not know currentdump
5151: # Do a dump and make it look like a currentdump
1.822 albertel 5152: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 5153: return if ($tmp[0] =~ /^(error:|no_such_host)/);
5154: my %hash = @tmp;
5155: @tmp=();
1.424 matthew 5156: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 5157: } else {
5158: my @pairs=split(/\&/,$rep);
1.800 albertel 5159: foreach my $pair (@pairs) {
5160: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 5161: my ($symb,$param) = split(/:/,$key);
5162: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 5163: &thaw_unescape($value);
1.319 matthew 5164: }
1.191 harris41 5165: }
1.12 www 5166: return %returnhash;
1.424 matthew 5167: }
5168:
5169: sub convert_dump_to_currentdump{
5170: my %hash = %{shift()};
5171: my %returnhash;
5172: # Code ripped from lond, essentially. The only difference
5173: # here is the unescaping done by lonnet::dump(). Conceivably
5174: # we might run in to problems with parameter names =~ /^v\./
5175: while (my ($key,$value) = each(%hash)) {
5176: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 5177: $symb = &unescape($symb);
5178: $param = &unescape($param);
1.424 matthew 5179: next if ($v eq 'version' || $symb eq 'keys');
5180: next if (exists($returnhash{$symb}) &&
5181: exists($returnhash{$symb}->{$param}) &&
5182: $returnhash{$symb}->{'v.'.$param} > $v);
5183: $returnhash{$symb}->{$param}=$value;
5184: $returnhash{$symb}->{'v.'.$param}=$v;
5185: }
5186: #
5187: # Remove all of the keys in the hashes which keep track of
5188: # the version of the parameter.
5189: while (my ($symb,$param_hash) = each(%returnhash)) {
5190: # use a foreach because we are going to delete from the hash.
5191: foreach my $key (keys(%$param_hash)) {
5192: delete($param_hash->{$key}) if ($key =~ /^v\./);
5193: }
5194: }
5195: return \%returnhash;
1.12 www 5196: }
5197:
1.627 albertel 5198: # ------------------------------------------------------ critical inc interface
5199:
5200: sub cinc {
5201: return &inc(@_,'critical');
5202: }
5203:
1.449 matthew 5204: # --------------------------------------------------------------- inc interface
5205:
5206: sub inc {
1.627 albertel 5207: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 5208: if (!$udomain) { $udomain=$env{'user.domain'}; }
5209: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 5210: my $uhome=&homeserver($uname,$udomain);
5211: my $items='';
5212: if (! ref($store)) {
5213: # got a single value, so use that instead
5214: $items = &escape($store).'=&';
5215: } elsif (ref($store) eq 'SCALAR') {
5216: $items = &escape($$store).'=&';
5217: } elsif (ref($store) eq 'ARRAY') {
5218: $items = join('=&',map {&escape($_);} @{$store});
5219: } elsif (ref($store) eq 'HASH') {
5220: while (my($key,$value) = each(%{$store})) {
5221: $items.= &escape($key).'='.&escape($value).'&';
5222: }
5223: }
5224: $items=~s/\&$//;
1.627 albertel 5225: if ($critical) {
5226: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
5227: } else {
5228: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
5229: }
1.449 matthew 5230: }
5231:
1.12 www 5232: # --------------------------------------------------------------- put interface
5233:
5234: sub put {
1.134 albertel 5235: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 5236: if (!$udomain) { $udomain=$env{'user.domain'}; }
5237: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 5238: my $uhome=&homeserver($uname,$udomain);
1.12 www 5239: my $items='';
1.800 albertel 5240: foreach my $item (keys(%$storehash)) {
5241: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 5242: }
1.12 www 5243: $items=~s/\&$//;
1.134 albertel 5244: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 5245: }
5246:
1.631 albertel 5247: # ------------------------------------------------------------ newput interface
5248:
5249: sub newput {
5250: my ($namespace,$storehash,$udomain,$uname)=@_;
5251: if (!$udomain) { $udomain=$env{'user.domain'}; }
5252: if (!$uname) { $uname=$env{'user.name'}; }
5253: my $uhome=&homeserver($uname,$udomain);
5254: my $items='';
5255: foreach my $key (keys(%$storehash)) {
5256: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
5257: }
5258: $items=~s/\&$//;
5259: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
5260: }
5261:
5262: # --------------------------------------------------------- putstore interface
5263:
1.524 raeburn 5264: sub putstore {
1.715 albertel 5265: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620 albertel 5266: if (!$udomain) { $udomain=$env{'user.domain'}; }
5267: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 5268: my $uhome=&homeserver($uname,$udomain);
5269: my $items='';
1.715 albertel 5270: foreach my $key (keys(%$storehash)) {
5271: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 5272: }
1.715 albertel 5273: $items=~s/\&$//;
1.716 albertel 5274: my $esc_symb=&escape($symb);
5275: my $esc_v=&escape($version);
1.715 albertel 5276: my $reply =
1.716 albertel 5277: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 5278: $uhome);
5279: if ($reply eq 'unknown_cmd') {
1.716 albertel 5280: # gfall back to way things use to be done
1.715 albertel 5281: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
5282: $uname);
1.524 raeburn 5283: }
1.715 albertel 5284: return $reply;
5285: }
5286:
5287: sub old_putstore {
1.716 albertel 5288: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
5289: if (!$udomain) { $udomain=$env{'user.domain'}; }
5290: if (!$uname) { $uname=$env{'user.name'}; }
5291: my $uhome=&homeserver($uname,$udomain);
5292: my %newstorehash;
1.800 albertel 5293: foreach my $item (keys(%$storehash)) {
5294: my $key = $version.':'.&escape($symb).':'.$item;
5295: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 5296: }
5297: my $items='';
5298: my %allitems = ();
1.800 albertel 5299: foreach my $item (keys(%newstorehash)) {
5300: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 5301: my $key = $1.':keys:'.$2;
5302: $allitems{$key} .= $3.':';
5303: }
1.800 albertel 5304: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 5305: }
1.800 albertel 5306: foreach my $item (keys(%allitems)) {
5307: $allitems{$item} =~ s/\:$//;
5308: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 5309: }
5310: $items=~s/\&$//;
5311: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 5312: }
5313:
1.47 www 5314: # ------------------------------------------------------ critical put interface
5315:
5316: sub cput {
1.134 albertel 5317: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 5318: if (!$udomain) { $udomain=$env{'user.domain'}; }
5319: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 5320: my $uhome=&homeserver($uname,$udomain);
1.47 www 5321: my $items='';
1.800 albertel 5322: foreach my $item (keys(%$storehash)) {
5323: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 5324: }
1.47 www 5325: $items=~s/\&$//;
1.134 albertel 5326: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 5327: }
5328:
5329: # -------------------------------------------------------------- eget interface
5330:
5331: sub eget {
1.133 albertel 5332: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 5333: my $items='';
1.800 albertel 5334: foreach my $item (@$storearr) {
5335: $items.=&escape($item).'&';
1.191 harris41 5336: }
1.12 www 5337: $items=~s/\&$//;
1.620 albertel 5338: if (!$udomain) { $udomain=$env{'user.domain'}; }
5339: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 5340: my $uhome=&homeserver($uname,$udomain);
5341: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 5342: my @pairs=split(/\&/,$rep);
5343: my %returnhash=();
1.42 www 5344: my $i=0;
1.800 albertel 5345: foreach my $item (@$storearr) {
5346: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 5347: $i++;
1.191 harris41 5348: }
1.12 www 5349: return %returnhash;
5350: }
5351:
1.667 albertel 5352: # ------------------------------------------------------------ tmpput interface
5353: sub tmpput {
1.802 raeburn 5354: my ($storehash,$server,$context)=@_;
1.667 albertel 5355: my $items='';
1.800 albertel 5356: foreach my $item (keys(%$storehash)) {
5357: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 5358: }
5359: $items=~s/\&$//;
1.802 raeburn 5360: if (defined($context)) {
5361: $items .= ':'.&escape($context);
5362: }
1.667 albertel 5363: return &reply("tmpput:$items",$server);
5364: }
5365:
5366: # ------------------------------------------------------------ tmpget interface
5367: sub tmpget {
1.688 albertel 5368: my ($token,$server)=@_;
5369: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5370: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 5371: my %returnhash;
5372: foreach my $item (split(/\&/,$rep)) {
5373: my ($key,$value)=split(/=/,$item);
1.951 raeburn 5374: next if ($key =~ /^error: 2 /);
1.667 albertel 5375: $returnhash{&unescape($key)}=&thaw_unescape($value);
5376: }
5377: return %returnhash;
5378: }
5379:
1.1113 raeburn 5380: # ------------------------------------------------------------ tmpdel interface
1.688 albertel 5381: sub tmpdel {
5382: my ($token,$server)=@_;
5383: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5384: return &reply("tmpdel:$token",$server);
5385: }
5386:
1.765 albertel 5387: # -------------------------------------------------- portfolio access checking
5388:
5389: sub portfolio_access {
1.766 albertel 5390: my ($requrl) = @_;
1.765 albertel 5391: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
5392: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814 raeburn 5393: if ($result) {
5394: my %setters;
5395: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
5396: my ($startblock,$endblock) =
5397: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
5398: if ($startblock && $endblock) {
5399: return 'B';
5400: }
5401: } else {
5402: my ($startblock,$endblock) =
5403: &Apache::loncommon::blockcheck(\%setters,'port');
5404: if ($startblock && $endblock) {
5405: return 'B';
5406: }
5407: }
5408: }
1.765 albertel 5409: if ($result eq 'ok') {
1.766 albertel 5410: return 'F';
1.765 albertel 5411: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 5412: return 'A';
1.765 albertel 5413: }
1.766 albertel 5414: return '';
1.765 albertel 5415: }
5416:
5417: sub get_portfolio_access {
1.767 albertel 5418: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
5419:
5420: if (!ref($access_hash)) {
5421: my $current_perms = &get_portfile_permissions($udom,$unum);
5422: my %access_controls = &get_access_controls($current_perms,$group,
5423: $file_name);
5424: $access_hash = $access_controls{$file_name};
5425: }
5426:
1.765 albertel 5427: my ($public,$guest,@domains,@users,@courses,@groups);
5428: my $now = time;
5429: if (ref($access_hash) eq 'HASH') {
5430: foreach my $key (keys(%{$access_hash})) {
5431: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
5432: if ($start > $now) {
5433: next;
5434: }
5435: if ($end && $end<$now) {
5436: next;
5437: }
5438: if ($scope eq 'public') {
5439: $public = $key;
5440: last;
5441: } elsif ($scope eq 'guest') {
5442: $guest = $key;
5443: } elsif ($scope eq 'domains') {
5444: push(@domains,$key);
5445: } elsif ($scope eq 'users') {
5446: push(@users,$key);
5447: } elsif ($scope eq 'course') {
5448: push(@courses,$key);
5449: } elsif ($scope eq 'group') {
5450: push(@groups,$key);
5451: }
5452: }
5453: if ($public) {
5454: return 'ok';
5455: }
5456: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
5457: if ($guest) {
5458: return $guest;
5459: }
5460: } else {
5461: if (@domains > 0) {
5462: foreach my $domkey (@domains) {
5463: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
5464: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
5465: return 'ok';
5466: }
5467: }
5468: }
5469: }
5470: if (@users > 0) {
5471: foreach my $userkey (@users) {
1.865 raeburn 5472: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
5473: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
5474: if (ref($item) eq 'HASH') {
5475: if (($item->{'uname'} eq $env{'user.name'}) &&
5476: ($item->{'udom'} eq $env{'user.domain'})) {
5477: return 'ok';
5478: }
5479: }
5480: }
5481: }
1.765 albertel 5482: }
5483: }
5484: my %roleshash;
5485: my @courses_and_groups = @courses;
5486: push(@courses_and_groups,@groups);
5487: if (@courses_and_groups > 0) {
5488: my (%allgroups,%allroles);
5489: my ($start,$end,$role,$sec,$group);
5490: foreach my $envkey (%env) {
1.1060 raeburn 5491: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 5492: my $cid = $2.'_'.$3;
5493: if ($1 eq 'gr') {
5494: $group = $4;
5495: $allgroups{$cid}{$group} = $env{$envkey};
5496: } else {
5497: if ($4 eq '') {
5498: $sec = 'none';
5499: } else {
5500: $sec = $4;
5501: }
5502: $allroles{$cid}{$1}{$sec} = $env{$envkey};
5503: }
1.811 albertel 5504: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 5505: my $cid = $2.'_'.$3;
5506: if ($4 eq '') {
5507: $sec = 'none';
5508: } else {
5509: $sec = $4;
5510: }
5511: $allroles{$cid}{$1}{$sec} = $env{$envkey};
5512: }
5513: }
5514: if (keys(%allroles) == 0) {
5515: return;
5516: }
5517: foreach my $key (@courses_and_groups) {
5518: my %content = %{$$access_hash{$key}};
5519: my $cnum = $content{'number'};
5520: my $cdom = $content{'domain'};
5521: my $cid = $cdom.'_'.$cnum;
5522: if (!exists($allroles{$cid})) {
5523: next;
5524: }
5525: foreach my $role_id (keys(%{$content{'roles'}})) {
5526: my @sections = @{$content{'roles'}{$role_id}{'section'}};
5527: my @groups = @{$content{'roles'}{$role_id}{'group'}};
5528: my @status = @{$content{'roles'}{$role_id}{'access'}};
5529: my @roles = @{$content{'roles'}{$role_id}{'role'}};
5530: foreach my $role (keys(%{$allroles{$cid}})) {
5531: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
5532: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
5533: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
5534: if (grep/^all$/,@sections) {
5535: return 'ok';
5536: } else {
5537: if (grep/^$sec$/,@sections) {
5538: return 'ok';
5539: }
5540: }
5541: }
5542: }
5543: if (keys(%{$allgroups{$cid}}) == 0) {
5544: if (grep/^none$/,@groups) {
5545: return 'ok';
5546: }
5547: } else {
5548: if (grep/^all$/,@groups) {
5549: return 'ok';
5550: }
5551: foreach my $group (keys(%{$allgroups{$cid}})) {
5552: if (grep/^$group$/,@groups) {
5553: return 'ok';
5554: }
5555: }
5556: }
5557: }
5558: }
5559: }
5560: }
5561: }
5562: if ($guest) {
5563: return $guest;
5564: }
5565: }
5566: }
5567: return;
5568: }
5569:
5570: sub course_group_datechecker {
5571: my ($dates,$now,$status) = @_;
5572: my ($start,$end) = split(/\./,$dates);
5573: if (!$start && !$end) {
5574: return 'ok';
5575: }
5576: if (grep/^active$/,@{$status}) {
5577: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
5578: return 'ok';
5579: }
5580: }
5581: if (grep/^previous$/,@{$status}) {
5582: if ($end > $now ) {
5583: return 'ok';
5584: }
5585: }
5586: if (grep/^future$/,@{$status}) {
5587: if ($start > $now) {
5588: return 'ok';
5589: }
5590: }
5591: return;
5592: }
5593:
5594: sub parse_portfolio_url {
5595: my ($url) = @_;
5596:
5597: my ($type,$udom,$unum,$group,$file_name);
5598:
1.823 albertel 5599: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 5600: $type = 1;
5601: $udom = $1;
5602: $unum = $2;
5603: $file_name = $3;
1.823 albertel 5604: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 5605: $type = 2;
5606: $udom = $1;
5607: $unum = $2;
5608: $group = $3;
5609: $file_name = $3.'/'.$4;
5610: }
5611: if (wantarray) {
5612: return ($type,$udom,$unum,$file_name,$group);
5613: }
5614: return $type;
5615: }
5616:
5617: sub is_portfolio_url {
5618: my ($url) = @_;
5619: return scalar(&parse_portfolio_url($url));
5620: }
5621:
1.798 raeburn 5622: sub is_portfolio_file {
5623: my ($file) = @_;
1.820 raeburn 5624: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 5625: return 1;
5626: }
5627: return;
5628: }
5629:
1.976 raeburn 5630: sub usertools_access {
1.1084 raeburn 5631: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 5632: my ($access,%tools);
5633: if ($context eq '') {
5634: $context = 'tools';
5635: }
5636: if ($context eq 'requestcourses') {
5637: %tools = (
5638: official => 1,
5639: unofficial => 1,
1.1006 raeburn 5640: community => 1,
1.985 raeburn 5641: );
5642: } else {
5643: %tools = (
5644: aboutme => 1,
5645: blog => 1,
5646: portfolio => 1,
5647: );
5648: }
1.976 raeburn 5649: return if (!defined($tools{$tool}));
5650:
5651: if ((!defined($udom)) || (!defined($uname))) {
5652: $udom = $env{'user.domain'};
5653: $uname = $env{'user.name'};
5654: }
5655:
1.978 raeburn 5656: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
5657: if ($action ne 'reload') {
1.985 raeburn 5658: if ($context eq 'requestcourses') {
5659: return $env{'environment.canrequest.'.$tool};
5660: } else {
5661: return $env{'environment.availabletools.'.$tool};
5662: }
5663: }
1.976 raeburn 5664: }
5665:
5666: my ($toolstatus,$inststatus);
5667:
1.985 raeburn 5668: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
5669: ($action ne 'reload')) {
5670: $toolstatus = $env{'environment.'.$context.'.'.$tool};
1.976 raeburn 5671: $inststatus = $env{'environment.inststatus'};
5672: } else {
1.1084 raeburn 5673: if (ref($userenvref) eq 'HASH') {
5674: $toolstatus = $userenvref->{$context.'.'.$tool};
5675: $inststatus = $userenvref->{'inststatus'};
5676: } else {
5677: my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
5678: $toolstatus = $userenv{$context.'.'.$tool};
5679: $inststatus = $userenv{'inststatus'};
5680: }
1.976 raeburn 5681: }
5682:
5683: if ($toolstatus ne '') {
5684: if ($toolstatus) {
5685: $access = 1;
5686: } else {
5687: $access = 0;
5688: }
5689: return $access;
5690: }
5691:
1.1084 raeburn 5692: my ($is_adv,%domdef);
5693: if (ref($is_advref) eq 'HASH') {
5694: $is_adv = $is_advref->{'is_adv'};
5695: } else {
5696: $is_adv = &is_advanced_user($udom,$uname);
5697: }
5698: if (ref($domdefref) eq 'HASH') {
5699: %domdef = %{$domdefref};
5700: } else {
5701: %domdef = &get_domain_defaults($udom);
5702: }
1.976 raeburn 5703: if (ref($domdef{$tool}) eq 'HASH') {
5704: if ($is_adv) {
5705: if ($domdef{$tool}{'_LC_adv'} ne '') {
5706: if ($domdef{$tool}{'_LC_adv'}) {
5707: $access = 1;
5708: } else {
5709: $access = 0;
5710: }
5711: return $access;
5712: }
5713: }
5714: if ($inststatus ne '') {
5715: my ($hasaccess,$hasnoaccess);
5716: foreach my $affiliation (split(/:/,$inststatus)) {
5717: if ($domdef{$tool}{$affiliation} ne '') {
5718: if ($domdef{$tool}{$affiliation}) {
5719: $hasaccess = 1;
5720: } else {
5721: $hasnoaccess = 1;
5722: }
5723: }
5724: }
5725: if ($hasaccess || $hasnoaccess) {
5726: if ($hasaccess) {
5727: $access = 1;
5728: } elsif ($hasnoaccess) {
5729: $access = 0;
5730: }
5731: return $access;
5732: }
5733: } else {
5734: if ($domdef{$tool}{'default'} ne '') {
5735: if ($domdef{$tool}{'default'}) {
5736: $access = 1;
5737: } elsif ($domdef{$tool}{'default'} == 0) {
5738: $access = 0;
5739: }
5740: return $access;
5741: }
5742: }
5743: } else {
1.985 raeburn 5744: if ($context eq 'tools') {
5745: $access = 1;
5746: } else {
5747: $access = 0;
5748: }
1.976 raeburn 5749: return $access;
5750: }
5751: }
5752:
1.1050 raeburn 5753: sub is_course_owner {
5754: my ($cdom,$cnum,$udom,$uname) = @_;
5755: if (($udom eq '') || ($uname eq '')) {
5756: $udom = $env{'user.domain'};
5757: $uname = $env{'user.name'};
5758: }
5759: unless (($udom eq '') || ($uname eq '')) {
5760: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
5761: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
5762: return 1;
5763: } else {
5764: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
5765: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
5766: return 1;
5767: }
5768: }
5769: }
5770: }
5771: return;
5772: }
5773:
1.976 raeburn 5774: sub is_advanced_user {
5775: my ($udom,$uname) = @_;
1.1085 raeburn 5776: if ($udom ne '' && $uname ne '') {
5777: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128 raeburn 5778: if (wantarray) {
5779: return ($env{'user.adv'},$env{'user.author'});
5780: } else {
5781: return $env{'user.adv'};
5782: }
1.1085 raeburn 5783: }
5784: }
1.976 raeburn 5785: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
5786: my %allroles;
1.1128 raeburn 5787: my ($is_adv,$is_author);
1.976 raeburn 5788: foreach my $role (keys(%roleshash)) {
5789: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
5790: my $area = '/'.$tdomain.'/'.$trest;
5791: if ($sec ne '') {
5792: $area .= '/'.$sec;
5793: }
5794: if (($area ne '') && ($trole ne '')) {
5795: my $spec=$trole.'.'.$area;
5796: if ($trole =~ /^cr\//) {
5797: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5798: } elsif ($trole ne 'gr') {
5799: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5800: }
1.1128 raeburn 5801: if ($trole eq 'au') {
5802: $is_author = 1;
5803: }
1.976 raeburn 5804: }
5805: }
5806: foreach my $role (keys(%allroles)) {
5807: last if ($is_adv);
5808: foreach my $item (split(/:/,$allroles{$role})) {
5809: if ($item ne '') {
5810: my ($privilege,$restrictions)=split(/&/,$item);
5811: if ($privilege eq 'adv') {
5812: $is_adv = 1;
5813: last;
5814: }
5815: }
5816: }
5817: }
1.1128 raeburn 5818: if (wantarray) {
5819: return ($is_adv,$is_author);
5820: }
1.976 raeburn 5821: return $is_adv;
5822: }
1.798 raeburn 5823:
1.1035 raeburn 5824: sub check_can_request {
1.1036 raeburn 5825: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 5826: my $canreq = 0;
5827: my ($types,$typename) = &Apache::loncommon::course_types();
5828: my @options = ('approval','validate','autolimit');
5829: my $optregex = join('|',@options);
5830: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
5831: foreach my $type (@{$types}) {
5832: if (&usertools_access($env{'user.name'},
5833: $env{'user.domain'},
5834: $type,undef,'requestcourses')) {
5835: $canreq ++;
1.1036 raeburn 5836: if (ref($request_domains) eq 'HASH') {
5837: push(@{$request_domains->{$type}},$env{'user.domain'});
5838: }
1.1035 raeburn 5839: if ($dom eq $env{'user.domain'}) {
5840: $can_request->{$type} = 1;
5841: }
5842: }
5843: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
5844: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
5845: if (@curr > 0) {
1.1036 raeburn 5846: foreach my $item (@curr) {
5847: if (ref($request_domains) eq 'HASH') {
5848: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
5849: if ($otherdom ne '') {
5850: if (ref($request_domains->{$type}) eq 'ARRAY') {
5851: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
5852: push(@{$request_domains->{$type}},$otherdom);
5853: }
5854: } else {
5855: push(@{$request_domains->{$type}},$otherdom);
5856: }
5857: }
5858: }
5859: }
5860: unless($dom eq $env{'user.domain'}) {
5861: $canreq ++;
1.1035 raeburn 5862: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
5863: $can_request->{$type} = 1;
5864: }
5865: }
5866: }
5867: }
5868: }
5869: }
5870: return $canreq;
5871: }
5872:
1.341 www 5873: # ---------------------------------------------- Custom access rule evaluation
5874:
5875: sub customaccess {
5876: my ($priv,$uri)=@_;
1.807 albertel 5877: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 5878: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 5879: $udom = &LONCAPA::clean_domain($udom);
5880: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 5881: my $access=0;
1.800 albertel 5882: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 5883: my ($effect,$realm,$role,$type)=split(/\:/,$right);
5884: if ($type eq 'user') {
5885: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 5886: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 5887: if ($tdom) {
5888: if ($tdom ne $env{'user.domain'}) { next; }
5889: }
1.896 albertel 5890: if ($tuname) {
5891: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 5892: }
5893: $access=($effect eq 'allow');
5894: last;
5895: }
5896: } else {
5897: if ($role) {
5898: if ($role ne $urole) { next; }
5899: }
5900: foreach my $scope (split(/\s*\,\s*/,$realm)) {
5901: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
5902: if ($tdom) {
5903: if ($tdom ne $udom) { next; }
5904: }
5905: if ($tcrs) {
5906: if ($tcrs ne $ucrs) { next; }
5907: }
5908: if ($tsec) {
5909: if ($tsec ne $usec) { next; }
5910: }
5911: $access=($effect eq 'allow');
5912: last;
5913: }
5914: if ($realm eq '' && $role eq '') {
5915: $access=($effect eq 'allow');
5916: }
1.402 bowersj2 5917: }
1.341 www 5918: }
5919: return $access;
5920: }
5921:
1.103 harris41 5922: # ------------------------------------------------- Check for a user privilege
1.12 www 5923:
5924: sub allowed {
1.810 raeburn 5925: my ($priv,$uri,$symb,$role)=@_;
1.705 albertel 5926: my $ver_orguri=$uri;
1.439 www 5927: $uri=&deversion($uri);
1.152 www 5928: my $orguri=$uri;
1.52 www 5929: $uri=&declutter($uri);
1.809 raeburn 5930:
1.810 raeburn 5931: if ($priv eq 'evb') {
5932: # Evade communication block restrictions for specified role in a course
5933: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
5934: return $1;
5935: } else {
5936: return;
5937: }
5938: }
5939:
1.620 albertel 5940: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 5941: # Free bre access to adm and meta resources
1.775 albertel 5942: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 5943: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
5944: && ($priv eq 'bre')) {
1.14 www 5945: return 'F';
1.159 www 5946: }
5947:
1.545 banghart 5948: # Free bre access to user's own portfolio contents
1.714 raeburn 5949: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 5950: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 5951: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 5952: my %setters;
5953: my ($startblock,$endblock) =
5954: &Apache::loncommon::blockcheck(\%setters,'port');
5955: if ($startblock && $endblock) {
5956: return 'B';
5957: } else {
5958: return 'F';
5959: }
1.545 banghart 5960: }
5961:
1.762 raeburn 5962: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 5963: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
5964: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
5965: if (exists($env{'request.course.id'})) {
5966: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
5967: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
5968: if (($domain eq $cdom) && ($name eq $cnum)) {
5969: my $courseprivid=$env{'request.course.id'};
5970: $courseprivid=~s/\_/\//;
5971: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
5972: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
5973: return $1;
1.762 raeburn 5974: } else {
5975: if ($env{'request.course.sec'}) {
5976: $courseprivid.='/'.$env{'request.course.sec'};
5977: }
5978: if ($env{'user.priv.'.$env{'request.role'}.'./'.
5979: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
5980: return $2;
5981: }
1.714 raeburn 5982: }
5983: }
5984: }
5985: }
5986:
1.159 www 5987: # Free bre to public access
5988:
5989: if ($priv eq 'bre') {
1.238 www 5990: my $copyright=&metadata($uri,'copyright');
1.620 albertel 5991: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 5992: return 'F';
5993: }
1.238 www 5994: if ($copyright eq 'priv') {
5995: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 5996: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 5997: return '';
5998: }
5999: }
6000: if ($copyright eq 'domain') {
6001: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 6002: unless (($env{'user.domain'} eq $1) ||
6003: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 6004: return '';
6005: }
1.262 matthew 6006: }
1.620 albertel 6007: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 6008: # Library role, so allow browsing of resources in this domain.
6009: return 'F';
1.238 www 6010: }
1.341 www 6011: if ($copyright eq 'custom') {
6012: unless (&customaccess($priv,$uri)) { return ''; }
6013: }
1.14 www 6014: }
1.264 matthew 6015: # Domain coordinator is trying to create a course
1.620 albertel 6016: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 6017: # uri is the requested domain in this case.
6018: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 6019: # a role of dc for the domain in question.
1.620 albertel 6020: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 6021: }
1.29 www 6022:
1.52 www 6023: my $thisallowed='';
6024: my $statecond=0;
6025: my $courseprivid='';
6026:
1.1039 raeburn 6027: my $ownaccess;
1.1043 raeburn 6028: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 6029: if (($priv eq 'bro') && ($env{'user.author'})) {
6030: if ($uri eq '') {
6031: $ownaccess = 1;
6032: } else {
6033: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
6034: my $udom = $env{'user.domain'};
6035: my $uname = $env{'user.name'};
6036: if ($uri =~ m{^\Q$udom\E/?$}) {
6037: $ownaccess = 1;
1.1040 raeburn 6038: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 6039: unless ($uri =~ m{\.\./}) {
6040: $ownaccess = 1;
6041: }
6042: } elsif (($udom ne 'public') && ($uname ne 'public')) {
6043: my $now = time;
6044: if ($uri =~ m{^([^/]+)/?$}) {
6045: my $adom = $1;
6046: foreach my $key (keys(%env)) {
1.1042 raeburn 6047: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 6048: my ($start,$end) = split('.',$env{$key});
6049: if (($now >= $start) && (!$end || $end < $now)) {
6050: $ownaccess = 1;
6051: last;
6052: }
6053: }
6054: }
6055: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
6056: my $adom = $1;
6057: my $aname = $2;
1.1042 raeburn 6058: foreach my $role ('ca','aa') {
6059: if ($env{"user.role.$role./$adom/$aname"}) {
6060: my ($start,$end) =
6061: split('.',$env{"user.role.$role./$adom/$aname"});
6062: if (($now >= $start) && (!$end || $end < $now)) {
6063: $ownaccess = 1;
6064: last;
6065: }
1.1039 raeburn 6066: }
6067: }
6068: }
6069: }
6070: }
6071: }
6072: }
6073:
1.52 www 6074: # Course
6075:
1.620 albertel 6076: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6077: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6078: $thisallowed.=$1;
6079: }
1.52 www 6080: }
1.29 www 6081:
1.52 www 6082: # Domain
6083:
1.620 albertel 6084: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 6085: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6086: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6087: $thisallowed.=$1;
6088: }
1.12 www 6089: }
1.52 www 6090:
1.1141 raeburn 6091: # User who is not author or co-author might still be able to edit
6092: # resource of an author in the domain (e.g., if Domain Coordinator).
6093: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
6094: (&allowed('mdc',$env{'request.course.id'}))) {
6095: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
6096: $thisallowed.=$1;
6097: }
6098: }
6099:
1.52 www 6100: # Course: uri itself is a course
1.66 www 6101: my $courseuri=$uri;
6102: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 6103: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 6104:
1.620 albertel 6105: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 6106: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6107: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6108: $thisallowed.=$1;
6109: }
1.12 www 6110: }
1.29 www 6111:
1.665 albertel 6112: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 6113: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 6114: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 6115: $thisallowed='';
1.671 raeburn 6116: my ($match)=&is_on_map($uri);
6117: if ($match) {
6118: if ($env{'user.priv.'.$env{'request.role'}.'./'}
6119: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6120: my @blockers = &has_comm_blocking($priv,$symb,$uri);
6121: if (@blockers > 0) {
6122: $thisallowed = 'B';
6123: } else {
6124: $thisallowed.=$1;
6125: }
1.671 raeburn 6126: }
6127: } else {
1.705 albertel 6128: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 6129: if ($refuri) {
6130: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 6131: $thisallowed='F';
1.671 raeburn 6132: } else {
6133: $refuri=&declutter($refuri);
6134: my ($match) = &is_on_map($refuri);
6135: if ($match) {
1.1162 raeburn 6136: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
6137: if (@blockers > 0) {
6138: $thisallowed = 'B';
6139: } else {
6140: $thisallowed='F';
6141: }
1.671 raeburn 6142: }
1.669 raeburn 6143: }
1.671 raeburn 6144: }
6145: }
1.314 www 6146: }
1.492 albertel 6147:
1.766 albertel 6148: if ($priv eq 'bre'
6149: && $thisallowed ne 'F'
6150: && $thisallowed ne '2'
6151: && &is_portfolio_url($uri)) {
6152: $thisallowed = &portfolio_access($uri);
6153: }
6154:
1.52 www 6155: # Full access at system, domain or course-wide level? Exit.
1.29 www 6156: if ($thisallowed=~/F/) {
6157: return 'F';
6158: }
6159:
1.52 www 6160: # If this is generating or modifying users, exit with special codes
1.29 www 6161:
1.643 www 6162: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
6163: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 6164: my ($audom,$auname)=split('/',$uri);
1.643 www 6165: # no author name given, so this just checks on the general right to make a co-author in this domain
6166: unless ($auname) { return $thisallowed; }
6167: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 6168: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
6169: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
6170: ($audom ne $env{'request.role.domain'}))) { return ''; }
6171: }
1.52 www 6172: return $thisallowed;
6173: }
6174: #
1.103 harris41 6175: # Gathered so far: system, domain and course wide privileges
1.52 www 6176: #
6177: # Course: See if uri or referer is an individual resource that is part of
6178: # the course
6179:
1.620 albertel 6180: if ($env{'request.course.id'}) {
1.232 www 6181:
1.620 albertel 6182: $courseprivid=$env{'request.course.id'};
6183: if ($env{'request.course.sec'}) {
6184: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 6185: }
6186: $courseprivid=~s/\_/\//;
6187: my $checkreferer=1;
1.232 www 6188: my ($match,$cond)=&is_on_map($uri);
6189: if ($match) {
6190: $statecond=$cond;
1.620 albertel 6191: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 6192: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6193: my $value = $1;
6194: if ($priv eq 'bre') {
6195: my @blockers = &has_comm_blocking($priv,$symb,$uri);
6196: if (@blockers > 0) {
6197: $thisallowed = 'B';
6198: } else {
6199: $thisallowed.=$value;
6200: }
6201: } else {
6202: $thisallowed.=$value;
6203: }
1.52 www 6204: $checkreferer=0;
6205: }
1.29 www 6206: }
1.83 www 6207:
1.148 www 6208: if ($checkreferer) {
1.620 albertel 6209: my $refuri=$env{'httpref.'.$orguri};
1.148 www 6210: unless ($refuri) {
1.800 albertel 6211: foreach my $key (keys(%env)) {
6212: if ($key=~/^httpref\..*\*/) {
6213: my $pattern=$key;
1.156 www 6214: $pattern=~s/^httpref\.\/res\///;
1.148 www 6215: $pattern=~s/\*/\[\^\/\]\+/g;
6216: $pattern=~s/\//\\\//g;
1.152 www 6217: if ($orguri=~/$pattern/) {
1.800 albertel 6218: $refuri=$env{$key};
1.148 www 6219: }
6220: }
1.191 harris41 6221: }
1.148 www 6222: }
1.232 www 6223:
1.148 www 6224: if ($refuri) {
1.152 www 6225: $refuri=&declutter($refuri);
1.232 www 6226: my ($match,$cond)=&is_on_map($refuri);
6227: if ($match) {
6228: my $refstatecond=$cond;
1.620 albertel 6229: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 6230: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6231: my $value = $1;
6232: if ($priv eq 'bre') {
6233: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
6234: if (@blockers > 0) {
6235: $thisallowed = 'B';
6236: } else {
6237: $thisallowed.=$value;
6238: }
6239: } else {
6240: $thisallowed.=$value;
6241: }
1.53 www 6242: $uri=$refuri;
6243: $statecond=$refstatecond;
1.52 www 6244: }
6245: }
1.148 www 6246: }
1.29 www 6247: }
1.52 www 6248: }
1.29 www 6249:
1.52 www 6250: #
1.103 harris41 6251: # Gathered now: all privileges that could apply, and condition number
1.52 www 6252: #
6253: #
6254: # Full or no access?
6255: #
1.29 www 6256:
1.52 www 6257: if ($thisallowed=~/F/) {
6258: return 'F';
6259: }
1.29 www 6260:
1.52 www 6261: unless ($thisallowed) {
6262: return '';
6263: }
1.29 www 6264:
1.52 www 6265: # Restrictions exist, deal with them
6266: #
6267: # C:according to course preferences
6268: # R:according to resource settings
6269: # L:unless locked
6270: # X:according to user session state
6271: #
6272:
6273: # Possibly locked functionality, check all courses
1.54 www 6274: # Locks might take effect only after 10 minutes cache expiration for other
6275: # courses, and 2 minutes for current course
1.52 www 6276:
6277: my $envkey;
6278: if ($thisallowed=~/L/) {
1.1000 raeburn 6279: foreach $envkey (keys(%env)) {
1.54 www 6280: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
6281: my $courseid=$2;
6282: my $roleid=$1.'.'.$2;
1.92 www 6283: $courseid=~s/^\///;
1.54 www 6284: my $expiretime=600;
1.620 albertel 6285: if ($env{'request.role'} eq $roleid) {
1.54 www 6286: $expiretime=120;
6287: }
6288: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
6289: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 6290: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 6291: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 6292: }
1.620 albertel 6293: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
6294: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
6295: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
6296: &log($env{'user.domain'},$env{'user.name'},
6297: $env{'user.home'},
1.57 www 6298: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 6299: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 6300: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 6301: return '';
6302: }
6303: }
1.620 albertel 6304: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
6305: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
6306: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
6307: &log($env{'user.domain'},$env{'user.name'},
6308: $env{'user.home'},
1.57 www 6309: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 6310: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 6311: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 6312: return '';
6313: }
6314: }
6315: }
1.29 www 6316: }
1.52 www 6317: }
6318:
6319: #
6320: # Rest of the restrictions depend on selected course
6321: #
6322:
1.620 albertel 6323: unless ($env{'request.course.id'}) {
1.766 albertel 6324: if ($thisallowed eq 'A') {
6325: return 'A';
1.814 raeburn 6326: } elsif ($thisallowed eq 'B') {
6327: return 'B';
1.766 albertel 6328: } else {
6329: return '1';
6330: }
1.52 www 6331: }
1.29 www 6332:
1.52 www 6333: #
6334: # Now user is definitely in a course
6335: #
1.53 www 6336:
6337:
6338: # Course preferences
6339:
6340: if ($thisallowed=~/C/) {
1.620 albertel 6341: my $rolecode=(split(/\./,$env{'request.role'}))[0];
6342: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
6343: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 6344: =~/\Q$rolecode\E/) {
1.1103 raeburn 6345: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 6346: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
6347: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
6348: $env{'request.course.id'});
6349: }
1.237 www 6350: return '';
6351: }
6352:
1.620 albertel 6353: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 6354: =~/\Q$unamedom\E/) {
1.1103 raeburn 6355: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 6356: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
6357: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
6358: $env{'request.course.id'});
6359: }
1.54 www 6360: return '';
6361: }
1.53 www 6362: }
6363:
6364: # Resource preferences
6365:
6366: if ($thisallowed=~/R/) {
1.620 albertel 6367: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 6368: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103 raeburn 6369: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 6370: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
6371: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
6372: }
6373: return '';
1.54 www 6374: }
1.53 www 6375: }
1.30 www 6376:
1.246 www 6377: # Restricted by state or randomout?
1.30 www 6378:
1.52 www 6379: if ($thisallowed=~/X/) {
1.620 albertel 6380: if ($env{'acc.randomout'}) {
1.579 albertel 6381: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 6382: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 6383: return '';
6384: }
1.247 www 6385: }
6386: if (&condval($statecond)) {
1.52 www 6387: return '2';
6388: } else {
6389: return '';
6390: }
6391: }
1.30 www 6392:
1.766 albertel 6393: if ($thisallowed eq 'A') {
6394: return 'A';
1.814 raeburn 6395: } elsif ($thisallowed eq 'B') {
6396: return 'B';
1.766 albertel 6397: }
1.52 www 6398: return 'F';
1.232 www 6399: }
1.1162 raeburn 6400:
6401: sub get_comm_blocks {
6402: my ($cdom,$cnum) = @_;
6403: if ($cdom eq '' || $cnum eq '') {
6404: return unless ($env{'request.course.id'});
6405: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6406: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6407: }
6408: my %commblocks;
6409: my $hashid=$cdom.'_'.$cnum;
6410: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
6411: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
6412: %commblocks = %{$blocksref};
6413: } else {
6414: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
6415: my $cachetime = 600;
6416: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
6417: }
6418: return %commblocks;
6419: }
6420:
6421: sub has_comm_blocking {
6422: my ($priv,$symb,$uri,$blocks) = @_;
6423: return unless ($env{'request.course.id'});
6424: return unless ($priv eq 'bre');
6425: return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
6426: my %commblocks;
6427: if (ref($blocks) eq 'HASH') {
6428: %commblocks = %{$blocks};
6429: } else {
6430: %commblocks = &get_comm_blocks();
6431: }
6432: return unless (keys(%commblocks) > 0);
6433: if (!$symb) { $symb=&symbread($uri,1); }
6434: my ($map,$resid,undef)=&decode_symb($symb);
6435: my %tocheck = (
6436: maps => $map,
6437: resources => $symb,
6438: );
6439: my @blockers;
6440: my $now = time;
1.1163 raeburn 6441: my $navmap = Apache::lonnavmaps::navmap->new();
1.1162 raeburn 6442: foreach my $block (keys(%commblocks)) {
6443: if ($block =~ /^(\d+)____(\d+)$/) {
6444: my ($start,$end) = ($1,$2);
6445: if ($start <= $now && $end >= $now) {
6446: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
6447: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
6448: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
6449: if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
6450: unless (grep(/^\Q$block\E$/,@blockers)) {
6451: push(@blockers,$block);
6452: }
6453: }
6454: }
6455: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
6456: if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
6457: unless (grep(/^\Q$block\E$/,@blockers)) {
6458: push(@blockers,$block);
6459: }
6460: }
6461: }
6462: }
6463: }
6464: }
6465: } elsif ($block =~ /^firstaccess____(.+)$/) {
6466: my $item = $1;
1.1163 raeburn 6467: my @to_test;
1.1162 raeburn 6468: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
6469: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
6470: my $check_interval;
6471: if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
6472: my @interval;
6473: my $type = 'map';
6474: if ($item eq 'course') {
6475: $type = 'course';
6476: @interval=&EXT("resource.0.interval");
6477: } else {
6478: if ($item =~ /___\d+___/) {
6479: $type = 'resource';
6480: @interval=&EXT("resource.0.interval",$item);
1.1163 raeburn 6481: if (ref($navmap)) {
6482: my $res = $navmap->getBySymb($item);
6483: push(@to_test,$res);
6484: }
1.1162 raeburn 6485: } else {
6486: my $mapsymb = &symbread($item,1);
6487: if ($mapsymb) {
6488: if (ref($navmap)) {
6489: my $mapres = $navmap->getBySymb($mapsymb);
1.1163 raeburn 6490: @to_test = $mapres->retrieveResources($mapres,undef,0,1);
6491: foreach my $res (@to_test) {
1.1162 raeburn 6492: my $symb = $res->symb();
6493: next if ($symb eq $mapsymb);
6494: if ($symb ne '') {
6495: @interval=&EXT("resource.0.interval",$symb);
6496: last;
6497: }
6498: }
6499: }
6500: }
6501: }
6502: }
6503: if ($interval[0] =~ /\d+/) {
6504: my $first_access;
6505: if ($type eq 'resource') {
6506: $first_access=&get_first_access($interval[1],$item);
6507: } elsif ($type eq 'map') {
6508: $first_access=&get_first_access($interval[1],undef,$item);
6509: } else {
6510: $first_access=&get_first_access($interval[1]);
6511: }
6512: if ($first_access) {
6513: my $timesup = $first_access+$interval[0];
6514: if ($timesup > $now) {
1.1163 raeburn 6515: foreach my $res (@to_test) {
6516: if ($res->is_problem()) {
6517: if ($res->completable()) {
6518: unless (grep(/^\Q$block\E$/,@blockers)) {
6519: push(@blockers,$block);
6520: }
6521: last;
6522: }
6523: }
1.1162 raeburn 6524: }
6525: }
6526: }
6527: }
6528: }
6529: }
6530: }
6531: }
6532: }
6533: return @blockers;
6534: }
6535:
6536: sub check_docs_block {
6537: my ($docsblock,$tocheck) =@_;
6538: if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
6539: return;
6540: }
6541: if (ref($docsblock->{'maps'}) eq 'HASH') {
6542: if ($tocheck->{'maps'}) {
6543: if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
6544: return 1;
6545: }
6546: }
6547: }
6548: if (ref($docsblock->{'resources'}) eq 'HASH') {
6549: if ($tocheck->{'resources'}) {
6550: if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
6551: return 1;
6552: }
6553: }
6554: }
6555: return;
6556: }
6557:
1.1133 foxr 6558: #
6559: # Removes the versino from a URI and
6560: # splits it in to its filename and path to the filename.
6561: # Seems like File::Basename could have done this more clearly.
6562: # Parameters:
6563: # $uri - input URI
6564: # Returns:
6565: # Two element list consisting of
6566: # $pathname - the URI up to and excluding the trailing /
6567: # $filename - The part of the URI following the last /
6568: # NOTE:
6569: # Another realization of this is simply:
6570: # use File::Basename;
6571: # ...
6572: # $uri = shift;
6573: # $filename = basename($uri);
6574: # $path = dirname($uri);
6575: # return ($filename, $path);
6576: #
6577: # The implementation below is probably faster however.
6578: #
1.710 albertel 6579: sub split_uri_for_cond {
6580: my $uri=&deversion(&declutter(shift));
6581: my @uriparts=split(/\//,$uri);
6582: my $filename=pop(@uriparts);
6583: my $pathname=join('/',@uriparts);
6584: return ($pathname,$filename);
6585: }
1.232 www 6586: # --------------------------------------------------- Is a resource on the map?
6587:
6588: sub is_on_map {
1.710 albertel 6589: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 6590: #Trying to find the conditional for the file
1.620 albertel 6591: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 6592: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 6593: if ($match) {
1.289 bowersj2 6594: return (1,$1);
6595: } else {
1.434 www 6596: return (0,0);
1.289 bowersj2 6597: }
1.12 www 6598: }
6599:
1.427 www 6600: # --------------------------------------------------------- Get symb from alias
6601:
6602: sub get_symb_from_alias {
6603: my $symb=shift;
6604: my ($map,$resid,$url)=&decode_symb($symb);
6605: # Already is a symb
6606: if ($url) { return $symb; }
6607: # Must be an alias
6608: my $aliassymb='';
6609: my %bighash;
1.620 albertel 6610: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 6611: &GDBM_READER(),0640)) {
6612: my $rid=$bighash{'mapalias_'.$symb};
6613: if ($rid) {
6614: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 6615: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
6616: $resid,$bighash{'src_'.$rid});
1.427 www 6617: }
6618: untie %bighash;
6619: }
6620: return $aliassymb;
6621: }
6622:
1.12 www 6623: # ----------------------------------------------------------------- Define Role
6624:
6625: sub definerole {
6626: if (allowed('mcr','/')) {
6627: my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800 albertel 6628: foreach my $role (split(':',$sysrole)) {
6629: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 6630: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
6631: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
6632: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 6633: return "refused:s:$crole&$cqual";
6634: }
6635: }
1.191 harris41 6636: }
1.800 albertel 6637: foreach my $role (split(':',$domrole)) {
6638: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 6639: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
6640: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
6641: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 6642: return "refused:d:$crole&$cqual";
6643: }
6644: }
1.191 harris41 6645: }
1.800 albertel 6646: foreach my $role (split(':',$courole)) {
6647: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 6648: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
6649: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
6650: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 6651: return "refused:c:$crole&$cqual";
6652: }
6653: }
1.191 harris41 6654: }
1.620 albertel 6655: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
6656: "$env{'user.domain'}:$env{'user.name'}:".
1.21 www 6657: "rolesdef_$rolename=".
6658: escape($sysrole.'_'.$domrole.'_'.$courole);
1.620 albertel 6659: return reply($command,$env{'user.home'});
1.12 www 6660: } else {
6661: return 'refused';
6662: }
1.105 harris41 6663: }
6664:
6665: # ---------------- Make a metadata query against the network of library servers
6666:
6667: sub metadata_query {
1.244 matthew 6668: my ($query,$custom,$customshow,$server_array)=@_;
1.120 harris41 6669: my %rhash;
1.845 albertel 6670: my %libserv = &all_library();
1.244 matthew 6671: my @server_list = (defined($server_array) ? @$server_array
6672: : keys(%libserv) );
6673: for my $server (@server_list) {
1.118 harris41 6674: unless ($custom or $customshow) {
6675: my $reply=&reply("querysend:".&escape($query),$server);
6676: $rhash{$server}=$reply;
6677: }
6678: else {
6679: my $reply=&reply("querysend:".&escape($query).':'.
6680: &escape($custom).':'.&escape($customshow),
6681: $server);
6682: $rhash{$server}=$reply;
6683: }
1.112 harris41 6684: }
1.118 harris41 6685: return \%rhash;
1.240 www 6686: }
6687:
6688: # ----------------------------------------- Send log queries and wait for reply
6689:
6690: sub log_query {
6691: my ($uname,$udom,$query,%filters)=@_;
6692: my $uhome=&homeserver($uname,$udom);
6693: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 6694: my $uhost=&hostname($uhome);
1.800 albertel 6695: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 6696: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
6697: $uhome);
1.479 albertel 6698: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 6699: return get_query_reply($queryid);
6700: }
6701:
1.818 raeburn 6702: # -------------------------- Update MySQL table for portfolio file
6703:
6704: sub update_portfolio_table {
1.821 raeburn 6705: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 6706: if ($group ne '') {
6707: $file_name =~s /^\Q$group\E//;
6708: }
1.818 raeburn 6709: my $homeserver = &homeserver($uname,$udom);
6710: my $queryid=
1.821 raeburn 6711: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
6712: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 6713: my $reply = &get_query_reply($queryid);
6714: return $reply;
6715: }
6716:
1.899 raeburn 6717: # -------------------------- Update MySQL allusers table
6718:
6719: sub update_allusers_table {
6720: my ($uname,$udom,$names) = @_;
6721: my $homeserver = &homeserver($uname,$udom);
6722: my $queryid=
6723: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
6724: 'lastname='.&escape($names->{'lastname'}).'%%'.
6725: 'firstname='.&escape($names->{'firstname'}).'%%'.
6726: 'middlename='.&escape($names->{'middlename'}).'%%'.
6727: 'generation='.&escape($names->{'generation'}).'%%'.
6728: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
6729: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 6730: return;
1.899 raeburn 6731: }
6732:
1.508 raeburn 6733: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 6734:
6735: sub fetch_enrollment_query {
1.511 raeburn 6736: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508 raeburn 6737: my $homeserver;
1.547 raeburn 6738: my $maxtries = 1;
1.508 raeburn 6739: if ($context eq 'automated') {
6740: $homeserver = $perlvar{'lonHostID'};
1.547 raeburn 6741: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 6742: } else {
6743: $homeserver = &homeserver($cnum,$dom);
6744: }
1.838 albertel 6745: my $host=&hostname($homeserver);
1.506 raeburn 6746: my $cmd = '';
1.1000 raeburn 6747: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 6748: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 6749: }
6750: $cmd =~ s/%%$//;
6751: $cmd = &escape($cmd);
6752: my $query = 'fetchenrollment';
1.620 albertel 6753: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 6754: unless ($queryid=~/^\Q$host\E\_/) {
6755: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
6756: return 'error: '.$queryid;
6757: }
1.506 raeburn 6758: my $reply = &get_query_reply($queryid);
1.547 raeburn 6759: my $tries = 1;
6760: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
6761: $reply = &get_query_reply($queryid);
6762: $tries ++;
6763: }
1.526 raeburn 6764: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 6765: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 6766: } else {
1.901 albertel 6767: my @responses = split(/:/,$reply);
1.515 raeburn 6768: if ($homeserver eq $perlvar{'lonHostID'}) {
1.800 albertel 6769: foreach my $line (@responses) {
6770: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 6771: $$replyref{$key} = $value;
6772: }
6773: } else {
1.1117 foxr 6774: my $pathname = LONCAPA::tempdir();
1.800 albertel 6775: foreach my $line (@responses) {
6776: my ($key,$value) = split(/=/,$line);
1.506 raeburn 6777: $$replyref{$key} = $value;
6778: if ($value > 0) {
1.800 albertel 6779: foreach my $item (@{$$affiliatesref{$key}}) {
6780: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 6781: my $destname = $pathname.'/'.$filename;
6782: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 6783: if ($xml_classlist =~ /^error/) {
6784: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
6785: } else {
1.506 raeburn 6786: if ( open(FILE,">$destname") ) {
6787: print FILE &unescape($xml_classlist);
6788: close(FILE);
1.526 raeburn 6789: } else {
6790: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 6791: }
6792: }
6793: }
6794: }
6795: }
6796: }
6797: return 'ok';
6798: }
6799: return 'error';
6800: }
6801:
1.242 www 6802: sub get_query_reply {
6803: my $queryid=shift;
1.1117 foxr 6804: my $replyfile=LONCAPA::tempdir().$queryid;
1.240 www 6805: my $reply='';
6806: for (1..100) {
6807: sleep 2;
6808: if (-e $replyfile.'.end') {
1.448 albertel 6809: if (open(my $fh,$replyfile)) {
1.904 albertel 6810: $reply = join('',<$fh>);
6811: close($fh);
1.240 www 6812: } else { return 'error: reply_file_error'; }
1.242 www 6813: return &unescape($reply);
6814: }
1.240 www 6815: }
1.242 www 6816: return 'timeout:'.$queryid;
1.240 www 6817: }
6818:
6819: sub courselog_query {
1.241 www 6820: #
6821: # possible filters:
6822: # url: url or symb
6823: # username
6824: # domain
6825: # action: view, submit, grade
6826: # start: timestamp
6827: # end: timestamp
6828: #
1.240 www 6829: my (%filters)=@_;
1.620 albertel 6830: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 6831: if ($filters{'url'}) {
6832: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
6833: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
6834: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
6835: }
1.620 albertel 6836: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
6837: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 6838: return &log_query($cname,$cdom,'courselog',%filters);
6839: }
6840:
6841: sub userlog_query {
1.858 raeburn 6842: #
6843: # possible filters:
6844: # action: log check role
6845: # start: timestamp
6846: # end: timestamp
6847: #
1.240 www 6848: my ($uname,$udom,%filters)=@_;
6849: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 6850: }
6851:
1.506 raeburn 6852: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
6853:
6854: sub auto_run {
1.508 raeburn 6855: my ($cnum,$cdom) = @_;
1.876 raeburn 6856: my $response = 0;
6857: my $settings;
6858: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
6859: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
6860: $settings = $domconfig{'autoenroll'};
6861: if ($settings->{'run'} eq '1') {
6862: $response = 1;
6863: }
6864: } else {
1.934 raeburn 6865: my $homeserver;
6866: if (&is_course($cdom,$cnum)) {
6867: $homeserver = &homeserver($cnum,$cdom);
6868: } else {
6869: $homeserver = &domain($cdom,'primary');
6870: }
6871: if ($homeserver ne 'no_host') {
6872: $response = &reply('autorun:'.$cdom,$homeserver);
6873: }
1.876 raeburn 6874: }
1.506 raeburn 6875: return $response;
6876: }
1.776 albertel 6877:
1.506 raeburn 6878: sub auto_get_sections {
1.508 raeburn 6879: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 6880: my $homeserver;
6881: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6882: $homeserver = &homeserver($cnum,$cdom);
6883: }
6884: if (!defined($homeserver)) {
6885: if ($cdom =~ /^$match_domain$/) {
6886: $homeserver = &domain($cdom,'primary');
6887: }
6888: }
6889: my @secs;
6890: if (defined($homeserver)) {
6891: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
6892: unless ($response eq 'refused') {
6893: @secs = split(/:/,$response);
6894: }
1.506 raeburn 6895: }
6896: return @secs;
6897: }
1.776 albertel 6898:
1.506 raeburn 6899: sub auto_new_course {
1.1099 raeburn 6900: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 6901: my $homeserver = &homeserver($cnum,$cdom);
1.1099 raeburn 6902: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 6903: return $response;
6904: }
1.776 albertel 6905:
1.506 raeburn 6906: sub auto_validate_courseID {
1.508 raeburn 6907: my ($cnum,$cdom,$inst_course_id) = @_;
6908: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 6909: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 6910: return $response;
6911: }
1.776 albertel 6912:
1.1007 raeburn 6913: sub auto_validate_instcode {
1.1020 raeburn 6914: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 6915: my ($homeserver,$response);
6916: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6917: $homeserver = &homeserver($cnum,$cdom);
6918: }
6919: if (!defined($homeserver)) {
6920: if ($cdom =~ /^$match_domain$/) {
6921: $homeserver = &domain($cdom,'primary');
6922: }
6923: }
1.1065 raeburn 6924: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
6925: &escape($instcode).':'.&escape($owner),$homeserver));
1.1027 raeburn 6926: my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
6927: return ($outcome,$description);
1.1007 raeburn 6928: }
6929:
1.506 raeburn 6930: sub auto_create_password {
1.873 raeburn 6931: my ($cnum,$cdom,$authparam,$udom) = @_;
6932: my ($homeserver,$response);
1.506 raeburn 6933: my $create_passwd = 0;
6934: my $authchk = '';
1.873 raeburn 6935: if ($udom =~ /^$match_domain$/) {
6936: $homeserver = &domain($udom,'primary');
6937: }
6938: if ($homeserver eq '') {
6939: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6940: $homeserver = &homeserver($cnum,$cdom);
6941: }
6942: }
6943: if ($homeserver eq '') {
6944: $authchk = 'nodomain';
1.506 raeburn 6945: } else {
1.873 raeburn 6946: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
6947: if ($response eq 'refused') {
6948: $authchk = 'refused';
6949: } else {
1.901 albertel 6950: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 6951: }
1.506 raeburn 6952: }
6953: return ($authparam,$create_passwd,$authchk);
6954: }
6955:
1.706 raeburn 6956: sub auto_photo_permission {
6957: my ($cnum,$cdom,$students) = @_;
6958: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 6959: my ($outcome,$perm_reqd,$conditions) =
6960: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 6961: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6962: return (undef,undef);
6963: }
1.706 raeburn 6964: return ($outcome,$perm_reqd,$conditions);
6965: }
6966:
6967: sub auto_checkphotos {
6968: my ($uname,$udom,$pid) = @_;
6969: my $homeserver = &homeserver($uname,$udom);
6970: my ($result,$resulttype);
6971: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 6972: &escape($uname).':'.&escape($pid),
6973: $homeserver));
1.709 albertel 6974: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6975: return (undef,undef);
6976: }
1.706 raeburn 6977: if ($outcome) {
6978: ($result,$resulttype) = split(/:/,$outcome);
6979: }
6980: return ($result,$resulttype);
6981: }
6982:
6983: sub auto_photochoice {
6984: my ($cnum,$cdom) = @_;
6985: my $homeserver = &homeserver($cnum,$cdom);
6986: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 6987: &escape($cdom),
6988: $homeserver)));
1.709 albertel 6989: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6990: return (undef,undef);
6991: }
1.706 raeburn 6992: return ($update,$comment);
6993: }
6994:
6995: sub auto_photoupdate {
6996: my ($affiliatesref,$dom,$cnum,$photo) = @_;
6997: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 6998: my $host=&hostname($homeserver);
1.706 raeburn 6999: my $cmd = '';
7000: my $maxtries = 1;
1.800 albertel 7001: foreach my $affiliate (keys(%{$affiliatesref})) {
7002: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 7003: }
7004: $cmd =~ s/%%$//;
7005: $cmd = &escape($cmd);
7006: my $query = 'institutionalphotos';
7007: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
7008: unless ($queryid=~/^\Q$host\E\_/) {
7009: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
7010: return 'error: '.$queryid;
7011: }
7012: my $reply = &get_query_reply($queryid);
7013: my $tries = 1;
7014: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
7015: $reply = &get_query_reply($queryid);
7016: $tries ++;
7017: }
7018: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
7019: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
7020: } else {
7021: my @responses = split(/:/,$reply);
7022: my $outcome = shift(@responses);
7023: foreach my $item (@responses) {
7024: my ($key,$value) = split(/=/,$item);
7025: $$photo{$key} = $value;
7026: }
7027: return $outcome;
7028: }
7029: return 'error';
7030: }
7031:
1.521 raeburn 7032: sub auto_instcode_format {
1.793 albertel 7033: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
7034: $cat_order) = @_;
1.521 raeburn 7035: my $courses = '';
1.772 raeburn 7036: my @homeservers;
1.521 raeburn 7037: if ($caller eq 'global') {
1.841 albertel 7038: my %servers = &get_servers($codedom,'library');
7039: foreach my $tryserver (keys(%servers)) {
7040: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7041: push(@homeservers,$tryserver);
7042: }
1.584 raeburn 7043: }
1.1022 raeburn 7044: } elsif ($caller eq 'requests') {
7045: if ($codedom =~ /^$match_domain$/) {
7046: my $chome = &domain($codedom,'primary');
7047: unless ($chome eq 'no_host') {
7048: push(@homeservers,$chome);
7049: }
7050: }
1.521 raeburn 7051: } else {
1.772 raeburn 7052: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 7053: }
1.793 albertel 7054: foreach my $code (keys(%{$instcodes})) {
7055: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 7056: }
7057: chop($courses);
1.772 raeburn 7058: my $ok_response = 0;
7059: my $response;
7060: while (@homeservers > 0 && $ok_response == 0) {
7061: my $server = shift(@homeservers);
7062: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
7063: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
7064: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 7065: split(/:/,$response);
1.772 raeburn 7066: %{$codes} = (%{$codes},&str2hash($codes_str));
7067: push(@{$codetitles},&str2array($codetitles_str));
7068: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
7069: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
7070: $ok_response = 1;
7071: }
7072: }
7073: if ($ok_response) {
1.521 raeburn 7074: return 'ok';
1.772 raeburn 7075: } else {
7076: return $response;
1.521 raeburn 7077: }
7078: }
7079:
1.792 raeburn 7080: sub auto_instcode_defaults {
7081: my ($domain,$returnhash,$code_order) = @_;
7082: my @homeservers;
1.841 albertel 7083:
7084: my %servers = &get_servers($domain,'library');
7085: foreach my $tryserver (keys(%servers)) {
7086: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7087: push(@homeservers,$tryserver);
7088: }
1.792 raeburn 7089: }
1.841 albertel 7090:
1.792 raeburn 7091: my $response;
1.841 albertel 7092: foreach my $server (@homeservers) {
1.792 raeburn 7093: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 7094: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
7095:
7096: foreach my $pair (split(/\&/,$response)) {
7097: my ($name,$value)=split(/\=/,$pair);
7098: if ($name eq 'code_order') {
7099: @{$code_order} = split(/\&/,&unescape($value));
7100: } else {
7101: $returnhash->{&unescape($name)}=&unescape($value);
7102: }
7103: }
7104: return 'ok';
1.792 raeburn 7105: }
1.841 albertel 7106:
7107: return $response;
1.1003 raeburn 7108: }
7109:
7110: sub auto_possible_instcodes {
1.1007 raeburn 7111: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
7112: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
7113: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
7114: return;
7115: }
1.1003 raeburn 7116: my (@homeservers,$uhome);
7117: if (defined(&domain($domain,'primary'))) {
7118: $uhome=&domain($domain,'primary');
7119: push(@homeservers,&domain($domain,'primary'));
7120: } else {
7121: my %servers = &get_servers($domain,'library');
7122: foreach my $tryserver (keys(%servers)) {
7123: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7124: push(@homeservers,$tryserver);
7125: }
7126: }
7127: }
7128: my $response;
7129: foreach my $server (@homeservers) {
7130: $response=&reply('autopossibleinstcodes:'.$domain,$server);
7131: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 7132: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
7133: split(':',$response);
7134: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
7135: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 7136: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 7137: my ($name,$value)=split('=',$item);
7138: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 7139: }
7140: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 7141: my ($name,$value)=split('=',$item);
7142: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 7143: }
7144: return 'ok';
7145: }
7146: return $response;
7147: }
1.792 raeburn 7148:
1.1010 raeburn 7149: sub auto_courserequest_checks {
7150: my ($dom) = @_;
1.1020 raeburn 7151: my ($homeserver,%validations);
7152: if ($dom =~ /^$match_domain$/) {
7153: $homeserver = &domain($dom,'primary');
7154: }
7155: unless ($homeserver eq 'no_host') {
7156: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
7157: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
7158: my @items = split(/&/,$response);
7159: foreach my $item (@items) {
7160: my ($key,$value) = split('=',$item);
7161: $validations{&unescape($key)} = &thaw_unescape($value);
7162: }
7163: }
7164: }
1.1010 raeburn 7165: return %validations;
7166: }
7167:
1.1020 raeburn 7168: sub auto_courserequest_validation {
7169: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
7170: my ($homeserver,$response);
7171: if ($dom =~ /^$match_domain$/) {
7172: $homeserver = &domain($dom,'primary');
7173: }
7174: unless ($homeserver eq 'no_host') {
1.1021 raeburn 7175:
1.1020 raeburn 7176: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 7177: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020 raeburn 7178: ':'.&escape($instcode).':'.&escape($instseclist),
7179: $homeserver));
7180: }
7181: return $response;
7182: }
7183:
1.777 albertel 7184: sub auto_validate_class_sec {
1.918 raeburn 7185: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 7186: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 7187: my $ownerlist;
7188: if (ref($owners) eq 'ARRAY') {
7189: $ownerlist = join(',',@{$owners});
7190: } else {
7191: $ownerlist = $owners;
7192: }
1.773 raeburn 7193: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 7194: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 7195: return $response;
7196: }
7197:
1.679 raeburn 7198: # ------------------------------------------------------- Course Group routines
7199:
7200: sub get_coursegroups {
1.809 raeburn 7201: my ($cdom,$cnum,$group,$namespace) = @_;
7202: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 7203: }
7204:
1.679 raeburn 7205: sub modify_coursegroup {
7206: my ($cdom,$cnum,$groupsettings) = @_;
7207: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
7208: }
7209:
1.809 raeburn 7210: sub toggle_coursegroup_status {
7211: my ($cdom,$cnum,$group,$action) = @_;
7212: my ($from_namespace,$to_namespace);
7213: if ($action eq 'delete') {
7214: $from_namespace = 'coursegroups';
7215: $to_namespace = 'deleted_groups';
7216: } else {
7217: $from_namespace = 'deleted_groups';
7218: $to_namespace = 'coursegroups';
7219: }
7220: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 7221: if (my $tmp = &error(%curr_group)) {
7222: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
7223: return ('read error',$tmp);
7224: } else {
7225: my %savedsettings = %curr_group;
1.809 raeburn 7226: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 7227: my $deloutcome;
7228: if ($result eq 'ok') {
1.809 raeburn 7229: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 7230: } else {
7231: return ('write error',$result);
7232: }
7233: if ($deloutcome eq 'ok') {
7234: return 'ok';
7235: } else {
7236: return ('delete error',$deloutcome);
7237: }
7238: }
7239: }
7240:
1.679 raeburn 7241: sub modify_group_roles {
1.957 raeburn 7242: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 7243: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
7244: my $role = 'gr/'.&escape($userprivs);
7245: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 7246: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 7247: if ($result eq 'ok') {
7248: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
7249: }
1.679 raeburn 7250: return $result;
7251: }
7252:
7253: sub modify_coursegroup_membership {
7254: my ($cdom,$cnum,$membership) = @_;
7255: my $result = &put('groupmembership',$membership,$cdom,$cnum);
7256: return $result;
7257: }
7258:
1.682 raeburn 7259: sub get_active_groups {
7260: my ($udom,$uname,$cdom,$cnum) = @_;
7261: my $now = time;
7262: my %groups = ();
7263: foreach my $key (keys(%env)) {
1.811 albertel 7264: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 7265: my ($start,$end) = split(/\./,$env{$key});
7266: if (($end!=0) && ($end<$now)) { next; }
7267: if (($start!=0) && ($start>$now)) { next; }
7268: if ($1 eq $cdom && $2 eq $cnum) {
7269: $groups{$3} = $env{$key} ;
7270: }
7271: }
7272: }
7273: return %groups;
7274: }
7275:
1.683 raeburn 7276: sub get_group_membership {
7277: my ($cdom,$cnum,$group) = @_;
7278: return(&dump('groupmembership',$cdom,$cnum,$group));
7279: }
7280:
7281: sub get_users_groups {
7282: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 7283: my @usersgroups;
1.683 raeburn 7284: my $cachetime=1800;
7285:
7286: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 7287: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
7288: if (defined($cached)) {
1.734 albertel 7289: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 7290: } else {
7291: $grouplist = '';
1.816 raeburn 7292: my $courseurl = &courseid_to_courseurl($courseid);
1.1166 raeburn 7293: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 7294: my $access_end = $env{'course.'.$courseid.
7295: '.default_enrollment_end_date'};
7296: my $now = time;
7297: foreach my $key (keys(%roleshash)) {
7298: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
7299: my $group = $1;
7300: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
7301: my $start = $2;
7302: my $end = $1;
7303: if ($start == -1) { next; } # deleted from group
7304: if (($start!=0) && ($start>$now)) { next; }
7305: if (($end!=0) && ($end<$now)) {
7306: if ($access_end && $access_end < $now) {
7307: if ($access_end - $end < 86400) {
7308: push(@usersgroups,$group);
1.733 raeburn 7309: }
7310: }
1.817 raeburn 7311: next;
1.733 raeburn 7312: }
1.817 raeburn 7313: push(@usersgroups,$group);
1.683 raeburn 7314: }
7315: }
7316: }
1.817 raeburn 7317: @usersgroups = &sort_course_groups($courseid,@usersgroups);
7318: $grouplist = join(':',@usersgroups);
7319: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 7320: }
1.733 raeburn 7321: return @usersgroups;
1.683 raeburn 7322: }
7323:
7324: sub devalidate_getgroups_cache {
7325: my ($udom,$uname,$cdom,$cnum)=@_;
7326: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 7327:
1.683 raeburn 7328: my $hashid="$udom:$uname:$courseid";
7329: &devalidate_cache_new('getgroups',$hashid);
7330: }
7331:
1.12 www 7332: # ------------------------------------------------------------------ Plain Text
7333:
7334: sub plaintext {
1.988 raeburn 7335: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 7336: if ($short =~ m{^cr/}) {
1.758 albertel 7337: return (split('/',$short))[-1];
7338: }
1.742 raeburn 7339: if (!defined($cid)) {
7340: $cid = $env{'request.course.id'};
7341: }
7342: my %rolenames = (
1.1008 raeburn 7343: Course => 'std',
7344: Community => 'alt1',
1.742 raeburn 7345: );
1.1037 raeburn 7346: if ($cid ne '') {
7347: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
7348: unless ($forcedefault) {
7349: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
7350: &Apache::lonlocal::mt_escape(\$roletext);
7351: return &Apache::lonlocal::mt($roletext);
7352: }
7353: }
7354: }
7355: if ((defined($type)) && (defined($rolenames{$type})) &&
7356: (defined($rolenames{$type})) &&
7357: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 7358: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 7359: } elsif ($cid ne '') {
7360: my $crstype = $env{'course.'.$cid.'.type'};
7361: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
7362: (defined($prp{$short}{$rolenames{$crstype}}))) {
7363: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
7364: }
1.742 raeburn 7365: }
1.1037 raeburn 7366: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 7367: }
7368:
7369: # ----------------------------------------------------------------- Assign Role
7370:
7371: sub assignrole {
1.957 raeburn 7372: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
7373: $context)=@_;
1.21 www 7374: my $mrole;
7375: if ($role =~ /^cr\//) {
1.393 www 7376: my $cwosec=$url;
1.811 albertel 7377: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 7378: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 7379: my $refused = 1;
7380: if ($context eq 'requestcourses') {
7381: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
7382: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
7383: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
7384: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
7385: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
7386: if ($crsenv{'internal.courseowner'} eq
7387: $env{'user.name'}.':'.$env{'user.domain'}) {
7388: $refused = '';
7389: }
7390: }
7391: }
7392: }
7393: }
7394: if ($refused) {
7395: &logthis('Refused custom assignrole: '.
7396: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
7397: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
7398: return 'refused';
7399: }
1.104 www 7400: }
1.21 www 7401: $mrole='cr';
1.678 raeburn 7402: } elsif ($role =~ /^gr\//) {
7403: my $cwogrp=$url;
1.811 albertel 7404: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 7405: unless (&allowed('mdg',$cwogrp)) {
7406: &logthis('Refused group assignrole: '.
7407: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
7408: $env{'user.name'}.' at '.$env{'user.domain'});
7409: return 'refused';
7410: }
7411: $mrole='gr';
1.21 www 7412: } else {
1.82 www 7413: my $cwosec=$url;
1.811 albertel 7414: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 7415: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
7416: my $refused;
7417: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
7418: if (!(&allowed('c'.$role,$url))) {
7419: $refused = 1;
7420: }
7421: } else {
7422: $refused = 1;
7423: }
1.947 raeburn 7424: if ($refused) {
1.1045 raeburn 7425: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
7426: if (!$selfenroll && $context eq 'course') {
7427: my %crsenv;
7428: if ($role eq 'cc' || $role eq 'co') {
7429: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
7430: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
7431: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
7432: if ($crsenv{'internal.courseowner'} eq
7433: $env{'user.name'}.':'.$env{'user.domain'}) {
7434: $refused = '';
7435: }
7436: }
7437: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
7438: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
7439: if ($crsenv{'internal.courseowner'} eq
7440: $env{'user.name'}.':'.$env{'user.domain'}) {
7441: $refused = '';
7442: }
7443: }
7444: }
7445: }
7446: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 7447: $refused = '';
1.1017 raeburn 7448: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 7449: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 7450: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 7451: my $wrongcc;
7452: if ($cnum =~ /^$match_community$/) {
7453: $wrongcc = 1 if ($role eq 'cc');
7454: } else {
7455: $wrongcc = 1 if ($role eq 'co');
7456: }
7457: unless ($wrongcc) {
7458: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
7459: if ($crsenv{'internal.courseowner'} eq
7460: $env{'user.name'}.':'.$env{'user.domain'}) {
7461: $refused = '';
7462: }
1.1017 raeburn 7463: }
7464: }
7465: }
7466: if ($refused) {
1.947 raeburn 7467: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
7468: ' '.$role.' '.$end.' '.$start.' by '.
7469: $env{'user.name'}.' at '.$env{'user.domain'});
7470: return 'refused';
7471: }
1.932 raeburn 7472: }
1.1131 raeburn 7473: } elsif ($role eq 'au') {
7474: if ($url ne '/'.$udom.'/') {
7475: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
7476: ' to assign author role for '.$uname.':'.$udom.
7477: ' in domain: '.$url.' refused (wrong domain).');
7478: return 'refused';
7479: }
1.104 www 7480: }
1.21 www 7481: $mrole=$role;
7482: }
1.620 albertel 7483: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 7484: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 7485: if ($end) { $command.='_'.$end; }
1.21 www 7486: if ($start) {
7487: if ($end) {
1.81 www 7488: $command.='_'.$start;
1.21 www 7489: } else {
1.81 www 7490: $command.='_0_'.$start;
1.21 www 7491: }
7492: }
1.739 raeburn 7493: my $origstart = $start;
7494: my $origend = $end;
1.957 raeburn 7495: my $delflag;
1.357 www 7496: # actually delete
7497: if ($deleteflag) {
1.373 www 7498: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 7499: # modify command to delete the role
1.620 albertel 7500: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 7501: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 7502: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 7503: # set start and finish to negative values for userrolelog
7504: $start=-1;
7505: $end=-1;
1.957 raeburn 7506: $delflag = 1;
1.357 www 7507: }
7508: }
7509: # send command
1.349 www 7510: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 7511: # log new user role if status is ok
1.349 www 7512: if ($answer eq 'ok') {
1.663 raeburn 7513: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.739 raeburn 7514: # for course roles, perform group memberships changes triggered by role change.
1.957 raeburn 7515: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739 raeburn 7516: unless ($role =~ /^gr/) {
7517: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957 raeburn 7518: $origstart,$selfenroll,$context);
1.739 raeburn 7519: }
1.1053 raeburn 7520: if ($role eq 'cc') {
7521: &autoupdate_coowners($url,$end,$start,$uname,$udom);
7522: }
1.349 www 7523: }
7524: return $answer;
1.169 harris41 7525: }
7526:
1.1053 raeburn 7527: sub autoupdate_coowners {
7528: my ($url,$end,$start,$uname,$udom) = @_;
7529: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
7530: if (($cdom ne '') && ($cnum ne '')) {
7531: my $now = time;
7532: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
7533: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
7534: my %coursehash = &coursedescription($cdom.'_'.$cnum);
7535: my $instcode = $coursehash{'internal.coursecode'};
7536: if ($instcode ne '') {
1.1056 raeburn 7537: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
7538: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 7539: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 7540: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
7541: if ($result eq 'valid') {
7542: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 7543: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
7544: push(@newcoowners,$coowner);
7545: }
7546: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
7547: push(@newcoowners,$uname.':'.$udom);
7548: }
7549: @newcoowners = sort(@newcoowners);
7550: } else {
7551: push(@newcoowners,$uname.':'.$udom);
7552: }
7553: } else {
7554: if ($coursehash{'internal.co-owners'}) {
7555: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
7556: unless ($coowner eq $uname.':'.$udom) {
7557: push(@newcoowners,$coowner);
7558: }
7559: }
7560: unless (@newcoowners > 0) {
7561: $delcoowners = 1;
7562: $coowners = '';
7563: }
7564: }
7565: }
7566: if (@newcoowners || $delcoowners) {
7567: &store_coowners($cdom,$cnum,$coursehash{'home'},
7568: $delcoowners,@newcoowners);
7569: }
7570: }
7571: }
7572: }
7573: }
7574: }
7575: }
7576:
7577: sub store_coowners {
7578: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
7579: my $cid = $cdom.'_'.$cnum;
7580: my ($coowners,$delresult,$putresult);
7581: if (@newcoowners) {
7582: $coowners = join(',',@newcoowners);
7583: my %coownershash = (
7584: 'internal.co-owners' => $coowners,
7585: );
7586: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
7587: if ($putresult eq 'ok') {
7588: if ($env{'course.'.$cid.'.num'} eq $cnum) {
7589: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
7590: }
7591: }
7592: }
7593: if ($delcoowners) {
7594: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
7595: if ($delresult eq 'ok') {
7596: if ($env{'course.'.$cid.'.internal.co-owners'}) {
7597: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
7598: }
7599: }
7600: }
7601: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
7602: my %crsinfo =
7603: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
7604: if (ref($crsinfo{$cid}) eq 'HASH') {
7605: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
7606: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
7607: }
7608: }
7609: }
7610:
1.169 harris41 7611: # -------------------------------------------------- Modify user authentication
1.197 www 7612: # Overrides without validation
7613:
1.169 harris41 7614: sub modifyuserauth {
7615: my ($udom,$uname,$umode,$upass)=@_;
7616: my $uhome=&homeserver($uname,$udom);
1.197 www 7617: unless (&allowed('mau',$udom)) { return 'refused'; }
7618: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 7619: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
7620: ' in domain '.$env{'request.role.domain'});
1.169 harris41 7621: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
7622: &escape($upass),$uhome);
1.620 albertel 7623: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 7624: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
7625: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
7626: &log($udom,,$uname,$uhome,
1.620 albertel 7627: 'Authentication changed by '.$env{'user.domain'}.', '.
7628: $env{'user.name'}.', '.$umode.
1.197 www 7629: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 7630: unless ($reply eq 'ok') {
1.197 www 7631: &logthis('Authentication mode error: '.$reply);
1.169 harris41 7632: return 'error: '.$reply;
7633: }
1.170 harris41 7634: return 'ok';
1.80 www 7635: }
7636:
1.81 www 7637: # --------------------------------------------------------------- Modify a user
1.80 www 7638:
1.81 www 7639: sub modifyuser {
1.206 matthew 7640: my ($udom, $uname, $uid,
7641: $umode, $upass, $first,
7642: $middle, $last, $gene,
1.1058 raeburn 7643: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 7644: $udom= &LONCAPA::clean_domain($udom);
7645: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 7646: my $showcandelete = 'none';
7647: if (ref($candelete) eq 'ARRAY') {
7648: if (@{$candelete} > 0) {
7649: $showcandelete = join(', ',@{$candelete});
7650: }
7651: }
1.81 www 7652: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 7653: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 7654: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 7655: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
7656: ' desiredhome not specified').
1.620 albertel 7657: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
7658: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 7659: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 7660: my $newuser;
7661: if ($uhome eq 'no_host') {
7662: $newuser = 1;
7663: }
1.80 www 7664: # ----------------------------------------------------------------- Create User
1.406 albertel 7665: if (($uhome eq 'no_host') &&
7666: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 7667: my $unhome='';
1.844 albertel 7668: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 7669: $unhome = $desiredhome;
1.620 albertel 7670: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
7671: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 7672: } else { # load balancing routine for determining $unhome
1.81 www 7673: my $loadm=10000000;
1.841 albertel 7674: my %servers = &get_servers($udom,'library');
7675: foreach my $tryserver (keys(%servers)) {
7676: my $answer=reply('load',$tryserver);
7677: if (($answer=~/\d+/) && ($answer<$loadm)) {
7678: $loadm=$answer;
7679: $unhome=$tryserver;
7680: }
1.80 www 7681: }
7682: }
7683: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 7684: return 'error: unable to find a home server for '.$uname.
7685: ' in domain '.$udom;
1.80 www 7686: }
7687: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
7688: &escape($upass),$unhome);
7689: unless ($reply eq 'ok') {
7690: return 'error: '.$reply;
7691: }
1.230 stredwic 7692: $uhome=&homeserver($uname,$udom,'true');
1.80 www 7693: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 7694: return 'error: unable verify users home machine.';
1.80 www 7695: }
1.209 matthew 7696: } # End of creation of new user
1.80 www 7697: # ---------------------------------------------------------------------- Add ID
7698: if ($uid) {
7699: $uid=~tr/A-Z/a-z/;
7700: my %uidhash=&idrget($udom,$uname);
1.196 www 7701: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
7702: && (!$forceid)) {
1.80 www 7703: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 7704: return 'error: user id "'.$uid.'" does not match '.
7705: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 7706: }
7707: } else {
7708: &idput($udom,($uname => $uid));
7709: }
7710: }
7711: # -------------------------------------------------------------- Add names, etc
1.313 matthew 7712: my @tmp=&get('environment',
1.899 raeburn 7713: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 7714: 'permanentemail','inststatus'],
1.134 albertel 7715: $udom,$uname);
1.1075 raeburn 7716: my (%names,%oldnames);
1.313 matthew 7717: if ($tmp[0] =~ m/^error:.*/) {
7718: %names=();
7719: } else {
7720: %names = @tmp;
1.1075 raeburn 7721: %oldnames = %names;
1.313 matthew 7722: }
1.388 www 7723: #
1.1058 raeburn 7724: # If name, email and/or uid are blank (e.g., because an uploaded file
7725: # of users did not contain them), do not overwrite existing values
7726: # unless field is in $candelete array ref.
7727: #
7728:
7729: my @fields = ('firstname','middlename','lastname','generation',
7730: 'permanentemail','id');
7731: my %newvalues;
7732: if (ref($candelete) eq 'ARRAY') {
7733: foreach my $field (@fields) {
7734: if (grep(/^\Q$field\E$/,@{$candelete})) {
7735: if ($field eq 'firstname') {
7736: $names{$field} = $first;
7737: } elsif ($field eq 'middlename') {
7738: $names{$field} = $middle;
7739: } elsif ($field eq 'lastname') {
7740: $names{$field} = $last;
7741: } elsif ($field eq 'generation') {
7742: $names{$field} = $gene;
7743: } elsif ($field eq 'permanentemail') {
7744: $names{$field} = $email;
7745: } elsif ($field eq 'id') {
7746: $names{$field} = $uid;
7747: }
7748: }
7749: }
7750: }
1.388 www 7751: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 7752: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 7753: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 7754: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 7755: if ($email) {
7756: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 7757: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 7758: }
1.899 raeburn 7759: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 7760: if (defined($inststatus)) {
7761: $names{'inststatus'} = '';
7762: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
7763: if (ref($usertypes) eq 'HASH') {
7764: my @okstatuses;
7765: foreach my $item (split(/:/,$inststatus)) {
7766: if (defined($usertypes->{$item})) {
7767: push(@okstatuses,$item);
7768: }
7769: }
7770: if (@okstatuses) {
7771: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
7772: }
7773: }
7774: }
1.1075 raeburn 7775: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 7776: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 7777: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 7778: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
7779: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
7780: } else {
7781: $logmsg .= ' during self creation';
7782: }
1.1075 raeburn 7783: my $changed;
7784: if ($newuser) {
7785: $changed = 1;
7786: } else {
7787: foreach my $field (@fields) {
7788: if ($names{$field} ne $oldnames{$field}) {
7789: $changed = 1;
7790: last;
7791: }
7792: }
7793: }
7794: unless ($changed) {
7795: $logmsg = 'No changes in user information needed for: '.$logmsg;
7796: &logthis($logmsg);
7797: return 'ok';
7798: }
7799: my $reply = &put('environment', \%names, $udom,$uname);
7800: if ($reply ne 'ok') {
7801: return 'error: '.$reply;
7802: }
1.1087 raeburn 7803: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
7804: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
7805: }
1.1075 raeburn 7806: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
7807: &devalidate_cache_new('namescache',$uname.':'.$udom);
7808: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 7809: &logthis($logmsg);
1.134 albertel 7810: return 'ok';
1.80 www 7811: }
7812:
1.81 www 7813: # -------------------------------------------------------------- Modify student
1.80 www 7814:
1.81 www 7815: sub modifystudent {
7816: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 7817: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.990 raeburn 7818: $selfenroll,$context,$inststatus)=@_;
1.455 albertel 7819: if (!$cid) {
1.620 albertel 7820: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 7821: return 'not_in_class';
7822: }
1.80 www 7823: }
7824: # --------------------------------------------------------------- Make the user
1.81 www 7825: my $reply=&modifyuser
1.209 matthew 7826: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 7827: $desiredhome,$email,$inststatus);
1.80 www 7828: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 7829: # This will cause &modify_student_enrollment to get the uid from the
7830: # students environment
7831: $uid = undef if (!$forceid);
1.455 albertel 7832: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957 raeburn 7833: $gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297 matthew 7834: return $reply;
7835: }
7836:
7837: sub modify_student_enrollment {
1.957 raeburn 7838: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455 albertel 7839: my ($cdom,$cnum,$chome);
7840: if (!$cid) {
1.620 albertel 7841: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 7842: return 'not_in_class';
7843: }
1.620 albertel 7844: $cdom=$env{'course.'.$cid.'.domain'};
7845: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 7846: } else {
7847: ($cdom,$cnum)=split(/_/,$cid);
7848: }
1.620 albertel 7849: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 7850: if (!$chome) {
1.457 raeburn 7851: $chome=&homeserver($cnum,$cdom);
1.297 matthew 7852: }
1.455 albertel 7853: if (!$chome) { return 'unknown_course'; }
1.297 matthew 7854: # Make sure the user exists
1.81 www 7855: my $uhome=&homeserver($uname,$udom);
7856: if (($uhome eq '') || ($uhome eq 'no_host')) {
7857: return 'error: no such user';
7858: }
1.297 matthew 7859: # Get student data if we were not given enough information
7860: if (!defined($first) || $first eq '' ||
7861: !defined($last) || $last eq '' ||
7862: !defined($uid) || $uid eq '' ||
7863: !defined($middle) || $middle eq '' ||
7864: !defined($gene) || $gene eq '') {
1.294 matthew 7865: # They did not supply us with enough data to enroll the student, so
7866: # we need to pick up more information.
1.297 matthew 7867: my %tmp = &get('environment',
1.294 matthew 7868: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 7869: ,$udom,$uname);
7870:
1.800 albertel 7871: #foreach my $key (keys(%tmp)) {
7872: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 7873: #}
1.294 matthew 7874: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
7875: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
7876: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 7877: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 7878: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
7879: }
1.556 albertel 7880: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148 raeburn 7881: my $user = "$uname:$udom";
7882: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487 albertel 7883: my $reply=cput('classlist',
1.1148 raeburn 7884: {$user =>
1.515 raeburn 7885: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487 albertel 7886: $cdom,$cnum);
1.1148 raeburn 7887: if (($reply eq 'ok') || ($reply eq 'delayed')) {
7888: &devalidate_getsection_cache($udom,$uname,$cid);
7889: } else {
1.81 www 7890: return 'error: '.$reply;
7891: }
1.297 matthew 7892: # Add student role to user
1.83 www 7893: my $uurl='/'.$cid;
1.81 www 7894: $uurl=~s/\_/\//g;
7895: if ($usec) {
7896: $uurl.='/'.$usec;
7897: }
1.1148 raeburn 7898: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
7899: $selfenroll,$context);
7900: if ($result ne 'ok') {
7901: if ($old_entry{$user} ne '') {
7902: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
7903: } else {
7904: $reply = &del('classlist',[$user],$cdom,$cnum);
7905: }
7906: }
7907: return $result;
1.21 www 7908: }
7909:
1.556 albertel 7910: sub format_name {
7911: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
7912: my $name;
7913: if ($first ne 'lastname') {
7914: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
7915: } else {
7916: if ($lastname=~/\S/) {
7917: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
7918: $name=~s/\s+,/,/;
7919: } else {
7920: $name.= $firstname.' '.$middlename.' '.$generation;
7921: }
7922: }
7923: $name=~s/^\s+//;
7924: $name=~s/\s+$//;
7925: $name=~s/\s+/ /g;
7926: return $name;
7927: }
7928:
1.84 www 7929: # ------------------------------------------------- Write to course preferences
7930:
7931: sub writecoursepref {
7932: my ($courseid,%prefs)=@_;
7933: $courseid=~s/^\///;
7934: $courseid=~s/\_/\//g;
7935: my ($cdomain,$cnum)=split(/\//,$courseid);
7936: my $chome=homeserver($cnum,$cdomain);
7937: if (($chome eq '') || ($chome eq 'no_host')) {
7938: return 'error: no such course';
7939: }
7940: my $cstring='';
1.800 albertel 7941: foreach my $pref (keys(%prefs)) {
7942: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 7943: }
1.84 www 7944: $cstring=~s/\&$//;
7945: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
7946: }
7947:
7948: # ---------------------------------------------------------- Make/modify course
7949:
7950: sub createcourse {
1.741 raeburn 7951: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 7952: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 7953: $url=&declutter($url);
7954: my $cid='';
1.1028 raeburn 7955: if ($context eq 'requestcourses') {
7956: my $can_create = 0;
7957: my ($ownername,$ownerdom) = split(':',$course_owner);
7958: if ($udom eq $ownerdom) {
7959: if (&usertools_access($ownername,$ownerdom,$category,undef,
7960: $context)) {
7961: $can_create = 1;
7962: }
7963: } else {
7964: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
7965: $category);
7966: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
7967: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
7968: if (@curr > 0) {
7969: my @options = qw(approval validate autolimit);
7970: my $optregex = join('|',@options);
7971: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
7972: $can_create = 1;
7973: }
7974: }
7975: }
7976: }
7977: if ($can_create) {
7978: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
7979: unless (&allowed('ccc',$udom)) {
7980: return 'refused';
7981: }
1.1017 raeburn 7982: }
7983: } else {
7984: return 'refused';
7985: }
1.1028 raeburn 7986: } elsif (!&allowed('ccc',$udom)) {
7987: return 'refused';
1.84 www 7988: }
1.1011 raeburn 7989: # --------------------------------------------------------------- Get Unique ID
7990: my $uname;
7991: if ($cnum =~ /^$match_courseid$/) {
7992: my $chome=&homeserver($cnum,$udom,'true');
7993: if (($chome eq '') || ($chome eq 'no_host')) {
7994: $uname = $cnum;
7995: } else {
1.1038 raeburn 7996: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 7997: }
7998: } else {
1.1038 raeburn 7999: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 8000: }
8001: return $uname if ($uname =~ /^error/);
8002: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 8003: if (!defined($course_server)) {
8004: if (defined(&domain($udom,'primary'))) {
8005: $course_server = &domain($udom,'primary');
8006: } else {
8007: $course_server = $env{'user.home'};
8008: }
8009: }
8010: my %host_servers =
8011: &Apache::lonnet::get_servers($udom,'library');
8012: unless ($host_servers{$course_server}) {
8013: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 8014: }
1.84 www 8015: # ------------------------------------------------------------- Make the course
8016: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 8017: $course_server);
1.84 www 8018: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 8019: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 8020: if (($uhome eq '') || ($uhome eq 'no_host')) {
8021: return 'error: no such course';
8022: }
1.271 www 8023: # ----------------------------------------------------------------- Course made
1.516 raeburn 8024: # log existence
1.1029 raeburn 8025: my $now = time;
1.918 raeburn 8026: my $newcourse = {
8027: $udom.'_'.$uname => {
1.921 raeburn 8028: description => $description,
8029: inst_code => $inst_code,
8030: owner => $course_owner,
8031: type => $crstype,
1.1029 raeburn 8032: creator => $env{'user.name'}.':'.
8033: $env{'user.domain'},
8034: created => $now,
8035: context => $context,
1.918 raeburn 8036: },
8037: };
1.921 raeburn 8038: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 8039: # set toplevel url
1.271 www 8040: my $topurl=$url;
8041: unless ($nonstandard) {
8042: # ------------------------------------------ For standard courses, make top url
8043: my $mapurl=&clutter($url);
1.278 www 8044: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 8045: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 8046: <map>
8047: <resource id="1" type="start"></resource>
8048: <resource id="2" src="$mapurl"></resource>
8049: <resource id="3" type="finish"></resource>
8050: <link index="1" from="1" to="2"></link>
8051: <link index="2" from="2" to="3"></link>
8052: </map>
8053: ENDINITMAP
8054: $topurl=&declutter(
1.638 albertel 8055: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 8056: );
8057: }
8058: # ----------------------------------------------------------- Write preferences
1.84 www 8059: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 8060: ('description' => $description,
8061: 'url' => $topurl,
8062: 'internal.creator' => $env{'user.name'}.':'.
8063: $env{'user.domain'},
8064: 'internal.created' => $now,
8065: 'internal.creationcontext' => $context)
8066: );
1.84 www 8067: return '/'.$udom.'/'.$uname;
8068: }
8069:
1.1011 raeburn 8070: # ------------------------------------------------------------------- Create ID
8071: sub generate_coursenum {
1.1038 raeburn 8072: my ($udom,$crstype) = @_;
1.1011 raeburn 8073: my $domdesc = &domain($udom);
8074: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 8075: my $first;
8076: if ($crstype eq 'Community') {
8077: $first = '0';
8078: } else {
8079: $first = int(1+rand(9));
8080: }
8081: my $uname=$first.
1.1011 raeburn 8082: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
8083: substr($$.time,0,5).unpack("H8",pack("I32",time)).
8084: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
8085: # ----------------------------------------------- Make sure that does not exist
8086: my $uhome=&homeserver($uname,$udom,'true');
8087: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 8088: if ($crstype eq 'Community') {
8089: $first = '0';
8090: } else {
8091: $first = int(1+rand(9));
8092: }
8093: $uname=$first.
1.1011 raeburn 8094: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
8095: substr($$.time,0,5).unpack("H8",pack("I32",time)).
8096: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
8097: $uhome=&homeserver($uname,$udom,'true');
8098: unless (($uhome eq '') || ($uhome eq 'no_host')) {
8099: return 'error: unable to generate unique course-ID';
8100: }
8101: }
8102: return $uname;
8103: }
8104:
1.813 albertel 8105: sub is_course {
1.1167 droeschl 8106: my ($cdom, $cnum) = scalar(@_) == 1 ?
8107: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
8108:
8109: return unless $cdom and $cnum;
8110:
8111: my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
8112: '.');
8113:
8114: return unless exists($courses{$cdom.'_'.$cnum});
8115: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813 albertel 8116: }
8117:
1.1015 raeburn 8118: sub store_userdata {
8119: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 8120: my $result;
1.1016 raeburn 8121: if ($datakey ne '') {
1.1013 raeburn 8122: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 8123: if ($udom eq '' || $uname eq '') {
8124: $udom = $env{'user.domain'};
8125: $uname = $env{'user.name'};
8126: }
8127: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 8128: if (($uhome eq '') || ($uhome eq 'no_host')) {
8129: $result = 'error: no_host';
8130: } else {
8131: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
8132: $storehash->{'host'} = $perlvar{'lonHostID'};
8133:
8134: my $namevalue='';
8135: foreach my $key (keys(%{$storehash})) {
8136: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
8137: }
8138: $namevalue=~s/\&$//;
1.1105 raeburn 8139: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
8140: $namevalue,$uhome);
1.1013 raeburn 8141: }
8142: } else {
8143: $result = 'error: data to store was not a hash reference';
8144: }
8145: } else {
8146: $result= 'error: invalid requestkey';
8147: }
8148: return $result;
8149: }
8150:
1.21 www 8151: # ---------------------------------------------------------- Assign Custom Role
8152:
8153: sub assigncustomrole {
1.957 raeburn 8154: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 8155: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 8156: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 8157: }
8158:
8159: # ----------------------------------------------------------------- Revoke Role
8160:
8161: sub revokerole {
1.957 raeburn 8162: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 8163: my $now=time;
1.965 raeburn 8164: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 8165: }
8166:
8167: # ---------------------------------------------------------- Revoke Custom Role
8168:
8169: sub revokecustomrole {
1.957 raeburn 8170: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 8171: my $now=time;
1.357 www 8172: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 8173: $deleteflag,$selfenroll,$context);
1.17 www 8174: }
8175:
1.533 banghart 8176: # ------------------------------------------------------------ Disk usage
1.535 albertel 8177: sub diskusage {
1.955 raeburn 8178: my ($udom,$uname,$directorypath,$getpropath)=@_;
8179: $directorypath =~ s/\/$//;
8180: my $listing=&reply('du2:'.&escape($directorypath).':'
8181: .&escape($getpropath).':'.&escape($uname).':'
8182: .&escape($udom),homeserver($uname,$udom));
8183: if ($listing eq 'unknown_cmd') {
8184: if ($getpropath) {
8185: $directorypath = &propath($udom,$uname).'/'.$directorypath;
8186: }
8187: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
8188: }
1.514 albertel 8189: return $listing;
1.512 banghart 8190: }
8191:
1.566 banghart 8192: sub is_locked {
1.1096 raeburn 8193: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 8194: my @check;
8195: my $is_locked;
1.1093 raeburn 8196: push (@check,$file_name);
1.613 albertel 8197: my %locked = &get('file_permissions',\@check,
1.620 albertel 8198: $env{'user.domain'},$env{'user.name'});
1.615 albertel 8199: my ($tmp)=keys(%locked);
8200: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 8201:
1.566 banghart 8202: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 8203: $is_locked = 'false';
8204: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 8205: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 8206: $is_locked = 'true';
1.1096 raeburn 8207: if (ref($which) eq 'ARRAY') {
8208: push(@{$which},$entry);
8209: } else {
8210: last;
8211: }
1.745 raeburn 8212: }
8213: }
1.566 banghart 8214: } else {
8215: $is_locked = 'false';
8216: }
1.1093 raeburn 8217: return $is_locked;
1.566 banghart 8218: }
8219:
1.759 albertel 8220: sub declutter_portfile {
8221: my ($file) = @_;
1.833 albertel 8222: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 8223: return $file;
8224: }
8225:
1.559 banghart 8226: # ------------------------------------------------------------- Mark as Read Only
8227:
8228: sub mark_as_readonly {
8229: my ($domain,$user,$files,$what) = @_;
1.613 albertel 8230: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 8231: my ($tmp)=keys(%current_permissions);
8232: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 8233: foreach my $file (@{$files}) {
1.759 albertel 8234: $file = &declutter_portfile($file);
1.561 banghart 8235: push(@{$current_permissions{$file}},$what);
1.559 banghart 8236: }
1.613 albertel 8237: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 8238: return;
8239: }
8240:
1.572 banghart 8241: # ------------------------------------------------------------Save Selected Files
8242:
8243: sub save_selected_files {
8244: my ($user, $path, @files) = @_;
8245: my $filename = $user."savedfiles";
1.573 banghart 8246: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 8247: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 8248: foreach my $file (@files) {
1.620 albertel 8249: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 8250: }
8251: foreach my $file (@other_files) {
1.574 banghart 8252: print (OUT $file."\n");
1.572 banghart 8253: }
1.574 banghart 8254: close (OUT);
1.572 banghart 8255: return 'ok';
8256: }
8257:
1.574 banghart 8258: sub clear_selected_files {
8259: my ($user) = @_;
8260: my $filename = $user."savedfiles";
1.1117 foxr 8261: open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574 banghart 8262: print (OUT undef);
8263: close (OUT);
8264: return ("ok");
8265: }
8266:
1.572 banghart 8267: sub files_in_path {
8268: my ($user, $path) = @_;
8269: my $filename = $user."savedfiles";
8270: my %return_files;
1.1117 foxr 8271: open (IN, '<'.LONCAPA::tempdir().$filename);
1.573 banghart 8272: while (my $line_in = <IN>) {
1.574 banghart 8273: chomp ($line_in);
8274: my @paths_and_file = split (m!/!, $line_in);
8275: my $file_part = pop (@paths_and_file);
8276: my $path_part = join ('/', @paths_and_file);
1.573 banghart 8277: $path_part.='/';
8278: my $path_and_file = $path_part.$file_part;
8279: if ($path_part eq $path) {
8280: $return_files{$file_part}= 'selected';
8281: }
8282: }
1.574 banghart 8283: close (IN);
8284: return (\%return_files);
1.572 banghart 8285: }
8286:
8287: # called in portfolio select mode, to show files selected NOT in current directory
8288: sub files_not_in_path {
8289: my ($user, $path) = @_;
8290: my $filename = $user."savedfiles";
8291: my @return_files;
8292: my $path_part;
1.1117 foxr 8293: open(IN, '<'.LONCAPA::.$filename);
1.800 albertel 8294: while (my $line = <IN>) {
1.572 banghart 8295: #ok, I know it's clunky, but I want it to work
1.800 albertel 8296: my @paths_and_file = split(m|/|, $line);
8297: my $file_part = pop(@paths_and_file);
8298: chomp($file_part);
8299: my $path_part = join('/', @paths_and_file);
1.572 banghart 8300: $path_part .= '/';
8301: my $path_and_file = $path_part.$file_part;
8302: if ($path_part ne $path) {
1.800 albertel 8303: push(@return_files, ($path_and_file));
1.572 banghart 8304: }
8305: }
1.800 albertel 8306: close(OUT);
1.574 banghart 8307: return (@return_files);
1.572 banghart 8308: }
8309:
1.745 raeburn 8310: #----------------------------------------------Get portfolio file permissions
1.629 banghart 8311:
1.745 raeburn 8312: sub get_portfile_permissions {
8313: my ($domain,$user) = @_;
1.613 albertel 8314: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 8315: my ($tmp)=keys(%current_permissions);
8316: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 8317: return \%current_permissions;
8318: }
8319:
8320: #---------------------------------------------Get portfolio file access controls
8321:
1.749 raeburn 8322: sub get_access_controls {
1.745 raeburn 8323: my ($current_permissions,$group,$file) = @_;
1.769 albertel 8324: my %access;
8325: my $real_file = $file;
8326: $file =~ s/\.meta$//;
1.745 raeburn 8327: if (defined($file)) {
1.749 raeburn 8328: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
8329: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 8330: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 8331: }
8332: }
1.745 raeburn 8333: } else {
1.749 raeburn 8334: foreach my $key (keys(%{$current_permissions})) {
8335: if ($key =~ /\0accesscontrol$/) {
8336: if (defined($group)) {
8337: if ($key !~ m-^\Q$group\E/-) {
8338: next;
8339: }
8340: }
8341: my ($fullpath) = split(/\0/,$key);
8342: if (ref($$current_permissions{$key}) eq 'HASH') {
8343: foreach my $control (keys(%{$$current_permissions{$key}})) {
8344: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
8345: }
8346: }
8347: }
8348: }
8349: }
8350: return %access;
8351: }
8352:
8353: sub modify_access_controls {
8354: my ($file_name,$changes,$domain,$user)=@_;
8355: my ($outcome,$deloutcome);
8356: my %store_permissions;
8357: my %new_values;
8358: my %new_control;
8359: my %translation;
8360: my @deletions = ();
8361: my $now = time;
8362: if (exists($$changes{'activate'})) {
8363: if (ref($$changes{'activate'}) eq 'HASH') {
8364: my @newitems = sort(keys(%{$$changes{'activate'}}));
8365: my $numnew = scalar(@newitems);
8366: for (my $i=0; $i<$numnew; $i++) {
8367: my $newkey = $newitems[$i];
8368: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 8369: if ($newkey =~ /^\d+:/) {
8370: $newkey =~ s/^(\d+)/$newid/;
8371: $translation{$1} = $newid;
8372: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
8373: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
8374: $translation{$1} = $newid;
8375: }
1.749 raeburn 8376: $new_values{$file_name."\0".$newkey} =
8377: $$changes{'activate'}{$newitems[$i]};
8378: $new_control{$newkey} = $now;
8379: }
8380: }
8381: }
8382: my %todelete;
8383: my %changed_items;
8384: foreach my $action ('delete','update') {
8385: if (exists($$changes{$action})) {
8386: if (ref($$changes{$action}) eq 'HASH') {
8387: foreach my $key (keys(%{$$changes{$action}})) {
8388: my ($itemnum) = ($key =~ /^([^:]+):/);
8389: if ($action eq 'delete') {
8390: $todelete{$itemnum} = 1;
8391: } else {
8392: $changed_items{$itemnum} = $key;
8393: }
8394: }
1.745 raeburn 8395: }
8396: }
1.749 raeburn 8397: }
8398: # get lock on access controls for file.
8399: my $lockhash = {
8400: $file_name."\0".'locked_access_records' => $env{'user.name'}.
8401: ':'.$env{'user.domain'},
8402: };
8403: my $tries = 0;
8404: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
8405:
8406: while (($gotlock ne 'ok') && $tries <3) {
8407: $tries ++;
8408: sleep 1;
8409: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
8410: }
8411: if ($gotlock eq 'ok') {
8412: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
8413: my ($tmp)=keys(%curr_permissions);
8414: if ($tmp=~/^error:/) { undef(%curr_permissions); }
8415: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
8416: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
8417: if (ref($curr_controls) eq 'HASH') {
8418: foreach my $control_item (keys(%{$curr_controls})) {
8419: my ($itemnum) = ($control_item =~ /^([^:]+):/);
8420: if (defined($todelete{$itemnum})) {
8421: push(@deletions,$file_name."\0".$control_item);
8422: } else {
8423: if (defined($changed_items{$itemnum})) {
8424: $new_control{$changed_items{$itemnum}} = $now;
8425: push(@deletions,$file_name."\0".$control_item);
8426: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
8427: } else {
8428: $new_control{$control_item} = $$curr_controls{$control_item};
8429: }
8430: }
1.745 raeburn 8431: }
8432: }
8433: }
1.970 raeburn 8434: my ($group);
8435: if (&is_course($domain,$user)) {
8436: ($group,my $file) = split(/\//,$file_name,2);
8437: }
1.749 raeburn 8438: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
8439: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
8440: $outcome = &put('file_permissions',\%new_values,$domain,$user);
8441: # remove lock
8442: my @del_lock = ($file_name."\0".'locked_access_records');
8443: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 8444: my $sqlresult =
1.970 raeburn 8445: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 8446: $group);
1.749 raeburn 8447: } else {
8448: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 8449: }
1.749 raeburn 8450: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 8451: }
8452:
1.827 raeburn 8453: sub make_public_indefinitely {
8454: my ($requrl) = @_;
8455: my $now = time;
8456: my $action = 'activate';
8457: my $aclnum = 0;
8458: if (&is_portfolio_url($requrl)) {
8459: my (undef,$udom,$unum,$file_name,$group) =
8460: &parse_portfolio_url($requrl);
8461: my $current_perms = &get_portfile_permissions($udom,$unum);
8462: my %access_controls = &get_access_controls($current_perms,
8463: $group,$file_name);
8464: foreach my $key (keys(%{$access_controls{$file_name}})) {
8465: my ($num,$scope,$end,$start) =
8466: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
8467: if ($scope eq 'public') {
8468: if ($start <= $now && $end == 0) {
8469: $action = 'none';
8470: } else {
8471: $action = 'update';
8472: $aclnum = $num;
8473: }
8474: last;
8475: }
8476: }
8477: if ($action eq 'none') {
8478: return 'ok';
8479: } else {
8480: my %changes;
8481: my $newend = 0;
8482: my $newstart = $now;
8483: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
8484: $changes{$action}{$newkey} = {
8485: type => 'public',
8486: time => {
8487: start => $newstart,
8488: end => $newend,
8489: },
8490: };
8491: my ($outcome,$deloutcome,$new_values,$translation) =
8492: &modify_access_controls($file_name,\%changes,$udom,$unum);
8493: return $outcome;
8494: }
8495: } else {
8496: return 'invalid';
8497: }
8498: }
8499:
1.745 raeburn 8500: #------------------------------------------------------Get Marked as Read Only
8501:
8502: sub get_marked_as_readonly {
8503: my ($domain,$user,$what,$group) = @_;
8504: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 8505: my @readonly_files;
1.629 banghart 8506: my $cmp1=$what;
8507: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 8508: while (my ($file_name,$value) = each(%{$current_permissions})) {
8509: if (defined($group)) {
8510: if ($file_name !~ m-^\Q$group\E/-) {
8511: next;
8512: }
8513: }
1.561 banghart 8514: if (ref($value) eq "ARRAY"){
8515: foreach my $stored_what (@{$value}) {
1.629 banghart 8516: my $cmp2=$stored_what;
1.759 albertel 8517: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 8518: $cmp2=join('',@{$stored_what});
1.745 raeburn 8519: }
1.629 banghart 8520: if ($cmp1 eq $cmp2) {
1.561 banghart 8521: push(@readonly_files, $file_name);
1.745 raeburn 8522: last;
1.563 banghart 8523: } elsif (!defined($what)) {
8524: push(@readonly_files, $file_name);
1.745 raeburn 8525: last;
1.561 banghart 8526: }
8527: }
1.745 raeburn 8528: }
1.561 banghart 8529: }
8530: return @readonly_files;
8531: }
1.577 banghart 8532: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 8533:
1.577 banghart 8534: sub get_marked_as_readonly_hash {
1.745 raeburn 8535: my ($current_permissions,$group,$what) = @_;
1.577 banghart 8536: my %readonly_files;
1.745 raeburn 8537: while (my ($file_name,$value) = each(%{$current_permissions})) {
8538: if (defined($group)) {
8539: if ($file_name !~ m-^\Q$group\E/-) {
8540: next;
8541: }
8542: }
1.577 banghart 8543: if (ref($value) eq "ARRAY"){
8544: foreach my $stored_what (@{$value}) {
1.745 raeburn 8545: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 8546: foreach my $lock_descriptor(@{$stored_what}) {
8547: if ($lock_descriptor eq 'graded') {
8548: $readonly_files{$file_name} = 'graded';
8549: } elsif ($lock_descriptor eq 'handback') {
8550: $readonly_files{$file_name} = 'handback';
8551: } else {
8552: if (!exists($readonly_files{$file_name})) {
8553: $readonly_files{$file_name} = 'locked';
8554: }
8555: }
1.745 raeburn 8556: }
1.750 banghart 8557: }
1.577 banghart 8558: }
8559: }
8560: }
8561: return %readonly_files;
8562: }
1.559 banghart 8563: # ------------------------------------------------------------ Unmark as Read Only
8564:
8565: sub unmark_as_readonly {
1.629 banghart 8566: # unmarks $file_name (if $file_name is defined), or all files locked by $what
8567: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 8568: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 8569: $file_name = &declutter_portfile($file_name);
1.634 albertel 8570: my $symb_crs = $what;
8571: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 8572: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 8573: my ($tmp)=keys(%current_permissions);
8574: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 8575: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 8576: foreach my $file (@readonly_files) {
1.759 albertel 8577: my $clean_file = &declutter_portfile($file);
8578: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 8579: my $current_locks = $current_permissions{$file};
1.563 banghart 8580: my @new_locks;
8581: my @del_keys;
8582: if (ref($current_locks) eq "ARRAY"){
8583: foreach my $locker (@{$current_locks}) {
1.632 albertel 8584: my $compare=$locker;
1.749 raeburn 8585: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 8586: $compare=join('',@{$locker});
1.746 raeburn 8587: if ($compare ne $symb_crs) {
8588: push(@new_locks, $locker);
8589: }
1.563 banghart 8590: }
8591: }
1.650 albertel 8592: if (scalar(@new_locks) > 0) {
1.563 banghart 8593: $current_permissions{$file} = \@new_locks;
8594: } else {
8595: push(@del_keys, $file);
1.613 albertel 8596: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 8597: delete($current_permissions{$file});
1.563 banghart 8598: }
8599: }
1.561 banghart 8600: }
1.613 albertel 8601: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 8602: return;
8603: }
1.512 banghart 8604:
1.17 www 8605: # ------------------------------------------------------------ Directory lister
8606:
8607: sub dirlist {
1.955 raeburn 8608: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 8609: $uri=~s/^\///;
8610: $uri=~s/\/$//;
1.253 stredwic 8611: my ($udom, $uname);
1.955 raeburn 8612: if ($getuserdir) {
1.253 stredwic 8613: $udom = $userdomain;
8614: $uname = $username;
1.955 raeburn 8615: } else {
8616: (undef,$udom,$uname)=split(/\//,$uri);
8617: if(defined($userdomain)) {
8618: $udom = $userdomain;
8619: }
8620: if(defined($username)) {
8621: $uname = $username;
8622: }
1.253 stredwic 8623: }
1.955 raeburn 8624: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 8625:
1.955 raeburn 8626: $dirRoot = $perlvar{'lonDocRoot'};
8627: if (defined($getpropath)) {
8628: $dirRoot = &propath($udom,$uname);
1.253 stredwic 8629: $dirRoot =~ s/\/$//;
1.955 raeburn 8630: } elsif (defined($getuserdir)) {
8631: my $subdir=$uname.'__';
8632: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
8633: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
8634: ."/$udom/$subdir/$uname";
8635: } elsif (defined($alternateRoot)) {
8636: $dirRoot = $alternateRoot;
1.751 banghart 8637: }
1.253 stredwic 8638:
8639: if($udom) {
8640: if($uname) {
1.1135 raeburn 8641: my $uhome = &homeserver($uname,$udom);
1.1136 raeburn 8642: if ($uhome eq 'no_host') {
8643: return ([],'no_host');
8644: }
1.955 raeburn 8645: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 8646: .$getuserdir.':'.&escape($dirRoot)
1.1135 raeburn 8647: .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955 raeburn 8648: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 8649: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955 raeburn 8650: } else {
8651: @listing_results = map { &unescape($_); } split(/:/,$listing);
8652: }
1.605 matthew 8653: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 8654: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605 matthew 8655: @listing_results = split(/:/,$listing);
8656: } else {
8657: @listing_results = map { &unescape($_); } split(/:/,$listing);
8658: }
1.1135 raeburn 8659: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
1.1136 raeburn 8660: ($listing eq 'rejected') || ($listing eq 'refused') ||
8661: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
8662: return ([],$listing);
8663: } else {
8664: return (\@listing_results);
1.1135 raeburn 8665: }
1.955 raeburn 8666: } elsif(!$alternateRoot) {
1.1136 raeburn 8667: my (%allusers,%listerror);
1.841 albertel 8668: my %servers = &get_servers($udom,'library');
1.955 raeburn 8669: foreach my $tryserver (keys(%servers)) {
8670: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
8671: &escape($udom),$tryserver);
8672: if ($listing eq 'unknown_cmd') {
8673: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
8674: $udom, $tryserver);
8675: } else {
8676: @listing_results = map { &unescape($_); } split(/:/,$listing);
8677: }
1.841 albertel 8678: if ($listing eq 'unknown_cmd') {
8679: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
8680: $udom, $tryserver);
8681: @listing_results = split(/:/,$listing);
8682: } else {
8683: @listing_results =
8684: map { &unescape($_); } split(/:/,$listing);
8685: }
1.1136 raeburn 8686: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
8687: ($listing eq 'rejected') || ($listing eq 'refused') ||
8688: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
8689: $listerror{$tryserver} = $listing;
8690: } else {
1.841 albertel 8691: foreach my $line (@listing_results) {
8692: my ($entry) = split(/&/,$line,2);
8693: $allusers{$entry} = 1;
8694: }
8695: }
1.253 stredwic 8696: }
1.1136 raeburn 8697: my @alluserslist=();
1.800 albertel 8698: foreach my $user (sort(keys(%allusers))) {
1.1136 raeburn 8699: push(@alluserslist,$user.'&user');
1.253 stredwic 8700: }
1.1136 raeburn 8701: return (\@alluserslist);
1.253 stredwic 8702: } else {
1.1136 raeburn 8703: return ([],'missing username');
1.253 stredwic 8704: }
1.955 raeburn 8705: } elsif(!defined($getpropath)) {
1.1136 raeburn 8706: my $path = $perlvar{'lonDocRoot'}.'/res/';
8707: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
8708: return (\@all_domains);
1.955 raeburn 8709: } else {
1.1136 raeburn 8710: return ([],'missing domain');
1.275 stredwic 8711: }
8712: }
8713:
8714: # --------------------------------------------- GetFileTimestamp
8715: # This function utilizes dirlist and returns the date stamp for
8716: # when it was last modified. It will also return an error of -1
8717: # if an error occurs
8718:
8719: sub GetFileTimestamp {
1.955 raeburn 8720: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 8721: $studentDomain = &LONCAPA::clean_domain($studentDomain);
8722: $studentName = &LONCAPA::clean_username($studentName);
1.1136 raeburn 8723: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
8724: undef,$getuserdir);
8725: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
8726: return -1;
8727: }
8728: if (ref($fileref) eq 'ARRAY') {
8729: my @stats = split('&',$fileref->[0]);
1.375 matthew 8730: # @stats contains first the filename, then the stat output
8731: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 8732: } else {
8733: return -1;
1.253 stredwic 8734: }
1.26 www 8735: }
8736:
1.712 albertel 8737: sub stat_file {
8738: my ($uri) = @_;
1.787 albertel 8739: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 8740:
1.955 raeburn 8741: my ($udom,$uname,$file);
1.712 albertel 8742: if ($uri =~ m-^/(uploaded|editupload)/-) {
8743: ($udom,$uname,$file) =
1.811 albertel 8744: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 8745: $file = 'userfiles/'.$file;
8746: }
8747: if ($uri =~ m-^/res/-) {
8748: ($udom,$uname) =
1.807 albertel 8749: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 8750: $file = $uri;
8751: }
8752:
8753: if (!$udom || !$uname || !$file) {
8754: # unable to handle the uri
8755: return ();
8756: }
1.956 raeburn 8757: my $getpropath;
8758: if ($file =~ /^userfiles\//) {
8759: $getpropath = 1;
8760: }
1.1136 raeburn 8761: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
8762: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
8763: return ();
8764: } else {
8765: if (ref($listref) eq 'ARRAY') {
8766: my @stats = split('&',$listref->[0]);
8767: shift(@stats); #filename is first
8768: return @stats;
8769: }
1.712 albertel 8770: }
8771: return ();
8772: }
8773:
1.26 www 8774: # -------------------------------------------------------- Value of a Condition
8775:
1.713 albertel 8776: # gets the value of a specific preevaluated condition
8777: # stored in the string $env{user.state.<cid>}
8778: # or looks up a condition reference in the bighash and if if hasn't
8779: # already been evaluated recurses into docondval to get the value of
8780: # the condition, then memoizing it to
8781: # $env{user.state.<cid>.<condition>}
1.40 www 8782: sub directcondval {
8783: my $number=shift;
1.620 albertel 8784: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 8785: &Apache::lonuserstate::evalstate();
8786: }
1.713 albertel 8787: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
8788: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
8789: } elsif ($number =~ /^_/) {
8790: my $sub_condition;
8791: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
8792: &GDBM_READER(),0640)) {
8793: $sub_condition=$bighash{'conditions'.$number};
8794: untie(%bighash);
8795: }
8796: my $value = &docondval($sub_condition);
1.949 raeburn 8797: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 8798: return $value;
8799: }
1.620 albertel 8800: if ($env{'user.state.'.$env{'request.course.id'}}) {
8801: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 8802: } else {
8803: return 2;
8804: }
8805: }
8806:
1.713 albertel 8807: # get the collection of conditions for this resource
1.26 www 8808: sub condval {
8809: my $condidx=shift;
1.54 www 8810: my $allpathcond='';
1.713 albertel 8811: foreach my $cond (split(/\|/,$condidx)) {
8812: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
8813: $allpathcond.=
8814: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
8815: }
1.191 harris41 8816: }
1.54 www 8817: $allpathcond=~s/\|$//;
1.713 albertel 8818: return &docondval($allpathcond);
8819: }
8820:
8821: #evaluates an expression of conditions
8822: sub docondval {
8823: my ($allpathcond) = @_;
8824: my $result=0;
8825: if ($env{'request.course.id'}
8826: && defined($allpathcond)) {
8827: my $operand='|';
8828: my @stack;
8829: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
8830: if ($chunk eq '(') {
8831: push @stack,($operand,$result);
8832: } elsif ($chunk eq ')') {
8833: my $before=pop @stack;
8834: if (pop @stack eq '&') {
8835: $result=$result>$before?$before:$result;
8836: } else {
8837: $result=$result>$before?$result:$before;
8838: }
8839: } elsif (($chunk eq '&') || ($chunk eq '|')) {
8840: $operand=$chunk;
8841: } else {
8842: my $new=directcondval($chunk);
8843: if ($operand eq '&') {
8844: $result=$result>$new?$new:$result;
8845: } else {
8846: $result=$result>$new?$result:$new;
8847: }
8848: }
8849: }
1.26 www 8850: }
8851: return $result;
1.421 albertel 8852: }
8853:
8854: # ---------------------------------------------------- Devalidate courseresdata
8855:
8856: sub devalidatecourseresdata {
8857: my ($coursenum,$coursedomain)=@_;
8858: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 8859: &devalidate_cache_new('courseres',$hashid);
1.28 www 8860: }
8861:
1.763 www 8862:
1.200 www 8863: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 8864: #
8865: # Parameters:
8866: # $coursenum - Number of the course.
8867: # $coursedomain - Domain at which the course was created.
8868: # Returns:
8869: # A hash of the course parameters along (I think) with timestamps
8870: # and version info.
1.877 foxr 8871:
1.624 albertel 8872: sub get_courseresdata {
8873: my ($coursenum,$coursedomain)=@_;
1.200 www 8874: my $coursehom=&homeserver($coursenum,$coursedomain);
8875: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 8876: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 8877: my %dumpreply;
1.417 albertel 8878: unless (defined($cached)) {
1.624 albertel 8879: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 8880: $result=\%dumpreply;
1.251 albertel 8881: my ($tmp) = keys(%dumpreply);
8882: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 8883: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 8884: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
8885: return $tmp;
1.416 albertel 8886: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 8887: $result=undef;
1.599 albertel 8888: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 8889: }
8890: }
1.624 albertel 8891: return $result;
8892: }
8893:
1.633 albertel 8894: sub devalidateuserresdata {
8895: my ($uname,$udom)=@_;
8896: my $hashid="$udom:$uname";
8897: &devalidate_cache_new('userres',$hashid);
8898: }
8899:
1.624 albertel 8900: sub get_userresdata {
8901: my ($uname,$udom)=@_;
8902: #most student don\'t have any data set, check if there is some data
8903: if (&EXT_cache_status($udom,$uname)) { return undef; }
8904:
8905: my $hashid="$udom:$uname";
8906: my ($result,$cached)=&is_cached_new('userres',$hashid);
8907: if (!defined($cached)) {
8908: my %resourcedata=&dump('resourcedata',$udom,$uname);
8909: $result=\%resourcedata;
8910: &do_cache_new('userres',$hashid,$result,600);
8911: }
8912: my ($tmp)=keys(%$result);
8913: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
8914: return $result;
8915: }
8916: #error 2 occurs when the .db doesn't exist
8917: if ($tmp!~/error: 2 /) {
1.672 albertel 8918: &logthis("<font color=\"blue\">WARNING:".
1.624 albertel 8919: " Trying to get resource data for ".
8920: $uname." at ".$udom.": ".
8921: $tmp."</font>");
8922: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 8923: #&EXT_cache_set($udom,$uname);
8924: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 8925: undef($tmp); # not really an error so don't send it back
1.624 albertel 8926: }
8927: return $tmp;
8928: }
1.879 foxr 8929: #----------------------------------------------- resdata - return resource data
8930: # Purpose:
8931: # Return resource data for either users or for a course.
8932: # Parameters:
8933: # $name - Course/user name.
8934: # $domain - Name of the domain the user/course is registered on.
8935: # $type - Type of thing $name is (must be 'course' or 'user'
8936: # @which - Array of names of resources desired.
8937: # Returns:
8938: # The value of the first reasource in @which that is found in the
8939: # resource hash.
8940: # Exceptional Conditions:
8941: # If the $type passed in is not valid (not the string 'course' or
8942: # 'user', an undefined reference is returned.
8943: # If none of the resources are found, an undef is returned
1.624 albertel 8944: sub resdata {
8945: my ($name,$domain,$type,@which)=@_;
8946: my $result;
8947: if ($type eq 'course') {
8948: $result=&get_courseresdata($name,$domain);
8949: } elsif ($type eq 'user') {
8950: $result=&get_userresdata($name,$domain);
8951: }
8952: if (!ref($result)) { return $result; }
1.251 albertel 8953: foreach my $item (@which) {
1.927 albertel 8954: if (defined($result->{$item->[0]})) {
8955: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 8956: }
1.250 albertel 8957: }
1.291 albertel 8958: return undef;
1.200 www 8959: }
8960:
1.379 matthew 8961: #
8962: # EXT resource caching routines
8963: #
8964:
8965: sub clear_EXT_cache_status {
1.383 albertel 8966: &delenv('cache.EXT.');
1.379 matthew 8967: }
8968:
8969: sub EXT_cache_status {
8970: my ($target_domain,$target_user) = @_;
1.383 albertel 8971: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 8972: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 8973: # We know already the user has no data
8974: return 1;
8975: } else {
8976: return 0;
8977: }
8978: }
8979:
8980: sub EXT_cache_set {
8981: my ($target_domain,$target_user) = @_;
1.383 albertel 8982: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 8983: #&appenv({$cachename => time});
1.379 matthew 8984: }
8985:
1.28 www 8986: # --------------------------------------------------------- Value of a Variable
1.58 www 8987: sub EXT {
1.715 albertel 8988:
1.395 albertel 8989: my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68 www 8990: unless ($varname) { return ''; }
1.218 albertel 8991: #get real user name/domain, courseid and symb
8992: my $courseid;
1.359 albertel 8993: my $publicuser;
1.427 www 8994: if ($symbparm) {
8995: $symbparm=&get_symb_from_alias($symbparm);
8996: }
1.218 albertel 8997: if (!($uname && $udom)) {
1.790 albertel 8998: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 8999: if (!$symbparm) { $symbparm=$cursymb; }
9000: } else {
1.620 albertel 9001: $courseid=$env{'request.course.id'};
1.218 albertel 9002: }
1.48 www 9003: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
9004: my $rest;
1.320 albertel 9005: if (defined($therest[0])) {
1.48 www 9006: $rest=join('.',@therest);
9007: } else {
9008: $rest='';
9009: }
1.320 albertel 9010:
1.57 www 9011: my $qualifierrest=$qualifier;
9012: if ($rest) { $qualifierrest.='.'.$rest; }
9013: my $spacequalifierrest=$space;
9014: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 9015: if ($realm eq 'user') {
1.48 www 9016: # --------------------------------------------------------------- user.resource
9017: if ($space eq 'resource') {
1.651 albertel 9018: if ( (defined($Apache::lonhomework::parsing_a_problem)
9019: || defined($Apache::lonhomework::parsing_a_task))
9020: &&
1.744 albertel 9021: ($symbparm eq &symbread()) ) {
9022: # if we are in the middle of processing the resource the
9023: # get the value we are planning on committing
9024: if (defined($Apache::lonhomework::results{$qualifierrest})) {
9025: return $Apache::lonhomework::results{$qualifierrest};
9026: } else {
9027: return $Apache::lonhomework::history{$qualifierrest};
9028: }
1.335 albertel 9029: } else {
1.359 albertel 9030: my %restored;
1.620 albertel 9031: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 9032: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
9033: } else {
9034: %restored=&restore($symbparm,$courseid,$udom,$uname);
9035: }
1.335 albertel 9036: return $restored{$qualifierrest};
9037: }
1.48 www 9038: # ----------------------------------------------------------------- user.access
9039: } elsif ($space eq 'access') {
1.218 albertel 9040: # FIXME - not supporting calls for a specific user
1.48 www 9041: return &allowed($qualifier,$rest);
9042: # ------------------------------------------ user.preferences, user.environment
9043: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 9044: if (($uname eq $env{'user.name'}) &&
9045: ($udom eq $env{'user.domain'})) {
9046: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 9047: } else {
1.359 albertel 9048: my %returnhash;
9049: if (!$publicuser) {
9050: %returnhash=&userenvironment($udom,$uname,
9051: $qualifierrest);
9052: }
1.218 albertel 9053: return $returnhash{$qualifierrest};
9054: }
1.48 www 9055: # ----------------------------------------------------------------- user.course
9056: } elsif ($space eq 'course') {
1.218 albertel 9057: # FIXME - not supporting calls for a specific user
1.620 albertel 9058: return $env{join('.',('request.course',$qualifier))};
1.48 www 9059: # ------------------------------------------------------------------- user.role
9060: } elsif ($space eq 'role') {
1.218 albertel 9061: # FIXME - not supporting calls for a specific user
1.620 albertel 9062: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 9063: if ($qualifier eq 'value') {
9064: return $role;
9065: } elsif ($qualifier eq 'extent') {
9066: return $where;
9067: }
9068: # ----------------------------------------------------------------- user.domain
9069: } elsif ($space eq 'domain') {
1.218 albertel 9070: return $udom;
1.48 www 9071: # ------------------------------------------------------------------- user.name
9072: } elsif ($space eq 'name') {
1.218 albertel 9073: return $uname;
1.48 www 9074: # ---------------------------------------------------- Any other user namespace
1.29 www 9075: } else {
1.359 albertel 9076: my %reply;
9077: if (!$publicuser) {
9078: %reply=&get($space,[$qualifierrest],$udom,$uname);
9079: }
9080: return $reply{$qualifierrest};
1.48 www 9081: }
1.236 www 9082: } elsif ($realm eq 'query') {
9083: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 9084: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
9085: [$spacequalifierrest]);
1.620 albertel 9086: return $env{'form.'.$spacequalifierrest};
1.236 www 9087: } elsif ($realm eq 'request') {
1.48 www 9088: # ------------------------------------------------------------- request.browser
9089: if ($space eq 'browser') {
1.1145 bisitz 9090: return $env{'browser.'.$qualifier};
1.57 www 9091: # ------------------------------------------------------------ request.filename
9092: } else {
1.620 albertel 9093: return $env{'request.'.$spacequalifierrest};
1.29 www 9094: }
1.28 www 9095: } elsif ($realm eq 'course') {
1.48 www 9096: # ---------------------------------------------------------- course.description
1.620 albertel 9097: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 9098: } elsif ($realm eq 'resource') {
1.165 www 9099:
1.620 albertel 9100: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 9101: if (!$symbparm) { $symbparm=&symbread(); }
9102: }
1.693 albertel 9103:
9104: if ($space eq 'title') {
9105: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
9106: return &gettitle($symbparm);
9107: }
9108:
9109: if ($space eq 'map') {
9110: my ($map) = &decode_symb($symbparm);
9111: return &symbread($map);
9112: }
1.905 albertel 9113: if ($space eq 'filename') {
9114: if ($symbparm) {
9115: return &clutter((&decode_symb($symbparm))[2]);
9116: }
9117: return &hreflocation('',$env{'request.filename'});
9118: }
1.693 albertel 9119:
9120: my ($section, $group, @groups);
1.593 albertel 9121: my ($courselevelm,$courselevel);
1.539 albertel 9122: if ($symbparm && defined($courseid) &&
1.620 albertel 9123: $courseid eq $env{'request.course.id'}) {
1.165 www 9124:
1.218 albertel 9125: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 9126:
1.60 www 9127: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 9128: my $symbp=$symbparm;
1.735 albertel 9129: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 9130:
9131: my $symbparm=$symbp.'.'.$spacequalifierrest;
9132: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
9133:
1.620 albertel 9134: if (($env{'user.name'} eq $uname) &&
9135: ($env{'user.domain'} eq $udom)) {
9136: $section=$env{'request.course.sec'};
1.733 raeburn 9137: @groups = split(/:/,$env{'request.course.groups'});
9138: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 9139: } else {
1.539 albertel 9140: if (! defined($usection)) {
1.551 albertel 9141: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 9142: } else {
9143: $section = $usection;
9144: }
1.733 raeburn 9145: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 9146: }
9147:
9148: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
9149: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
9150: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
9151:
1.593 albertel 9152: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 9153: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 9154: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 9155:
1.60 www 9156: # ----------------------------------------------------------- first, check user
1.624 albertel 9157:
9158: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 9159: ([$courselevelr,'resource'],
9160: [$courselevelm,'map' ],
9161: [$courselevel, 'course' ]));
1.931 albertel 9162: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 9163:
1.594 albertel 9164: # ------------------------------------------------ second, check some of course
1.684 raeburn 9165: my $coursereply;
1.691 raeburn 9166: if (@groups > 0) {
9167: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
9168: $mapparm,$spacequalifierrest);
1.927 albertel 9169: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 9170: }
1.96 www 9171:
1.684 raeburn 9172: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 9173: $env{'course.'.$courseid.'.domain'},
9174: 'course',
9175: ([$seclevelr, 'resource'],
9176: [$seclevelm, 'map' ],
9177: [$seclevel, 'course' ],
9178: [$courselevelr,'resource']));
9179: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 9180:
1.60 www 9181: # ------------------------------------------------------ third, check map parms
1.218 albertel 9182: my %parmhash=();
9183: my $thisparm='';
9184: if (tie(%parmhash,'GDBM_File',
1.620 albertel 9185: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 9186: &GDBM_READER(),0640)) {
1.218 albertel 9187: $thisparm=$parmhash{$symbparm};
9188: untie(%parmhash);
9189: }
1.927 albertel 9190: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 9191: }
1.594 albertel 9192: # ------------------------------------------ fourth, look in resource metadata
1.71 www 9193:
1.218 albertel 9194: $spacequalifierrest=~s/\./\_/;
1.282 albertel 9195: my $filename;
9196: if (!$symbparm) { $symbparm=&symbread(); }
9197: if ($symbparm) {
1.409 www 9198: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 9199: } else {
1.620 albertel 9200: $filename=$env{'request.filename'};
1.282 albertel 9201: }
9202: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 9203: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 9204: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 9205: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 9206:
1.927 albertel 9207: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 9208: if ($symbparm && defined($courseid) &&
1.620 albertel 9209: $courseid eq $env{'request.course.id'}) {
1.624 albertel 9210: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
9211: $env{'course.'.$courseid.'.domain'},
9212: 'course',
1.927 albertel 9213: ([$courselevelm,'map' ],
9214: [$courselevel, 'course']));
9215: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 9216: }
1.145 www 9217: # ------------------------------------------------------------------ Cascade up
1.218 albertel 9218: unless ($space eq '0') {
1.336 albertel 9219: my @parts=split(/_/,$space);
9220: my $id=pop(@parts);
9221: my $part=join('_',@parts);
9222: if ($part eq '') { $part='0'; }
1.927 albertel 9223: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 9224: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 9225: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 9226: }
1.395 albertel 9227: if ($recurse) { return undef; }
9228: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 9229: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 9230: # ---------------------------------------------------- Any other user namespace
9231: } elsif ($realm eq 'environment') {
9232: # ----------------------------------------------------------------- environment
1.620 albertel 9233: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
9234: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 9235: } else {
1.770 albertel 9236: if ($uname eq 'anonymous' && $udom eq '') {
9237: return '';
9238: }
1.219 albertel 9239: my %returnhash=&userenvironment($udom,$uname,
9240: $spacequalifierrest);
9241: return $returnhash{$spacequalifierrest};
9242: }
1.28 www 9243: } elsif ($realm eq 'system') {
1.48 www 9244: # ----------------------------------------------------------------- system.time
9245: if ($space eq 'time') {
9246: return time;
9247: }
1.696 albertel 9248: } elsif ($realm eq 'server') {
9249: # ----------------------------------------------------------------- system.time
9250: if ($space eq 'name') {
9251: return $ENV{'SERVER_NAME'};
9252: }
1.28 www 9253: }
1.48 www 9254: return '';
1.61 www 9255: }
9256:
1.927 albertel 9257: sub get_reply {
9258: my ($reply_value) = @_;
1.940 raeburn 9259: if (ref($reply_value) eq 'ARRAY') {
9260: if (wantarray) {
9261: return @$reply_value;
9262: }
9263: return $reply_value->[0];
9264: } else {
9265: return $reply_value;
1.927 albertel 9266: }
9267: }
9268:
1.691 raeburn 9269: sub check_group_parms {
9270: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
9271: my @groupitems = ();
9272: my $resultitem;
1.927 albertel 9273: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 9274: foreach my $group (@{$groups}) {
9275: foreach my $level (@levels) {
1.927 albertel 9276: my $item = $courseid.'.['.$group.'].'.$level->[0];
9277: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 9278: }
9279: }
9280: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
9281: $env{'course.'.$courseid.'.domain'},
9282: 'course',@groupitems);
9283: return $coursereply;
9284: }
9285:
9286: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 9287: my ($courseid,@groups) = @_;
9288: @groups = sort(@groups);
1.691 raeburn 9289: return @groups;
9290: }
9291:
1.395 albertel 9292: sub packages_tab_default {
9293: my ($uri,$varname)=@_;
9294: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 9295:
9296: my (@extension,@specifics,$do_default);
9297: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 9298: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 9299: if ($pack_type eq 'default') {
9300: $do_default=1;
9301: } elsif ($pack_type eq 'extension') {
9302: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 9303: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 9304: # only look at packages defaults for packages that this id is
1.738 albertel 9305: push(@specifics,[$package,$pack_type,$pack_part]);
9306: }
9307: }
9308: # first look for a package that matches the requested part id
9309: foreach my $package (@specifics) {
9310: my (undef,$pack_type,$pack_part)=@{$package};
9311: next if ($pack_part ne $part);
9312: if (defined($packagetab{"$pack_type&$name&default"})) {
9313: return $packagetab{"$pack_type&$name&default"};
9314: }
9315: }
9316: # look for any possible matching non extension_ package
9317: foreach my $package (@specifics) {
9318: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 9319: if (defined($packagetab{"$pack_type&$name&default"})) {
9320: return $packagetab{"$pack_type&$name&default"};
9321: }
1.585 albertel 9322: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 9323: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
9324: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 9325: }
9326: }
1.738 albertel 9327: # look for any posible extension_ match
9328: foreach my $package (@extension) {
9329: my ($package,$pack_type)=@{$package};
9330: if (defined($packagetab{"$pack_type&$name&default"})) {
9331: return $packagetab{"$pack_type&$name&default"};
9332: }
9333: if (defined($packagetab{$package."&$name&default"})) {
9334: return $packagetab{$package."&$name&default"};
9335: }
9336: }
9337: # look for a global default setting
9338: if ($do_default && defined($packagetab{"default&$name&default"})) {
9339: return $packagetab{"default&$name&default"};
9340: }
1.395 albertel 9341: return undef;
9342: }
9343:
1.334 albertel 9344: sub add_prefix_and_part {
9345: my ($prefix,$part)=@_;
9346: my $keyroot;
9347: if (defined($prefix) && $prefix !~ /^__/) {
9348: # prefix that has a part already
9349: $keyroot=$prefix;
9350: } elsif (defined($prefix)) {
9351: # prefix that is missing a part
9352: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
9353: } else {
9354: # no prefix at all
9355: if (defined($part)) { $keyroot='_'.$part; }
9356: }
9357: return $keyroot;
9358: }
9359:
1.71 www 9360: # ---------------------------------------------------------------- Get metadata
9361:
1.599 albertel 9362: my %metaentry;
1.1070 www 9363: my %importedpartids;
1.71 www 9364: sub metadata {
1.176 www 9365: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 9366: $uri=&declutter($uri);
1.288 albertel 9367: # if it is a non metadata possible uri return quickly
1.529 albertel 9368: if (($uri eq '') ||
9369: (($uri =~ m|^/*adm/|) &&
1.698 albertel 9370: ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.1108 raeburn 9371: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 9372: return undef;
9373: }
1.1140 www 9374: if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/)
1.924 albertel 9375: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 9376: return undef;
1.288 albertel 9377: }
1.73 www 9378: my $filename=$uri;
9379: $uri=~s/\.meta$//;
1.172 www 9380: #
9381: # Is the metadata already cached?
1.177 www 9382: # Look at timestamp of caching
1.172 www 9383: # Everything is cached by the main uri, libraries are never directly cached
9384: #
1.428 albertel 9385: if (!defined($liburi)) {
1.599 albertel 9386: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 9387: if (defined($cached)) { return $result->{':'.$what}; }
9388: }
9389: {
1.1069 www 9390: # Imported parts would go here
1.1070 www 9391: my %importedids=();
9392: my @origfileimportpartids=();
1.1069 www 9393: my $importedparts=0;
1.172 www 9394: #
9395: # Is this a recursive call for a library?
9396: #
1.599 albertel 9397: # if (! exists($metacache{$uri})) {
9398: # $metacache{$uri}={};
9399: # }
1.924 albertel 9400: my $cachetime = 60*60;
1.171 www 9401: if ($liburi) {
9402: $liburi=&declutter($liburi);
9403: $filename=$liburi;
1.401 bowersj2 9404: } else {
1.599 albertel 9405: &devalidate_cache_new('meta',$uri);
9406: undef(%metaentry);
1.401 bowersj2 9407: }
1.140 www 9408: my %metathesekeys=();
1.73 www 9409: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 9410: my $metastring;
1.1140 www 9411: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929 albertel 9412: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 9413: $metastring =
1.929 albertel 9414: &Apache::lonnet::ssi_body($which,
1.924 albertel 9415: ('grade_target' => 'meta'));
9416: $cachetime = 1; # only want this cached in the child not long term
1.1108 raeburn 9417: } elsif (($uri !~ m -^(editupload)/-) &&
9418: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 9419: my $file=&filelocation('',&clutter($filename));
1.599 albertel 9420: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 9421: $metastring=&getfile($file);
1.489 albertel 9422: }
1.208 albertel 9423: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 9424: my $token;
1.140 www 9425: undef %metathesekeys;
1.71 www 9426: while ($token=$parser->get_token) {
1.339 albertel 9427: if ($token->[0] eq 'S') {
9428: if (defined($token->[2]->{'package'})) {
1.172 www 9429: #
9430: # This is a package - get package info
9431: #
1.339 albertel 9432: my $package=$token->[2]->{'package'};
9433: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
9434: if (defined($token->[2]->{'id'})) {
9435: $keyroot.='_'.$token->[2]->{'id'};
9436: }
1.599 albertel 9437: if ($metaentry{':packages'}) {
9438: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 9439: } else {
1.599 albertel 9440: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 9441: }
1.736 albertel 9442: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 9443: my $part=$keyroot;
9444: $part=~s/^\_//;
1.736 albertel 9445: if ($pack_entry=~/^\Q$package\E\&/ ||
9446: $pack_entry=~/^\Q$package\E_0\&/) {
9447: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 9448: # ignore package.tab specified default values
9449: # here &package_tab_default() will fetch those
9450: if ($subp eq 'default') { next; }
1.736 albertel 9451: my $value=$packagetab{$pack_entry};
1.432 albertel 9452: my $unikey;
9453: if ($pack =~ /_0$/) {
9454: $unikey='parameter_0_'.$name;
9455: $part=0;
9456: } else {
9457: $unikey='parameter'.$keyroot.'_'.$name;
9458: }
1.339 albertel 9459: if ($subp eq 'display') {
9460: $value.=' [Part: '.$part.']';
9461: }
1.599 albertel 9462: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 9463: $metathesekeys{$unikey}=1;
1.599 albertel 9464: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
9465: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 9466: }
1.599 albertel 9467: if (defined($metaentry{':'.$unikey.'.default'})) {
9468: $metaentry{':'.$unikey}=
9469: $metaentry{':'.$unikey.'.default'};
1.356 albertel 9470: }
1.339 albertel 9471: }
9472: }
9473: } else {
1.172 www 9474: #
9475: # This is not a package - some other kind of start tag
1.339 albertel 9476: #
9477: my $entry=$token->[1];
1.1068 www 9478: my $unikey='';
1.175 www 9479:
1.339 albertel 9480: if ($entry eq 'import') {
1.175 www 9481: #
9482: # Importing a library here
1.339 albertel 9483: #
1.1067 www 9484: my $location=$parser->get_text('/import');
9485: my $dir=$filename;
9486: $dir=~s|[^/]*$||;
9487: $location=&filelocation($dir,$location);
1.1069 www 9488:
1.1068 www 9489: my $importmode=$token->[2]->{'importmode'};
9490: if ($importmode eq 'problem') {
1.1069 www 9491: # Import as problem/response
1.1068 www 9492: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
9493: } elsif ($importmode eq 'part') {
9494: # Import as part(s)
1.1069 www 9495: $importedparts=1;
9496: # We need to get the original file and the imported file to get the part order correct
9497: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
9498: # Load and inspect original file
1.1070 www 9499: if ($#origfileimportpartids<0) {
9500: undef(%importedpartids);
9501: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
9502: my $origfile=&getfile($origfilelocation);
9503: @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
9504: }
9505:
1.1069 www 9506: # Load and inspect imported file
9507: my $impfile=&getfile($location);
9508: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
9509: if ($#impfilepartids>=0) {
9510: # This problem had parts
1.1070 www 9511: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 9512: } else {
9513: # Importing by turning a single problem into a problem part
9514: # It gets the import-tags ID as part-ID
9515: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 9516: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 9517: }
1.1068 www 9518: } else {
9519: # Normal import
9520: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
9521: if (defined($token->[2]->{'id'})) {
9522: $unikey.='_'.$token->[2]->{'id'};
9523: }
1.1067 www 9524: }
9525:
1.339 albertel 9526: if ($depthcount<20) {
1.736 albertel 9527: my $metadata =
9528: &metadata($uri,'keys', $location,$unikey,
9529: $depthcount+1);
9530: foreach my $meta (split(',',$metadata)) {
9531: $metaentry{':'.$meta}=$metaentry{':'.$meta};
9532: $metathesekeys{$meta}=1;
1.339 albertel 9533: }
1.1068 www 9534:
9535: }
1.1067 www 9536: } else {
9537: #
9538: # Not importing, some other kind of non-package, non-library start tag
9539: #
9540: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
9541: if (defined($token->[2]->{'id'})) {
9542: $unikey.='_'.$token->[2]->{'id'};
9543: }
1.339 albertel 9544: if (defined($token->[2]->{'name'})) {
9545: $unikey.='_'.$token->[2]->{'name'};
9546: }
9547: $metathesekeys{$unikey}=1;
1.736 albertel 9548: foreach my $param (@{$token->[3]}) {
9549: $metaentry{':'.$unikey.'.'.$param} =
9550: $token->[2]->{$param};
1.339 albertel 9551: }
9552: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 9553: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 9554: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
9555: # only ws inside the tag, and not in default, so use default
9556: # as value
1.599 albertel 9557: $metaentry{':'.$unikey}=$default;
1.908 albertel 9558: } elsif ( $internaltext =~ /\S/ ) {
9559: # something interesting inside the tag
9560: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 9561: } else {
1.908 albertel 9562: # no interesting values, don't set a default
1.339 albertel 9563: }
1.172 www 9564: # end of not-a-package not-a-library import
1.339 albertel 9565: }
1.172 www 9566: # end of not-a-package start tag
1.339 albertel 9567: }
1.172 www 9568: # the next is the end of "start tag"
1.339 albertel 9569: }
9570: }
1.483 albertel 9571: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 9572: $extension = lc($extension);
9573: if ($extension eq 'htm') { $extension='html'; }
9574:
1.737 albertel 9575: foreach my $key (keys(%packagetab)) {
1.483 albertel 9576: #no specific packages #how's our extension
9577: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 9578: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 9579: \%metathesekeys);
9580: }
1.883 albertel 9581:
9582: if (!exists($metaentry{':packages'})
9583: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 9584: foreach my $key (keys(%packagetab)) {
1.483 albertel 9585: #no specific packages well let's get default then
9586: if ($key!~/^default&/) { next; }
1.488 albertel 9587: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 9588: \%metathesekeys);
9589: }
9590: }
1.338 www 9591: # are there custom rights to evaluate
1.599 albertel 9592: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 9593:
1.338 www 9594: #
9595: # Importing a rights file here
1.339 albertel 9596: #
9597: unless ($depthcount) {
1.599 albertel 9598: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 9599: my $dir=$filename;
9600: $dir=~s|[^/]*$||;
9601: $location=&filelocation($dir,$location);
1.736 albertel 9602: my $rights_metadata =
9603: &metadata($uri,'keys',$location,'_rights',
9604: $depthcount+1);
9605: foreach my $rights (split(',',$rights_metadata)) {
9606: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
9607: $metathesekeys{$rights}=1;
1.339 albertel 9608: }
9609: }
9610: }
1.737 albertel 9611: # uniqifiy package listing
9612: my %seen;
9613: my @uniq_packages =
9614: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
9615: $metaentry{':packages'} = join(',',@uniq_packages);
9616:
1.1070 www 9617: if ($importedparts) {
9618: # We had imported parts and need to rebuild partorder
9619: $metaentry{':partorder'}='';
9620: $metathesekeys{'partorder'}=1;
9621: for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
9622: if ($origfileimportpartids[$index] eq 'part') {
9623: # original part, part of the problem
9624: $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
9625: } else {
9626: # we have imported parts at this position
9627: $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
9628: }
9629: }
9630: $metaentry{':partorder'}=~s/^\,//;
9631: }
9632:
1.737 albertel 9633: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 9634: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
9635: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924 albertel 9636: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 9637: # this is the end of "was not already recently cached
1.71 www 9638: }
1.599 albertel 9639: return $metaentry{':'.$what};
1.261 albertel 9640: }
9641:
1.488 albertel 9642: sub metadata_create_package_def {
1.483 albertel 9643: my ($uri,$key,$package,$metathesekeys)=@_;
9644: my ($pack,$name,$subp)=split(/\&/,$key);
9645: if ($subp eq 'default') { next; }
9646:
1.599 albertel 9647: if (defined($metaentry{':packages'})) {
9648: $metaentry{':packages'}.=','.$package;
1.483 albertel 9649: } else {
1.599 albertel 9650: $metaentry{':packages'}=$package;
1.483 albertel 9651: }
9652: my $value=$packagetab{$key};
9653: my $unikey;
9654: $unikey='parameter_0_'.$name;
1.599 albertel 9655: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 9656: $$metathesekeys{$unikey}=1;
1.599 albertel 9657: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
9658: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 9659: }
1.599 albertel 9660: if (defined($metaentry{':'.$unikey.'.default'})) {
9661: $metaentry{':'.$unikey}=
9662: $metaentry{':'.$unikey.'.default'};
1.483 albertel 9663: }
9664: }
9665:
1.261 albertel 9666: sub metadata_generate_part0 {
9667: my ($metadata,$metacache,$uri) = @_;
9668: my %allnames;
1.737 albertel 9669: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 9670: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 9671: my $part=$$metacache{':'.$metakey.'.part'};
9672: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 9673: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 9674: $allnames{$name}=$part;
9675: }
9676: }
9677: }
9678: foreach my $name (keys(%allnames)) {
9679: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 9680: my $key=":parameter_0_$name";
1.261 albertel 9681: $$metacache{"$key.part"}='0';
9682: $$metacache{"$key.name"}=$name;
1.428 albertel 9683: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 9684: $allnames{$name}.'_'.$name.
9685: '.type'};
1.428 albertel 9686: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 9687: '.display'};
1.644 www 9688: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 9689: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 9690: $$metacache{"$key.display"}=$olddis;
9691: }
1.71 www 9692: }
9693:
1.764 albertel 9694: # ------------------------------------------------------ Devalidate title cache
9695:
9696: sub devalidate_title_cache {
9697: my ($url)=@_;
9698: if (!$env{'request.course.id'}) { return; }
9699: my $symb=&symbread($url);
9700: if (!$symb) { return; }
9701: my $key=$env{'request.course.id'}."\0".$symb;
9702: &devalidate_cache_new('title',$key);
9703: }
9704:
1.1014 droeschl 9705: # ------------------------------------------------- Get the title of a course
9706:
9707: sub current_course_title {
9708: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
9709: }
1.301 www 9710: # ------------------------------------------------- Get the title of a resource
9711:
9712: sub gettitle {
9713: my $urlsymb=shift;
9714: my $symb=&symbread($urlsymb);
1.534 albertel 9715: if ($symb) {
1.620 albertel 9716: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 9717: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 9718: if (defined($cached)) {
9719: return $result;
9720: }
1.534 albertel 9721: my ($map,$resid,$url)=&decode_symb($symb);
9722: my $title='';
1.907 albertel 9723: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
9724: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
9725: } else {
9726: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
9727: &GDBM_READER(),0640)) {
9728: my $mapid=$bighash{'map_pc_'.&clutter($map)};
9729: $title=$bighash{'title_'.$mapid.'.'.$resid};
9730: untie(%bighash);
9731: }
1.534 albertel 9732: }
9733: $title=~s/\&colon\;/\:/gs;
9734: if ($title) {
1.1159 www 9735: # Remember both $symb and $title for dynamic metadata
9736: $accesshash{$symb.'___crstitle'}=$title;
1.1161 www 9737: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159 www 9738: # Cache this title and then return it
1.599 albertel 9739: return &do_cache_new('title',$key,$title,600);
1.534 albertel 9740: }
9741: $urlsymb=$url;
9742: }
9743: my $title=&metadata($urlsymb,'title');
9744: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
9745: return $title;
1.301 www 9746: }
1.613 albertel 9747:
1.614 albertel 9748: sub get_slot {
9749: my ($which,$cnum,$cdom)=@_;
9750: if (!$cnum || !$cdom) {
1.790 albertel 9751: (undef,my $courseid)=&whichuser();
1.620 albertel 9752: $cdom=$env{'course.'.$courseid.'.domain'};
9753: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 9754: }
1.703 albertel 9755: my $key=join("\0",'slots',$cdom,$cnum,$which);
9756: my %slotinfo;
9757: if (exists($remembered{$key})) {
9758: $slotinfo{$which} = $remembered{$key};
9759: } else {
9760: %slotinfo=&get('slots',[$which],$cdom,$cnum);
9761: &Apache::lonhomework::showhash(%slotinfo);
9762: my ($tmp)=keys(%slotinfo);
9763: if ($tmp=~/^error:/) { return (); }
9764: $remembered{$key} = $slotinfo{$which};
9765: }
1.616 albertel 9766: if (ref($slotinfo{$which}) eq 'HASH') {
9767: return %{$slotinfo{$which}};
9768: }
9769: return $slotinfo{$which};
1.614 albertel 9770: }
1.1150 raeburn 9771:
9772: sub get_reservable_slots {
9773: my ($cnum,$cdom,$uname,$udom) = @_;
9774: my $now = time;
9775: my $reservable_info;
9776: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
9777: if (exists($remembered{$key})) {
9778: $reservable_info = $remembered{$key};
9779: } else {
9780: my %resv;
9781: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
9782: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
9783: $reservable_info = \%resv;
9784: $remembered{$key} = $reservable_info;
9785: }
9786: return $reservable_info;
9787: }
9788:
9789: sub get_course_slots {
9790: my ($cnum,$cdom) = @_;
9791: my $hashid=$cnum.':'.$cdom;
9792: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
9793: if (defined($cached)) {
9794: if (ref($result) eq 'HASH') {
9795: return %{$result};
9796: }
9797: } else {
9798: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
9799: my ($tmp) = keys(%slots);
9800: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
9801: &Apache::lonnet::do_cache_new('allslots',$hashid,\%slots,600);
9802: return %slots;
9803: }
9804: }
9805: return;
9806: }
9807:
9808: sub devalidate_slots_cache {
9809: my ($cnum,$cdom)=@_;
9810: my $hashid=$cnum.':'.$cdom;
9811: &devalidate_cache_new('allslots',$hashid);
9812: }
9813:
1.31 www 9814: # ------------------------------------------------- Update symbolic store links
9815:
9816: sub symblist {
9817: my ($mapname,%newhash)=@_;
1.438 www 9818: $mapname=&deversion(&declutter($mapname));
1.31 www 9819: my %hash;
1.620 albertel 9820: if (($env{'request.course.fn'}) && (%newhash)) {
9821: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 9822: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 9823: foreach my $url (keys(%newhash)) {
1.711 albertel 9824: next if ($url eq 'last_known'
9825: && $env{'form.no_update_last_known'});
9826: $hash{declutter($url)}=&encode_symb($mapname,
9827: $newhash{$url}->[1],
9828: $newhash{$url}->[0]);
1.191 harris41 9829: }
1.31 www 9830: if (untie(%hash)) {
9831: return 'ok';
9832: }
9833: }
9834: }
9835: return 'error';
1.212 www 9836: }
9837:
9838: # --------------------------------------------------------------- Verify a symb
9839:
9840: sub symbverify {
1.510 www 9841: my ($symb,$thisurl)=@_;
9842: my $thisfn=$thisurl;
1.439 www 9843: $thisfn=&declutter($thisfn);
1.215 www 9844: # direct jump to resource in page or to a sequence - will construct own symbs
9845: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
9846: # check URL part
1.409 www 9847: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 9848:
1.431 www 9849: unless ($url eq $thisfn) { return 0; }
1.213 www 9850:
1.216 www 9851: $symb=&symbclean($symb);
1.510 www 9852: $thisurl=&deversion($thisurl);
1.439 www 9853: $thisfn=&deversion($thisfn);
1.213 www 9854:
9855: my %bighash;
9856: my $okay=0;
1.431 www 9857:
1.620 albertel 9858: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 9859: &GDBM_READER(),0640)) {
1.1032 raeburn 9860: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
9861: $thisurl =~ s/\?.+$//;
9862: }
1.510 www 9863: my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1102 raeburn 9864: unless ($ids) {
9865: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
9866: $ids=$bighash{$idkey};
1.216 www 9867: }
9868: if ($ids) {
9869: # ------------------------------------------------------------------- Has ID(s)
1.800 albertel 9870: foreach my $id (split(/\,/,$ids)) {
9871: my ($mapid,$resid)=split(/\./,$id);
1.1032 raeburn 9872: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
9873: $symb =~ s/\?.+$//;
9874: }
1.216 www 9875: if (
9876: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
9877: eq $symb) {
1.620 albertel 9878: if (($env{'request.role.adv'}) ||
1.1101 raeburn 9879: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
9880: ($thisurl eq '/adm/navmaps')) {
1.582 albertel 9881: $okay=1;
9882: }
9883: }
1.216 www 9884: }
9885: }
1.213 www 9886: untie(%bighash);
9887: }
9888: return $okay;
1.31 www 9889: }
9890:
1.210 www 9891: # --------------------------------------------------------------- Clean-up symb
9892:
9893: sub symbclean {
9894: my $symb=shift;
1.568 albertel 9895: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 9896: # remove version from map
9897: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 9898:
1.210 www 9899: # remove version from URL
9900: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 9901:
1.507 www 9902: # remove wrapper
9903:
1.510 www 9904: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 9905: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 9906: return $symb;
1.409 www 9907: }
9908:
9909: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 9910:
9911: sub encode_symb {
9912: my ($map,$resid,$url)=@_;
9913: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
9914: }
1.409 www 9915:
9916: sub decode_symb {
1.568 albertel 9917: my $symb=shift;
9918: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
9919: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 9920: return (&fixversion($map),$resid,&fixversion($url));
9921: }
9922:
9923: sub fixversion {
9924: my $fn=shift;
1.609 banghart 9925: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 9926: my %bighash;
9927: my $uri=&clutter($fn);
1.620 albertel 9928: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 9929: # is this cached?
1.599 albertel 9930: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 9931: if (defined($cached)) { return $result; }
9932: # unfortunately not cached, or expired
1.620 albertel 9933: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 9934: &GDBM_READER(),0640)) {
9935: if ($bighash{'version_'.$uri}) {
9936: my $version=$bighash{'version_'.$uri};
1.444 www 9937: unless (($version eq 'mostrecent') ||
9938: ($version==&getversion($uri))) {
1.440 www 9939: $uri=~s/\.(\w+)$/\.$version\.$1/;
9940: }
9941: }
9942: untie %bighash;
1.413 www 9943: }
1.599 albertel 9944: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 9945: }
9946:
9947: sub deversion {
9948: my $url=shift;
9949: $url=~s/\.\d+\.(\w+)$/\.$1/;
9950: return $url;
1.210 www 9951: }
9952:
1.31 www 9953: # ------------------------------------------------------ Return symb list entry
9954:
9955: sub symbread {
1.249 www 9956: my ($thisfn,$donotrecurse)=@_;
1.542 albertel 9957: my $cache_str='request.symbread.cached.'.$thisfn;
1.620 albertel 9958: if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242 www 9959: # no filename provided? try from environment
1.44 www 9960: unless ($thisfn) {
1.620 albertel 9961: if ($env{'request.symb'}) {
9962: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 9963: }
1.620 albertel 9964: $thisfn=$env{'request.filename'};
1.44 www 9965: }
1.569 albertel 9966: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 9967: # is that filename actually a symb? Verify, clean, and return
9968: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 9969: if (&symbverify($thisfn,$1)) {
1.620 albertel 9970: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 9971: }
1.242 www 9972: }
1.44 www 9973: $thisfn=declutter($thisfn);
1.31 www 9974: my %hash;
1.37 www 9975: my %bighash;
9976: my $syval='';
1.620 albertel 9977: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 9978: my $targetfn = $thisfn;
1.609 banghart 9979: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 9980: $targetfn = 'adm/wrapper/'.$thisfn;
9981: }
1.687 albertel 9982: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
9983: $targetfn=$1;
9984: }
1.620 albertel 9985: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 9986: &GDBM_READER(),0640)) {
1.481 raeburn 9987: $syval=$hash{$targetfn};
1.37 www 9988: untie(%hash);
9989: }
9990: # ---------------------------------------------------------- There was an entry
9991: if ($syval) {
1.601 albertel 9992: #unless ($syval=~/\_\d+$/) {
1.620 albertel 9993: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 9994: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 9995: #return $env{$cache_str}='';
1.601 albertel 9996: #}
9997: #$syval.=$1;
9998: #}
1.37 www 9999: } else {
10000: # ------------------------------------------------------- Was not in symb table
1.620 albertel 10001: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 10002: &GDBM_READER(),0640)) {
1.37 www 10003: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 10004: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 10005: unless ($ids) {
10006: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 10007: }
10008: unless ($ids) {
10009: # alias?
10010: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 10011: }
1.37 www 10012: if ($ids) {
10013: # ------------------------------------------------------------------- Has ID(s)
10014: my @possibilities=split(/\,/,$ids);
1.39 www 10015: if ($#possibilities==0) {
10016: # ----------------------------------------------- There is only one possibility
1.37 www 10017: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 10018: $syval=&encode_symb($bighash{'map_id_'.$mapid},
10019: $resid,$thisfn);
1.249 www 10020: } elsif (!$donotrecurse) {
1.39 www 10021: # ------------------------------------------ There is more than one possibility
10022: my $realpossible=0;
1.800 albertel 10023: foreach my $id (@possibilities) {
10024: my $file=$bighash{'src_'.$id};
1.39 www 10025: if (&allowed('bre',$file)) {
1.800 albertel 10026: my ($mapid,$resid)=split(/\./,$id);
1.39 www 10027: if ($bighash{'map_type_'.$mapid} ne 'page') {
10028: $realpossible++;
1.626 albertel 10029: $syval=&encode_symb($bighash{'map_id_'.$mapid},
10030: $resid,$thisfn);
1.39 www 10031: }
10032: }
1.191 harris41 10033: }
1.39 www 10034: if ($realpossible!=1) { $syval=''; }
1.249 www 10035: } else {
10036: $syval='';
1.37 www 10037: }
10038: }
10039: untie(%bighash)
1.481 raeburn 10040: }
1.31 www 10041: }
1.62 www 10042: if ($syval) {
1.620 albertel 10043: return $env{$cache_str}=$syval;
1.62 www 10044: }
1.31 www 10045: }
1.949 raeburn 10046: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 10047: return $env{$cache_str}='';
1.31 www 10048: }
10049:
10050: # ---------------------------------------------------------- Return random seed
10051:
1.32 www 10052: sub numval {
10053: my $txt=shift;
10054: $txt=~tr/A-J/0-9/;
10055: $txt=~tr/a-j/0-9/;
10056: $txt=~tr/K-T/0-9/;
10057: $txt=~tr/k-t/0-9/;
10058: $txt=~tr/U-Z/0-5/;
10059: $txt=~tr/u-z/0-5/;
10060: $txt=~s/\D//g;
1.564 albertel 10061: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 10062: return int($txt);
1.368 albertel 10063: }
10064:
1.484 albertel 10065: sub numval2 {
10066: my $txt=shift;
10067: $txt=~tr/A-J/0-9/;
10068: $txt=~tr/a-j/0-9/;
10069: $txt=~tr/K-T/0-9/;
10070: $txt=~tr/k-t/0-9/;
10071: $txt=~tr/U-Z/0-5/;
10072: $txt=~tr/u-z/0-5/;
10073: $txt=~s/\D//g;
10074: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10075: my $total;
10076: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 10077: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 10078: return int($total);
10079: }
10080:
1.575 albertel 10081: sub numval3 {
10082: use integer;
10083: my $txt=shift;
10084: $txt=~tr/A-J/0-9/;
10085: $txt=~tr/a-j/0-9/;
10086: $txt=~tr/K-T/0-9/;
10087: $txt=~tr/k-t/0-9/;
10088: $txt=~tr/U-Z/0-5/;
10089: $txt=~tr/u-z/0-5/;
10090: $txt=~s/\D//g;
10091: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10092: my $total;
10093: foreach my $val (@txts) { $total+=$val; }
10094: if ($_64bit) { $total=(($total<<32)>>32); }
10095: return $total;
10096: }
10097:
1.675 albertel 10098: sub digest {
10099: my ($data)=@_;
10100: my $digest=&Digest::MD5::md5($data);
10101: my ($a,$b,$c,$d)=unpack("iiii",$digest);
10102: my ($e,$f);
10103: {
10104: use integer;
10105: $e=($a+$b);
10106: $f=($c+$d);
10107: if ($_64bit) {
10108: $e=(($e<<32)>>32);
10109: $f=(($f<<32)>>32);
10110: }
10111: }
10112: if (wantarray) {
10113: return ($e,$f);
10114: } else {
10115: my $g;
10116: {
10117: use integer;
10118: $g=($e+$f);
10119: if ($_64bit) {
10120: $g=(($g<<32)>>32);
10121: }
10122: }
10123: return $g;
10124: }
10125: }
10126:
1.368 albertel 10127: sub latest_rnd_algorithm_id {
1.675 albertel 10128: return '64bit5';
1.366 albertel 10129: }
1.32 www 10130:
1.503 albertel 10131: sub get_rand_alg {
10132: my ($courseid)=@_;
1.790 albertel 10133: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 10134: if ($courseid) {
1.620 albertel 10135: return $env{"course.$courseid.rndseed"};
1.503 albertel 10136: }
10137: return &latest_rnd_algorithm_id();
10138: }
10139:
1.562 albertel 10140: sub validCODE {
10141: my ($CODE)=@_;
10142: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
10143: return 0;
10144: }
10145:
1.491 albertel 10146: sub getCODE {
1.620 albertel 10147: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 10148: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
10149: defined($Apache::lonhomework::parsing_a_task) ) &&
10150: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 10151: return $Apache::lonhomework::history{'resource.CODE'};
10152: }
10153: return undef;
10154: }
1.1133 foxr 10155: #
10156: # Determines the random seed for a specific context:
10157: #
10158: # parameters:
10159: # symb - in course context the symb for the seed.
10160: # course_id - The course id of the form domain_coursenum.
10161: # domain - Domain for the user.
10162: # course - Course for the user.
10163: # cenv - environment of the course.
10164: #
10165: # NOTE:
10166: # All parameters are picked out of the environment if missing
10167: # or not defined.
10168: # If a symb cannot be determined the current time is used instead.
10169: #
10170: # For a given well defined symb, courside, domain, username,
10171: # and course environment, the seed is reproducible.
10172: #
1.31 www 10173: sub rndseed {
1.1133 foxr 10174: my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790 albertel 10175: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 10176: if (!defined($symb)) {
1.366 albertel 10177: unless ($symb=$wsymb) { return time; }
10178: }
1.1146 foxr 10179: if (!defined $courseid) {
10180: $courseid=$wcourseid;
10181: }
10182: if (!defined $domain) { $domain=$wdomain; }
10183: if (!defined $username) { $username=$wusername }
1.1133 foxr 10184:
10185: my $which;
10186: if (defined($cenv->{'rndseed'})) {
10187: $which = $cenv->{'rndseed'};
10188: } else {
10189: $which =&get_rand_alg($courseid);
10190: }
1.491 albertel 10191: if (defined(&getCODE())) {
1.1133 foxr 10192:
1.675 albertel 10193: if ($which eq '64bit5') {
10194: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
10195: } elsif ($which eq '64bit4') {
1.575 albertel 10196: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
10197: } else {
10198: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
10199: }
1.675 albertel 10200: } elsif ($which eq '64bit5') {
10201: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 10202: } elsif ($which eq '64bit4') {
10203: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 10204: } elsif ($which eq '64bit3') {
10205: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 10206: } elsif ($which eq '64bit2') {
10207: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 10208: } elsif ($which eq '64bit') {
10209: return &rndseed_64bit($symb,$courseid,$domain,$username);
10210: }
10211: return &rndseed_32bit($symb,$courseid,$domain,$username);
10212: }
10213:
10214: sub rndseed_32bit {
10215: my ($symb,$courseid,$domain,$username)=@_;
10216: {
10217: use integer;
10218: my $symbchck=unpack("%32C*",$symb) << 27;
10219: my $symbseed=numval($symb) << 22;
10220: my $namechck=unpack("%32C*",$username) << 17;
10221: my $nameseed=numval($username) << 12;
10222: my $domainseed=unpack("%32C*",$domain) << 7;
10223: my $courseseed=unpack("%32C*",$courseid);
10224: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 10225: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10226: #&logthis("rndseed :$num:$symb");
1.564 albertel 10227: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 10228: return $num;
10229: }
10230: }
10231:
10232: sub rndseed_64bit {
10233: my ($symb,$courseid,$domain,$username)=@_;
10234: {
10235: use integer;
10236: my $symbchck=unpack("%32S*",$symb) << 21;
10237: my $symbseed=numval($symb) << 10;
10238: my $namechck=unpack("%32S*",$username);
10239:
10240: my $nameseed=numval($username) << 21;
10241: my $domainseed=unpack("%32S*",$domain) << 10;
10242: my $courseseed=unpack("%32S*",$courseid);
10243:
10244: my $num1=$symbchck+$symbseed+$namechck;
10245: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 10246: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10247: #&logthis("rndseed :$num:$symb");
1.564 albertel 10248: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 10249: return "$num1,$num2";
1.155 albertel 10250: }
1.366 albertel 10251: }
10252:
1.443 albertel 10253: sub rndseed_64bit2 {
10254: my ($symb,$courseid,$domain,$username)=@_;
10255: {
10256: use integer;
10257: # strings need to be an even # of cahracters long, it it is odd the
10258: # last characters gets thrown away
10259: my $symbchck=unpack("%32S*",$symb.' ') << 21;
10260: my $symbseed=numval($symb) << 10;
10261: my $namechck=unpack("%32S*",$username.' ');
10262:
10263: my $nameseed=numval($username) << 21;
1.501 albertel 10264: my $domainseed=unpack("%32S*",$domain.' ') << 10;
10265: my $courseseed=unpack("%32S*",$courseid.' ');
10266:
10267: my $num1=$symbchck+$symbseed+$namechck;
10268: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 10269: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10270: #&logthis("rndseed :$num:$symb");
1.803 albertel 10271: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 10272: return "$num1,$num2";
10273: }
10274: }
10275:
10276: sub rndseed_64bit3 {
10277: my ($symb,$courseid,$domain,$username)=@_;
10278: {
10279: use integer;
10280: # strings need to be an even # of cahracters long, it it is odd the
10281: # last characters gets thrown away
10282: my $symbchck=unpack("%32S*",$symb.' ') << 21;
10283: my $symbseed=numval2($symb) << 10;
10284: my $namechck=unpack("%32S*",$username.' ');
10285:
10286: my $nameseed=numval2($username) << 21;
1.443 albertel 10287: my $domainseed=unpack("%32S*",$domain.' ') << 10;
10288: my $courseseed=unpack("%32S*",$courseid.' ');
10289:
10290: my $num1=$symbchck+$symbseed+$namechck;
10291: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 10292: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10293: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 10294: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 10295:
1.503 albertel 10296: return "$num1:$num2";
1.443 albertel 10297: }
10298: }
10299:
1.575 albertel 10300: sub rndseed_64bit4 {
10301: my ($symb,$courseid,$domain,$username)=@_;
10302: {
10303: use integer;
10304: # strings need to be an even # of cahracters long, it it is odd the
10305: # last characters gets thrown away
10306: my $symbchck=unpack("%32S*",$symb.' ') << 21;
10307: my $symbseed=numval3($symb) << 10;
10308: my $namechck=unpack("%32S*",$username.' ');
10309:
10310: my $nameseed=numval3($username) << 21;
10311: my $domainseed=unpack("%32S*",$domain.' ') << 10;
10312: my $courseseed=unpack("%32S*",$courseid.' ');
10313:
10314: my $num1=$symbchck+$symbseed+$namechck;
10315: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 10316: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10317: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 10318: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 10319:
1.575 albertel 10320: return "$num1:$num2";
10321: }
10322: }
10323:
1.675 albertel 10324: sub rndseed_64bit5 {
10325: my ($symb,$courseid,$domain,$username)=@_;
10326: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
10327: return "$num1:$num2";
10328: }
10329:
1.366 albertel 10330: sub rndseed_CODE_64bit {
10331: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 10332: {
1.366 albertel 10333: use integer;
1.443 albertel 10334: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 10335: my $symbseed=numval2($symb);
1.491 albertel 10336: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
10337: my $CODEseed=numval(&getCODE());
1.443 albertel 10338: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 10339: my $num1=$symbseed+$CODEchck;
10340: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 10341: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
10342: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 10343: if ($_64bit) { $num1=(($num1<<32)>>32); }
10344: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 10345: return "$num1:$num2";
1.366 albertel 10346: }
10347: }
10348:
1.575 albertel 10349: sub rndseed_CODE_64bit4 {
10350: my ($symb,$courseid,$domain,$username)=@_;
10351: {
10352: use integer;
10353: my $symbchck=unpack("%32S*",$symb.' ') << 16;
10354: my $symbseed=numval3($symb);
10355: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
10356: my $CODEseed=numval3(&getCODE());
10357: my $courseseed=unpack("%32S*",$courseid.' ');
10358: my $num1=$symbseed+$CODEchck;
10359: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 10360: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
10361: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 10362: if ($_64bit) { $num1=(($num1<<32)>>32); }
10363: if ($_64bit) { $num2=(($num2<<32)>>32); }
10364: return "$num1:$num2";
10365: }
10366: }
10367:
1.675 albertel 10368: sub rndseed_CODE_64bit5 {
10369: my ($symb,$courseid,$domain,$username)=@_;
10370: my $code = &getCODE();
10371: my ($num1,$num2)=&digest("$symb,$courseid,$code");
10372: return "$num1:$num2";
10373: }
10374:
1.366 albertel 10375: sub setup_random_from_rndseed {
10376: my ($rndseed)=@_;
1.503 albertel 10377: if ($rndseed =~/([,:])/) {
10378: my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366 albertel 10379: &Math::Random::random_set_seed(abs($num1),abs($num2));
10380: } else {
10381: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 10382: }
1.36 albertel 10383: }
10384:
1.474 albertel 10385: sub latest_receipt_algorithm_id {
1.835 albertel 10386: return 'receipt3';
1.474 albertel 10387: }
10388:
1.480 www 10389: sub recunique {
10390: my $fucourseid=shift;
10391: my $unique;
1.835 albertel 10392: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
10393: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 10394: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 10395: } else {
10396: $unique=$perlvar{'lonReceipt'};
10397: }
10398: return unpack("%32C*",$unique);
10399: }
10400:
10401: sub recprefix {
10402: my $fucourseid=shift;
10403: my $prefix;
1.835 albertel 10404: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
10405: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 10406: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 10407: } else {
10408: $prefix=$perlvar{'lonHostID'};
10409: }
10410: return unpack("%32C*",$prefix);
10411: }
10412:
1.76 www 10413: sub ireceipt {
1.474 albertel 10414: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 10415:
10416: my $return =&recprefix($fucourseid).'-';
10417:
10418: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
10419: $env{'request.state'} eq 'construct') {
10420: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
10421: return $return;
10422: }
10423:
1.76 www 10424: my $cuname=unpack("%32C*",$funame);
10425: my $cudom=unpack("%32C*",$fudom);
10426: my $cucourseid=unpack("%32C*",$fucourseid);
10427: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 10428: my $cunique=&recunique($fucourseid);
1.474 albertel 10429: my $cpart=unpack("%32S*",$part);
1.835 albertel 10430: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
10431:
1.790 albertel 10432: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 10433:
10434: $return.= ($cunique%$cuname+
10435: $cunique%$cudom+
10436: $cusymb%$cuname+
10437: $cusymb%$cudom+
10438: $cucourseid%$cuname+
10439: $cucourseid%$cudom+
10440: $cpart%$cuname+
10441: $cpart%$cudom);
10442: } else {
10443: $return.= ($cunique%$cuname+
10444: $cunique%$cudom+
10445: $cusymb%$cuname+
10446: $cusymb%$cudom+
10447: $cucourseid%$cuname+
10448: $cucourseid%$cudom);
10449: }
10450: return $return;
1.76 www 10451: }
10452:
10453: sub receipt {
1.474 albertel 10454: my ($part)=@_;
1.790 albertel 10455: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 10456: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 10457: }
1.260 ng 10458:
1.790 albertel 10459: sub whichuser {
10460: my ($passedsymb)=@_;
10461: my ($symb,$courseid,$domain,$name,$publicuser);
10462: if (defined($env{'form.grade_symb'})) {
10463: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
10464: my $allowed=&allowed('vgr',$tmp_courseid);
10465: if (!$allowed &&
10466: exists($env{'request.course.sec'}) &&
10467: $env{'request.course.sec'} !~ /^\s*$/) {
10468: $allowed=&allowed('vgr',$tmp_courseid.
10469: '/'.$env{'request.course.sec'});
10470: }
10471: if ($allowed) {
10472: ($symb)=&get_env_multiple('form.grade_symb');
10473: $courseid=$tmp_courseid;
10474: ($domain)=&get_env_multiple('form.grade_domain');
10475: ($name)=&get_env_multiple('form.grade_username');
10476: return ($symb,$courseid,$domain,$name,$publicuser);
10477: }
10478: }
10479: if (!$passedsymb) {
10480: $symb=&symbread();
10481: } else {
10482: $symb=$passedsymb;
10483: }
10484: $courseid=$env{'request.course.id'};
10485: $domain=$env{'user.domain'};
10486: $name=$env{'user.name'};
10487: if ($name eq 'public' && $domain eq 'public') {
10488: if (!defined($env{'form.username'})) {
10489: $env{'form.username'}.=time.rand(10000000);
10490: }
10491: $name.=$env{'form.username'};
10492: }
10493: return ($symb,$courseid,$domain,$name,$publicuser);
10494:
10495: }
10496:
1.36 albertel 10497: # ------------------------------------------------------------ Serves up a file
1.472 albertel 10498: # returns either the contents of the file or
10499: # -1 if the file doesn't exist
1.481 raeburn 10500: #
10501: # if the target is a file that was uploaded via DOCS,
10502: # a check will be made to see if a current copy exists on the local server,
10503: # if it does this will be served, otherwise a copy will be retrieved from
10504: # the home server for the course and stored in /home/httpd/html/userfiles on
10505: # the local server.
1.472 albertel 10506:
1.36 albertel 10507: sub getfile {
1.538 albertel 10508: my ($file) = @_;
1.609 banghart 10509: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 10510: &repcopy($file);
10511: return &readfile($file);
10512: }
10513:
10514: sub repcopy_userfile {
10515: my ($file)=@_;
1.1142 raeburn 10516: my $londocroot = $perlvar{'lonDocRoot'};
10517: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164 raeburn 10518: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538 albertel 10519: my ($cdom,$cnum,$filename) =
1.811 albertel 10520: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 10521: my $uri="/uploaded/$cdom/$cnum/$filename";
10522: if (-e "$file") {
1.828 www 10523: # we already have a local copy, check it out
1.538 albertel 10524: my @fileinfo = stat($file);
1.828 www 10525: my $rtncode;
10526: my $info;
1.538 albertel 10527: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 10528: if ($lwpresp ne 'ok') {
1.828 www 10529: # there is no such file anymore, even though we had a local copy
1.482 albertel 10530: if ($rtncode eq '404') {
1.538 albertel 10531: unlink($file);
1.482 albertel 10532: }
10533: return -1;
10534: }
10535: if ($info < $fileinfo[9]) {
1.828 www 10536: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 10537: return 'ok';
1.828 www 10538: } else {
10539: # the file is outdated, get rid of it
10540: unlink($file);
1.482 albertel 10541: }
1.828 www 10542: }
10543: # one way or the other, at this point, we don't have the file
10544: # construct the correct path for the file
10545: my @parts = ($cdom,$cnum);
10546: if ($filename =~ m|^(.+)/[^/]+$|) {
10547: push @parts, split(/\//,$1);
10548: }
10549: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
10550: foreach my $part (@parts) {
10551: $path .= '/'.$part;
10552: if (!-e $path) {
10553: mkdir($path,0770);
1.482 albertel 10554: }
10555: }
1.828 www 10556: # now the path exists for sure
10557: # get a user agent
10558: my $ua=new LWP::UserAgent;
10559: my $transferfile=$file.'.in.transfer';
10560: # FIXME: this should flock
10561: if (-e $transferfile) { return 'ok'; }
10562: my $request;
10563: $uri=~s/^\///;
1.980 raeburn 10564: my $homeserver = &homeserver($cnum,$cdom);
10565: my $protocol = $protocol{$homeserver};
10566: $protocol = 'http' if ($protocol ne 'https');
10567: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 10568: my $response=$ua->request($request,$transferfile);
10569: # did it work?
10570: if ($response->is_error()) {
10571: unlink($transferfile);
10572: &logthis("Userfile repcopy failed for $uri");
10573: return -1;
10574: }
10575: # worked, rename the transfer file
10576: rename($transferfile,$file);
1.607 raeburn 10577: return 'ok';
1.481 raeburn 10578: }
10579:
1.517 albertel 10580: sub tokenwrapper {
10581: my $uri=shift;
1.980 raeburn 10582: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 10583: $uri=~s|^/||;
1.620 albertel 10584: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 10585: my $token=$1;
1.552 albertel 10586: my (undef,$udom,$uname,$file)=split('/',$uri,4);
10587: if ($udom && $uname && $file) {
10588: $file=~s|(\?\.*)*$||;
1.949 raeburn 10589: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 10590: my $homeserver = &homeserver($uname,$udom);
10591: my $protocol = $protocol{$homeserver};
10592: $protocol = 'http' if ($protocol ne 'https');
10593: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 10594: (($uri=~/\?/)?'&':'?').'token='.$token.
10595: '&tokenissued='.$perlvar{'lonHostID'};
10596: } else {
10597: return '/adm/notfound.html';
10598: }
10599: }
10600:
1.828 www 10601: # call with reqtype HEAD: get last modification time
10602: # call with reqtype GET: get the file contents
10603: # Do not call this with reqtype GET for large files! It loads everything into memory
10604: #
1.481 raeburn 10605: sub getuploaded {
10606: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
10607: $uri=~s/^\///;
1.980 raeburn 10608: my $homeserver = &homeserver($cnum,$cdom);
10609: my $protocol = $protocol{$homeserver};
10610: $protocol = 'http' if ($protocol ne 'https');
10611: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 10612: my $ua=new LWP::UserAgent;
10613: my $request=new HTTP::Request($reqtype,$uri);
10614: my $response=$ua->request($request);
10615: $$rtncode = $response->code;
1.482 albertel 10616: if (! $response->is_success()) {
10617: return 'failed';
10618: }
10619: if ($reqtype eq 'HEAD') {
1.486 www 10620: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 10621: } elsif ($reqtype eq 'GET') {
10622: $$info = $response->content;
1.472 albertel 10623: }
1.482 albertel 10624: return 'ok';
1.36 albertel 10625: }
10626:
1.481 raeburn 10627: sub readfile {
10628: my $file = shift;
10629: if ( (! -e $file ) || ($file eq '') ) { return -1; };
10630: my $fh;
10631: open($fh,"<$file");
10632: my $a='';
1.800 albertel 10633: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 10634: return $a;
10635: }
10636:
1.36 albertel 10637: sub filelocation {
1.590 banghart 10638: my ($dir,$file) = @_;
10639: my $location;
10640: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 10641:
10642: if ($file =~ m-^/adm/-) {
10643: $file=~s-^/adm/wrapper/-/-;
10644: $file=~s-^/adm/coursedocs/showdoc/-/-;
10645: }
1.882 albertel 10646:
1.1139 www 10647: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956 raeburn 10648: $location = $file;
1.609 banghart 10649: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 10650: my ($udom,$uname,$filename)=
1.811 albertel 10651: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 10652: my $home=&homeserver($uname,$udom);
10653: my $is_me=0;
10654: my @ids=¤t_machine_ids();
10655: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
10656: if ($is_me) {
1.1117 foxr 10657: $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 10658: } else {
10659: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
10660: $udom.'/'.$uname.'/'.$filename;
10661: }
1.882 albertel 10662: } elsif ($file =~ m-^/adm/-) {
10663: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 10664: } else {
10665: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139 www 10666: $file=~s:^/(res|priv)/:/:;
10667: my $space=$1;
1.590 banghart 10668: if ( !( $file =~ m:^/:) ) {
10669: $location = $dir. '/'.$file;
10670: } else {
1.1142 raeburn 10671: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590 banghart 10672: }
1.59 albertel 10673: }
1.590 banghart 10674: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 10675: while ($location=~m{/\.\./}) {
10676: if ($location =~ m{/[^/]+/\.\./}) {
10677: $location=~ s{/[^/]+/\.\./}{/}g;
10678: } else {
10679: $location=~ s{/\.\./}{/}g;
10680: }
10681: } #remove dir/..
1.590 banghart 10682: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
10683: return $location;
1.46 www 10684: }
1.36 albertel 10685:
1.46 www 10686: sub hreflocation {
10687: my ($dir,$file)=@_;
1.980 raeburn 10688: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 10689: $file=filelocation($dir,$file);
1.700 albertel 10690: } elsif ($file=~m-^/adm/-) {
10691: $file=~s-^/adm/wrapper/-/-;
10692: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 10693: }
10694: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
10695: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
10696: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143 raeburn 10697: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
10698: {/uploaded/$1/$2/}x;
1.46 www 10699: }
1.913 albertel 10700: if ($file=~ m{^/userfiles/}) {
10701: $file =~ s{^/userfiles/}{/uploaded/};
10702: }
1.462 albertel 10703: return $file;
1.465 albertel 10704: }
10705:
1.1139 www 10706:
10707:
10708:
10709:
1.465 albertel 10710: sub current_machine_domains {
1.853 albertel 10711: return &machine_domains(&hostname($perlvar{'lonHostID'}));
10712: }
10713:
10714: sub machine_domains {
10715: my ($hostname) = @_;
1.465 albertel 10716: my @domains;
1.838 albertel 10717: my %hostname = &all_hostnames();
1.465 albertel 10718: while( my($id, $name) = each(%hostname)) {
1.467 matthew 10719: # &logthis("-$id-$name-$hostname-");
1.465 albertel 10720: if ($hostname eq $name) {
1.844 albertel 10721: push(@domains,&host_domain($id));
1.465 albertel 10722: }
10723: }
10724: return @domains;
10725: }
10726:
10727: sub current_machine_ids {
1.853 albertel 10728: return &machine_ids(&hostname($perlvar{'lonHostID'}));
10729: }
10730:
10731: sub machine_ids {
10732: my ($hostname) = @_;
10733: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 10734: my @ids;
1.888 albertel 10735: my %name_to_host = &all_names();
1.889 albertel 10736: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
10737: return @{ $name_to_host{$hostname} };
10738: }
10739: return;
1.31 www 10740: }
10741:
1.824 raeburn 10742: sub additional_machine_domains {
10743: my @domains;
10744: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
10745: while( my $line = <$fh>) {
10746: $line =~ s/\s//g;
10747: push(@domains,$line);
10748: }
10749: return @domains;
10750: }
10751:
10752: sub default_login_domain {
10753: my $domain = $perlvar{'lonDefDomain'};
10754: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
10755: foreach my $posdom (¤t_machine_domains(),
10756: &additional_machine_domains()) {
10757: if (lc($posdom) eq lc($testdomain)) {
10758: $domain=$posdom;
10759: last;
10760: }
10761: }
10762: return $domain;
10763: }
10764:
1.31 www 10765: # ------------------------------------------------------------- Declutters URLs
10766:
10767: sub declutter {
10768: my $thisfn=shift;
1.569 albertel 10769: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479 albertel 10770: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31 www 10771: $thisfn=~s/^\///;
1.697 albertel 10772: $thisfn=~s|^adm/wrapper/||;
10773: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 10774: $thisfn=~s/^res\///;
1.1172 bisitz 10775: $thisfn=~s/^priv\///;
1.1032 raeburn 10776: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
10777: $thisfn=~s/\?.+$//;
10778: }
1.268 www 10779: return $thisfn;
10780: }
10781:
10782: # ------------------------------------------------------------- Clutter up URLs
10783:
10784: sub clutter {
10785: my $thisfn='/'.&declutter(shift);
1.887 albertel 10786: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 10787: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 10788: $thisfn='/res'.$thisfn;
10789: }
1.1031 raeburn 10790: if ($thisfn !~m|^/adm|) {
10791: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 10792: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 10793: } else {
10794: my ($ext) = ($thisfn =~ /\.(\w+)$/);
10795: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 10796: if ($embstyle eq 'ssi'
10797: || ($embstyle eq 'hdn')
10798: || ($embstyle eq 'rat')
10799: || ($embstyle eq 'prv')
10800: || ($embstyle eq 'ign')) {
10801: #do nothing with these
10802: } elsif (($embstyle eq 'img')
1.695 albertel 10803: || ($embstyle eq 'emb')
10804: || ($embstyle eq 'wrp')) {
10805: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 10806: } elsif ($embstyle eq 'unk'
10807: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 10808: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 10809: } else {
1.718 www 10810: # &logthis("Got a blank emb style");
1.695 albertel 10811: }
1.694 albertel 10812: }
10813: }
1.31 www 10814: return $thisfn;
1.12 www 10815: }
10816:
1.787 albertel 10817: sub clutter_with_no_wrapper {
10818: my $uri = &clutter(shift);
10819: if ($uri =~ m-^/adm/-) {
10820: $uri =~ s-^/adm/wrapper/-/-;
10821: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
10822: }
10823: return $uri;
10824: }
10825:
1.557 albertel 10826: sub freeze_escape {
10827: my ($value)=@_;
10828: if (ref($value)) {
10829: $value=&nfreeze($value);
10830: return '__FROZEN__'.&escape($value);
10831: }
10832: return &escape($value);
10833: }
10834:
1.11 www 10835:
1.557 albertel 10836: sub thaw_unescape {
10837: my ($value)=@_;
10838: if ($value =~ /^__FROZEN__/) {
10839: substr($value,0,10,undef);
10840: $value=&unescape($value);
10841: return &thaw($value);
10842: }
10843: return &unescape($value);
10844: }
10845:
1.436 albertel 10846: sub correct_line_ends {
10847: my ($result)=@_;
10848: $$result =~s/\r\n/\n/mg;
10849: $$result =~s/\r/\n/mg;
1.415 albertel 10850: }
1.1 albertel 10851: # ================================================================ Main Program
10852:
1.184 www 10853: sub goodbye {
1.204 albertel 10854: &logthis("Starting Shut down");
1.443 albertel 10855: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 10856: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 10857: #converted
1.599 albertel 10858: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 10859: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
10860: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
10861: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 10862: #1.1 only
1.870 albertel 10863: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
10864: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
10865: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
10866: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
10867: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 10868: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
10869: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 10870: &flushcourselogs();
10871: &logthis("Shutting down");
10872: }
10873:
1.852 albertel 10874: sub get_dns {
1.869 albertel 10875: my ($url,$func,$ignore_cache) = @_;
10876: if (!$ignore_cache) {
10877: my ($content,$cached)=
10878: &Apache::lonnet::is_cached_new('dns',$url);
10879: if ($cached) {
10880: &$func($content);
10881: return;
10882: }
10883: }
10884:
10885: my %alldns;
1.852 albertel 10886: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
10887: foreach my $dns (<$config>) {
10888: next if ($dns !~ /^\^(\S*)/x);
1.979 raeburn 10889: my $line = $1;
10890: my ($host,$protocol) = split(/:/,$line);
10891: if ($protocol ne 'https') {
10892: $protocol = 'http';
10893: }
10894: $alldns{$host} = $protocol;
1.869 albertel 10895: }
10896: while (%alldns) {
10897: my ($dns) = keys(%alldns);
1.852 albertel 10898: my $ua=new LWP::UserAgent;
1.1134 raeburn 10899: $ua->timeout(30);
1.979 raeburn 10900: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 10901: my $response=$ua->request($request);
1.979 raeburn 10902: delete($alldns{$dns});
1.852 albertel 10903: next if ($response->is_error());
10904: my @content = split("\n",$response->content);
1.869 albertel 10905: &Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852 albertel 10906: &$func(\@content);
1.869 albertel 10907: return;
1.852 albertel 10908: }
10909: close($config);
1.871 albertel 10910: my $which = (split('/',$url))[3];
10911: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
10912: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 10913: my @content = <$config>;
10914: &$func(\@content);
10915: return;
1.852 albertel 10916: }
1.327 albertel 10917: # ------------------------------------------------------------ Read domain file
10918: {
1.852 albertel 10919: my $loaded;
1.846 albertel 10920: my %domain;
10921:
1.852 albertel 10922: sub parse_domain_tab {
10923: my ($lines) = @_;
10924: foreach my $line (@$lines) {
10925: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 10926:
1.846 albertel 10927: chomp($line);
1.852 albertel 10928: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 10929: my %this_domain;
10930: foreach my $field ('description', 'auth_def', 'auth_arg_def',
10931: 'lang_def', 'city', 'longi', 'lati',
10932: 'primary') {
10933: $this_domain{$field} = shift(@elements);
10934: }
10935: $domain{$name} = \%this_domain;
1.852 albertel 10936: }
10937: }
1.864 albertel 10938:
10939: sub reset_domain_info {
10940: undef($loaded);
10941: undef(%domain);
10942: }
10943:
1.852 albertel 10944: sub load_domain_tab {
1.869 albertel 10945: my ($ignore_cache) = @_;
10946: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852 albertel 10947: my $fh;
10948: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
10949: my @lines = <$fh>;
10950: &parse_domain_tab(\@lines);
1.448 albertel 10951: }
1.852 albertel 10952: close($fh);
10953: $loaded = 1;
1.327 albertel 10954: }
1.846 albertel 10955:
10956: sub domain {
1.852 albertel 10957: &load_domain_tab() if (!$loaded);
10958:
1.846 albertel 10959: my ($name,$what) = @_;
10960: return if ( !exists($domain{$name}) );
10961:
10962: if (!$what) {
10963: return $domain{$name}{'description'};
10964: }
10965: return $domain{$name}{$what};
10966: }
1.974 raeburn 10967:
10968: sub domain_info {
10969: &load_domain_tab() if (!$loaded);
10970: return %domain;
10971: }
10972:
1.327 albertel 10973: }
10974:
10975:
1.1 albertel 10976: # ------------------------------------------------------------- Read hosts file
10977: {
1.838 albertel 10978: my %hostname;
1.844 albertel 10979: my %hostdom;
1.845 albertel 10980: my %libserv;
1.852 albertel 10981: my $loaded;
1.888 albertel 10982: my %name_to_host;
1.1074 raeburn 10983: my %internetdom;
1.1107 raeburn 10984: my %LC_dns_serv;
1.852 albertel 10985:
10986: sub parse_hosts_tab {
10987: my ($file) = @_;
10988: foreach my $configline (@$file) {
10989: next if ($configline =~ /^(\#|\s*$ )/x);
1.1107 raeburn 10990: chomp($configline);
10991: if ($configline =~ /^\^/) {
10992: if ($configline =~ /^\^([\w.\-]+)/) {
10993: $LC_dns_serv{$1} = 1;
10994: }
10995: next;
10996: }
1.1074 raeburn 10997: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 10998: $name=~s/\s//g;
10999: if ($id && $domain && $role && $name) {
11000: $hostname{$id}=$name;
1.888 albertel 11001: push(@{$name_to_host{$name}}, $id);
1.852 albertel 11002: $hostdom{$id}=$domain;
11003: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 11004: if (defined($protocol)) {
11005: if ($protocol eq 'https') {
11006: $protocol{$id} = $protocol;
11007: } else {
11008: $protocol{$id} = 'http';
11009: }
1.968 raeburn 11010: } else {
1.969 raeburn 11011: $protocol{$id} = 'http';
1.968 raeburn 11012: }
1.1074 raeburn 11013: if (defined($intdom)) {
11014: $internetdom{$id} = $intdom;
11015: }
1.852 albertel 11016: }
11017: }
11018: }
1.864 albertel 11019:
11020: sub reset_hosts_info {
1.897 albertel 11021: &purge_remembered();
1.864 albertel 11022: &reset_domain_info();
11023: &reset_hosts_ip_info();
1.892 albertel 11024: undef(%name_to_host);
1.864 albertel 11025: undef(%hostname);
11026: undef(%hostdom);
11027: undef(%libserv);
11028: undef($loaded);
11029: }
1.1 albertel 11030:
1.852 albertel 11031: sub load_hosts_tab {
1.869 albertel 11032: my ($ignore_cache) = @_;
11033: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852 albertel 11034: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11035: my @config = <$config>;
11036: &parse_hosts_tab(\@config);
11037: close($config);
11038: $loaded=1;
1.1 albertel 11039: }
1.852 albertel 11040:
1.838 albertel 11041: sub hostname {
1.852 albertel 11042: &load_hosts_tab() if (!$loaded);
11043:
1.838 albertel 11044: my ($lonid) = @_;
11045: return $hostname{$lonid};
11046: }
1.845 albertel 11047:
1.838 albertel 11048: sub all_hostnames {
1.852 albertel 11049: &load_hosts_tab() if (!$loaded);
11050:
1.838 albertel 11051: return %hostname;
11052: }
1.845 albertel 11053:
1.888 albertel 11054: sub all_names {
11055: &load_hosts_tab() if (!$loaded);
11056:
11057: return %name_to_host;
11058: }
11059:
1.974 raeburn 11060: sub all_host_domain {
11061: &load_hosts_tab() if (!$loaded);
11062: return %hostdom;
11063: }
11064:
1.845 albertel 11065: sub is_library {
1.852 albertel 11066: &load_hosts_tab() if (!$loaded);
11067:
1.845 albertel 11068: return exists($libserv{$_[0]});
11069: }
11070:
11071: sub all_library {
1.852 albertel 11072: &load_hosts_tab() if (!$loaded);
11073:
1.845 albertel 11074: return %libserv;
11075: }
11076:
1.1062 droeschl 11077: sub unique_library {
11078: #2x reverse removes all hostnames that appear more than once
11079: my %unique = reverse &all_library();
11080: return reverse %unique;
11081: }
11082:
1.841 albertel 11083: sub get_servers {
1.852 albertel 11084: &load_hosts_tab() if (!$loaded);
11085:
1.841 albertel 11086: my ($domain,$type) = @_;
11087: my %possible_hosts = ($type eq 'library') ? %libserv
11088: : %hostname;
11089: my %result;
1.842 albertel 11090: if (ref($domain) eq 'ARRAY') {
11091: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 11092: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 11093: $result{$host} = $hostname;
11094: }
11095: }
11096: } else {
11097: while ( my ($host,$hostname) = each(%possible_hosts)) {
11098: if ($hostdom{$host} eq $domain) {
11099: $result{$host} = $hostname;
11100: }
1.841 albertel 11101: }
11102: }
11103: return %result;
11104: }
1.845 albertel 11105:
1.1062 droeschl 11106: sub get_unique_servers {
11107: my %unique = reverse &get_servers(@_);
11108: return reverse %unique;
11109: }
11110:
1.844 albertel 11111: sub host_domain {
1.852 albertel 11112: &load_hosts_tab() if (!$loaded);
11113:
1.844 albertel 11114: my ($lonid) = @_;
11115: return $hostdom{$lonid};
11116: }
11117:
1.841 albertel 11118: sub all_domains {
1.852 albertel 11119: &load_hosts_tab() if (!$loaded);
11120:
1.841 albertel 11121: my %seen;
11122: my @uniq = grep(!$seen{$_}++, values(%hostdom));
11123: return @uniq;
11124: }
1.1074 raeburn 11125:
11126: sub internet_dom {
11127: &load_hosts_tab() if (!$loaded);
11128:
11129: my ($lonid) = @_;
11130: return $internetdom{$lonid};
11131: }
1.1107 raeburn 11132:
11133: sub is_LC_dns {
11134: &load_hosts_tab() if (!$loaded);
11135:
11136: my ($hostname) = @_;
11137: return exists($LC_dns_serv{$hostname});
11138: }
11139:
1.1 albertel 11140: }
11141:
1.847 albertel 11142: {
11143: my %iphost;
1.856 albertel 11144: my %name_to_ip;
11145: my %lonid_to_ip;
1.869 albertel 11146:
1.847 albertel 11147: sub get_hosts_from_ip {
11148: my ($ip) = @_;
11149: my %iphosts = &get_iphost();
11150: if (ref($iphosts{$ip})) {
11151: return @{$iphosts{$ip}};
11152: }
11153: return;
1.839 albertel 11154: }
1.864 albertel 11155:
11156: sub reset_hosts_ip_info {
11157: undef(%iphost);
11158: undef(%name_to_ip);
11159: undef(%lonid_to_ip);
11160: }
1.856 albertel 11161:
11162: sub get_host_ip {
11163: my ($lonid) = @_;
11164: if (exists($lonid_to_ip{$lonid})) {
11165: return $lonid_to_ip{$lonid};
11166: }
11167: my $name=&hostname($lonid);
11168: my $ip = gethostbyname($name);
11169: return if (!$ip || length($ip) ne 4);
11170: $ip=inet_ntoa($ip);
11171: $name_to_ip{$name} = $ip;
11172: $lonid_to_ip{$lonid} = $ip;
11173: return $ip;
11174: }
1.847 albertel 11175:
11176: sub get_iphost {
1.869 albertel 11177: my ($ignore_cache) = @_;
1.894 albertel 11178:
1.869 albertel 11179: if (!$ignore_cache) {
11180: if (%iphost) {
11181: return %iphost;
11182: }
11183: my ($ip_info,$cached)=
11184: &Apache::lonnet::is_cached_new('iphost','iphost');
11185: if ($cached) {
11186: %iphost = %{$ip_info->[0]};
11187: %name_to_ip = %{$ip_info->[1]};
11188: %lonid_to_ip = %{$ip_info->[2]};
11189: return %iphost;
11190: }
11191: }
1.894 albertel 11192:
11193: # get yesterday's info for fallback
11194: my %old_name_to_ip;
11195: my ($ip_info,$cached)=
11196: &Apache::lonnet::is_cached_new('iphost','iphost');
11197: if ($cached) {
11198: %old_name_to_ip = %{$ip_info->[1]};
11199: }
11200:
1.888 albertel 11201: my %name_to_host = &all_names();
11202: foreach my $name (keys(%name_to_host)) {
1.847 albertel 11203: my $ip;
11204: if (!exists($name_to_ip{$name})) {
11205: $ip = gethostbyname($name);
11206: if (!$ip || length($ip) ne 4) {
1.894 albertel 11207: if (defined($old_name_to_ip{$name})) {
11208: $ip = $old_name_to_ip{$name};
11209: &logthis("Can't find $name defaulting to old $ip");
11210: } else {
11211: &logthis("Name $name no IP found");
11212: next;
11213: }
11214: } else {
11215: $ip=inet_ntoa($ip);
1.847 albertel 11216: }
11217: $name_to_ip{$name} = $ip;
11218: } else {
11219: $ip = $name_to_ip{$name};
1.653 albertel 11220: }
1.888 albertel 11221: foreach my $id (@{ $name_to_host{$name} }) {
11222: $lonid_to_ip{$id} = $ip;
11223: }
11224: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 11225: }
1.869 albertel 11226: &Apache::lonnet::do_cache_new('iphost','iphost',
11227: [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894 albertel 11228: 48*60*60);
1.869 albertel 11229:
1.847 albertel 11230: return %iphost;
1.598 albertel 11231: }
11232:
1.992 raeburn 11233: #
11234: # Given a DNS returns the loncapa host name for that DNS
11235: #
11236: sub host_from_dns {
11237: my ($dns) = @_;
11238: my @hosts;
11239: my $ip;
11240:
1.993 raeburn 11241: if (exists($name_to_ip{$dns})) {
1.992 raeburn 11242: $ip = $name_to_ip{$dns};
11243: }
11244: if (!$ip) {
11245: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
11246: if (length($ip) == 4) {
11247: $ip = &IO::Socket::inet_ntoa($ip);
11248: }
11249: }
11250: if ($ip) {
11251: @hosts = get_hosts_from_ip($ip);
11252: return $hosts[0];
11253: }
11254: return undef;
1.986 foxr 11255: }
1.992 raeburn 11256:
1.1074 raeburn 11257: sub get_internet_names {
11258: my ($lonid) = @_;
11259: return if ($lonid eq '');
11260: my ($idnref,$cached)=
11261: &Apache::lonnet::is_cached_new('internetnames',$lonid);
11262: if ($cached) {
11263: return $idnref;
11264: }
11265: my $ip = &get_host_ip($lonid);
11266: my @hosts = &get_hosts_from_ip($ip);
11267: my %iphost = &get_iphost();
11268: my (@idns,%seen);
11269: foreach my $id (@hosts) {
11270: my $dom = &host_domain($id);
11271: my $prim_id = &domain($dom,'primary');
11272: my $prim_ip = &get_host_ip($prim_id);
11273: next if ($seen{$prim_ip});
11274: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
11275: foreach my $id (@{$iphost{$prim_ip}}) {
11276: my $intdom = &internet_dom($id);
11277: unless (grep(/^\Q$intdom\E$/,@idns)) {
11278: push(@idns,$intdom);
11279: }
11280: }
11281: }
11282: $seen{$prim_ip} = 1;
11283: }
11284: return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
11285: }
11286:
1.986 foxr 11287: }
11288:
1.1079 raeburn 11289: sub all_loncaparevs {
11290: 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);
11291: }
11292:
1.862 albertel 11293: BEGIN {
11294:
11295: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
11296: unless ($readit) {
11297: {
11298: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
11299: %perlvar = (%perlvar,%{$configvars});
11300: }
11301:
11302:
1.1 albertel 11303: # ------------------------------------------------------ Read spare server file
11304: {
1.448 albertel 11305: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 11306:
11307: while (my $configline=<$config>) {
11308: chomp($configline);
1.284 matthew 11309: if ($configline) {
1.784 albertel 11310: my ($host,$type) = split(':',$configline,2);
1.785 albertel 11311: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 11312: push(@{ $spareid{$type} }, $host);
1.1 albertel 11313: }
11314: }
1.448 albertel 11315: close($config);
1.1 albertel 11316: }
1.11 www 11317: # ------------------------------------------------------------ Read permissions
11318: {
1.448 albertel 11319: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 11320:
11321: while (my $configline=<$config>) {
1.448 albertel 11322: chomp($configline);
11323: if ($configline) {
11324: my ($role,$perm)=split(/ /,$configline);
11325: if ($perm ne '') { $pr{$role}=$perm; }
11326: }
1.11 www 11327: }
1.448 albertel 11328: close($config);
1.11 www 11329: }
11330:
11331: # -------------------------------------------- Read plain texts for permissions
11332: {
1.448 albertel 11333: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 11334:
11335: while (my $configline=<$config>) {
1.448 albertel 11336: chomp($configline);
11337: if ($configline) {
1.742 raeburn 11338: my ($short,@plain)=split(/:/,$configline);
11339: %{$prp{$short}} = ();
11340: if (@plain > 0) {
11341: $prp{$short}{'std'} = $plain[0];
11342: for (my $i=1; $i<@plain; $i++) {
11343: $prp{$short}{'alt'.$i} = $plain[$i];
11344: }
11345: }
1.448 albertel 11346: }
1.135 www 11347: }
1.448 albertel 11348: close($config);
1.135 www 11349: }
11350:
11351: # ---------------------------------------------------------- Read package table
11352: {
1.448 albertel 11353: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 11354:
11355: while (my $configline=<$config>) {
1.483 albertel 11356: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 11357: chomp($configline);
11358: my ($short,$plain)=split(/:/,$configline);
11359: my ($pack,$name)=split(/\&/,$short);
11360: if ($plain ne '') {
11361: $packagetab{$pack.'&'.$name.'&name'}=$name;
11362: $packagetab{$short}=$plain;
11363: }
1.11 www 11364: }
1.448 albertel 11365: close($config);
1.329 matthew 11366: }
11367:
1.1073 raeburn 11368: # ---------------------------------------------------------- Read loncaparev table
11369: {
11370: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
11371: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
11372: while (my $configline=<$config>) {
11373: chomp($configline);
11374: my ($hostid,$loncaparev)=split(/:/,$configline);
11375: $loncaparevs{$hostid}=$loncaparev;
11376: }
11377: close($config);
11378: }
11379: }
11380: }
11381:
1.1074 raeburn 11382: # ---------------------------------------------------------- Read serverhostID table
11383: {
11384: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
11385: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
11386: while (my $configline=<$config>) {
11387: chomp($configline);
11388: my ($name,$id)=split(/:/,$configline);
11389: $serverhomeIDs{$name}=$id;
11390: }
11391: close($config);
11392: }
11393: }
11394: }
11395:
1.1079 raeburn 11396: {
11397: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
11398: if (-e $file) {
11399: my $parser = HTML::LCParser->new($file);
11400: while (my $token = $parser->get_token()) {
11401: if ($token->[0] eq 'S') {
11402: my $item = $token->[1];
11403: my $name = $token->[2]{'name'};
11404: my $value = $token->[2]{'value'};
11405: if ($item ne '' && $name ne '' && $value ne '') {
11406: my $release = $parser->get_text();
11407: $release =~ s/(^\s*|\s*$ )//gx;
11408: $needsrelease{$item.':'.$name.':'.$value} = $release;
11409: }
11410: }
11411: }
11412: }
1.1073 raeburn 11413: }
11414:
1.1138 raeburn 11415: # ---------------------------------------------------------- Read managers table
11416: {
11417: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
11418: if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
11419: while (my $configline=<$config>) {
11420: chomp($configline);
11421: next if ($configline =~ /^\#/);
11422: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
11423: $managerstab{$configline} = 1;
11424: }
11425: }
11426: close($config);
11427: }
11428: }
11429: }
11430:
1.329 matthew 11431: # ------------- set up temporary directory
11432: {
1.1117 foxr 11433: $tmpdir = LONCAPA::tempdir();
1.329 matthew 11434:
1.11 www 11435: }
11436:
1.794 albertel 11437: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
11438: 'compress_threshold'=> 20_000,
11439: });
1.185 www 11440:
1.281 www 11441: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 11442: $dumpcount=0;
1.958 www 11443: $locknum=0;
1.22 www 11444:
1.163 harris41 11445: &logtouch();
1.672 albertel 11446: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 11447: $readit=1;
1.564 albertel 11448: {
11449: use integer;
11450: my $test=(2**32)+1;
1.568 albertel 11451: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 11452: &logthis(" Detected 64bit platform ($_64bit)");
11453: }
1.195 www 11454: }
1.1 albertel 11455: }
1.179 www 11456:
1.1 albertel 11457: 1;
1.191 harris41 11458: __END__
11459:
1.243 albertel 11460: =pod
11461:
1.191 harris41 11462: =head1 NAME
11463:
1.243 albertel 11464: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 11465:
11466: =head1 SYNOPSIS
11467:
1.243 albertel 11468: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 11469:
11470: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
11471:
1.243 albertel 11472: Common parameters:
11473:
11474: =over 4
11475:
11476: =item *
11477:
11478: $uname : an internal username (if $cname expecting a course Id specifically)
11479:
11480: =item *
11481:
11482: $udom : a domain (if $cdom expecting a course's domain specifically)
11483:
11484: =item *
11485:
11486: $symb : a resource instance identifier
11487:
11488: =item *
11489:
11490: $namespace : the name of a .db file that contains the data needed or
11491: being set.
11492:
11493: =back
11494:
1.394 bowersj2 11495: =head1 OVERVIEW
1.191 harris41 11496:
1.394 bowersj2 11497: lonnet provides subroutines which interact with the
11498: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
11499: about classes, users, and resources.
1.243 albertel 11500:
11501: For many of these objects you can also use this to store data about
11502: them or modify them in various ways.
1.191 harris41 11503:
1.394 bowersj2 11504: =head2 Symbs
1.191 harris41 11505:
1.394 bowersj2 11506: To identify a specific instance of a resource, LON-CAPA uses symbols
11507: or "symbs"X<symb>. These identifiers are built from the URL of the
11508: map, the resource number of the resource in the map, and the URL of
11509: the resource itself. The latter is somewhat redundant, but might help
11510: if maps change.
11511:
11512: An example is
11513:
11514: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
11515:
11516: The respective map entry is
11517:
11518: <resource id="19" src="/res/msu/korte/tests/part12.problem"
11519: title="Problem 2">
11520: </resource>
11521:
11522: Symbs are used by the random number generator, as well as to store and
11523: restore data specific to a certain instance of for example a problem.
11524:
11525: =head2 Storing And Retrieving Data
11526:
11527: X<store()>X<cstore()>X<restore()>Three of the most important functions
11528: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
11529: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
11530: is is the non-critical message twin of cstore. These functions are for
11531: handlers to store a perl hash to a user's permanent data space in an
11532: easy manner, and to retrieve it again on another call. It is expected
11533: that a handler would use this once at the beginning to retrieve data,
11534: and then again once at the end to send only the new data back.
11535:
11536: The data is stored in the user's data directory on the user's
11537: homeserver under the ID of the course.
11538:
11539: The hash that is returned by restore will have all of the previous
11540: value for all of the elements of the hash.
11541:
11542: Example:
11543:
11544: #creating a hash
11545: my %hash;
11546: $hash{'foo'}='bar';
11547:
11548: #storing it
11549: &Apache::lonnet::cstore(\%hash);
11550:
11551: #changing a value
11552: $hash{'foo'}='notbar';
11553:
11554: #adding a new value
11555: $hash{'bar'}='foo';
11556: &Apache::lonnet::cstore(\%hash);
11557:
11558: #retrieving the hash
11559: my %history=&Apache::lonnet::restore();
11560:
11561: #print the hash
11562: foreach my $key (sort(keys(%history))) {
11563: print("\%history{$key} = $history{$key}");
11564: }
11565:
11566: Will print out:
1.191 harris41 11567:
1.394 bowersj2 11568: %history{1:foo} = bar
11569: %history{1:keys} = foo:timestamp
11570: %history{1:timestamp} = 990455579
11571: %history{2:bar} = foo
11572: %history{2:foo} = notbar
11573: %history{2:keys} = foo:bar:timestamp
11574: %history{2:timestamp} = 990455580
11575: %history{bar} = foo
11576: %history{foo} = notbar
11577: %history{timestamp} = 990455580
11578: %history{version} = 2
11579:
11580: Note that the special hash entries C<keys>, C<version> and
11581: C<timestamp> were added to the hash. C<version> will be equal to the
11582: total number of versions of the data that have been stored. The
11583: C<timestamp> attribute will be the UNIX time the hash was
11584: stored. C<keys> is available in every historical section to list which
11585: keys were added or changed at a specific historical revision of a
11586: hash.
11587:
11588: B<Warning>: do not store the hash that restore returns directly. This
11589: will cause a mess since it will restore the historical keys as if the
11590: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 11591:
1.394 bowersj2 11592: Calling convention:
1.191 harris41 11593:
1.394 bowersj2 11594: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
11595: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191 harris41 11596:
1.394 bowersj2 11597: For more detailed information, see lonnet specific documentation.
1.191 harris41 11598:
1.394 bowersj2 11599: =head1 RETURN MESSAGES
1.191 harris41 11600:
1.394 bowersj2 11601: =over 4
1.191 harris41 11602:
1.394 bowersj2 11603: =item * B<con_lost>: unable to contact remote host
1.191 harris41 11604:
1.394 bowersj2 11605: =item * B<con_delayed>: unable to contact remote host, message will be delivered
11606: when the connection is brought back up
1.191 harris41 11607:
1.394 bowersj2 11608: =item * B<con_failed>: unable to contact remote host and unable to save message
11609: for later delivery
1.191 harris41 11610:
1.967 bisitz 11611: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 11612:
1.394 bowersj2 11613: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 11614: that was requested
1.191 harris41 11615:
1.243 albertel 11616: =back
1.191 harris41 11617:
1.243 albertel 11618: =head1 PUBLIC SUBROUTINES
1.191 harris41 11619:
1.243 albertel 11620: =head2 Session Environment Functions
1.191 harris41 11621:
1.243 albertel 11622: =over 4
1.191 harris41 11623:
1.394 bowersj2 11624: =item *
11625: X<appenv()>
1.949 raeburn 11626: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 11627: the user envirnoment file, and will be restored for each access this
1.620 albertel 11628: user makes during this session, also modifies the %env for the current
1.949 raeburn 11629: process. Optional rolesarrayref - if defined contains a reference to an array
11630: of roles which are exempt from the restriction on modifying user.role entries
11631: in the user's environment.db and in %env.
1.191 harris41 11632:
11633: =item *
1.394 bowersj2 11634: X<delenv()>
1.987 raeburn 11635: B<delenv($delthis,$regexp)>: removes all items from the session
11636: environment file that begin with $delthis. If the
11637: optional second arg - $regexp - is true, $delthis is treated as a
11638: regular expression, otherwise \Q$delthis\E is used.
11639: The values are also deleted from the current processes %env.
1.191 harris41 11640:
1.795 albertel 11641: =item * get_env_multiple($name)
11642:
11643: gets $name from the %env hash, it seemlessly handles the cases where multiple
11644: values may be defined and end up as an array ref.
11645:
11646: returns an array of values
11647:
1.243 albertel 11648: =back
11649:
11650: =head2 User Information
1.191 harris41 11651:
1.243 albertel 11652: =over 4
1.191 harris41 11653:
11654: =item *
1.394 bowersj2 11655: X<queryauthenticate()>
11656: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 11657: authentication scheme
11658:
11659: =item *
1.394 bowersj2 11660: X<authenticate()>
1.1073 raeburn 11661: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 11662: authenticate user from domain's lib servers (first use the current
11663: one). C<$upass> should be the users password.
1.1073 raeburn 11664: $checkdefauth is optional (value is 1 if a check should be made to
11665: authenticate user using default authentication method, and allow
11666: account creation if username does not have account in the domain).
11667: $clientcancheckhost is optional (value is 1 if checking whether the
11668: server can host will occur on the client side in lonauth.pm).
1.191 harris41 11669:
11670: =item *
1.394 bowersj2 11671: X<homeserver()>
11672: B<homeserver($uname,$udom)>: find the server which has
11673: the user's directory and files (there must be only one), this caches
11674: the answer, and also caches if there is a borken connection.
1.191 harris41 11675:
11676: =item *
1.394 bowersj2 11677: X<idget()>
11678: B<idget($udom,@ids)>: find the usernames behind a list of IDs
11679: (IDs are a unique resource in a domain, there must be only 1 ID per
11680: username, and only 1 username per ID in a specific domain) (returns
11681: hash: id=>name,id=>name)
1.191 harris41 11682:
11683: =item *
1.394 bowersj2 11684: X<idrget()>
11685: B<idrget($udom,@unames)>: find the IDs behind a list of
11686: usernames (returns hash: name=>id,name=>id)
1.191 harris41 11687:
11688: =item *
1.394 bowersj2 11689: X<idput()>
11690: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 11691:
11692: =item *
1.394 bowersj2 11693: X<rolesinit()>
1.1169 droeschl 11694: B<rolesinit($udom,$username)>: get user privileges.
11695: returns user role, first access and timer interval hashes
1.243 albertel 11696:
11697: =item *
1.1171 droeschl 11698: X<privileged()>
11699: B<privileged($username,$domain)>: returns a true if user has a
11700: privileged and active role (i.e. su or dc), false otherwise.
11701:
11702: =item *
1.551 albertel 11703: X<getsection()>
11704: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 11705: course $cname, return section name/number or '' for "not in course"
11706: and '-1' for "no section"
11707:
11708: =item *
1.394 bowersj2 11709: X<userenvironment()>
11710: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 11711: passed in @what from the requested user's environment, returns a hash
11712:
1.858 raeburn 11713: =item *
11714: X<userlog_query()>
1.859 albertel 11715: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
11716: activity.log file. %filters defines filters applied when parsing the
11717: log file. These can be start or end timestamps, or the type of action
11718: - log to look for Login or Logout events, check for Checkin or
11719: Checkout, role for role selection. The response is in the form
11720: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
11721: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 11722:
1.243 albertel 11723: =back
11724:
11725: =head2 User Roles
11726:
11727: =over 4
11728:
11729: =item *
11730:
1.810 raeburn 11731: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243 albertel 11732: F: full access
11733: U,I,K: authentication modes (cxx only)
11734: '': forbidden
11735: 1: user needs to choose course
11736: 2: browse allowed
1.766 albertel 11737: A: passphrase authentication needed
1.243 albertel 11738:
11739: =item *
11740:
11741: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
11742: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
11743: and course level
11744:
11745: =item *
11746:
1.988 raeburn 11747: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
11748: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 11749: $type is Course (default) or Community.
1.988 raeburn 11750: If $forcedefault evaluates to true, text returned will be default
11751: text for $type. Otherwise, if this is a course, the text returned
11752: will be a custom name for the role (if defined in the course's
11753: environment). If no custom name is defined the default is returned.
11754:
1.832 raeburn 11755: =item *
11756:
1.935 raeburn 11757: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858 raeburn 11758: All arguments are optional. Returns a hash of a roles, either for
11759: co-author/assistant author roles for a user's Construction Space
1.906 albertel 11760: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 11761: In the hash, keys are set to colon-separated $uname,$udom,$role, and
11762: (optionally) if $withsec is true, a fourth colon-separated item - $section.
11763: For each key, value is set to colon-separated start and end times for
11764: the role. If no username and domain are specified, will default to
1.934 raeburn 11765: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 11766: of role statuses (active, future or previous), roles
11767: (e.g., cc,in, st etc.) and domains of the roles which can be used
11768: to restrict the list of roles reported. If no array ref is
11769: provided for types, will default to return only active roles.
1.834 albertel 11770:
1.243 albertel 11771: =back
11772:
11773: =head2 User Modification
11774:
11775: =over 4
11776:
11777: =item *
11778:
1.957 raeburn 11779: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 11780: user for the level given by URL. Optional start and end dates (leave empty
11781: string or zero for "no date")
1.191 harris41 11782:
11783: =item *
11784:
1.243 albertel 11785: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
11786: change a users, password, possible return values are: ok,
11787: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
11788: refused
1.191 harris41 11789:
11790: =item *
11791:
1.243 albertel 11792: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 11793:
11794: =item *
11795:
1.1058 raeburn 11796: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
11797: $forceid,$desiredhome,$email,$inststatus,$candelete) :
11798:
11799: will update user information (firstname,middlename,lastname,generation,
11800: permanentemail), and if forceid is true, student/employee ID also.
11801: A user's institutional affiliation(s) can also be updated.
11802: User information fields will not be overwritten with empty entries
11803: unless the field is included in the $candelete array reference.
11804: This array is included when a single user is modified via "Manage Users",
11805: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 11806:
11807: =item *
11808:
1.286 matthew 11809: modifystudent
11810:
1.957 raeburn 11811: modify a student's enrollment and identification information.
1.286 matthew 11812: The course id is resolved based on the current users environment.
11813: This means the envoking user must be a course coordinator or otherwise
11814: associated with a course.
11815:
1.297 matthew 11816: This call is essentially a wrapper for lonnet::modifyuser and
11817: lonnet::modify_student_enrollment
1.286 matthew 11818:
11819: Inputs:
11820:
11821: =over 4
11822:
1.957 raeburn 11823: =item B<$udom> Student's loncapa domain
1.286 matthew 11824:
1.957 raeburn 11825: =item B<$uname> Student's loncapa login name
1.286 matthew 11826:
1.964 bisitz 11827: =item B<$uid> Student/Employee ID
1.286 matthew 11828:
1.957 raeburn 11829: =item B<$umode> Student's authentication mode
1.286 matthew 11830:
1.957 raeburn 11831: =item B<$upass> Student's password
1.286 matthew 11832:
1.957 raeburn 11833: =item B<$first> Student's first name
1.286 matthew 11834:
1.957 raeburn 11835: =item B<$middle> Student's middle name
1.286 matthew 11836:
1.957 raeburn 11837: =item B<$last> Student's last name
1.286 matthew 11838:
1.957 raeburn 11839: =item B<$gene> Student's generation
1.286 matthew 11840:
1.957 raeburn 11841: =item B<$usec> Student's section in course
1.286 matthew 11842:
11843: =item B<$end> Unix time of the roles expiration
11844:
11845: =item B<$start> Unix time of the roles start date
11846:
11847: =item B<$forceid> If defined, allow $uid to be changed
11848:
11849: =item B<$desiredhome> server to use as home server for student
11850:
1.957 raeburn 11851: =item B<$email> Student's permanent e-mail address
11852:
11853: =item B<$type> Type of enrollment (auto or manual)
11854:
1.963 raeburn 11855: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
11856:
11857: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 11858:
1.963 raeburn 11859: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 11860:
1.963 raeburn 11861: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 11862:
1.963 raeburn 11863: =item B<$inststatus> institutional status of user - : separated string of escaped status types
1.957 raeburn 11864:
1.286 matthew 11865: =back
1.297 matthew 11866:
11867: =item *
11868:
11869: modify_student_enrollment
11870:
11871: Change a students enrollment status in a class. The environment variable
11872: 'role.request.course' must be defined for this function to proceed.
11873:
11874: Inputs:
11875:
11876: =over 4
11877:
11878: =item $udom, students domain
11879:
11880: =item $uname, students name
11881:
11882: =item $uid, students user id
11883:
11884: =item $first, students first name
11885:
11886: =item $middle
11887:
11888: =item $last
11889:
11890: =item $gene
11891:
11892: =item $usec
11893:
11894: =item $end
11895:
11896: =item $start
11897:
1.957 raeburn 11898: =item $type
11899:
11900: =item $locktype
11901:
11902: =item $cid
11903:
11904: =item $selfenroll
11905:
11906: =item $context
11907:
1.297 matthew 11908: =back
11909:
1.191 harris41 11910:
11911: =item *
11912:
1.243 albertel 11913: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
11914: custom role; give a custom role to a user for the level given by URL. Specify
11915: name and domain of role author, and role name
1.191 harris41 11916:
11917: =item *
11918:
1.243 albertel 11919: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 11920:
11921: =item *
11922:
1.243 albertel 11923: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
11924:
11925: =back
11926:
11927: =head2 Course Infomation
11928:
11929: =over 4
1.191 harris41 11930:
11931: =item *
11932:
1.1118 foxr 11933: coursedescription($courseid,$options) : returns a hash of information about the
1.631 albertel 11934: specified course id, including all environment settings for the
11935: course, the description of the course will be in the hash under the
11936: key 'description'
1.191 harris41 11937:
1.1118 foxr 11938: $options is an optional parameter that if supplied is a hash reference that controls
11939: what how this function works. It has the following key/values:
11940:
11941: =over 4
11942:
11943: =item freshen_cache
11944:
11945: If defined, and the environment cache for the course is valid, it is
11946: returned in the returned hash.
11947:
11948: =item one_time
11949:
11950: If defined, the last cache time is set to _now_
11951:
11952: =item user
11953:
11954: If defined, the supplied username is used instead of the current user.
11955:
11956:
11957: =back
11958:
1.191 harris41 11959: =item *
11960:
1.624 albertel 11961: resdata($name,$domain,$type,@which) : request for current parameter
11962: setting for a specific $type, where $type is either 'course' or 'user',
11963: @what should be a list of parameters to ask about. This routine caches
11964: answers for 5 minutes.
1.243 albertel 11965:
1.877 foxr 11966: =item *
11967:
11968: get_courseresdata($courseid, $domain) : dump the entire course resource
11969: data base, returning a hash that is keyed by the resource name and has
11970: values that are the resource value. I believe that the timestamps and
11971: versions are also returned.
11972:
11973:
1.243 albertel 11974: =back
11975:
11976: =head2 Course Modification
11977:
11978: =over 4
1.191 harris41 11979:
11980: =item *
11981:
1.243 albertel 11982: writecoursepref($courseid,%prefs) : write preferences (environment
11983: database) for a course
1.191 harris41 11984:
11985: =item *
11986:
1.1011 raeburn 11987: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
11988:
11989: =item *
11990:
1.1038 raeburn 11991: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 11992:
1.1167 droeschl 11993: =item *
11994:
11995: is_course($courseid), is_course($cdom, $cnum)
11996:
11997: Accepts either a combined $courseid (in the form of domain_courseid) or the
11998: two component version $cdom, $cnum. It checks if the specified course exists.
11999:
12000: Returns:
12001: undef if the course doesn't exist, otherwise
12002: in scalar context the combined courseid.
12003: in list context the two components of the course identifier, domain and
12004: courseid.
12005:
1.243 albertel 12006: =back
12007:
12008: =head2 Resource Subroutines
12009:
12010: =over 4
1.191 harris41 12011:
12012: =item *
12013:
1.243 albertel 12014: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 12015:
12016: =item *
12017:
1.243 albertel 12018: repcopy($filename) : subscribes to the requested file, and attempts to
12019: replicate from the owning library server, Might return
1.607 raeburn 12020: 'unavailable', 'not_found', 'forbidden', 'ok', or
12021: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 12022: resource. Expects the local filesystem pathname
12023: (/home/httpd/html/res/....)
12024:
12025: =back
12026:
12027: =head2 Resource Information
12028:
12029: =over 4
1.191 harris41 12030:
12031: =item *
12032:
1.243 albertel 12033: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
12034: a vairety of different possible values, $varname should be a request
12035: string, and the other parameters can be used to specify who and what
12036: one is asking about.
12037:
12038: Possible values for $varname are environment.lastname (or other item
12039: from the envirnment hash), user.name (or someother aspect about the
12040: user), resource.0.maxtries (or some other part and parameter of a
12041: resource)
1.204 albertel 12042:
12043: =item *
12044:
1.243 albertel 12045: directcondval($number) : get current value of a condition; reads from a state
12046: string
1.204 albertel 12047:
12048: =item *
12049:
1.243 albertel 12050: condval($condidx) : value of condition index based on state
1.204 albertel 12051:
12052: =item *
12053:
1.243 albertel 12054: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
12055: resource's metadata, $what should be either a specific key, or either
12056: 'keys' (to get a list of possible keys) or 'packages' to get a list of
12057: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
12058:
12059: this function automatically caches all requests
1.191 harris41 12060:
12061: =item *
12062:
1.243 albertel 12063: metadata_query($query,$custom,$customshow) : make a metadata query against the
12064: network of library servers; returns file handle of where SQL and regex results
12065: will be stored for query
1.191 harris41 12066:
12067: =item *
12068:
1.243 albertel 12069: symbread($filename) : return symbolic list entry (filename argument optional);
12070: returns the data handle
1.191 harris41 12071:
12072: =item *
12073:
1.243 albertel 12074: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582 albertel 12075: a possible symb for the URL in $thisfn, and if is an encryypted
12076: resource that the user accessed using /enc/ returns a 1 on success, 0
12077: on failure, user must be in a course, as it assumes the existance of
1.620 albertel 12078: the course initial hash, and uses $env('request.course.id'}
1.243 albertel 12079:
1.191 harris41 12080:
12081: =item *
12082:
1.243 albertel 12083: symbclean($symb) : removes versions numbers from a symb, returns the
12084: cleaned symb
1.191 harris41 12085:
12086: =item *
12087:
1.243 albertel 12088: is_on_map($uri) : checks if the $uri is somewhere on the current
12089: course map, user must be in a course for it to work.
1.191 harris41 12090:
12091: =item *
12092:
1.243 albertel 12093: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 12094:
12095: =item *
12096:
1.243 albertel 12097: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
12098: a random seed, all arguments are optional, if they aren't sent it uses the
12099: environment to derive them. Note: if symb isn't sent and it can't get one
12100: from &symbread it will use the current time as its return value
1.191 harris41 12101:
12102: =item *
12103:
1.243 albertel 12104: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
12105: unfakeable, receipt
1.191 harris41 12106:
12107: =item *
12108:
1.620 albertel 12109: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 12110:
12111: =item *
12112:
1.243 albertel 12113: countacc($url) : count the number of accesses to a given URL
1.191 harris41 12114:
12115: =item *
12116:
1.243 albertel 12117: 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 12118:
12119: =item *
12120:
1.243 albertel 12121: 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 12122:
12123: =item *
12124:
1.243 albertel 12125: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 12126:
12127: =item *
12128:
1.243 albertel 12129: devalidate($symb) : devalidate temporary spreadsheet calculations,
12130: forcing spreadsheet to reevaluate the resource scores next time.
12131:
12132: =back
12133:
12134: =head2 Storing/Retreiving Data
12135:
12136: =over 4
1.191 harris41 12137:
12138: =item *
12139:
1.243 albertel 12140: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
12141: for this url; hashref needs to be given and should be a \%hashname; the
12142: remaining args aren't required and if they aren't passed or are '' they will
1.620 albertel 12143: be derived from the env
1.191 harris41 12144:
12145: =item *
12146:
1.243 albertel 12147: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
12148: uses critical subroutine
1.191 harris41 12149:
12150: =item *
12151:
1.243 albertel 12152: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
12153: all args are optional
1.191 harris41 12154:
12155: =item *
12156:
1.717 albertel 12157: dumpstore($namespace,$udom,$uname,$regexp,$range) :
12158: dumps the complete (or key matching regexp) namespace into a hash
12159: ($udom, $uname, $regexp, $range are optional) for a namespace that is
12160: normally &store()ed into
12161:
12162: $range should be either an integer '100' (give me the first 100
12163: matching records)
12164: or be two integers sperated by a - with no spaces
12165: '30-50' (give me the 30th through the 50th matching
12166: records)
12167:
12168:
12169: =item *
12170:
12171: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
12172: replaces a &store() version of data with a replacement set of data
12173: for a particular resource in a namespace passed in the $storehash hash
12174: reference
12175:
12176: =item *
12177:
1.243 albertel 12178: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
12179: works very similar to store/cstore, but all data is stored in a
12180: temporary location and can be reset using tmpreset, $storehash should
12181: be a hash reference, returns nothing on success
1.191 harris41 12182:
12183: =item *
12184:
1.243 albertel 12185: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
12186: similar to restore, but all data is stored in a temporary location and
12187: can be reset using tmpreset. Returns a hash of values on success,
12188: error string otherwise.
1.191 harris41 12189:
12190: =item *
12191:
1.243 albertel 12192: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
12193: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 12194:
12195: =item *
12196:
1.243 albertel 12197: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
12198: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 12199:
12200: =item *
12201:
1.243 albertel 12202: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
12203: namesp ($udom and $uname are optional)
1.191 harris41 12204:
12205: =item *
12206:
1.702 albertel 12207: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 12208: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 12209: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 12210:
1.702 albertel 12211: $range should be either an integer '100' (give me the first 100
12212: matching records)
12213: or be two integers sperated by a - with no spaces
12214: '30-50' (give me the 30th through the 50th matching
12215: records)
1.449 matthew 12216: =item *
12217:
12218: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
12219: $store can be a scalar, an array reference, or if the amount to be
12220: incremented is > 1, a hash reference.
12221:
12222: ($udom and $uname are optional)
1.191 harris41 12223:
12224: =item *
12225:
1.243 albertel 12226: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
12227: ($udom and $uname are optional)
1.191 harris41 12228:
12229: =item *
12230:
1.243 albertel 12231: cput($namespace,$storehash,$udom,$uname) : critical put
12232: ($udom and $uname are optional)
1.191 harris41 12233:
12234: =item *
12235:
1.748 albertel 12236: newput($namespace,$storehash,$udom,$uname) :
12237:
12238: Attempts to store the items in the $storehash, but only if they don't
12239: currently exist, if this succeeds you can be certain that you have
12240: successfully created a new key value pair in the $namespace db.
12241:
12242:
12243: Args:
12244: $namespace: name of database to store values to
12245: $storehash: hashref to store to the db
12246: $udom: (optional) domain of user containing the db
12247: $uname: (optional) name of user caontaining the db
12248:
12249: Returns:
12250: 'ok' -> succeeded in storing all keys of $storehash
12251: 'key_exists: <key>' -> failed to anything out of $storehash, as at
12252: least <key> already existed in the db (other
12253: requested keys may also already exist)
1.967 bisitz 12254: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 12255: 'con_lost' -> unable to contact request server
12256: 'refused' -> action was not allowed by remote machine
12257:
12258:
12259: =item *
12260:
1.243 albertel 12261: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
12262: reference filled in from namesp (encrypts the return communication)
12263: ($udom and $uname are optional)
1.191 harris41 12264:
12265: =item *
12266:
1.243 albertel 12267: log($udom,$name,$home,$message) : write to permanent log for user; use
12268: critical subroutine
12269:
1.806 raeburn 12270: =item *
12271:
1.860 raeburn 12272: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
12273: array reference filled in from namespace found in domain level on either
12274: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 12275:
12276: =item *
12277:
1.860 raeburn 12278: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
12279: domain level either on specified domain server ($uhome) or primary domain
12280: server ($udom and $uhome are optional)
1.806 raeburn 12281:
1.943 raeburn 12282: =item *
12283:
12284: get_domain_defaults($target_domain) : returns hash with defaults for
12285: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
12286: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
12287: or localauth), initial password or a kerberos realm, language (e.g., en-us).
12288: Values are retrieved from cache (if current), or from domain's configuration.db
12289: (if available), or lastly from values in lonTabs/dns_domain,tab,
12290: or lonTabs/domain.tab.
12291:
12292: %domdefaults = &get_auth_defaults($target_domain);
12293:
1.243 albertel 12294: =back
12295:
12296: =head2 Network Status Functions
12297:
12298: =over 4
1.191 harris41 12299:
12300: =item *
12301:
1.1137 raeburn 12302: dirlist() : return directory list based on URI (first arg).
12303:
12304: Inputs: 1 required, 5 optional.
12305:
12306: =over
12307:
12308: =item
12309: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
12310:
12311: =item
12312: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
12313:
12314: =item
12315: $username - username of user/course to be listed. Extracted from $uri if absent.
12316:
12317: =item
12318: $getpropath - boolean: 1 if prepend path using &propath().
12319:
12320: =item
12321: $getuserdir - boolean: 1 if prepend path for "userfiles".
12322:
12323: =item
12324: $alternateRoot - path to prepend in place of path from $uri.
12325:
12326: =back
12327:
12328: Returns: Array of up to two items.
12329:
12330: =over
12331:
12332: a reference to an array of files/subdirectories
12333:
12334: =over
12335:
12336: Each element in the array of files/subdirectories is a & separated list of
12337: item name and the result of running stat on the item. If dirlist was requested
12338: for a file instead of a directory, the item name will be ''. For a directory
12339: listing, if the item is a metadata file, the element will end &N&M
12340: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
12341: default copyright set (1).
12342:
12343: =back
12344:
12345: a scalar containing error condition (if encountered).
12346:
12347: =over
12348:
12349: =item
12350: no_host (no homeserver identified for $username:$domain).
12351:
12352: =item
12353: no_such_host (server contacted for listing not identified as valid host).
12354:
12355: =item
12356: con_lost (connection to remote server failed).
12357:
12358: =item
12359: refused (invalid $username:$domain received on lond side).
12360:
12361: =item
12362: no_such_dir (directory at specified path on lond side does not exist).
12363:
12364: =item
12365: empty (directory at specified path on lond side is empty).
12366:
12367: =over
12368:
12369: This is currently not encountered because the &ls3, &ls2,
12370: &ls (_handler) routines on the lond side do not filter out
12371: . and .. from a directory listing.
12372:
12373: =back
12374:
12375: =back
12376:
12377: =back
1.191 harris41 12378:
12379: =item *
12380:
1.243 albertel 12381: spareserver() : find server with least workload from spare.tab
12382:
1.986 foxr 12383:
12384: =item *
12385:
12386: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
12387: if there is no corresponding loncapa host.
12388:
1.243 albertel 12389: =back
12390:
1.986 foxr 12391:
1.243 albertel 12392: =head2 Apache Request
12393:
12394: =over 4
1.191 harris41 12395:
12396: =item *
12397:
1.243 albertel 12398: ssi($url,%hash) : server side include, does a complete request cycle on url to
12399: localhost, posts hash
12400:
12401: =back
12402:
12403: =head2 Data to String to Data
12404:
12405: =over 4
1.191 harris41 12406:
12407: =item *
12408:
1.243 albertel 12409: hash2str(%hash) : convert a hash into a string complete with escaping and '='
12410: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 12411:
12412: =item *
12413:
1.243 albertel 12414: hashref2str($hashref) : convert a hashref into a string complete with
12415: escaping and '=' and '&' separators, supports elements that are
12416: arrayrefs and hashrefs
1.191 harris41 12417:
12418: =item *
12419:
1.243 albertel 12420: arrayref2str($arrayref) : convert an arrayref into a string complete
12421: with escaping and '&' separators, supports elements that are arrayrefs
12422: and hashrefs
1.191 harris41 12423:
12424: =item *
12425:
1.243 albertel 12426: str2hash($string) : convert string to hash using unescaping and
12427: splitting on '=' and '&', supports elements that are arrayrefs and
12428: hashrefs
1.191 harris41 12429:
12430: =item *
12431:
1.243 albertel 12432: str2array($string) : convert string to hash using unescaping and
12433: splitting on '&', supports elements that are arrayrefs and hashrefs
12434:
12435: =back
12436:
12437: =head2 Logging Routines
12438:
12439:
12440: These routines allow one to make log messages in the lonnet.log and
12441: lonnet.perm logfiles.
1.191 harris41 12442:
1.1119 foxr 12443: =over 4
12444:
1.191 harris41 12445: =item *
12446:
1.243 albertel 12447: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 12448:
12449: =item *
12450:
1.243 albertel 12451: logthis() : append message to the normal lonnet.log file, it gets
12452: preiodically rolled over and deleted.
1.191 harris41 12453:
12454: =item *
12455:
1.243 albertel 12456: logperm() : append a permanent message to lonnet.perm.log, this log
12457: file never gets deleted by any automated portion of the system, only
12458: messages of critical importance should go in here.
12459:
1.1119 foxr 12460:
1.243 albertel 12461: =back
12462:
12463: =head2 General File Helper Routines
12464:
12465: =over 4
1.191 harris41 12466:
12467: =item *
12468:
1.481 raeburn 12469: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
12470: (a) files in /uploaded
12471: (i) If a local copy of the file exists -
12472: compares modification date of local copy with last-modified date for
12473: definitive version stored on home server for course. If local copy is
12474: stale, requests a new version from the home server and stores it.
12475: If the original has been removed from the home server, then local copy
12476: is unlinked.
12477: (ii) If local copy does not exist -
12478: requests the file from the home server and stores it.
12479:
12480: If $caller is 'uploadrep':
12481: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
12482: for request for files originally uploaded via DOCS.
12483: - returns 'ok' if fresh local copy now available, -1 otherwise.
12484:
12485: Otherwise:
12486: This indicates a call from the content generation phase of the request.
12487: - returns the entire contents of the file or -1.
12488:
12489: (b) files in /res
12490: - returns the entire contents of a file or -1;
12491: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 12492:
1.712 albertel 12493:
12494: =item *
12495:
12496: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
12497: reference
12498:
12499: returns either a stat() list of data about the file or an empty list
12500: if the file doesn't exist or couldn't find out about it (connection
12501: problems or user unknown)
12502:
1.191 harris41 12503: =item *
12504:
1.243 albertel 12505: filelocation($dir,$file) : returns file system location of a file
12506: based on URI; meant to be "fairly clean" absolute reference, $dir is a
12507: directory that relative $file lookups are to looked in ($dir of /a/dir
12508: and a file of ../bob will become /a/bob)
1.191 harris41 12509:
12510: =item *
12511:
12512: hreflocation($dir,$file) : returns file system location or a URL; same as
12513: filelocation except for hrefs
12514:
12515: =item *
12516:
12517: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
12518:
1.243 albertel 12519: =back
12520:
1.608 albertel 12521: =head2 Usererfile file routines (/uploaded*)
12522:
12523: =over 4
12524:
12525: =item *
12526:
12527: userfileupload(): main rotine for putting a file in a user or course's
12528: filespace, arguments are,
12529:
1.620 albertel 12530: formname - required - this is the name of the element in $env where the
1.608 albertel 12531: filename, and the contents of the file to create/modifed exist
1.620 albertel 12532: the filename is in $env{'form.'.$formname.'.filename'} and the
12533: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 12534: context - if coursedoc, store the file in the course of the active role
12535: of the current user;
12536: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
12537: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 12538: subdir - required - subdirectory to put the file in under ../userfiles/
12539: if undefined, it will be placed in "unknown"
12540:
12541: (This routine calls clean_filename() to remove any dangerous
12542: characters from the filename, and then calls finuserfileupload() to
12543: complete the transaction)
12544:
12545: returns either the url of the uploaded file (/uploaded/....) if successful
12546: and /adm/notfound.html if unsuccessful
12547:
12548: =item *
12549:
12550: clean_filename(): routine for cleaing a filename up for storage in
12551: userfile space, argument is:
12552:
12553: filename - proposed filename
12554:
12555: returns: the new clean filename
12556:
12557: =item *
12558:
1.1090 raeburn 12559: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 12560: userspace, probably shouldn't be called directly
12561:
12562: docuname: username or courseid of destination for the file
12563: docudom: domain of user/course of destination for the file
12564: formname: same as for userfileupload()
1.1090 raeburn 12565: fname: filename (including subdirectories) for the file
12566: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
12567: allfiles: reference to hash used to store objects found by parser
12568: codebase: reference to hash used for codebases of java objects found by parser
12569: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
12570: thumbheight: height (pixels) of thumbnail to be created for uploaded image
12571: resizewidth: width to be used to resize image using resizeImage from ImageMagick
12572: resizeheight: height to be used to resize image using resizeImage from ImageMagick
12573: context: if 'overwrite', will move the uploaded file from its temporary location to
12574: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 12575: mimetype: reference to scalar to accommodate mime type determined
12576: from File::MMagic if $parser = parse.
1.608 albertel 12577:
12578: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 12579: and /adm/notfound.html if unsuccessful (or an error message if context
12580: was 'overwrite').
12581:
1.608 albertel 12582:
12583: =item *
12584:
12585: renameuserfile(): renames an existing userfile to a new name
12586:
12587: Args:
12588: docuname: username or courseid of destination for the file
12589: docudom: domain of user/course of destination for the file
12590: old: current file name (including any subdirs under userfiles)
12591: new: desired file name (including any subdirs under userfiles)
12592:
12593: =item *
12594:
12595: mkdiruserfile(): creates a directory is a userfiles dir
12596:
12597: Args:
12598: docuname: username or courseid of destination for the file
12599: docudom: domain of user/course of destination for the file
12600: dir: dir to create (including any subdirs under userfiles)
12601:
12602: =item *
12603:
12604: removeuserfile(): removes a file that exists in userfiles
12605:
12606: Args:
12607: docuname: username or courseid of destination for the file
12608: docudom: domain of user/course of destination for the file
12609: fname: filname to delete (including any subdirs under userfiles)
12610:
12611: =item *
12612:
12613: removeuploadedurl(): convience function for removeuserfile()
12614:
12615: Args:
12616: url: a full /uploaded/... url to delete
12617:
1.747 albertel 12618: =item *
12619:
12620: get_portfile_permissions():
12621: Args:
12622: domain: domain of user or course contain the portfolio files
12623: user: name of user or num of course contain the portfolio files
12624: Returns:
12625: hashref of a dump of the proper file_permissions.db
12626:
12627:
12628: =item *
12629:
12630: get_access_controls():
12631:
12632: Args:
12633: current_permissions: the hash ref returned from get_portfile_permissions()
12634: group: (optional) the group you want the files associated with
12635: file: (optional) the file you want access info on
12636:
12637: Returns:
1.749 raeburn 12638: a hash (keys are file names) of hashes containing
12639: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
12640: values are XML containing access control settings (see below)
1.747 albertel 12641:
12642: Internal notes:
12643:
1.749 raeburn 12644: access controls are stored in file_permissions.db as key=value pairs.
12645: key -> path to file/file_name\0uniqueID:scope_end_start
12646: where scope -> public,guest,course,group,domains or users.
12647: end -> UNIX time for end of access (0 -> no end date)
12648: start -> UNIX time for start of access
12649:
12650: value -> XML description of access control
12651: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
12652: <start></start>
12653: <end></end>
12654:
12655: <password></password> for scope type = guest
12656:
12657: <domain></domain> for scope type = course or group
12658: <number></number>
12659: <roles id="">
12660: <role></role>
12661: <access></access>
12662: <section></section>
12663: <group></group>
12664: </roles>
12665:
12666: <dom></dom> for scope type = domains
12667:
12668: <users> for scope type = users
12669: <user>
12670: <uname></uname>
12671: <udom></udom>
12672: </user>
12673: </users>
12674: </scope>
12675:
12676: Access data is also aggregated for each file in an additional key=value pair:
12677: key -> path to file/file_name\0accesscontrol
12678: value -> reference to hash
12679: hash contains key = value pairs
12680: where key = uniqueID:scope_end_start
12681: value = UNIX time record was last updated
12682:
12683: Used to improve speed of look-ups of access controls for each file.
12684:
12685: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
12686:
12687: modify_access_controls():
12688:
12689: Modifies access controls for a portfolio file
12690: Args
12691: 1. file name
12692: 2. reference to hash of required changes,
12693: 3. domain
12694: 4. username
12695: where domain,username are the domain of the portfolio owner
12696: (either a user or a course)
12697:
12698: Returns:
12699: 1. result of additions or updates ('ok' or 'error', with error message).
12700: 2. result of deletions ('ok' or 'error', with error message).
12701: 3. reference to hash of any new or updated access controls.
12702: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
12703: key = integer (inbound ID)
12704: value = uniqueID
1.747 albertel 12705:
1.608 albertel 12706: =back
12707:
1.243 albertel 12708: =head2 HTTP Helper Routines
12709:
12710: =over 4
12711:
1.191 harris41 12712: =item *
12713:
12714: escape() : unpack non-word characters into CGI-compatible hex codes
12715:
12716: =item *
12717:
12718: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
12719:
1.243 albertel 12720: =back
12721:
12722: =head1 PRIVATE SUBROUTINES
12723:
12724: =head2 Underlying communication routines (Shouldn't call)
12725:
12726: =over 4
12727:
12728: =item *
12729:
12730: subreply() : tries to pass a message to lonc, returns con_lost if incapable
12731:
12732: =item *
12733:
12734: reply() : uses subreply to send a message to remote machine, logs all failures
12735:
12736: =item *
12737:
12738: critical() : passes a critical message to another server; if cannot
12739: get through then place message in connection buffer directory and
12740: returns con_delayed, if incapable of saving message, returns
12741: con_failed
12742:
12743: =item *
12744:
12745: reconlonc() : tries to reconnect lonc client processes.
12746:
12747: =back
12748:
12749: =head2 Resource Access Logging
12750:
12751: =over 4
12752:
12753: =item *
12754:
12755: flushcourselogs() : flush (save) buffer logs and access logs
12756:
12757: =item *
12758:
12759: courselog($what) : save message for course in hash
12760:
12761: =item *
12762:
12763: courseacclog($what) : save message for course using &courselog(). Perform
12764: special processing for specific resource types (problems, exams, quizzes, etc).
12765:
1.191 harris41 12766: =item *
12767:
12768: goodbye() : flush course logs and log shutting down; it is called in srm.conf
12769: as a PerlChildExitHandler
1.243 albertel 12770:
12771: =back
12772:
12773: =head2 Other
12774:
12775: =over 4
12776:
12777: =item *
12778:
12779: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 12780:
12781: =back
12782:
12783: =cut
1.877 foxr 12784:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>