Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1168
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1168 ! www 4: # $Id: lonnet.pm,v 1.1167 2012/05/16 21:19:33 droeschl 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.1167 droeschl 100: use LONCAPA::Lond;
1.1117 foxr 101:
1.1090 raeburn 102: use File::Copy;
1.676 albertel 103:
1.195 www 104: my $readit;
1.550 foxr 105: my $max_connection_retries = 10; # Or some such value.
1.1 albertel 106:
1.619 albertel 107: require Exporter;
108:
109: our @ISA = qw (Exporter);
110: our @EXPORT = qw(%env);
111:
1.449 matthew 112:
1.1 albertel 113: # --------------------------------------------------------------------- Logging
1.729 www 114: {
115: my $logid;
116: sub instructor_log {
1.957 raeburn 117: my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
118: if (($cnum eq '') || ($cdom eq '')) {
119: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
120: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
121: }
1.729 www 122: $logid++;
1.957 raeburn 123: my $now = time();
124: my $id=$now.'00000'.$$.'00000'.$logid;
1.729 www 125: return &Apache::lonnet::put('nohist_'.$hash_name,
1.730 www 126: { $id => {
127: 'exe_uname' => $env{'user.name'},
128: 'exe_udom' => $env{'user.domain'},
1.957 raeburn 129: 'exe_time' => $now,
1.730 www 130: 'exe_ip' => $ENV{'REMOTE_ADDR'},
131: 'delflag' => $delflag,
132: 'logentry' => $storehash,
133: 'uname' => $uname,
134: 'udom' => $udom,
135: }
1.957 raeburn 136: },$cdom,$cnum);
1.729 www 137: }
138: }
1.1 albertel 139:
1.163 harris41 140: sub logtouch {
141: my $execdir=$perlvar{'lonDaemons'};
1.448 albertel 142: unless (-e "$execdir/logs/lonnet.log") {
143: open(my $fh,">>$execdir/logs/lonnet.log");
1.163 harris41 144: close $fh;
145: }
146: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
147: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
148: }
149:
1.1 albertel 150: sub logthis {
151: my $message=shift;
152: my $execdir=$perlvar{'lonDaemons'};
153: my $now=time;
154: my $local=localtime($now);
1.448 albertel 155: if (open(my $fh,">>$execdir/logs/lonnet.log")) {
1.986 foxr 156: my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
157: print $fh $logstring;
1.448 albertel 158: close($fh);
159: }
1.1 albertel 160: return 1;
161: }
162:
163: sub logperm {
164: my $message=shift;
165: my $execdir=$perlvar{'lonDaemons'};
166: my $now=time;
167: my $local=localtime($now);
1.448 albertel 168: if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
169: print $fh "$now:$message:$local\n";
170: close($fh);
171: }
1.1 albertel 172: return 1;
173: }
174:
1.850 albertel 175: sub create_connection {
1.853 albertel 176: my ($hostname,$lonid) = @_;
1.851 albertel 177: my $client=IO::Socket::UNIX->new(Peer => $perlvar{'lonSockCreate'},
1.850 albertel 178: Type => SOCK_STREAM,
179: Timeout => 10);
180: return 0 if (!$client);
1.890 albertel 181: print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850 albertel 182: my $result = <$client>;
183: chomp($result);
184: return 1 if ($result eq 'done');
185: return 0;
186: }
187:
1.983 raeburn 188: sub get_server_timezone {
189: my ($cnum,$cdom) = @_;
190: my $home=&homeserver($cnum,$cdom);
191: if ($home ne 'no_host') {
192: my $cachetime = 24*3600;
193: my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
194: if (defined($cached)) {
195: return $timezone;
196: } else {
197: my $timezone = &reply('servertimezone',$home);
198: return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
199: }
200: }
201: }
1.850 albertel 202:
1.1106 raeburn 203: sub get_server_distarch {
204: my ($lonhost,$ignore_cache) = @_;
205: if (defined($lonhost)) {
206: if (!defined(&hostname($lonhost))) {
207: return;
208: }
209: my $cachetime = 12*3600;
210: if (!$ignore_cache) {
211: my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
212: if (defined($cached)) {
213: return $distarch;
214: }
215: }
216: my $rep = &reply('serverdistarch',$lonhost);
217: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
218: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
219: $rep eq '') {
220: return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
221: }
222: }
223: return;
224: }
225:
1.993 raeburn 226: sub get_server_loncaparev {
1.1073 raeburn 227: my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993 raeburn 228: if (defined($lonhost)) {
229: if (!defined(&hostname($lonhost))) {
230: undef($lonhost);
231: }
232: }
233: if (!defined($lonhost)) {
234: if (defined(&domain($dom,'primary'))) {
235: $lonhost=&domain($dom,'primary');
236: if ($lonhost eq 'no_host') {
237: undef($lonhost);
238: }
239: }
240: }
241: if (defined($lonhost)) {
1.1073 raeburn 242: my $cachetime = 12*3600;
243: if (!$ignore_cache) {
244: my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
245: if (defined($cached)) {
246: return $loncaparev;
247: }
248: }
249: my ($answer,$loncaparev);
250: my @ids=¤t_machine_ids();
251: if (grep(/^\Q$lonhost\E$/,@ids)) {
252: $answer = $perlvar{'lonVersion'};
1.1081 raeburn 253: if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 254: $loncaparev = $1;
255: }
256: } else {
257: $answer = &reply('serverloncaparev',$lonhost);
258: if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
259: if ($caller eq 'loncron') {
260: my $ua=new LWP::UserAgent;
1.1082 raeburn 261: $ua->timeout(4);
1.1073 raeburn 262: my $protocol = $protocol{$lonhost};
263: $protocol = 'http' if ($protocol ne 'https');
264: my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
265: my $request=new HTTP::Request('GET',$url);
266: my $response=$ua->request($request);
267: unless ($response->is_error()) {
268: my $content = $response->content;
1.1081 raeburn 269: if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073 raeburn 270: $loncaparev = $1;
271: }
272: }
273: } else {
274: $loncaparev = $loncaparevs{$lonhost};
275: }
1.1081 raeburn 276: } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 277: $loncaparev = $1;
278: }
1.993 raeburn 279: }
1.1073 raeburn 280: return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993 raeburn 281: }
282: }
283:
1.1074 raeburn 284: sub get_server_homeID {
285: my ($hostname,$ignore_cache,$caller) = @_;
286: unless ($ignore_cache) {
287: my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
288: if (defined($cached)) {
289: return $serverhomeID;
290: }
291: }
292: my $cachetime = 12*3600;
293: my $serverhomeID;
294: if ($caller eq 'loncron') {
295: my @machine_ids = &machine_ids($hostname);
296: foreach my $id (@machine_ids) {
297: my $response = &reply('serverhomeID',$id);
298: unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
299: $serverhomeID = $response;
300: last;
301: }
302: }
303: if ($serverhomeID eq '') {
304: $serverhomeID = $machine_ids[-1];
305: }
306: } else {
307: $serverhomeID = $serverhomeIDs{$hostname};
308: }
309: return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
310: }
311:
1.1121 raeburn 312: sub get_remote_globals {
313: my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125 raeburn 314: my ($result,%returnhash,%whatneeded);
315: if (ref($whathash) eq 'HASH') {
1.1121 raeburn 316: foreach my $what (sort(keys(%{$whathash}))) {
317: my $hashid = $lonhost.'-'.$what;
1.1125 raeburn 318: my ($response,$cached);
1.1121 raeburn 319: unless ($ignore_cache) {
1.1125 raeburn 320: ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121 raeburn 321: }
322: if (defined($cached)) {
1.1125 raeburn 323: $returnhash{$what} = $response;
1.1121 raeburn 324: } else {
1.1125 raeburn 325: $whatneeded{$what} = 1;
1.1121 raeburn 326: }
327: }
1.1125 raeburn 328: if (keys(%whatneeded) == 0) {
329: $result = 'ok';
330: } else {
1.1121 raeburn 331: my $requested = &freeze_escape(\%whatneeded);
332: my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125 raeburn 333: if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
334: ($rep eq 'unknown_cmd')) {
335: $result = $rep;
336: } else {
337: $result = 'ok';
1.1121 raeburn 338: my @pairs=split(/\&/,$rep);
1.1125 raeburn 339: foreach my $item (@pairs) {
340: my ($key,$value)=split(/=/,$item,2);
341: my $what = &unescape($key);
342: my $hashid = $lonhost.'-'.$what;
343: $returnhash{$what}=&thaw_unescape($value);
344: &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121 raeburn 345: }
346: }
347: }
348: }
1.1125 raeburn 349: return ($result,\%returnhash);
1.1121 raeburn 350: }
351:
1.1124 raeburn 352: sub remote_devalidate_cache {
353: my ($lonhost,$name,$id) = @_;
1.1130 raeburn 354: my $response = &reply('devalidatecache:'.&escape($name).':'.&escape($id),$lonhost);
1.1124 raeburn 355: return $response;
356: }
357:
1.1 albertel 358: # -------------------------------------------------- Non-critical communication
359: sub subreply {
360: my ($cmd,$server)=@_;
1.838 albertel 361: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549 foxr 362: #
363: # With loncnew process trimming, there's a timing hole between lonc server
364: # process exit and the master server picking up the listen on the AF_UNIX
365: # socket. In that time interval, a lock file will exist:
366:
367: my $lockfile=$peerfile.".lock";
368: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
369: sleep(1);
370: }
371: # At this point, either a loncnew parent is listening or an old lonc
1.550 foxr 372: # or loncnew child is listening so we can connect or everything's dead.
1.549 foxr 373: #
1.550 foxr 374: # We'll give the connection a few tries before abandoning it. If
375: # connection is not possible, we'll con_lost back to the client.
376: #
377: my $client;
378: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
379: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
380: Type => SOCK_STREAM,
381: Timeout => 10);
1.869 albertel 382: if ($client) {
1.550 foxr 383: last; # Connected!
1.850 albertel 384: } else {
1.853 albertel 385: &create_connection(&hostname($server),$server);
1.550 foxr 386: }
1.850 albertel 387: sleep(1); # Try again later if failed connection.
1.550 foxr 388: }
389: my $answer;
390: if ($client) {
1.704 albertel 391: print $client "sethost:$server:$cmd\n";
1.550 foxr 392: $answer=<$client>;
393: if (!$answer) { $answer="con_lost"; }
394: chomp($answer);
395: } else {
396: $answer = 'con_lost'; # Failed connection.
397: }
1.1 albertel 398: return $answer;
399: }
400:
401: sub reply {
402: my ($cmd,$server)=@_;
1.838 albertel 403: unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1 albertel 404: my $answer=subreply($cmd,$server);
1.65 www 405: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672 albertel 406: &logthis("<font color=\"blue\">WARNING:".
1.12 www 407: " $cmd to $server returned $answer</font>");
408: }
1.1 albertel 409: return $answer;
410: }
411:
412: # ----------------------------------------------------------- Send USR1 to lonc
413:
414: sub reconlonc {
1.891 albertel 415: my ($lonid) = @_;
416: my $hostname = &hostname($lonid);
417: if ($lonid) {
418: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
419: if ($hostname && -e $peerfile) {
420: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
421: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
422: Type => SOCK_STREAM,
423: Timeout => 10);
424: if ($client) {
425: print $client ("reset_retries\n");
426: my $answer=<$client>;
427: #reset just this one.
428: }
429: }
430: return;
431: }
432:
1.836 www 433: &logthis("Trying to reconnect lonc");
1.1 albertel 434: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448 albertel 435: if (open(my $fh,"<$loncfile")) {
1.1 albertel 436: my $loncpid=<$fh>;
437: chomp($loncpid);
438: if (kill 0 => $loncpid) {
439: &logthis("lonc at pid $loncpid responding, sending USR1");
440: kill USR1 => $loncpid;
441: sleep 1;
1.836 www 442: } else {
1.12 www 443: &logthis(
1.672 albertel 444: "<font color=\"blue\">WARNING:".
1.12 www 445: " lonc at pid $loncpid not responding, giving up</font>");
1.1 albertel 446: }
447: } else {
1.836 www 448: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1 albertel 449: }
450: }
451:
452: # ------------------------------------------------------ Critical communication
1.12 www 453:
1.1 albertel 454: sub critical {
455: my ($cmd,$server)=@_;
1.838 albertel 456: unless (&hostname($server)) {
1.672 albertel 457: &logthis("<font color=\"blue\">WARNING:".
1.89 www 458: " Critical message to unknown server ($server)</font>");
459: return 'no_such_host';
460: }
1.1 albertel 461: my $answer=reply($cmd,$server);
462: if ($answer eq 'con_lost') {
463: &reconlonc("$perlvar{'lonSockDir'}/$server");
1.589 albertel 464: my $answer=reply($cmd,$server);
1.1 albertel 465: if ($answer eq 'con_lost') {
466: my $now=time;
467: my $middlename=$cmd;
1.5 www 468: $middlename=substr($middlename,0,16);
1.1 albertel 469: $middlename=~s/\W//g;
470: my $dfilename=
1.305 www 471: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
472: $dumpcount++;
1.1 albertel 473: {
1.448 albertel 474: my $dfh;
475: if (open($dfh,">$dfilename")) {
476: print $dfh "$cmd\n";
477: close($dfh);
478: }
1.1 albertel 479: }
480: sleep 2;
481: my $wcmd='';
482: {
1.448 albertel 483: my $dfh;
484: if (open($dfh,"<$dfilename")) {
485: $wcmd=<$dfh>;
486: close($dfh);
487: }
1.1 albertel 488: }
489: chomp($wcmd);
1.7 www 490: if ($wcmd eq $cmd) {
1.672 albertel 491: &logthis("<font color=\"blue\">WARNING: ".
1.12 www 492: "Connection buffer $dfilename: $cmd</font>");
1.1 albertel 493: &logperm("D:$server:$cmd");
494: return 'con_delayed';
495: } else {
1.672 albertel 496: &logthis("<font color=\"red\">CRITICAL:"
1.12 www 497: ." Critical connection failed: $server $cmd</font>");
1.1 albertel 498: &logperm("F:$server:$cmd");
499: return 'con_failed';
500: }
501: }
502: }
503: return $answer;
1.405 albertel 504: }
505:
1.755 albertel 506: # ------------------------------------------- check if return value is an error
507:
508: sub error {
509: my ($result) = @_;
1.756 albertel 510: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755 albertel 511: if ($2 == 2) { return undef; }
512: return $1;
513: }
514: return undef;
515: }
516:
1.783 albertel 517: sub convert_and_load_session_env {
518: my ($lonidsdir,$handle)=@_;
519: my @profile;
520: {
1.917 albertel 521: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
522: if (!$opened) {
1.915 albertel 523: return 0;
524: }
1.783 albertel 525: flock($idf,LOCK_SH);
526: @profile=<$idf>;
527: close($idf);
528: }
529: my %temp_env;
530: foreach my $line (@profile) {
1.786 albertel 531: if ($line !~ m/=/) {
532: return 0;
533: }
1.783 albertel 534: chomp($line);
535: my ($envname,$envvalue)=split(/=/,$line,2);
536: $temp_env{&unescape($envname)} = &unescape($envvalue);
537: }
538: unlink("$lonidsdir/$handle.id");
539: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
540: 0640)) {
541: %disk_env = %temp_env;
542: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
543: untie(%disk_env);
544: }
1.786 albertel 545: return 1;
1.783 albertel 546: }
547:
1.374 www 548: # ------------------------------------------- Transfer profile into environment
1.780 albertel 549: my $env_loaded;
550: sub transfer_profile_to_env {
1.788 albertel 551: my ($lonidsdir,$handle,$force_transfer) = @_;
552: if (!$force_transfer && $env_loaded) { return; }
1.374 www 553:
1.720 albertel 554: if (!defined($lonidsdir)) {
555: $lonidsdir = $perlvar{'lonIDsDir'};
556: }
557: if (!defined($handle)) {
558: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
559: }
560:
1.786 albertel 561: my $convert;
562: {
1.917 albertel 563: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
564: if (!$opened) {
1.915 albertel 565: return;
566: }
1.786 albertel 567: flock($idf,LOCK_SH);
568: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
569: &GDBM_READER(),0640)) {
570: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
571: untie(%disk_env);
572: } else {
573: $convert = 1;
574: }
575: }
576: if ($convert) {
577: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
578: &logthis("Failed to load session, or convert session.");
579: }
1.374 www 580: }
1.783 albertel 581:
1.786 albertel 582: my %remove;
1.783 albertel 583: while ( my $envname = each(%env) ) {
1.433 matthew 584: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
585: if ($time < time-300) {
1.783 albertel 586: $remove{$key}++;
1.433 matthew 587: }
588: }
589: }
1.783 albertel 590:
1.619 albertel 591: $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780 albertel 592: $env_loaded=1;
1.783 albertel 593: foreach my $expired_key (keys(%remove)) {
1.433 matthew 594: &delenv($expired_key);
1.374 www 595: }
1.1 albertel 596: }
597:
1.916 albertel 598: # ---------------------------------------------------- Check for valid session
599: sub check_for_valid_session {
1.1155 raeburn 600: my ($r,$name) = @_;
1.916 albertel 601: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1155 raeburn 602: if ($name eq '') {
603: $name = 'lonID';
604: }
605: my $lonid=$cookies{$name};
1.916 albertel 606: return undef if (!$lonid);
607:
608: my $handle=&LONCAPA::clean_handle($lonid->value);
1.1155 raeburn 609: my $lonidsdir;
610: if ($name eq 'lonDAV') {
611: $lonidsdir=$r->dir_config('lonDAVsessDir');
612: } else {
613: $lonidsdir=$r->dir_config('lonIDsDir');
614: }
1.916 albertel 615: return undef if (!-e "$lonidsdir/$handle.id");
616:
1.917 albertel 617: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
618: return undef if (!$opened);
1.916 albertel 619:
620: flock($idf,LOCK_SH);
621: my %disk_env;
622: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
623: &GDBM_READER(),0640)) {
624: return undef;
625: }
626:
627: if (!defined($disk_env{'user.name'})
628: || !defined($disk_env{'user.domain'})) {
629: return undef;
630: }
631: return $handle;
632: }
633:
1.830 albertel 634: sub timed_flock {
635: my ($file,$lock_type) = @_;
636: my $failed=0;
637: eval {
638: local $SIG{__DIE__}='DEFAULT';
639: local $SIG{ALRM}=sub {
640: $failed=1;
641: die("failed lock");
642: };
643: alarm(13);
644: flock($file,$lock_type);
645: alarm(0);
646: };
647: if ($failed) {
648: return undef;
649: } else {
650: return 1;
651: }
652: }
653:
1.5 www 654: # ---------------------------------------------------------- Append Environment
655:
656: sub appenv {
1.949 raeburn 657: my ($newenv,$roles) = @_;
658: if (ref($newenv) eq 'HASH') {
659: foreach my $key (keys(%{$newenv})) {
660: my $refused = 0;
661: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
662: $refused = 1;
663: if (ref($roles) eq 'ARRAY') {
664: my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
665: if (grep(/^\Q$role\E$/,@{$roles})) {
666: $refused = 0;
667: }
668: }
669: }
670: if ($refused) {
671: &logthis("<font color=\"blue\">WARNING: ".
672: "Attempt to modify environment ".$key." to ".$newenv->{$key}
673: .'</font>');
674: delete($newenv->{$key});
675: } else {
676: $env{$key}=$newenv->{$key};
677: }
678: }
679: my $opened = open(my $env_file,'+<',$env{'user.environment'});
680: if ($opened
681: && &timed_flock($env_file,LOCK_EX)
682: &&
683: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
684: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
685: while (my ($key,$value) = each(%{$newenv})) {
686: $disk_env{$key} = $value;
687: }
688: untie(%disk_env);
1.35 www 689: }
1.191 harris41 690: }
1.56 www 691: return 'ok';
692: }
693: # ----------------------------------------------------- Delete from Environment
694:
695: sub delenv {
1.1104 raeburn 696: my ($delthis,$regexp,$roles) = @_;
697: if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
698: my $refused = 1;
699: if (ref($roles) eq 'ARRAY') {
700: my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
701: if (grep(/^\Q$role\E$/,@{$roles})) {
702: $refused = 0;
703: }
704: }
705: if ($refused) {
706: &logthis("<font color=\"blue\">WARNING: ".
707: "Attempt to delete from environment ".$delthis);
708: return 'error';
709: }
1.56 www 710: }
1.917 albertel 711: my $opened = open(my $env_file,'+<',$env{'user.environment'});
712: if ($opened
1.915 albertel 713: && &timed_flock($env_file,LOCK_EX)
1.830 albertel 714: &&
715: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
716: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 717: foreach my $key (keys(%disk_env)) {
1.987 raeburn 718: if ($regexp) {
719: if ($key=~/^$delthis/) {
720: delete($env{$key});
721: delete($disk_env{$key});
722: }
723: } else {
724: if ($key=~/^\Q$delthis\E/) {
725: delete($env{$key});
726: delete($disk_env{$key});
727: }
728: }
1.448 albertel 729: }
1.783 albertel 730: untie(%disk_env);
1.5 www 731: }
732: return 'ok';
1.369 albertel 733: }
734:
1.790 albertel 735: sub get_env_multiple {
736: my ($name) = @_;
737: my @values;
738: if (defined($env{$name})) {
739: # exists is it an array
740: if (ref($env{$name})) {
741: @values=@{ $env{$name} };
742: } else {
743: $values[0]=$env{$name};
744: }
745: }
746: return(@values);
747: }
748:
1.958 www 749: # ------------------------------------------------------------------- Locking
750:
751: sub set_lock {
752: my ($text)=@_;
753: $locknum++;
754: my $id=$$.'-'.$locknum;
755: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
756: 'session.lock.'.$id => $text});
757: return $id;
758: }
759:
760: sub get_locks {
761: my $num=0;
762: my %texts=();
763: foreach my $lock (split(/\,/,$env{'session.locks'})) {
764: if ($lock=~/\w/) {
765: $num++;
766: $texts{$lock}=$env{'session.lock.'.$lock};
767: }
768: }
769: return ($num,%texts);
770: }
771:
772: sub remove_lock {
773: my ($id)=@_;
774: my $newlocks='';
775: foreach my $lock (split(/\,/,$env{'session.locks'})) {
776: if (($lock=~/\w/) && ($lock ne $id)) {
777: $newlocks.=','.$lock;
778: }
779: }
780: &appenv({'session.locks' => $newlocks});
781: &delenv('session.lock.'.$id);
782: }
783:
784: sub remove_all_locks {
785: my $activelocks=$env{'session.locks'};
786: foreach my $lock (split(/\,/,$env{'session.locks'})) {
787: if ($lock=~/\w/) {
788: &remove_lock($lock);
789: }
790: }
791: }
792:
793:
1.369 albertel 794: # ------------------------------------------ Find out current server userload
795: sub userload {
796: my $numusers=0;
797: {
798: opendir(LONIDS,$perlvar{'lonIDsDir'});
799: my $filename;
800: my $curtime=time;
801: while ($filename=readdir(LONIDS)) {
1.925 albertel 802: next if ($filename eq '.' || $filename eq '..');
803: next if ($filename =~ /publicuser_\d+\.id/);
1.404 albertel 804: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437 albertel 805: if ($curtime-$mtime < 1800) { $numusers++; }
1.369 albertel 806: }
807: closedir(LONIDS);
808: }
809: my $userloadpercent=0;
810: my $maxuserload=$perlvar{'lonUserLoadLim'};
811: if ($maxuserload) {
1.371 albertel 812: $userloadpercent=100*$numusers/$maxuserload;
1.369 albertel 813: }
1.372 albertel 814: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369 albertel 815: return $userloadpercent;
1.283 www 816: }
817:
1.1 albertel 818: # ------------------------------ Find server with least workload from spare.tab
1.11 www 819:
1.1 albertel 820: sub spareserver {
1.1083 raeburn 821: my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784 albertel 822: my $spare_server;
1.370 albertel 823: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784 albertel 824: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
825: : $userloadpercent;
1.1083 raeburn 826: my ($uint_dom,$remotesessions);
827: if (($udom ne '') && (&domain($udom) ne '')) {
828: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
829: $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
830: my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
831: $remotesessions = $udomdefaults{'remotesessions'};
832: }
1.1123 raeburn 833: my $spareshash = &this_host_spares($udom);
834: if (ref($spareshash) eq 'HASH') {
835: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
836: foreach my $try_server (@{ $spareshash->{'primary'} }) {
837: if ($uint_dom) {
838: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
839: $try_server));
840: }
841: ($spare_server, $lowest_load) =
842: &compare_server_load($try_server, $spare_server, $lowest_load);
843: }
1.1083 raeburn 844: }
1.784 albertel 845:
1.1123 raeburn 846: my $found_server = ($spare_server ne '' && $lowest_load < 100);
847:
848: if (!$found_server) {
849: if (ref($spareshash->{'default'}) eq 'ARRAY') {
850: foreach my $try_server (@{ $spareshash->{'default'} }) {
851: if ($uint_dom) {
852: next unless (&spare_can_host($udom,$uint_dom,
853: $remotesessions,$try_server));
854: }
855: ($spare_server, $lowest_load) =
856: &compare_server_load($try_server, $spare_server, $lowest_load);
857: }
858: }
859: }
1.784 albertel 860: }
861:
862: if (!$want_server_name) {
1.968 raeburn 863: my $protocol = 'http';
864: if ($protocol{$spare_server} eq 'https') {
865: $protocol = $protocol{$spare_server};
866: }
1.1001 raeburn 867: if (defined($spare_server)) {
868: my $hostname = &hostname($spare_server);
1.1083 raeburn 869: if (defined($hostname)) {
1.1001 raeburn 870: $spare_server = $protocol.'://'.$hostname;
871: }
872: }
1.784 albertel 873: }
874: return $spare_server;
875: }
876:
877: sub compare_server_load {
878: my ($try_server, $spare_server, $lowest_load) = @_;
879:
880: my $loadans = &reply('load', $try_server);
881: my $userloadans = &reply('userload',$try_server);
882:
883: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114 raeburn 884: return ($spare_server, $lowest_load); #didn't get a number from the server
1.784 albertel 885: }
886:
887: my $load;
888: if ($loadans =~ /\d/) {
889: if ($userloadans =~ /\d/) {
890: #both are numbers, pick the bigger one
891: $load = ($loadans > $userloadans) ? $loadans
892: : $userloadans;
1.411 albertel 893: } else {
1.784 albertel 894: $load = $loadans;
1.411 albertel 895: }
1.784 albertel 896: } else {
897: $load = $userloadans;
898: }
899:
900: if (($load =~ /\d/) && ($load < $lowest_load)) {
901: $spare_server = $try_server;
902: $lowest_load = $load;
1.370 albertel 903: }
1.784 albertel 904: return ($spare_server,$lowest_load);
1.202 matthew 905: }
1.914 albertel 906:
907: # --------------------------- ask offload servers if user already has a session
908: sub find_existing_session {
909: my ($udom,$uname) = @_;
1.1123 raeburn 910: my $spareshash = &this_host_spares($udom);
911: if (ref($spareshash) eq 'HASH') {
912: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
913: foreach my $try_server (@{ $spareshash->{'primary'} }) {
914: return $try_server if (&has_user_session($try_server, $udom, $uname));
915: }
916: }
917: if (ref($spareshash->{'default'}) eq 'ARRAY') {
918: foreach my $try_server (@{ $spareshash->{'default'} }) {
919: return $try_server if (&has_user_session($try_server, $udom, $uname));
920: }
921: }
1.914 albertel 922: }
923: return;
924: }
925:
926: # -------------------------------- ask if server already has a session for user
927: sub has_user_session {
928: my ($lonid,$udom,$uname) = @_;
929: my $result = &reply(join(':','userhassession',
930: map {&escape($_)} ($udom,$uname)),$lonid);
931: return 1 if ($result eq 'ok');
932:
933: return 0;
934: }
935:
1.1076 raeburn 936: # --------- determine least loaded server in a user's domain which allows login
937:
938: sub choose_server {
1.1115 raeburn 939: my ($udom,$checkloginvia) = @_;
1.1076 raeburn 940: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077 raeburn 941: my %servers = &get_servers($udom);
1.1076 raeburn 942: my $lowest_load = 30000;
1.1151 raeburn 943: my ($login_host,$hostname,$portal_path,$isredirect);
1.1076 raeburn 944: foreach my $lonhost (keys(%servers)) {
1.1115 raeburn 945: my $loginvia;
946: if ($checkloginvia) {
947: $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116 raeburn 948: if ($loginvia) {
949: my ($server,$path) = split(/:/,$loginvia);
950: ($login_host, $lowest_load) =
951: &compare_server_load($server, $login_host, $lowest_load);
952: if ($login_host eq $server) {
953: $portal_path = $path;
1.1151 raeburn 954: $isredirect = 1;
1.1116 raeburn 955: }
956: } else {
957: ($login_host, $lowest_load) =
958: &compare_server_load($lonhost, $login_host, $lowest_load);
959: if ($login_host eq $lonhost) {
960: $portal_path = '';
1.1151 raeburn 961: $isredirect = '';
1.1116 raeburn 962: }
963: }
964: } else {
1.1076 raeburn 965: ($login_host, $lowest_load) =
1.1116 raeburn 966: &compare_server_load($lonhost, $login_host, $lowest_load);
1.1076 raeburn 967: }
968: }
969: if ($login_host ne '') {
1.1116 raeburn 970: $hostname = &hostname($login_host);
1.1076 raeburn 971: }
1.1151 raeburn 972: return ($login_host,$hostname,$portal_path,$isredirect);
1.1076 raeburn 973: }
974:
1.202 matthew 975: # --------------------------------------------- Try to change a user's password
976:
977: sub changepass {
1.799 raeburn 978: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 979: $currentpass = &escape($currentpass);
980: $newpass = &escape($newpass);
1.1030 raeburn 981: my $lonhost = $perlvar{'lonHostID'};
982: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202 matthew 983: $server);
984: if (! $answer) {
985: &logthis("No reply on password change request to $server ".
986: "by $uname in domain $udom.");
987: } elsif ($answer =~ "^ok") {
988: &logthis("$uname in $udom successfully changed their password ".
989: "on $server.");
990: } elsif ($answer =~ "^pwchange_failure") {
991: &logthis("$uname in $udom was unable to change their password ".
992: "on $server. The action was blocked by either lcpasswd ".
993: "or pwchange");
994: } elsif ($answer =~ "^non_authorized") {
995: &logthis("$uname in $udom did not get their password correct when ".
996: "attempting to change it on $server.");
997: } elsif ($answer =~ "^auth_mode_error") {
998: &logthis("$uname in $udom attempted to change their password despite ".
999: "not being locally or internally authenticated on $server.");
1000: } elsif ($answer =~ "^unknown_user") {
1001: &logthis("$uname in $udom attempted to change their password ".
1002: "on $server but were unable to because $server is not ".
1003: "their home server.");
1004: } elsif ($answer =~ "^refused") {
1005: &logthis("$server refused to change $uname in $udom password because ".
1006: "it was sent an unencrypted request to change the password.");
1.1030 raeburn 1007: } elsif ($answer =~ "invalid_client") {
1008: &logthis("$server refused to change $uname in $udom password because ".
1009: "it was a reset by e-mail originating from an invalid server.");
1.202 matthew 1010: }
1011: return $answer;
1.1 albertel 1012: }
1013:
1.169 harris41 1014: # ----------------------- Try to determine user's current authentication scheme
1015:
1016: sub queryauthenticate {
1017: my ($uname,$udom)=@_;
1.456 albertel 1018: my $uhome=&homeserver($uname,$udom);
1019: if (!$uhome) {
1020: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
1021: return 'no_host';
1022: }
1023: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
1024: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
1025: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 1026: }
1.456 albertel 1027: return $answer;
1.169 harris41 1028: }
1029:
1.1 albertel 1030: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 1031:
1.1 albertel 1032: sub authenticate {
1.1073 raeburn 1033: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807 albertel 1034: $upass=&escape($upass);
1035: $uname= &LONCAPA::clean_username($uname);
1.836 www 1036: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 1037: my $newhome;
1.836 www 1038: if ((!$uhome) || ($uhome eq 'no_host')) {
1039: # Maybe the machine was offline and only re-appeared again recently?
1040: &reconlonc();
1041: # One more
1.952 raeburn 1042: $uhome=&homeserver($uname,$udom,1);
1043: if (($uhome eq 'no_host') && $checkdefauth) {
1044: if (defined(&domain($udom,'primary'))) {
1045: $newhome=&domain($udom,'primary');
1046: }
1047: if ($newhome ne '') {
1048: $uhome = $newhome;
1049: }
1050: }
1.836 www 1051: if ((!$uhome) || ($uhome eq 'no_host')) {
1052: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 1053: return 'no_host';
1054: }
1.1 albertel 1055: }
1.1073 raeburn 1056: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471 albertel 1057: if ($answer eq 'authorized') {
1.952 raeburn 1058: if ($newhome) {
1059: &logthis("User $uname at $udom authorized by $uhome, but needs account");
1060: return 'no_account_on_host';
1061: } else {
1062: &logthis("User $uname at $udom authorized by $uhome");
1063: return $uhome;
1064: }
1.471 albertel 1065: }
1066: if ($answer eq 'non_authorized') {
1067: &logthis("User $uname at $udom rejected by $uhome");
1068: return 'no_host';
1.9 www 1069: }
1.471 albertel 1070: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 1071: return 'no_host';
1072: }
1073:
1.1073 raeburn 1074: sub can_host_session {
1.1074 raeburn 1075: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073 raeburn 1076: my $canhost = 1;
1.1074 raeburn 1077: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073 raeburn 1078: if (ref($remotesessions) eq 'HASH') {
1079: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074 raeburn 1080: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073 raeburn 1081: $canhost = 0;
1082: } else {
1083: $canhost = 1;
1084: }
1085: }
1086: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074 raeburn 1087: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073 raeburn 1088: $canhost = 1;
1089: } else {
1090: $canhost = 0;
1091: }
1092: }
1093: if ($canhost) {
1094: if ($remotesessions->{'version'} ne '') {
1095: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1096: if ($reqmajor ne '' && $reqminor ne '') {
1097: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1098: my $major = $1;
1099: my $minor = $2;
1100: if (($major < $reqmajor ) ||
1101: (($major == $reqmajor) && ($minor < $reqminor))) {
1102: $canhost = 0;
1103: }
1104: } else {
1105: $canhost = 0;
1106: }
1107: }
1108: }
1109: }
1110: }
1111: if ($canhost) {
1112: if (ref($hostedsessions) eq 'HASH') {
1.1120 raeburn 1113: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1114: my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073 raeburn 1115: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120 raeburn 1116: if (($uint_dom ne '') &&
1117: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073 raeburn 1118: $canhost = 0;
1119: } else {
1120: $canhost = 1;
1121: }
1122: }
1123: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120 raeburn 1124: if (($uint_dom ne '') &&
1125: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073 raeburn 1126: $canhost = 1;
1127: } else {
1128: $canhost = 0;
1129: }
1130: }
1131: }
1132: }
1133: return $canhost;
1134: }
1135:
1.1083 raeburn 1136: sub spare_can_host {
1137: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1138: my $canhost=1;
1139: my @intdoms;
1140: my $internet_names = &Apache::lonnet::get_internet_names($try_server);
1141: if (ref($internet_names) eq 'ARRAY') {
1142: @intdoms = @{$internet_names};
1143: }
1144: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1145: my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
1146: my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
1147: my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
1148: my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
1149: $canhost = &can_host_session($udom,$try_server,$remoterev,
1150: $remotesessions,
1151: $defdomdefaults{'hostedsessions'});
1152: }
1153: return $canhost;
1154: }
1155:
1.1123 raeburn 1156: sub this_host_spares {
1157: my ($dom) = @_;
1.1126 raeburn 1158: my ($dom_in_use,$lonhost_in_use,$result);
1.1123 raeburn 1159: my @hosts = ¤t_machine_ids();
1160: foreach my $lonhost (@hosts) {
1161: if (&host_domain($lonhost) eq $dom) {
1.1126 raeburn 1162: $dom_in_use = $dom;
1163: $lonhost_in_use = $lonhost;
1.1123 raeburn 1164: last;
1165: }
1166: }
1.1126 raeburn 1167: if ($dom_in_use ne '') {
1168: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1169: }
1170: if (ref($result) ne 'HASH') {
1171: $lonhost_in_use = $perlvar{'lonHostID'};
1172: $dom_in_use = &host_domain($lonhost_in_use);
1173: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1174: if (ref($result) ne 'HASH') {
1175: $result = \%spareid;
1176: }
1177: }
1178: return $result;
1179: }
1180:
1181: sub spares_for_offload {
1182: my ($dom_in_use,$lonhost_in_use) = @_;
1183: my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123 raeburn 1184: if (defined($cached)) {
1185: return $result;
1186: } else {
1.1126 raeburn 1187: my $cachetime = 60*60*24;
1188: my %domconfig =
1189: &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
1190: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1191: if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
1192: if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
1193: return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123 raeburn 1194: }
1195: }
1196: }
1197: }
1.1126 raeburn 1198: return;
1.1123 raeburn 1199: }
1200:
1.1129 raeburn 1201: sub get_lonbalancer_config {
1202: my ($servers) = @_;
1203: my ($currbalancer,$currtargets);
1204: if (ref($servers) eq 'HASH') {
1205: foreach my $server (keys(%{$servers})) {
1206: my %what = (
1207: spareid => 1,
1208: perlvar => 1,
1209: );
1210: my ($result,$returnhash) = &get_remote_globals($server,\%what);
1211: if ($result eq 'ok') {
1212: if (ref($returnhash) eq 'HASH') {
1213: if (ref($returnhash->{'perlvar'}) eq 'HASH') {
1214: if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
1215: $currbalancer = $server;
1216: $currtargets = {};
1217: if (ref($returnhash->{'spareid'}) eq 'HASH') {
1218: if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
1219: $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
1220: }
1221: if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
1222: $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
1223: }
1224: }
1225: last;
1226: }
1227: }
1228: }
1229: }
1230: }
1231: }
1232: return ($currbalancer,$currtargets);
1233: }
1234:
1235: sub check_loadbalancing {
1236: my ($uname,$udom) = @_;
1237: my ($is_balancer,$dom_in_use,$homeintdom,$rule_in_effect,
1238: $offloadto,$otherserver);
1239: my $lonhost = $perlvar{'lonHostID'};
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: my @hosts = ¤t_machine_ids();
1267: if (grep(/^\Q$currbalancer\E$/,@hosts)) {
1268: $is_balancer = 1;
1269: }
1270: }
1271: if ($is_balancer) {
1272: if (ref($currrules) eq 'HASH') {
1273: if ($homeintdom) {
1274: if ($uname ne '') {
1275: if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
1276: my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
1277: if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
1278: $rule_in_effect = $currrules->{'_LC_author'};
1279: } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
1280: $rule_in_effect = $currrules->{'_LC_adv'}
1281: }
1282: }
1283: if ($rule_in_effect eq '') {
1284: my %userenv = &userenvironment($udom,$uname,'inststatus');
1285: if ($userenv{'inststatus'} ne '') {
1286: my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
1287: my ($othertitle,$usertypes,$types) =
1288: &Apache::loncommon::sorted_inst_types($udom);
1289: if (ref($types) eq 'ARRAY') {
1290: foreach my $type (@{$types}) {
1291: if (grep(/^\Q$type\E$/,@statuses)) {
1292: if (exists($currrules->{$type})) {
1293: $rule_in_effect = $currrules->{$type};
1294: }
1295: }
1296: }
1297: }
1298: } else {
1299: if (exists($currrules->{'default'})) {
1300: $rule_in_effect = $currrules->{'default'};
1301: }
1302: }
1303: }
1304: } else {
1305: if (exists($currrules->{'default'})) {
1306: $rule_in_effect = $currrules->{'default'};
1307: }
1308: }
1309: } else {
1310: if ($currrules->{'_LC_external'} ne '') {
1311: $rule_in_effect = $currrules->{'_LC_external'};
1312: }
1313: }
1314: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1315: $uname,$udom);
1316: }
1317: }
1318: } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1319: my ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1320: unless (defined($cached)) {
1321: my %domconfig =
1322: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
1323: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1324: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129 raeburn 1325: }
1326: }
1327: if (ref($result) eq 'HASH') {
1328: my $currbalancer = $result->{'lonhost'};
1329: my $currtargets = $result->{'targets'};
1330: my $currrules = $result->{'rules'};
1331:
1332: if ($currbalancer eq $lonhost) {
1333: $is_balancer = 1;
1334: if (ref($currrules) eq 'HASH') {
1335: if ($currrules->{'_LC_internetdom'} ne '') {
1336: $rule_in_effect = $currrules->{'_LC_internetdom'};
1337: }
1338: }
1339: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1340: $uname,$udom);
1341: }
1342: } else {
1343: if ($perlvar{'lonBalancer'} eq 'yes') {
1344: $is_balancer = 1;
1345: $offloadto = &this_host_spares($dom_in_use);
1346: }
1347: }
1348: } else {
1349: if ($perlvar{'lonBalancer'} eq 'yes') {
1350: $is_balancer = 1;
1351: $offloadto = &this_host_spares($dom_in_use);
1352: }
1353: }
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: }
1361: }
1362: my $found_server = ($otherserver ne '' && $lowest_load < 100);
1363:
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}) {
1377: ($otherserver,$lowest_load) =
1378: &compare_server_load($try_server,$otherserver,$lowest_load);
1379: }
1380: }
1381: }
1382: return ($is_balancer,$otherserver);
1383: }
1384:
1385: sub get_loadbalancer_targets {
1386: my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
1387: my $offloadto;
1388: if ($rule_in_effect eq '') {
1389: $offloadto = $currtargets;
1390: } else {
1391: if ($rule_in_effect eq 'homeserver') {
1392: my $homeserver = &homeserver($uname,$udom);
1393: if ($homeserver ne 'no_host') {
1394: $offloadto = [$homeserver];
1395: }
1396: } elsif ($rule_in_effect eq 'externalbalancer') {
1397: my %domconfig =
1398: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1399: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1400: if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
1401: if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
1402: $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
1403: }
1404: }
1405: } else {
1406: my %servers = &dom_servers($udom);
1407: my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
1408: if (&hostname($remotebalancer) ne '') {
1409: $offloadto = [$remotebalancer];
1410: }
1411: }
1412: } elsif (&hostname($rule_in_effect) ne '') {
1413: $offloadto = [$rule_in_effect];
1414: }
1415: }
1416: return $offloadto;
1417: }
1418:
1.1127 raeburn 1419: sub internet_dom_servers {
1420: my ($dom) = @_;
1421: my (%uniqservers,%servers);
1422: my $primaryserver = &hostname(&domain($dom,'primary'));
1423: my @machinedoms = &machine_domains($primaryserver);
1424: foreach my $mdom (@machinedoms) {
1425: my %currservers = %servers;
1426: my %server = &get_servers($mdom);
1427: %servers = (%currservers,%server);
1428: }
1429: my %by_hostname;
1430: foreach my $id (keys(%servers)) {
1431: push(@{$by_hostname{$servers{$id}}},$id);
1432: }
1433: foreach my $hostname (sort(keys(%by_hostname))) {
1434: if (@{$by_hostname{$hostname}} > 1) {
1435: my $match = 0;
1436: foreach my $id (@{$by_hostname{$hostname}}) {
1437: if (&host_domain($id) eq $dom) {
1438: $uniqservers{$id} = $hostname;
1439: $match = 1;
1440: }
1441: }
1442: unless ($match) {
1443: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1444: }
1445: } else {
1446: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1447: }
1448: }
1449: return %uniqservers;
1450: }
1451:
1.1 albertel 1452: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 1453:
1.599 albertel 1454: my %homecache;
1.1 albertel 1455: sub homeserver {
1.230 stredwic 1456: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 1457: my $index="$uname:$udom";
1.426 albertel 1458:
1.599 albertel 1459: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 1460:
1461: my %servers = &get_servers($udom,'library');
1462: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 1463: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 1464: exists($badServerCache{$tryserver}));
1.841 albertel 1465:
1466: my $answer=reply("home:$udom:$uname",$tryserver);
1467: if ($answer eq 'found') {
1468: delete($badServerCache{$tryserver});
1469: return $homecache{$index}=$tryserver;
1470: } elsif ($answer eq 'no_host') {
1471: $badServerCache{$tryserver}=1;
1472: }
1.1 albertel 1473: }
1474: return 'no_host';
1.70 www 1475: }
1476:
1477: # ------------------------------------- Find the usernames behind a list of IDs
1478:
1479: sub idget {
1480: my ($udom,@ids)=@_;
1481: my %returnhash=();
1482:
1.841 albertel 1483: my %servers = &get_servers($udom,'library');
1484: foreach my $tryserver (keys(%servers)) {
1485: my $idlist=join('&',@ids);
1486: $idlist=~tr/A-Z/a-z/;
1487: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
1488: my @answer=();
1489: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1490: @answer=split(/\&/,$reply);
1491: } ;
1492: my $i;
1493: for ($i=0;$i<=$#ids;$i++) {
1494: if ($answer[$i]) {
1495: $returnhash{$ids[$i]}=$answer[$i];
1496: }
1497: }
1498: }
1.70 www 1499: return %returnhash;
1500: }
1501:
1502: # ------------------------------------- Find the IDs behind a list of usernames
1503:
1504: sub idrget {
1505: my ($udom,@unames)=@_;
1506: my %returnhash=();
1.800 albertel 1507: foreach my $uname (@unames) {
1508: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 1509: }
1.70 www 1510: return %returnhash;
1511: }
1512:
1513: # ------------------------------- Store away a list of names and associated IDs
1514:
1515: sub idput {
1516: my ($udom,%ids)=@_;
1517: my %servers=();
1.800 albertel 1518: foreach my $uname (keys(%ids)) {
1519: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1520: my $uhom=&homeserver($uname,$udom);
1.70 www 1521: if ($uhom ne 'no_host') {
1.800 albertel 1522: my $id=&escape($ids{$uname});
1.70 www 1523: $id=~tr/A-Z/a-z/;
1.800 albertel 1524: my $esc_unam=&escape($uname);
1.70 www 1525: if ($servers{$uhom}) {
1.800 albertel 1526: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70 www 1527: } else {
1.800 albertel 1528: $servers{$uhom}=$id.'='.$esc_unam;
1.70 www 1529: }
1530: }
1.191 harris41 1531: }
1.800 albertel 1532: foreach my $server (keys(%servers)) {
1533: &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191 harris41 1534: }
1.344 www 1535: }
1536:
1.1023 raeburn 1537: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 1538: sub dump_dom {
1.1165 droeschl 1539: my ($namespace, $udom, $regexp) = @_;
1540:
1541: $udom ||= $env{'user.domain'};
1542:
1543: return () unless $udom;
1544:
1545: return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012 raeburn 1546: }
1547:
1.1023 raeburn 1548: # ------------------------------------------ get items from domain db files
1.806 raeburn 1549:
1550: sub get_dom {
1.860 raeburn 1551: my ($namespace,$storearr,$udom,$uhome)=@_;
1.806 raeburn 1552: my $items='';
1553: foreach my $item (@$storearr) {
1554: $items.=&escape($item).'&';
1555: }
1556: $items=~s/\&$//;
1.860 raeburn 1557: if (!$udom) {
1558: $udom=$env{'user.domain'};
1559: if (defined(&domain($udom,'primary'))) {
1560: $uhome=&domain($udom,'primary');
1561: } else {
1.874 albertel 1562: undef($uhome);
1.860 raeburn 1563: }
1564: } else {
1565: if (!$uhome) {
1566: if (defined(&domain($udom,'primary'))) {
1567: $uhome=&domain($udom,'primary');
1568: }
1569: }
1570: }
1571: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1572: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866 raeburn 1573: my %returnhash;
1.875 albertel 1574: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 1575: return %returnhash;
1576: }
1.806 raeburn 1577: my @pairs=split(/\&/,$rep);
1578: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1579: return @pairs;
1580: }
1581: my $i=0;
1582: foreach my $item (@$storearr) {
1583: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1584: $i++;
1585: }
1586: return %returnhash;
1587: } else {
1.880 banghart 1588: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 1589: }
1590: }
1591:
1592: # -------------------------------------------- put items in domain db files
1593:
1594: sub put_dom {
1.860 raeburn 1595: my ($namespace,$storehash,$udom,$uhome)=@_;
1596: if (!$udom) {
1597: $udom=$env{'user.domain'};
1598: if (defined(&domain($udom,'primary'))) {
1599: $uhome=&domain($udom,'primary');
1600: } else {
1.874 albertel 1601: undef($uhome);
1.860 raeburn 1602: }
1603: } else {
1604: if (!$uhome) {
1605: if (defined(&domain($udom,'primary'))) {
1606: $uhome=&domain($udom,'primary');
1607: }
1608: }
1609: }
1610: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1611: my $items='';
1612: foreach my $item (keys(%$storehash)) {
1613: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1614: }
1615: $items=~s/\&$//;
1616: return &reply("putdom:$udom:$namespace:$items",$uhome);
1617: } else {
1.860 raeburn 1618: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 1619: }
1620: }
1621:
1.1023 raeburn 1622: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 1623: sub newput_dom {
1.1023 raeburn 1624: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 1625: my $result;
1626: if (!$udom) {
1627: $udom=$env{'user.domain'};
1628: }
1.1023 raeburn 1629: if ($udom) {
1630: my $uname = &get_domainconfiguser($udom);
1631: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 1632: }
1633: return $result;
1634: }
1635:
1.1023 raeburn 1636: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 1637: sub del_dom {
1.1023 raeburn 1638: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 1639: if (ref($storearr) eq 'ARRAY') {
1640: if (!$udom) {
1641: $udom=$env{'user.domain'};
1642: }
1.1023 raeburn 1643: if ($udom) {
1644: my $uname = &get_domainconfiguser($udom);
1645: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 1646: }
1647: }
1648: }
1649:
1.1023 raeburn 1650: # ----------------------------------construct domainconfig user for a domain
1651: sub get_domainconfiguser {
1652: my ($udom) = @_;
1653: return $udom.'-domainconfig';
1654: }
1655:
1.837 raeburn 1656: sub retrieve_inst_usertypes {
1657: my ($udom) = @_;
1658: my (%returnhash,@order);
1.989 raeburn 1659: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1660: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1661: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1662: %returnhash = %{$domdefs{'inststatustypes'}};
1663: @order = @{$domdefs{'inststatusorder'}};
1664: } else {
1665: if (defined(&domain($udom,'primary'))) {
1666: my $uhome=&domain($udom,'primary');
1667: my $rep=&reply("inst_usertypes:$udom",$uhome);
1668: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1669: &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
1670: return (\%returnhash,\@order);
1671: }
1672: my ($hashitems,$orderitems) = split(/:/,$rep);
1673: my @pairs=split(/\&/,$hashitems);
1674: foreach my $item (@pairs) {
1675: my ($key,$value)=split(/=/,$item,2);
1676: $key = &unescape($key);
1677: next if ($key =~ /^error: 2 /);
1678: $returnhash{$key}=&thaw_unescape($value);
1679: }
1680: my @esc_order = split(/\&/,$orderitems);
1681: foreach my $item (@esc_order) {
1682: push(@order,&unescape($item));
1683: }
1684: } else {
1685: &logthis("get_dom failed - no primary domain server for $udom");
1.837 raeburn 1686: }
1687: }
1688: return (\%returnhash,\@order);
1689: }
1690:
1.868 raeburn 1691: sub is_domainimage {
1692: my ($url) = @_;
1693: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
1694: if (&domain($1) ne '') {
1695: return '1';
1696: }
1697: }
1698: return;
1699: }
1700:
1.899 raeburn 1701: sub inst_directory_query {
1702: my ($srch) = @_;
1703: my $udom = $srch->{'srchdomain'};
1704: my %results;
1705: my $homeserver = &domain($udom,'primary');
1.909 raeburn 1706: my $outcome;
1.899 raeburn 1707: if ($homeserver ne '') {
1.904 albertel 1708: my $queryid=&reply("querysend:instdirsearch:".
1709: &escape($srch->{'srchby'}).':'.
1710: &escape($srch->{'srchterm'}).':'.
1711: &escape($srch->{'srchtype'}),$homeserver);
1712: my $host=&hostname($homeserver);
1713: if ($queryid !~/^\Q$host\E\_/) {
1714: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1715: return;
1716: }
1717: my $response = &get_query_reply($queryid);
1718: my $maxtries = 5;
1719: my $tries = 1;
1720: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1721: $response = &get_query_reply($queryid);
1722: $tries ++;
1723: }
1724:
1725: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 1726: if ($response eq 'unavailable') {
1727: $outcome = $response;
1728: } else {
1729: $outcome = 'ok';
1730: my @matches = split(/\n/,$response);
1731: foreach my $match (@matches) {
1732: my ($key,$value) = split(/=/,$match);
1733: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1734: }
1.899 raeburn 1735: }
1736: }
1737: }
1.909 raeburn 1738: return ($outcome,%results);
1.899 raeburn 1739: }
1740:
1741: sub usersearch {
1742: my ($srch) = @_;
1743: my $dom = $srch->{'srchdomain'};
1744: my %results;
1745: my %libserv = &all_library();
1746: my $query = 'usersearch';
1747: foreach my $tryserver (keys(%libserv)) {
1748: if (&host_domain($tryserver) eq $dom) {
1749: my $host=&hostname($tryserver);
1750: my $queryid=
1.911 raeburn 1751: &reply("querysend:".&escape($query).':'.
1752: &escape($srch->{'srchby'}).':'.
1.899 raeburn 1753: &escape($srch->{'srchtype'}).':'.
1754: &escape($srch->{'srchterm'}),$tryserver);
1755: if ($queryid !~/^\Q$host\E\_/) {
1756: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 1757: next;
1.899 raeburn 1758: }
1759: my $reply = &get_query_reply($queryid);
1760: my $maxtries = 1;
1761: my $tries = 1;
1762: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1763: $reply = &get_query_reply($queryid);
1764: $tries ++;
1765: }
1766: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1767: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1768: } else {
1.911 raeburn 1769: my @matches;
1770: if ($reply =~ /\n/) {
1771: @matches = split(/\n/,$reply);
1772: } else {
1773: @matches = split(/\&/,$reply);
1774: }
1.899 raeburn 1775: foreach my $match (@matches) {
1776: my ($uname,$udom,%userhash);
1.911 raeburn 1777: foreach my $entry (split(/:/,$match)) {
1778: my ($key,$value) =
1779: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 1780: $userhash{$key} = $value;
1781: if ($key eq 'username') {
1782: $uname = $value;
1783: } elsif ($key eq 'domain') {
1784: $udom = $value;
1.911 raeburn 1785: }
1.899 raeburn 1786: }
1787: $results{$uname.':'.$udom} = \%userhash;
1788: }
1789: }
1790: }
1791: }
1792: return %results;
1793: }
1794:
1.912 raeburn 1795: sub get_instuser {
1796: my ($udom,$uname,$id) = @_;
1797: my $homeserver = &domain($udom,'primary');
1798: my ($outcome,%results);
1799: if ($homeserver ne '') {
1800: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1801: &escape($id).':'.&escape($udom),$homeserver);
1802: my $host=&hostname($homeserver);
1803: if ($queryid !~/^\Q$host\E\_/) {
1804: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1805: return;
1806: }
1807: my $response = &get_query_reply($queryid);
1808: my $maxtries = 5;
1809: my $tries = 1;
1810: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1811: $response = &get_query_reply($queryid);
1812: $tries ++;
1813: }
1814: if (!&error($response) && $response ne 'refused') {
1815: if ($response eq 'unavailable') {
1816: $outcome = $response;
1817: } else {
1818: $outcome = 'ok';
1819: my @matches = split(/\n/,$response);
1820: foreach my $match (@matches) {
1821: my ($key,$value) = split(/=/,$match);
1822: $results{&unescape($key)} = &thaw_unescape($value);
1823: }
1824: }
1825: }
1826: }
1827: my %userinfo;
1828: if (ref($results{$uname}) eq 'HASH') {
1829: %userinfo = %{$results{$uname}};
1830: }
1831: return ($outcome,%userinfo);
1832: }
1833:
1834: sub inst_rulecheck {
1.923 raeburn 1835: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 1836: my %returnhash;
1837: if ($udom ne '') {
1838: if (ref($rules) eq 'ARRAY') {
1839: @{$rules} = map {&escape($_);} (@{$rules});
1840: my $rulestr = join(':',@{$rules});
1841: my $homeserver=&domain($udom,'primary');
1842: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1843: my $response;
1844: if ($item eq 'username') {
1845: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
1846: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 1847: $homeserver));
1.923 raeburn 1848: } elsif ($item eq 'id') {
1849: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
1850: ':'.&escape($id).':'.$rulestr,
1851: $homeserver));
1.945 raeburn 1852: } elsif ($item eq 'selfcreate') {
1853: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 1854: &escape($udom).':'.&escape($uname).
1855: ':'.$rulestr,$homeserver));
1.923 raeburn 1856: }
1.912 raeburn 1857: if ($response ne 'refused') {
1858: my @pairs=split(/\&/,$response);
1859: foreach my $item (@pairs) {
1860: my ($key,$value)=split(/=/,$item,2);
1861: $key = &unescape($key);
1862: next if ($key =~ /^error: 2 /);
1863: $returnhash{$key}=&thaw_unescape($value);
1864: }
1865: }
1866: }
1867: }
1868: }
1869: return %returnhash;
1870: }
1871:
1872: sub inst_userrules {
1.923 raeburn 1873: my ($udom,$check) = @_;
1.912 raeburn 1874: my (%ruleshash,@ruleorder);
1875: if ($udom ne '') {
1876: my $homeserver=&domain($udom,'primary');
1877: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1878: my $response;
1879: if ($check eq 'id') {
1880: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 1881: $homeserver);
1.943 raeburn 1882: } elsif ($check eq 'email') {
1883: $response=&reply('instemailrules:'.&escape($udom),
1884: $homeserver);
1.923 raeburn 1885: } else {
1886: $response=&reply('instuserrules:'.&escape($udom),
1887: $homeserver);
1888: }
1.912 raeburn 1889: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 1890: ($response ne 'unknown_cmd') &&
1.912 raeburn 1891: ($response ne 'no_such_host')) {
1892: my ($hashitems,$orderitems) = split(/:/,$response);
1893: my @pairs=split(/\&/,$hashitems);
1894: foreach my $item (@pairs) {
1895: my ($key,$value)=split(/=/,$item,2);
1896: $key = &unescape($key);
1897: next if ($key =~ /^error: 2 /);
1898: $ruleshash{$key}=&thaw_unescape($value);
1899: }
1900: my @esc_order = split(/\&/,$orderitems);
1901: foreach my $item (@esc_order) {
1902: push(@ruleorder,&unescape($item));
1903: }
1904: }
1905: }
1906: }
1907: return (\%ruleshash,\@ruleorder);
1908: }
1909:
1.976 raeburn 1910: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 1911:
1912: sub get_domain_defaults {
1913: my ($domain) = @_;
1914: my $cachetime = 60*60*24;
1915: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
1916: if (defined($cached)) {
1917: if (ref($result) eq 'HASH') {
1918: return %{$result};
1919: }
1920: }
1921: my %domdefaults;
1922: my %domconfig =
1.989 raeburn 1923: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 1924: 'requestcourses','inststatus',
1.1073 raeburn 1925: 'coursedefaults','usersessions'],$domain);
1.943 raeburn 1926: if (ref($domconfig{'defaults'}) eq 'HASH') {
1927: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
1928: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
1929: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 1930: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 1931: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147 raeburn 1932: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943 raeburn 1933: } else {
1934: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
1935: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
1936: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
1937: }
1.976 raeburn 1938: if (ref($domconfig{'quotas'}) eq 'HASH') {
1939: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
1940: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
1941: } else {
1942: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1943: }
1944: my @usertools = ('aboutme','blog','portfolio');
1945: foreach my $item (@usertools) {
1946: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
1947: $domdefaults{$item} = $domconfig{'quotas'}{$item};
1948: }
1949: }
1950: }
1.985 raeburn 1951: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006 raeburn 1952: foreach my $item ('official','unofficial','community') {
1.985 raeburn 1953: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
1954: }
1955: }
1.989 raeburn 1956: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1957: foreach my $item ('inststatustypes','inststatusorder') {
1958: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
1959: }
1960: }
1.1047 raeburn 1961: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1962: foreach my $item ('canuse_pdfforms') {
1963: $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
1964: }
1965: }
1.1073 raeburn 1966: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1967: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
1968: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
1969: }
1970: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
1971: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
1972: }
1973: }
1.943 raeburn 1974: &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
1975: $cachetime);
1976: return %domdefaults;
1977: }
1978:
1.344 www 1979: # --------------------------------------------------- Assign a key to a student
1980:
1981: sub assign_access_key {
1.364 www 1982: #
1983: # a valid key looks like uname:udom#comments
1984: # comments are being appended
1985: #
1.498 www 1986: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
1987: $kdom=
1.620 albertel 1988: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 1989: $knum=
1.620 albertel 1990: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 1991: $cdom=
1.620 albertel 1992: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1993: $cnum=
1.620 albertel 1994: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1995: $udom=$env{'user.name'} unless (defined($udom));
1996: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 1997: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 1998: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 1999: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 2000: # assigned to this person
2001: # - this should not happen,
1.345 www 2002: # unless something went wrong
2003: # the first time around
2004: # ready to assign
1.364 www 2005: $logentry=$1.'; '.$logentry;
1.496 www 2006: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 2007: $kdom,$knum) eq 'ok') {
1.345 www 2008: # key now belongs to user
1.346 www 2009: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 2010: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 2011: &appenv({'environment.'.$envkey => $ckey});
1.345 www 2012: return 'ok';
2013: } else {
2014: return
2015: 'error: Count not permanently assign key, will need to be re-entered later.';
2016: }
2017: } else {
2018: return 'error: Could not assign key, try again later.';
2019: }
1.364 www 2020: } elsif (!$existing{$ckey}) {
1.345 www 2021: # the key does not exist
2022: return 'error: The key does not exist';
2023: } else {
2024: # the key is somebody else's
2025: return 'error: The key is already in use';
2026: }
1.344 www 2027: }
2028:
1.364 www 2029: # ------------------------------------------ put an additional comment on a key
2030:
2031: sub comment_access_key {
2032: #
2033: # a valid key looks like uname:udom#comments
2034: # comments are being appended
2035: #
2036: my ($ckey,$cdom,$cnum,$logentry)=@_;
2037: $cdom=
1.620 albertel 2038: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 2039: $cnum=
1.620 albertel 2040: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 2041: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2042: if ($existing{$ckey}) {
2043: $existing{$ckey}.='; '.$logentry;
2044: # ready to assign
1.367 www 2045: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 2046: $cdom,$cnum) eq 'ok') {
2047: return 'ok';
2048: } else {
2049: return 'error: Count not store comment.';
2050: }
2051: } else {
2052: # the key does not exist
2053: return 'error: The key does not exist';
2054: }
2055: }
2056:
1.344 www 2057: # ------------------------------------------------------ Generate a set of keys
2058:
2059: sub generate_access_keys {
1.364 www 2060: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 2061: $cdom=
1.620 albertel 2062: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2063: $cnum=
1.620 albertel 2064: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 2065: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 2066: unless (($cdom) && ($cnum)) { return 0; }
2067: if ($number>10000) { return 0; }
2068: sleep(2); # make sure don't get same seed twice
2069: srand(time()^($$+($$<<15))); # from "Programming Perl"
2070: my $total=0;
2071: for (my $i=1;$i<=$number;$i++) {
2072: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
2073: sprintf("%lx",int(100000*rand)).'-'.
2074: sprintf("%lx",int(100000*rand));
2075: $newkey=~s/1/g/g; # folks mix up 1 and l
2076: $newkey=~s/0/h/g; # and also 0 and O
2077: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
2078: if ($existing{$newkey}) {
2079: $i--;
2080: } else {
1.364 www 2081: if (&put('accesskeys',
2082: { $newkey => '# generated '.localtime().
1.620 albertel 2083: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 2084: '; '.$logentry },
2085: $cdom,$cnum) eq 'ok') {
1.344 www 2086: $total++;
2087: }
2088: }
2089: }
1.620 albertel 2090: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 2091: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
2092: return $total;
2093: }
2094:
2095: # ------------------------------------------------------- Validate an accesskey
2096:
2097: sub validate_access_key {
2098: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
2099: $cdom=
1.620 albertel 2100: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2101: $cnum=
1.620 albertel 2102: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2103: $udom=$env{'user.domain'} unless (defined($udom));
2104: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 2105: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 2106: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 2107: }
2108:
2109: # ------------------------------------- Find the section of student in a course
1.652 albertel 2110: sub devalidate_getsection_cache {
2111: my ($udom,$unam,$courseid)=@_;
2112: my $hashid="$udom:$unam:$courseid";
2113: &devalidate_cache_new('getsection',$hashid);
2114: }
1.298 matthew 2115:
1.815 albertel 2116: sub courseid_to_courseurl {
2117: my ($courseid) = @_;
2118: #already url style courseid
2119: return $courseid if ($courseid =~ m{^/});
2120:
2121: if (exists($env{'course.'.$courseid.'.num'})) {
2122: my $cnum = $env{'course.'.$courseid.'.num'};
2123: my $cdom = $env{'course.'.$courseid.'.domain'};
2124: return "/$cdom/$cnum";
2125: }
2126:
2127: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
2128: if (exists($courseinfo{'num'})) {
2129: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
2130: }
2131:
2132: return undef;
2133: }
2134:
1.298 matthew 2135: sub getsection {
2136: my ($udom,$unam,$courseid)=@_;
1.599 albertel 2137: my $cachetime=1800;
1.551 albertel 2138:
2139: my $hashid="$udom:$unam:$courseid";
1.599 albertel 2140: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 2141: if (defined($cached)) { return $result; }
2142:
1.298 matthew 2143: my %Pending;
2144: my %Expired;
2145: #
2146: # Each role can either have not started yet (pending), be active,
2147: # or have expired.
2148: #
2149: # If there is an active role, we are done.
2150: #
2151: # If there is more than one role which has not started yet,
2152: # choose the one which will start sooner
2153: # If there is one role which has not started yet, return it.
2154: #
2155: # If there is more than one expired role, choose the one which ended last.
2156: # If there is a role which has expired, return it.
2157: #
1.815 albertel 2158: $courseid = &courseid_to_courseurl($courseid);
1.1166 raeburn 2159: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817 raeburn 2160: foreach my $key (keys(%roleshash)) {
1.479 albertel 2161: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 2162: my $section=$1;
2163: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 2164: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 2165: my $now=time;
1.548 albertel 2166: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 2167: $Expired{$end}=$section;
2168: next;
2169: }
1.548 albertel 2170: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 2171: $Pending{$start}=$section;
2172: next;
2173: }
1.599 albertel 2174: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 2175: }
2176: #
2177: # Presumedly there will be few matching roles from the above
2178: # loop and the sorting time will be negligible.
2179: if (scalar(keys(%Pending))) {
2180: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 2181: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 2182: }
2183: if (scalar(keys(%Expired))) {
2184: my @sorted = sort {$a <=> $b} keys(%Expired);
2185: my $time = pop(@sorted);
1.599 albertel 2186: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 2187: }
1.599 albertel 2188: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 2189: }
1.70 www 2190:
1.599 albertel 2191: sub save_cache {
2192: &purge_remembered();
1.722 albertel 2193: #&Apache::loncommon::validate_page();
1.620 albertel 2194: undef(%env);
1.780 albertel 2195: undef($env_loaded);
1.599 albertel 2196: }
1.452 albertel 2197:
1.599 albertel 2198: my $to_remember=-1;
2199: my %remembered;
2200: my %accessed;
2201: my $kicks=0;
2202: my $hits=0;
1.849 albertel 2203: sub make_key {
2204: my ($name,$id) = @_;
1.872 albertel 2205: if (length($id) > 65
2206: && length(&escape($id)) > 200) {
2207: $id=length($id).':'.&Digest::MD5::md5_hex($id);
2208: }
1.849 albertel 2209: return &escape($name.':'.$id);
2210: }
2211:
1.599 albertel 2212: sub devalidate_cache_new {
2213: my ($name,$id,$debug) = @_;
2214: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849 albertel 2215: $id=&make_key($name,$id);
1.599 albertel 2216: $memcache->delete($id);
2217: delete($remembered{$id});
2218: delete($accessed{$id});
2219: }
2220:
2221: sub is_cached_new {
2222: my ($name,$id,$debug) = @_;
1.849 albertel 2223: $id=&make_key($name,$id);
1.599 albertel 2224: if (exists($remembered{$id})) {
1.1133 foxr 2225: if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
1.599 albertel 2226: $accessed{$id}=[&gettimeofday()];
2227: $hits++;
2228: return ($remembered{$id},1);
2229: }
2230: my $value = $memcache->get($id);
2231: if (!(defined($value))) {
2232: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 2233: return (undef,undef);
1.416 albertel 2234: }
1.599 albertel 2235: if ($value eq '__undef__') {
2236: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
2237: $value=undef;
2238: }
2239: &make_room($id,$value,$debug);
2240: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
2241: return ($value,1);
2242: }
2243:
2244: sub do_cache_new {
2245: my ($name,$id,$value,$time,$debug) = @_;
1.849 albertel 2246: $id=&make_key($name,$id);
1.599 albertel 2247: my $setvalue=$value;
2248: if (!defined($setvalue)) {
2249: $setvalue='__undef__';
2250: }
1.623 albertel 2251: if (!defined($time) ) {
2252: $time=600;
2253: }
1.599 albertel 2254: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 2255: my $result = $memcache->set($id,$setvalue,$time);
2256: if (! $result) {
1.872 albertel 2257: &logthis("caching of id -> $id failed");
1.910 albertel 2258: $memcache->disconnect_all();
1.872 albertel 2259: }
1.600 albertel 2260: # need to make a copy of $value
1.919 albertel 2261: &make_room($id,$value,$debug);
1.599 albertel 2262: return $value;
2263: }
2264:
2265: sub make_room {
2266: my ($id,$value,$debug)=@_;
1.919 albertel 2267:
2268: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
2269: : $value;
1.599 albertel 2270: if ($to_remember<0) { return; }
2271: $accessed{$id}=[&gettimeofday()];
2272: if (scalar(keys(%remembered)) <= $to_remember) { return; }
2273: my $to_kick;
2274: my $max_time=0;
2275: foreach my $other (keys(%accessed)) {
2276: if (&tv_interval($accessed{$other}) > $max_time) {
2277: $to_kick=$other;
2278: $max_time=&tv_interval($accessed{$other});
2279: }
2280: }
2281: delete($remembered{$to_kick});
2282: delete($accessed{$to_kick});
2283: $kicks++;
2284: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 2285: return;
2286: }
2287:
1.599 albertel 2288: sub purge_remembered {
1.604 albertel 2289: #&logthis("Tossing ".scalar(keys(%remembered)));
2290: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 2291: undef(%remembered);
2292: undef(%accessed);
1.428 albertel 2293: }
1.70 www 2294: # ------------------------------------- Read an entry from a user's environment
2295:
2296: sub userenvironment {
2297: my ($udom,$unam,@what)=@_;
1.976 raeburn 2298: my $items;
2299: foreach my $item (@what) {
2300: $items.=&escape($item).'&';
2301: }
2302: $items=~s/\&$//;
1.70 www 2303: my %returnhash=();
1.1009 raeburn 2304: my $uhome = &homeserver($unam,$udom);
2305: unless ($uhome eq 'no_host') {
2306: my @answer=split(/\&/,
2307: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 2308: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
2309: return %returnhash;
2310: }
1.1009 raeburn 2311: my $i;
2312: for ($i=0;$i<=$#what;$i++) {
2313: $returnhash{$what[$i]}=&unescape($answer[$i]);
2314: }
1.70 www 2315: }
2316: return %returnhash;
1.1 albertel 2317: }
2318:
1.617 albertel 2319: # ---------------------------------------------------------- Get a studentphoto
2320: sub studentphoto {
2321: my ($udom,$unam,$ext) = @_;
2322: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 2323: if (defined($env{'request.course.id'})) {
1.708 raeburn 2324: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 2325: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
2326: return(&retrievestudentphoto($udom,$unam,$ext));
2327: } else {
2328: my ($result,$perm_reqd)=
1.707 albertel 2329: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2330: if ($result eq 'ok') {
2331: if (!($perm_reqd eq 'yes')) {
2332: return(&retrievestudentphoto($udom,$unam,$ext));
2333: }
2334: }
2335: }
2336: }
2337: } else {
2338: my ($result,$perm_reqd) =
1.707 albertel 2339: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2340: if ($result eq 'ok') {
2341: if (!($perm_reqd eq 'yes')) {
2342: return(&retrievestudentphoto($udom,$unam,$ext));
2343: }
2344: }
2345: }
2346: return '/adm/lonKaputt/lonlogo_broken.gif';
2347: }
2348:
2349: sub retrievestudentphoto {
2350: my ($udom,$unam,$ext,$type) = @_;
2351: my $home=&Apache::lonnet::homeserver($unam,$udom);
2352: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
2353: if ($ret eq 'ok') {
2354: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
2355: if ($type eq 'thumbnail') {
2356: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
2357: }
2358: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
2359: return $tokenurl;
2360: } else {
2361: if ($type eq 'thumbnail') {
2362: return '/adm/lonKaputt/genericstudent_tn.gif';
2363: } else {
2364: return '/adm/lonKaputt/lonlogo_broken.gif';
2365: }
1.617 albertel 2366: }
2367: }
2368:
1.263 www 2369: # -------------------------------------------------------------------- New chat
2370:
2371: sub chatsend {
1.724 raeburn 2372: my ($newentry,$anon,$group)=@_;
1.620 albertel 2373: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
2374: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2375: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 2376: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 2377: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 2378: &escape($newentry)).':'.$group,$chome);
1.292 www 2379: }
2380:
2381: # ------------------------------------------ Find current version of a resource
2382:
2383: sub getversion {
2384: my $fname=&clutter(shift);
2385: unless ($fname=~/^\/res\//) { return -1; }
2386: return ¤tversion(&filelocation('',$fname));
2387: }
2388:
2389: sub currentversion {
2390: my $fname=shift;
2391: my $author=$fname;
2392: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2393: my ($udom,$uname)=split(/\//,$author);
1.1112 www 2394: my $home=&homeserver($uname,$udom);
1.292 www 2395: if ($home eq 'no_host') {
2396: return -1;
2397: }
1.1112 www 2398: my $answer=&reply("currentversion:$fname",$home);
1.292 www 2399: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2400: return -1;
2401: }
1.1112 www 2402: return $answer;
1.263 www 2403: }
2404:
1.1111 www 2405: #
2406: # Return special version number of resource if set by override, empty otherwise
2407: #
2408: sub usedversion {
2409: my $fname=shift;
2410: unless ($fname) { $fname=$env{'request.uri'}; }
2411: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
2412: if ($urlversion) { return $urlversion; }
2413: return '';
2414: }
2415:
1.1 albertel 2416: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 2417:
1.1 albertel 2418: sub subscribe {
2419: my $fname=shift;
1.761 raeburn 2420: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 2421: $fname=~s/[\n\r]//g;
1.1 albertel 2422: my $author=$fname;
2423: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2424: my ($udom,$uname)=split(/\//,$author);
2425: my $home=homeserver($uname,$udom);
1.335 albertel 2426: if ($home eq 'no_host') {
2427: return 'not_found';
1.1 albertel 2428: }
2429: my $answer=reply("sub:$fname",$home);
1.64 www 2430: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2431: $answer.=' by '.$home;
2432: }
1.1 albertel 2433: return $answer;
2434: }
2435:
1.8 www 2436: # -------------------------------------------------------------- Replicate file
2437:
2438: sub repcopy {
2439: my $filename=shift;
1.23 www 2440: $filename=~s/\/+/\//g;
1.1142 raeburn 2441: my $londocroot = $perlvar{'lonDocRoot'};
2442: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164 raeburn 2443: if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142 raeburn 2444: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
2445: $filename=~m{^/*(uploaded|editupload)/}) {
1.538 albertel 2446: return &repcopy_userfile($filename);
2447: }
1.532 albertel 2448: $filename=~s/[\n\r]//g;
1.8 www 2449: my $transname="$filename.in.transfer";
1.828 www 2450: # FIXME: this should flock
1.607 raeburn 2451: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 2452: my $remoteurl=subscribe($filename);
1.64 www 2453: if ($remoteurl =~ /^con_lost by/) {
2454: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2455: return 'unavailable';
1.8 www 2456: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 2457: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 2458: return 'not_found';
1.64 www 2459: } elsif ($remoteurl =~ /^rejected by/) {
2460: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2461: return 'forbidden';
1.20 www 2462: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 2463: return 'ok';
1.8 www 2464: } else {
1.290 www 2465: my $author=$filename;
2466: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2467: my ($udom,$uname)=split(/\//,$author);
2468: my $home=homeserver($uname,$udom);
2469: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 2470: my @parts=split(/\//,$filename);
2471: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142 raeburn 2472: if ($path ne "$londocroot/res") {
1.8 www 2473: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 2474: return 'bad_request';
1.8 www 2475: }
2476: my $count;
2477: for ($count=5;$count<$#parts;$count++) {
2478: $path.="/$parts[$count]";
2479: if ((-e $path)!=1) {
2480: mkdir($path,0777);
2481: }
2482: }
2483: my $ua=new LWP::UserAgent;
2484: my $request=new HTTP::Request('GET',"$remoteurl");
2485: my $response=$ua->request($request,$transname);
2486: if ($response->is_error()) {
2487: unlink($transname);
2488: my $message=$response->status_line;
1.672 albertel 2489: &logthis("<font color=\"blue\">WARNING:"
1.12 www 2490: ." LWP get: $message: $filename</font>");
1.607 raeburn 2491: return 'unavailable';
1.8 www 2492: } else {
1.16 www 2493: if ($remoteurl!~/\.meta$/) {
2494: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2495: my $mresponse=$ua->request($mrequest,$filename.'.meta');
2496: if ($mresponse->is_error()) {
2497: unlink($filename.'.meta');
2498: &logthis(
1.672 albertel 2499: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 2500: }
2501: }
1.8 www 2502: rename($transname,$filename);
1.607 raeburn 2503: return 'ok';
1.8 www 2504: }
1.290 www 2505: }
1.8 www 2506: }
1.330 www 2507: }
2508:
2509: # ------------------------------------------------ Get server side include body
2510: sub ssi_body {
1.381 albertel 2511: my ($filelink,%form)=@_;
1.606 matthew 2512: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
2513: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
2514: }
1.953 www 2515: my $output='';
2516: my $response;
1.980 raeburn 2517: if ($filelink=~/^https?\:/) {
1.954 raeburn 2518: ($output,$response)=&externalssi($filelink);
1.953 www 2519: } else {
1.1004 droeschl 2520: $filelink .= $filelink=~/\?/ ? '&' : '?';
2521: $filelink .= 'inhibitmenu=yes';
1.953 www 2522: ($output,$response)=&ssi($filelink,%form);
2523: }
1.778 albertel 2524: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 2525: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 2526: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 2527: if (wantarray) {
2528: return ($output, $response);
2529: } else {
2530: return $output;
2531: }
1.8 www 2532: }
2533:
1.15 www 2534: # --------------------------------------------------------- Server Side Include
2535:
1.782 albertel 2536: sub absolute_url {
2537: my ($host_name) = @_;
2538: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
2539: if ($host_name eq '') {
2540: $host_name = $ENV{'SERVER_NAME'};
2541: }
2542: return $protocol.$host_name;
2543: }
2544:
1.942 foxr 2545: #
2546: # Server side include.
2547: # Parameters:
2548: # fn Possibly encrypted resource name/id.
2549: # form Hash that describes how the rendering should be done
2550: # and other things.
1.944 foxr 2551: # Returns:
1.950 raeburn 2552: # Scalar context: The content of the response.
2553: # Array context: 2 element list of the content and the full response object.
1.942 foxr 2554: #
1.15 www 2555: sub ssi {
2556:
1.944 foxr 2557: my ($fn,%form)=@_;
1.15 www 2558: my $ua=new LWP::UserAgent;
1.23 www 2559: my $request;
1.711 albertel 2560:
2561: $form{'no_update_last_known'}=1;
1.895 albertel 2562: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 2563: if (%form) {
1.782 albertel 2564: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000 raeburn 2565: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23 www 2566: } else {
1.782 albertel 2567: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 2568: }
2569:
1.15 www 2570: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
2571: my $response=$ua->request($request);
2572:
1.944 foxr 2573: if (wantarray) {
2574: return ($response->content, $response);
2575: } else {
2576: return $response->content;
1.942 foxr 2577: }
1.324 www 2578: }
2579:
2580: sub externalssi {
2581: my ($url)=@_;
2582: my $ua=new LWP::UserAgent;
2583: my $request=new HTTP::Request('GET',$url);
2584: my $response=$ua->request($request);
1.954 raeburn 2585: if (wantarray) {
2586: return ($response->content, $response);
2587: } else {
2588: return $response->content;
2589: }
1.15 www 2590: }
1.254 www 2591:
1.492 albertel 2592: # -------------------------------- Allow a /uploaded/ URI to be vouched for
2593:
2594: sub allowuploaded {
2595: my ($srcurl,$url)=@_;
2596: $url=&clutter(&declutter($url));
2597: my $dir=$url;
2598: $dir=~s/\/[^\/]+$//;
2599: my %httpref=();
2600: my $httpurl=&hreflocation('',$url);
2601: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 2602: &Apache::lonnet::appenv(\%httpref);
1.254 www 2603: }
1.477 raeburn 2604:
1.478 albertel 2605: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 2606: # input: action, courseID, current domain, intended
1.637 raeburn 2607: # path to file, source of file, instruction to parse file for objects,
2608: # ref to hash for embedded objects,
2609: # ref to hash for codebase of java objects.
1.1095 raeburn 2610: # reference to scalar to accommodate mime type determined
2611: # from File::MMagic if $parser = parse.
1.637 raeburn 2612: #
1.485 raeburn 2613: # output: url to file (if action was uploaddoc),
2614: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 2615: #
1.478 albertel 2616: # Allows directory structure to be used within lonUsers/../userfiles/ for a
2617: # course.
1.477 raeburn 2618: #
1.478 albertel 2619: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2620: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
2621: # course's home server.
1.477 raeburn 2622: #
1.478 albertel 2623: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
2624: # be copied from $source (current location) to
2625: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2626: # and will then be copied to
2627: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
2628: # course's home server.
1.485 raeburn 2629: #
1.481 raeburn 2630: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 2631: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 2632: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2633: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
2634: # in course's home server.
1.637 raeburn 2635: #
1.477 raeburn 2636:
2637: sub process_coursefile {
1.1095 raeburn 2638: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
2639: $mimetype)=@_;
1.477 raeburn 2640: my $fetchresult;
1.638 albertel 2641: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 2642: if ($action eq 'propagate') {
1.638 albertel 2643: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2644: $home);
1.481 raeburn 2645: } else {
1.477 raeburn 2646: my $fpath = '';
2647: my $fname = $file;
1.478 albertel 2648: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 2649: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 2650: my $filepath = &build_filepath($fpath);
1.481 raeburn 2651: if ($action eq 'copy') {
2652: if ($source eq '') {
2653: $fetchresult = 'no source file';
2654: return $fetchresult;
2655: } else {
2656: my $destination = $filepath.'/'.$fname;
2657: rename($source,$destination);
2658: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2659: $home);
1.481 raeburn 2660: }
2661: } elsif ($action eq 'uploaddoc') {
2662: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 2663: print $fh $env{'form.'.$source};
1.481 raeburn 2664: close($fh);
1.637 raeburn 2665: if ($parser eq 'parse') {
1.1024 raeburn 2666: my $mm = new File::MMagic;
1.1095 raeburn 2667: my $type = $mm->checktype_filename($filepath.'/'.$fname);
2668: if ($type eq 'text/html') {
1.1024 raeburn 2669: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
2670: unless ($parse_result eq 'ok') {
2671: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
2672: }
1.637 raeburn 2673: }
1.1095 raeburn 2674: if (ref($mimetype)) {
2675: $$mimetype = $type;
2676: }
1.637 raeburn 2677: }
1.477 raeburn 2678: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2679: $home);
1.481 raeburn 2680: if ($fetchresult eq 'ok') {
2681: return '/uploaded/'.$fpath.'/'.$fname;
2682: } else {
2683: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 2684: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 2685: return '/adm/notfound.html';
2686: }
1.477 raeburn 2687: }
2688: }
1.485 raeburn 2689: unless ( $fetchresult eq 'ok') {
1.477 raeburn 2690: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 2691: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 2692: }
2693: return $fetchresult;
2694: }
2695:
1.637 raeburn 2696: sub build_filepath {
2697: my ($fpath) = @_;
2698: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
2699: unless ($fpath eq '') {
2700: my @parts=split('/',$fpath);
2701: foreach my $part (@parts) {
2702: $filepath.= '/'.$part;
2703: if ((-e $filepath)!=1) {
2704: mkdir($filepath,0777);
2705: }
2706: }
2707: }
2708: return $filepath;
2709: }
2710:
2711: sub store_edited_file {
1.638 albertel 2712: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 2713: my $file = $primary_url;
2714: $file =~ s#^/uploaded/$docudom/$docuname/##;
2715: my $fpath = '';
2716: my $fname = $file;
2717: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
2718: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
2719: my $filepath = &build_filepath($fpath);
2720: open(my $fh,'>'.$filepath.'/'.$fname);
2721: print $fh $content;
2722: close($fh);
1.638 albertel 2723: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 2724: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2725: $home);
1.637 raeburn 2726: if ($$fetchresult eq 'ok') {
2727: return '/uploaded/'.$fpath.'/'.$fname;
2728: } else {
1.638 albertel 2729: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
2730: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 2731: return '/adm/notfound.html';
2732: }
2733: }
2734:
1.531 albertel 2735: sub clean_filename {
1.831 albertel 2736: my ($fname,$args)=@_;
1.315 www 2737: # Replace Windows backslashes by forward slashes
1.257 www 2738: $fname=~s/\\/\//g;
1.831 albertel 2739: if (!$args->{'keep_path'}) {
2740: # Get rid of everything but the actual filename
2741: $fname=~s/^.*\/([^\/]+)$/$1/;
2742: }
1.315 www 2743: # Replace spaces by underscores
2744: $fname=~s/\s+/\_/g;
2745: # Replace all other weird characters by nothing
1.831 albertel 2746: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 2747: # Replace all .\d. sequences with _\d. so they no longer look like version
2748: # numbers
2749: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 2750: return $fname;
2751: }
1.1051 raeburn 2752: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
2753: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
2754: # image with the same aspect ratio as the original, but with dimensions which do
2755: # not exceed $resizewidth and $resizeheight.
2756:
1.984 neumanie 2757: sub resizeImage {
1.1051 raeburn 2758: my ($img_path,$resizewidth,$resizeheight) = @_;
2759: my $ima = Image::Magick->new;
2760: my $resized;
2761: if (-e $img_path) {
2762: $ima->Read($img_path);
2763: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
2764: my $width = $ima->Get('width');
2765: my $height = $ima->Get('height');
2766: if ($width > $resizewidth) {
2767: my $factor = $width/$resizewidth;
2768: my $newheight = $height/$factor;
2769: $ima->Scale(width=>$resizewidth,height=>$newheight);
2770: $resized = 1;
2771: }
2772: }
2773: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
2774: my $width = $ima->Get('width');
2775: my $height = $ima->Get('height');
2776: if ($height > $resizeheight) {
2777: my $factor = $height/$resizeheight;
2778: my $newwidth = $width/$factor;
2779: $ima->Scale(width=>$newwidth,height=>$resizeheight);
2780: $resized = 1;
2781: }
2782: }
2783: if ($resized) {
2784: $ima->Write($img_path);
2785: }
2786: }
2787: return;
1.977 amueller 2788: }
2789:
1.608 albertel 2790: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 2791: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093 raeburn 2792: # the desired filename is in $env{"form.$formname.filename"}
1.1090 raeburn 2793: # $context - possible values: coursedoc, existingfile, overwrite,
2794: # canceloverwrite, or ''.
2795: # if 'coursedoc': upload to the current course
2796: # if 'existingfile': write file to tmp/overwrites directory
2797: # if 'canceloverwrite': delete file written to tmp/overwrites directory
2798: # $context is passed as argument to &finishuserfileupload
1.686 albertel 2799: # $subdir - directory in userfile to store the file into
1.858 raeburn 2800: # $parser - instruction to parse file for objects ($parser = parse)
2801: # $allfiles - reference to hash for embedded objects
2802: # $codebase - reference to hash for codebase of java objects
2803: # $desuname - username for permanent storage of uploaded file
2804: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 2805: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
2806: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 2807: # $resizewidth - width (pixels) to which to resize uploaded image
2808: # $resizeheight - height (pixels) to which to resize uploaded image
1.1095 raeburn 2809: # $mimetype - reference to scalar to accommodate mime type determined
1.1152 raeburn 2810: # from File::MMagic.
1.858 raeburn 2811: #
1.686 albertel 2812: # output: url of file in userspace, or error: <message>
2813: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 2814:
1.531 albertel 2815: sub userfileupload {
1.1090 raeburn 2816: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095 raeburn 2817: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531 albertel 2818: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 2819: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 2820: $fname=&clean_filename($fname);
1.1090 raeburn 2821: # See if there is anything left
1.257 www 2822: unless ($fname) { return 'error: no uploaded file'; }
1.1090 raeburn 2823: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
2824: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
2825: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
2826: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523 raeburn 2827: my $now = time;
1.1090 raeburn 2828: my $filepath;
1.1095 raeburn 2829: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090 raeburn 2830: $filepath = 'tmp/helprequests/'.$now;
2831: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
2832: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
2833: '_'.$env{'user.domain'}.'/pending';
2834: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
2835: my ($docuname,$docudom);
2836: if ($destudom) {
2837: $docudom = $destudom;
2838: } else {
2839: $docudom = $env{'user.domain'};
2840: }
2841: if ($destuname) {
2842: $docuname = $destuname;
2843: } else {
2844: $docuname = $env{'user.name'};
2845: }
2846: if (exists($env{'form.group'})) {
2847: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2848: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2849: }
2850: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
2851: if ($context eq 'canceloverwrite') {
2852: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
2853: if (-e $tempfile) {
2854: my @info = stat($tempfile);
2855: if ($info[9] eq $env{'form.timestamp'}) {
2856: unlink($tempfile);
2857: }
2858: }
2859: return;
1.523 raeburn 2860: }
2861: }
1.1090 raeburn 2862: # Create the directory if not present
1.741 raeburn 2863: my @parts=split(/\//,$filepath);
2864: my $fullpath = $perlvar{'lonDaemons'};
2865: for (my $i=0;$i<@parts;$i++) {
2866: $fullpath .= '/'.$parts[$i];
2867: if ((-e $fullpath)!=1) {
2868: mkdir($fullpath,0777);
2869: }
2870: }
2871: open(my $fh,'>'.$fullpath.'/'.$fname);
2872: print $fh $env{'form.'.$formname};
2873: close($fh);
1.1090 raeburn 2874: if ($context eq 'existingfile') {
2875: my @info = stat($fullpath.'/'.$fname);
2876: return ($fullpath.'/'.$fname,$info[9]);
2877: } else {
2878: return $fullpath.'/'.$fname;
2879: }
1.523 raeburn 2880: }
1.995 raeburn 2881: if ($subdir eq 'scantron') {
2882: $fname = 'scantron_orig_'.$fname;
1.1093 raeburn 2883: } else {
1.995 raeburn 2884: $fname="$subdir/$fname";
2885: }
1.1090 raeburn 2886: if ($context eq 'coursedoc') {
1.638 albertel 2887: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2888: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 2889: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 2890: return &finishuserfileupload($docuname,$docudom,
2891: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 2892: $codebase,$thumbwidth,$thumbheight,
1.1095 raeburn 2893: $resizewidth,$resizeheight,$context,$mimetype);
1.481 raeburn 2894: } else {
1.620 albertel 2895: $fname=$env{'form.folder'}.'/'.$fname;
1.638 albertel 2896: return &process_coursefile('uploaddoc',$docuname,$docudom,
2897: $fname,$formname,$parser,
1.1095 raeburn 2898: $allfiles,$codebase,$mimetype);
1.481 raeburn 2899: }
1.719 banghart 2900: } elsif (defined($destuname)) {
2901: my $docuname=$destuname;
2902: my $docudom=$destudom;
1.860 raeburn 2903: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2904: $parser,$allfiles,$codebase,
1.1051 raeburn 2905: $thumbwidth,$thumbheight,
1.1095 raeburn 2906: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 2907: } else {
1.638 albertel 2908: my $docuname=$env{'user.name'};
2909: my $docudom=$env{'user.domain'};
1.714 raeburn 2910: if (exists($env{'form.group'})) {
2911: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2912: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2913: }
1.860 raeburn 2914: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2915: $parser,$allfiles,$codebase,
1.1051 raeburn 2916: $thumbwidth,$thumbheight,
1.1095 raeburn 2917: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 2918: }
1.271 www 2919: }
2920:
2921: sub finishuserfileupload {
1.860 raeburn 2922: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095 raeburn 2923: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477 raeburn 2924: my $path=$docudom.'/'.$docuname.'/';
1.258 www 2925: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 2926:
1.860 raeburn 2927: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 2928: $file=$fname;
2929: if ($fname=~m|/|) {
2930: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
2931: $path.=$fnamepath.'/';
2932: }
1.259 www 2933: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 2934: my $count;
2935: for ($count=4;$count<=$#parts;$count++) {
2936: $filepath.="/$parts[$count]";
2937: if ((-e $filepath)!=1) {
2938: mkdir($filepath,0777);
2939: }
2940: }
1.984 neumanie 2941:
1.258 www 2942: # Save the file
2943: {
1.701 albertel 2944: if (!open(FH,'>'.$filepath.'/'.$file)) {
2945: &logthis('Failed to create '.$filepath.'/'.$file);
2946: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
2947: return '/adm/notfound.html';
2948: }
1.1090 raeburn 2949: if ($context eq 'overwrite') {
1.1117 foxr 2950: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090 raeburn 2951: my $target = $filepath.'/'.$file;
2952: if (-e $source) {
2953: my @info = stat($source);
2954: if ($info[9] eq $env{'form.timestamp'}) {
2955: unless (&File::Copy::move($source,$target)) {
2956: &logthis('Failed to overwrite '.$filepath.'/'.$file);
2957: return "Moving from $source failed";
2958: }
2959: } else {
2960: return "Temporary file: $source had unexpected date/time for last modification";
2961: }
2962: } else {
2963: return "Temporary file: $source missing";
2964: }
2965: } elsif (!print FH ($env{'form.'.$formname})) {
1.701 albertel 2966: &logthis('Failed to write to '.$filepath.'/'.$file);
2967: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
2968: return '/adm/notfound.html';
2969: }
1.570 albertel 2970: close(FH);
1.1051 raeburn 2971: if ($resizewidth && $resizeheight) {
2972: my $mm = new File::MMagic;
2973: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
2974: if ($mime_type =~ m{^image/}) {
2975: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
2976: }
1.977 amueller 2977: }
1.258 www 2978: }
1.1152 raeburn 2979: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
2980: if (ref($mimetype)) {
2981: if ($$mimetype eq '') {
2982: my $mm = new File::MMagic;
2983: my $type = $mm->checktype_filename($filepath.'/'.$file);
2984: $$mimetype = $type;
2985: }
2986: }
2987: }
1.637 raeburn 2988: if ($parser eq 'parse') {
1.1152 raeburn 2989: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024 raeburn 2990: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
2991: $allfiles,$codebase);
2992: unless ($parse_result eq 'ok') {
2993: &logthis('Failed to parse '.$filepath.$file.
2994: ' for embedded media: '.$parse_result);
2995: }
1.637 raeburn 2996: }
2997: }
1.860 raeburn 2998: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
2999: my $input = $filepath.'/'.$file;
3000: my $output = $filepath.'/'.'tn-'.$file;
3001: my $thumbsize = $thumbwidth.'x'.$thumbheight;
3002: system("convert -sample $thumbsize $input $output");
3003: if (-e $filepath.'/'.'tn-'.$file) {
3004: $fetchthumb = 1;
3005: }
3006: }
1.858 raeburn 3007:
1.259 www 3008: # Notify homeserver to grep it
3009: #
1.984 neumanie 3010: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 3011: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 3012: if ($fetchresult eq 'ok') {
1.860 raeburn 3013: if ($fetchthumb) {
3014: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
3015: if ($thumbresult ne 'ok') {
3016: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
3017: $docuhome.': '.$thumbresult);
3018: }
3019: }
1.259 www 3020: #
1.258 www 3021: # Return the URL to it
1.494 albertel 3022: return '/uploaded/'.$path.$file;
1.263 www 3023: } else {
1.494 albertel 3024: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
3025: ': '.$fetchresult);
1.263 www 3026: return '/adm/notfound.html';
1.858 raeburn 3027: }
1.493 albertel 3028: }
3029:
1.637 raeburn 3030: sub extract_embedded_items {
1.961 raeburn 3031: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 3032: my @state = ();
1.1164 raeburn 3033: my (%lastids,%related,%shockwave,%flashvars);
1.637 raeburn 3034: my %javafiles = (
3035: codebase => '',
3036: code => '',
3037: archive => ''
3038: );
3039: my %mediafiles = (
3040: src => '',
3041: movie => '',
3042: );
1.648 raeburn 3043: my $p;
3044: if ($content) {
3045: $p = HTML::LCParser->new($content);
3046: } else {
1.961 raeburn 3047: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 3048: }
1.641 albertel 3049: while (my $t=$p->get_token()) {
1.640 albertel 3050: if ($t->[0] eq 'S') {
3051: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 3052: push(@state, $tagname);
1.648 raeburn 3053: if (lc($tagname) eq 'allow') {
3054: &add_filetype($allfiles,$attr->{'src'},'src');
3055: }
1.640 albertel 3056: if (lc($tagname) eq 'img') {
3057: &add_filetype($allfiles,$attr->{'src'},'src');
3058: }
1.886 albertel 3059: if (lc($tagname) eq 'a') {
3060: &add_filetype($allfiles,$attr->{'href'},'href');
3061: }
1.645 raeburn 3062: if (lc($tagname) eq 'script') {
1.1164 raeburn 3063: my $src;
1.645 raeburn 3064: if ($attr->{'archive'} =~ /\.jar$/i) {
3065: &add_filetype($allfiles,$attr->{'archive'},'archive');
3066: } else {
1.1164 raeburn 3067: if ($attr->{'src'} ne '') {
3068: $src = $attr->{'src'};
3069: &add_filetype($allfiles,$src,'src');
3070: }
3071: }
3072: my $text = $p->get_trimmed_text();
3073: if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
3074: my @swfargs = split(/,/,$1);
3075: foreach my $item (@swfargs) {
3076: $item =~ s/["']//g;
3077: $item =~ s/^\s+//;
3078: $item =~ s/\s+$//;
3079: }
3080: if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
3081: if (ref($related{$swfargs[0]}) eq 'ARRAY') {
3082: push(@{$related{$swfargs[0]}},$swfargs[2]);
3083: } else {
3084: $related{$swfargs[0]} = [$swfargs[2]];
3085: }
3086: }
1.645 raeburn 3087: }
3088: }
3089: if (lc($tagname) eq 'link') {
3090: if (lc($attr->{'rel'}) eq 'stylesheet') {
3091: &add_filetype($allfiles,$attr->{'href'},'href');
3092: }
3093: }
1.640 albertel 3094: if (lc($tagname) eq 'object' ||
3095: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
3096: foreach my $item (keys(%javafiles)) {
3097: $javafiles{$item} = '';
3098: }
1.1164 raeburn 3099: if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
3100: $lastids{lc($tagname)} = $attr->{'id'};
3101: }
1.640 albertel 3102: }
3103: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
3104: my $name = lc($attr->{'name'});
3105: foreach my $item (keys(%javafiles)) {
3106: if ($name eq $item) {
3107: $javafiles{$item} = $attr->{'value'};
3108: last;
3109: }
3110: }
1.1164 raeburn 3111: my $pathfrom;
1.640 albertel 3112: foreach my $item (keys(%mediafiles)) {
3113: if ($name eq $item) {
1.1164 raeburn 3114: $pathfrom = $attr->{'value'};
3115: $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
3116: &add_filetype($allfiles,$pathfrom,$name);
1.640 albertel 3117: last;
3118: }
3119: }
1.1164 raeburn 3120: if ($name eq 'flashvars') {
3121: $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
3122: }
3123: if ($pathfrom ne '') {
3124: &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
3125: $pathfrom);
3126: }
1.640 albertel 3127: }
3128: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
3129: foreach my $item (keys(%javafiles)) {
3130: if ($attr->{$item}) {
3131: $javafiles{$item} = $attr->{$item};
3132: last;
3133: }
3134: }
3135: foreach my $item (keys(%mediafiles)) {
3136: if ($attr->{$item}) {
3137: &add_filetype($allfiles,$attr->{$item},$item);
3138: last;
3139: }
3140: }
1.1164 raeburn 3141: if (lc($tagname) eq 'embed') {
3142: if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
3143: &embedded_dependency($allfiles,\%related,$attr->{'name'},
3144: $attr->{'src'});
3145: }
3146: }
1.640 albertel 3147: }
1.1164 raeburn 3148: if ($t->[4] =~ m{/>$}) {
3149: pop(@state);
3150: }
1.640 albertel 3151: } elsif ($t->[0] eq 'E') {
3152: my ($tagname) = ($t->[1]);
3153: if ($javafiles{'codebase'} ne '') {
3154: $javafiles{'codebase'} .= '/';
3155: }
3156: if (lc($tagname) eq 'applet' ||
3157: lc($tagname) eq 'object' ||
3158: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
3159: ) {
3160: foreach my $item (keys(%javafiles)) {
3161: if ($item ne 'codebase' && $javafiles{$item} ne '') {
3162: my $file=$javafiles{'codebase'}.$javafiles{$item};
3163: &add_filetype($allfiles,$file,$item);
3164: }
3165: }
3166: }
3167: pop @state;
3168: }
3169: }
1.1164 raeburn 3170: foreach my $id (sort(keys(%flashvars))) {
3171: if ($shockwave{$id} ne '') {
3172: my @pairs = split(/\&/,$flashvars{$id});
3173: foreach my $pair (@pairs) {
3174: my ($key,$value) = split(/\=/,$pair);
3175: if ($key eq 'thumb') {
3176: &add_filetype($allfiles,$value,$key);
3177: } elsif ($key eq 'content') {
3178: my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
3179: my ($ext) = ($value =~ /\.([^.]+)$/);
3180: if ($ext ne '') {
3181: &add_filetype($allfiles,$path.$value,$ext);
3182: }
3183: }
3184: }
3185: }
3186: }
1.637 raeburn 3187: return 'ok';
3188: }
3189:
1.639 albertel 3190: sub add_filetype {
3191: my ($allfiles,$file,$type)=@_;
3192: if (exists($allfiles->{$file})) {
3193: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
3194: push(@{$allfiles->{$file}}, &escape($type));
3195: }
3196: } else {
3197: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 3198: }
3199: }
3200:
1.1164 raeburn 3201: sub embedded_dependency {
3202: my ($allfiles,$related,$identifier,$pathfrom) = @_;
3203: if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
3204: if (($identifier ne '') &&
3205: (ref($related->{$identifier}) eq 'ARRAY') &&
3206: ($pathfrom ne '')) {
3207: my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
3208: foreach my $dep (@{$related->{$identifier}}) {
3209: &add_filetype($allfiles,$path.$dep,'object');
3210: }
3211: }
3212: }
3213: return;
3214: }
3215:
1.493 albertel 3216: sub removeuploadedurl {
1.984 neumanie 3217: my ($url)=@_;
3218: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 3219: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 3220: }
3221:
3222: sub removeuserfile {
3223: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 3224: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3225: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 3226: if ($result eq 'ok') {
1.798 raeburn 3227: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
3228: my $metafile = $fname.'.meta';
3229: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 3230: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 3231: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3232: my $sqlresult =
1.823 albertel 3233: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3234: 'portfolio_metadata',$group,
3235: 'delete');
1.798 raeburn 3236: }
3237: }
3238: return $result;
1.257 www 3239: }
1.15 www 3240:
1.530 albertel 3241: sub mkdiruserfile {
3242: my ($docuname,$docudom,$dir)=@_;
3243: my $home=&homeserver($docuname,$docudom);
3244: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
3245: }
3246:
1.531 albertel 3247: sub renameuserfile {
3248: my ($docuname,$docudom,$old,$new)=@_;
3249: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3250: my $result = &reply("renameuserfile:$docudom:$docuname:".
3251: &escape("$old").':'.&escape("$new"),$home);
3252: if ($result eq 'ok') {
3253: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
3254: my $oldmeta = $old.'.meta';
3255: my $newmeta = $new.'.meta';
3256: my $metaresult =
3257: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 3258: my $url = "/uploaded/$docudom/$docuname/$old";
3259: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3260: my $sqlresult =
1.823 albertel 3261: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3262: 'portfolio_metadata',$group,
3263: 'delete');
1.798 raeburn 3264: }
3265: }
3266: return $result;
1.531 albertel 3267: }
3268:
1.14 www 3269: # ------------------------------------------------------------------------- Log
3270:
3271: sub log {
3272: my ($dom,$nam,$hom,$what)=@_;
1.47 www 3273: return critical("log:$dom:$nam:$what",$hom);
1.157 www 3274: }
3275:
3276: # ------------------------------------------------------------------ Course Log
1.352 www 3277: #
3278: # This routine flushes several buffers of non-mission-critical nature
3279: #
1.157 www 3280:
3281: sub flushcourselogs {
1.352 www 3282: &logthis('Flushing log buffers');
3283: #
3284: # course logs
3285: # This is a log of all transactions in a course, which can be used
3286: # for data mining purposes
3287: #
3288: # It also collects the courseid database, which lists last transaction
3289: # times and course titles for all courseids
3290: #
3291: my %courseidbuffer=();
1.921 raeburn 3292: foreach my $crsid (keys(%courselogs)) {
1.352 www 3293: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 3294: &escape($courselogs{$crsid}),
3295: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 3296: delete $courselogs{$crsid};
3297: } else {
3298: &logthis('Failed to flush log buffer for '.$crsid);
3299: if (length($courselogs{$crsid})>40000) {
1.672 albertel 3300: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 3301: " exceeded maximum size, deleting.</font>");
3302: delete $courselogs{$crsid};
3303: }
1.352 www 3304: }
1.920 raeburn 3305: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 3306: 'description' => $coursedescrbuf{$crsid},
3307: 'inst_code' => $courseinstcodebuf{$crsid},
3308: 'type' => $coursetypebuf{$crsid},
3309: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 3310: };
1.191 harris41 3311: }
1.352 www 3312: #
3313: # Write course id database (reverse lookup) to homeserver of courses
3314: # Is used in pickcourse
3315: #
1.840 albertel 3316: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 3317: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 3318: $courseidbuffer{$crs_home},
3319: $crs_home,'timeonly');
1.352 www 3320: }
3321: #
3322: # File accesses
3323: # Writes to the dynamic metadata of resources to get hit counts, etc.
3324: #
1.449 matthew 3325: foreach my $entry (keys(%accesshash)) {
1.458 matthew 3326: if ($entry =~ /___count$/) {
3327: my ($dom,$name);
1.807 albertel 3328: ($dom,$name,undef)=
1.811 albertel 3329: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 3330: if (! defined($dom) || $dom eq '' ||
3331: ! defined($name) || $name eq '') {
1.620 albertel 3332: my $cid = $env{'request.course.id'};
3333: $dom = $env{'request.'.$cid.'.domain'};
3334: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 3335: }
1.450 matthew 3336: my $value = $accesshash{$entry};
3337: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
3338: my %temphash=($url => $value);
1.449 matthew 3339: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
3340: if ($result eq 'ok') {
3341: delete $accesshash{$entry};
3342: }
3343: } else {
1.811 albertel 3344: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159 www 3345: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450 matthew 3346: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 3347: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
3348: delete $accesshash{$entry};
3349: }
1.185 www 3350: }
1.191 harris41 3351: }
1.352 www 3352: #
3353: # Roles
3354: # Reverse lookup of user roles for course faculty/staff and co-authorship
3355: #
1.800 albertel 3356: foreach my $entry (keys(%userrolehash)) {
1.351 www 3357: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 3358: split(/\:/,$entry);
3359: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 3360: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 3361: $rudom,$runame) eq 'ok') {
3362: delete $userrolehash{$entry};
3363: }
3364: }
1.662 raeburn 3365: #
3366: # Reverse lookup of domain roles (dc, ad, li, sc, au)
3367: #
3368: my %domrolebuffer = ();
1.1000 raeburn 3369: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 3370: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 3371: if ($domrolebuffer{$rudom}) {
3372: $domrolebuffer{$rudom}.='&'.&escape($entry).
3373: '='.&escape($domainrolehash{$entry});
3374: } else {
3375: $domrolebuffer{$rudom}.=&escape($entry).
3376: '='.&escape($domainrolehash{$entry});
3377: }
3378: delete $domainrolehash{$entry};
3379: }
3380: foreach my $dom (keys(%domrolebuffer)) {
1.841 albertel 3381: my %servers = &get_servers($dom,'library');
3382: foreach my $tryserver (keys(%servers)) {
3383: unless (&reply('domroleput:'.$dom.':'.
3384: $domrolebuffer{$dom},$tryserver) eq 'ok') {
3385: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
3386: }
1.662 raeburn 3387: }
3388: }
1.186 www 3389: $dumpcount++;
1.157 www 3390: }
3391:
3392: sub courselog {
3393: my $what=shift;
1.158 www 3394: $what=time.':'.$what;
1.620 albertel 3395: unless ($env{'request.course.id'}) { return ''; }
3396: $coursedombuf{$env{'request.course.id'}}=
3397: $env{'course.'.$env{'request.course.id'}.'.domain'};
3398: $coursenumbuf{$env{'request.course.id'}}=
3399: $env{'course.'.$env{'request.course.id'}.'.num'};
3400: $coursehombuf{$env{'request.course.id'}}=
3401: $env{'course.'.$env{'request.course.id'}.'.home'};
3402: $coursedescrbuf{$env{'request.course.id'}}=
3403: $env{'course.'.$env{'request.course.id'}.'.description'};
3404: $courseinstcodebuf{$env{'request.course.id'}}=
3405: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
3406: $courseownerbuf{$env{'request.course.id'}}=
3407: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 3408: $coursetypebuf{$env{'request.course.id'}}=
3409: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 3410: if (defined $courselogs{$env{'request.course.id'}}) {
3411: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 3412: } else {
1.620 albertel 3413: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 3414: }
1.620 albertel 3415: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 3416: &flushcourselogs();
3417: }
1.158 www 3418: }
3419:
3420: sub courseacclog {
3421: my $fnsymb=shift;
1.620 albertel 3422: unless ($env{'request.course.id'}) { return ''; }
3423: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144 www 3424: if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187 www 3425: $what.=':POST';
1.583 matthew 3426: # FIXME: Probably ought to escape things....
1.800 albertel 3427: foreach my $key (keys(%env)) {
3428: if ($key=~/^form\.(.*)/) {
1.975 raeburn 3429: my $formitem = $1;
3430: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
3431: $what.=':'.$formitem.'='.$env{$key};
3432: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
3433: $what.=':'.$formitem.'='.$env{$key};
3434: }
1.158 www 3435: }
1.191 harris41 3436: }
1.583 matthew 3437: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
3438: # FIXME: We should not be depending on a form parameter that someone
3439: # editing lonsearchcat.pm might change in the future.
1.620 albertel 3440: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 3441: $what.= ':POST';
3442: # FIXME: Probably ought to escape things....
3443: foreach my $element ('courseexp','crsfulltext','crsrelated',
3444: 'crsdiscuss') {
1.620 albertel 3445: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 3446: }
3447: }
1.158 www 3448: }
3449: &courselog($what);
1.149 www 3450: }
3451:
1.185 www 3452: sub countacc {
3453: my $url=&declutter(shift);
1.458 matthew 3454: return if (! defined($url) || $url eq '');
1.620 albertel 3455: unless ($env{'request.course.id'}) { return ''; }
1.1158 www 3456: #
3457: # Mark that this url was used in this course
3458: #
1.620 albertel 3459: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158 www 3460: #
3461: # Increase the access count for this resource in this child process
3462: #
1.281 www 3463: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 3464: $accesshash{$key}++;
1.185 www 3465: }
1.349 www 3466:
1.361 www 3467: sub linklog {
3468: my ($from,$to)=@_;
3469: $from=&declutter($from);
3470: $to=&declutter($to);
3471: $accesshash{$from.'___'.$to.'___comefrom'}=1;
3472: $accesshash{$to.'___'.$from.'___goto'}=1;
3473: }
1.1160 www 3474:
3475: sub statslog {
3476: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
3477: if ($users<2) { return; }
3478: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
3479: 'course' => $env{'request.course.id'},
3480: 'sections' => '"all"',
3481: 'num_students' => $users,
3482: 'part' => $part,
3483: 'symb' => $symb,
3484: 'mean_tries' => $av_attempts,
3485: 'deg_of_diff' => $degdiff});
3486: foreach my $key (keys(%dynstore)) {
3487: $accesshash{$key}=$dynstore{$key};
3488: }
3489: }
1.361 www 3490:
1.349 www 3491: sub userrolelog {
3492: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661 raeburn 3493: if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662 raeburn 3494: ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661 raeburn 3495: ($trole=~/^ep/) || ($trole=~/^cr/) ||
1.1041 raeburn 3496: ($trole=~/^ta/) || ($trole=~/^co/)) {
1.350 www 3497: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3498: $userrolehash
3499: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 3500: =$tend.':'.$tstart;
1.662 raeburn 3501: }
1.898 albertel 3502: if (($env{'request.role'} =~ /dc\./) &&
3503: (($trole=~/^au/) || ($trole=~/^in/) ||
3504: ($trole=~/^cc/) || ($trole=~/^ep/) ||
1.1041 raeburn 3505: ($trole=~/^cr/) || ($trole=~/^ta/) ||
3506: ($trole=~/^co/))) {
1.898 albertel 3507: $userrolehash
3508: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
3509: =$tend.':'.$tstart;
3510: }
1.662 raeburn 3511: if (($trole=~/^dc/) || ($trole=~/^ad/) ||
3512: ($trole=~/^li/) || ($trole=~/^li/) ||
3513: ($trole=~/^au/) || ($trole=~/^dg/) ||
3514: ($trole=~/^sc/)) {
3515: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3516: $domainrolehash
3517: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
3518: = $tend.':'.$tstart;
3519: }
1.351 www 3520: }
3521:
1.957 raeburn 3522: sub courserolelog {
3523: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
3524: if (($trole eq 'cc') || ($trole eq 'in') ||
3525: ($trole eq 'ep') || ($trole eq 'ad') ||
3526: ($trole eq 'ta') || ($trole eq 'st') ||
1.1044 raeburn 3527: ($trole=~/^cr/) || ($trole eq 'gr') ||
3528: ($trole eq 'co')) {
1.957 raeburn 3529: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
3530: my $cdom = $1;
3531: my $cnum = $2;
3532: my $sec = $3;
3533: my $namespace = 'rolelog';
3534: my %storehash = (
3535: role => $trole,
3536: start => $tstart,
3537: end => $tend,
3538: selfenroll => $selfenroll,
3539: context => $context,
3540: );
3541: if ($trole eq 'gr') {
3542: $namespace = 'groupslog';
3543: $storehash{'group'} = $sec;
3544: } else {
3545: $storehash{'section'} = $sec;
3546: }
3547: &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
1.996 raeburn 3548: if (($trole ne 'st') || ($sec ne '')) {
3549: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
3550: }
1.957 raeburn 3551: }
3552: }
3553: return;
3554: }
3555:
1.351 www 3556: sub get_course_adv_roles {
1.948 raeburn 3557: my ($cid,$codes) = @_;
1.620 albertel 3558: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 3559: my %coursehash=&coursedescription($cid);
1.988 raeburn 3560: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 3561: my %nothide=();
1.800 albertel 3562: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 3563: if ($user !~ /:/) {
3564: $nothide{join(':',split(/[\@]/,$user))}=1;
3565: } else {
3566: $nothide{$user}=1;
3567: }
1.470 www 3568: }
1.351 www 3569: my %returnhash=();
3570: my %dumphash=
3571: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
3572: my $now=time;
1.997 raeburn 3573: my %privileged;
1.1000 raeburn 3574: foreach my $entry (keys(%dumphash)) {
1.800 albertel 3575: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 3576: if (($tstart) && ($tstart<0)) { next; }
3577: if (($tend) && ($tend<$now)) { next; }
3578: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 3579: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 3580: if ($username eq '' || $domain eq '') { next; }
1.997 raeburn 3581: unless (ref($privileged{$domain}) eq 'HASH') {
3582: my %dompersonnel =
1.998 raeburn 3583: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
1.997 raeburn 3584: $privileged{$domain} = {};
3585: foreach my $server (keys(%dompersonnel)) {
1.999 raeburn 3586: if (ref($dompersonnel{$server}) eq 'HASH') {
1.997 raeburn 3587: foreach my $user (keys(%{$dompersonnel{$server}})) {
3588: my ($trole,$uname,$udom) = split(/:/,$user);
3589: $privileged{$udom}{$uname} = 1;
3590: }
3591: }
3592: }
3593: }
3594: if ((exists($privileged{$domain}{$username})) &&
3595: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 3596: if ($role eq 'cr') { next; }
1.948 raeburn 3597: if ($codes) {
3598: if ($section) { $role .= ':'.$section; }
3599: if ($returnhash{$role}) {
3600: $returnhash{$role}.=','.$username.':'.$domain;
3601: } else {
3602: $returnhash{$role}=$username.':'.$domain;
3603: }
1.351 www 3604: } else {
1.988 raeburn 3605: my $key=&plaintext($role,$crstype);
1.973 bisitz 3606: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 3607: if ($returnhash{$key}) {
3608: $returnhash{$key}.=','.$username.':'.$domain;
3609: } else {
3610: $returnhash{$key}=$username.':'.$domain;
3611: }
1.351 www 3612: }
1.948 raeburn 3613: }
1.400 www 3614: return %returnhash;
3615: }
3616:
3617: sub get_my_roles {
1.937 raeburn 3618: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 3619: unless (defined($uname)) { $uname=$env{'user.name'}; }
3620: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 3621: my (%dumphash,%nothide);
1.1086 raeburn 3622: if ($context eq 'userroles') {
1.1166 raeburn 3623: %dumphash = &dump('roles',$udom,$uname);
1.858 raeburn 3624: } else {
3625: %dumphash=
1.400 www 3626: &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 3627: if ($hidepriv) {
3628: my %coursehash=&coursedescription($udom.'_'.$uname);
3629: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3630: if ($user !~ /:/) {
3631: $nothide{join(':',split(/[\@]/,$user))} = 1;
3632: } else {
3633: $nothide{$user} = 1;
3634: }
3635: }
3636: }
1.858 raeburn 3637: }
1.400 www 3638: my %returnhash=();
3639: my $now=time;
1.999 raeburn 3640: my %privileged;
1.800 albertel 3641: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 3642: my ($role,$tend,$tstart);
3643: if ($context eq 'userroles') {
1.1149 raeburn 3644: next if ($entry =~ /^rolesdef/);
1.867 raeburn 3645: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
3646: } else {
3647: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
3648: }
1.400 www 3649: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 3650: my $status = 'active';
1.939 raeburn 3651: if (($tend) && ($tend<=$now)) {
1.832 raeburn 3652: $status = 'previous';
3653: }
3654: if (($tstart) && ($now<$tstart)) {
3655: $status = 'future';
3656: }
3657: if (ref($types) eq 'ARRAY') {
3658: if (!grep(/^\Q$status\E$/,@{$types})) {
3659: next;
3660: }
3661: } else {
3662: if ($status ne 'active') {
3663: next;
3664: }
3665: }
1.867 raeburn 3666: my ($rolecode,$username,$domain,$section,$area);
3667: if ($context eq 'userroles') {
3668: ($area,$rolecode) = split(/_/,$entry);
3669: (undef,$domain,$username,$section) = split(/\//,$area);
3670: } else {
3671: ($role,$username,$domain,$section) = split(/\:/,$entry);
3672: }
1.832 raeburn 3673: if (ref($roledoms) eq 'ARRAY') {
3674: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
3675: next;
3676: }
3677: }
3678: if (ref($roles) eq 'ARRAY') {
3679: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 3680: if ($role =~ /^cr\//) {
3681: if (!grep(/^cr$/,@{$roles})) {
3682: next;
3683: }
1.1104 raeburn 3684: } elsif ($role =~ /^gr\//) {
3685: if (!grep(/^gr$/,@{$roles})) {
3686: next;
3687: }
1.922 raeburn 3688: } else {
3689: next;
3690: }
1.832 raeburn 3691: }
1.867 raeburn 3692: }
1.937 raeburn 3693: if ($hidepriv) {
1.999 raeburn 3694: if ($context eq 'userroles') {
3695: if ((&privileged($username,$domain)) &&
3696: (!$nothide{$username.':'.$domain})) {
3697: next;
3698: }
3699: } else {
3700: unless (ref($privileged{$domain}) eq 'HASH') {
3701: my %dompersonnel =
3702: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
3703: $privileged{$domain} = {};
3704: if (keys(%dompersonnel)) {
3705: foreach my $server (keys(%dompersonnel)) {
3706: if (ref($dompersonnel{$server}) eq 'HASH') {
3707: foreach my $user (keys(%{$dompersonnel{$server}})) {
3708: my ($trole,$uname,$udom) = split(/:/,$user);
3709: $privileged{$udom}{$uname} = $trole;
3710: }
3711: }
3712: }
3713: }
3714: }
3715: if (exists($privileged{$domain}{$username})) {
3716: if (!$nothide{$username.':'.$domain}) {
3717: next;
3718: }
3719: }
1.937 raeburn 3720: }
3721: }
1.933 raeburn 3722: if ($withsec) {
3723: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
3724: $tstart.':'.$tend;
3725: } else {
3726: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
3727: }
1.832 raeburn 3728: }
1.373 www 3729: return %returnhash;
1.399 www 3730: }
3731:
3732: # ----------------------------------------------------- Frontpage Announcements
3733: #
3734: #
3735:
3736: sub postannounce {
3737: my ($server,$text)=@_;
1.844 albertel 3738: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 3739: unless ($text=~/\w/) { $text=''; }
3740: return &reply('setannounce:'.&escape($text),$server);
3741: }
3742:
3743: sub getannounce {
1.448 albertel 3744:
3745: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 3746: my $announcement='';
1.800 albertel 3747: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 3748: close($fh);
1.399 www 3749: if ($announcement=~/\w/) {
3750: return
3751: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 3752: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 3753: } else {
3754: return '';
3755: }
3756: } else {
3757: return '';
3758: }
1.351 www 3759: }
1.353 www 3760:
3761: # ---------------------------------------------------------- Course ID routines
3762: # Deal with domain's nohist_courseid.db files
3763: #
3764:
3765: sub courseidput {
1.921 raeburn 3766: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 3767: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 3768: my $outcome;
3769: if ($caller eq 'timeonly') {
3770: my $cids = '';
3771: foreach my $item (keys(%$storehash)) {
3772: $cids.=&escape($item).'&';
3773: }
3774: $cids=~s/\&$//;
3775: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
3776: $coursehome);
3777: } else {
3778: my $items = '';
3779: foreach my $item (keys(%$storehash)) {
3780: $items.= &escape($item).'='.
3781: &freeze_escape($$storehash{$item}).'&';
3782: }
3783: $items=~s/\&$//;
3784: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
3785: $coursehome);
1.918 raeburn 3786: }
3787: if ($outcome eq 'unknown_cmd') {
3788: my $what;
3789: foreach my $cid (keys(%$storehash)) {
3790: $what .= &escape($cid).'=';
1.921 raeburn 3791: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 3792: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 3793: }
3794: $what =~ s/\:$/&/;
3795: }
3796: $what =~ s/\&$//;
3797: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
3798: } else {
3799: return $outcome;
3800: }
1.353 www 3801: }
3802:
3803: sub courseiddump {
1.921 raeburn 3804: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 3805: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 3806: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1071 raeburn 3807: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918 raeburn 3808: my $as_hash = 1;
3809: my %returnhash;
3810: if (!$domfilter) { $domfilter=''; }
1.845 albertel 3811: my %libserv = &all_library();
3812: foreach my $tryserver (keys(%libserv)) {
3813: if ( ( $hostidflag == 1
3814: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
3815: || (!defined($hostidflag)) ) {
3816:
1.918 raeburn 3817: if (($domfilter eq '') ||
3818: (&host_domain($tryserver) eq $domfilter)) {
3819: my $rep =
3820: &reply('courseiddump:'.&host_domain($tryserver).':'.
3821: $sincefilter.':'.&escape($descfilter).':'.
3822: &escape($instcodefilter).':'.&escape($ownerfilter).
3823: ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947 raeburn 3824: ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962 raeburn 3825: &escape($selfenrollonly).':'.&escape($catfilter).':'.
1.1008 raeburn 3826: $showhidden.':'.$caller.':'.&escape($cloner).':'.
1.1029 raeburn 3827: &escape($cc_clone).':'.$cloneonly.':'.
3828: &escape($createdbefore).':'.&escape($createdafter).':'.
1.1071 raeburn 3829: &escape($creationcontext).':'.$domcloner,
3830: $tryserver);
1.918 raeburn 3831: my @pairs=split(/\&/,$rep);
3832: foreach my $item (@pairs) {
3833: my ($key,$value)=split(/\=/,$item,2);
3834: $key = &unescape($key);
3835: next if ($key =~ /^error: 2 /);
3836: my $result = &thaw_unescape($value);
3837: if (ref($result) eq 'HASH') {
3838: $returnhash{$key}=$result;
3839: } else {
1.921 raeburn 3840: my @responses = split(/:/,$value);
3841: my @items = ('description','inst_code','owner','type');
1.918 raeburn 3842: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 3843: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 3844: }
1.1008 raeburn 3845: }
1.353 www 3846: }
3847: }
3848: }
3849: }
3850: return %returnhash;
3851: }
3852:
1.1055 raeburn 3853: sub courselastaccess {
3854: my ($cdom,$cnum,$hostidref) = @_;
3855: my %returnhash;
3856: if ($cdom && $cnum) {
3857: my $chome = &homeserver($cnum,$cdom);
3858: if ($chome ne 'no_host') {
3859: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
3860: &extract_lastaccess(\%returnhash,$rep);
3861: }
3862: } else {
3863: if (!$cdom) { $cdom=''; }
3864: my %libserv = &all_library();
3865: foreach my $tryserver (keys(%libserv)) {
3866: if (ref($hostidref) eq 'ARRAY') {
3867: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
3868: }
3869: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
3870: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
3871: &extract_lastaccess(\%returnhash,$rep);
3872: }
3873: }
3874: }
3875: return %returnhash;
3876: }
3877:
3878: sub extract_lastaccess {
3879: my ($returnhash,$rep) = @_;
3880: if (ref($returnhash) eq 'HASH') {
3881: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
3882: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
3883: $rep eq '') {
3884: my @pairs=split(/\&/,$rep);
3885: foreach my $item (@pairs) {
3886: my ($key,$value)=split(/\=/,$item,2);
3887: $key = &unescape($key);
3888: next if ($key =~ /^error: 2 /);
3889: $returnhash->{$key} = &thaw_unescape($value);
3890: }
3891: }
3892: }
3893: return;
3894: }
3895:
1.658 raeburn 3896: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 3897:
3898: sub dcmailput {
1.685 raeburn 3899: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 3900: my $status = &Apache::lonnet::critical(
1.740 www 3901: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
3902: &escape($message),$server);
1.662 raeburn 3903: return $status;
3904: }
3905:
1.658 raeburn 3906: sub dcmaildump {
3907: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 3908: my %returnhash=();
1.846 albertel 3909:
3910: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 3911: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
3912: &escape($enddate).':';
3913: my @esc_senders=map { &escape($_)} @$senders;
3914: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 3915: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 3916: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 3917: if (($key) && ($value)) {
3918: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 3919: }
3920: }
3921: }
3922: return %returnhash;
3923: }
1.662 raeburn 3924: # ---------------------------------------------------------- Domain roles
3925:
3926: sub get_domain_roles {
3927: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 3928: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 3929: $startdate = '.';
3930: }
1.1018 raeburn 3931: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 3932: $enddate = '.';
3933: }
1.922 raeburn 3934: my $rolelist;
3935: if (ref($roles) eq 'ARRAY') {
3936: $rolelist = join(':',@{$roles});
3937: }
1.662 raeburn 3938: my %personnel = ();
1.841 albertel 3939:
3940: my %servers = &get_servers($dom,'library');
3941: foreach my $tryserver (keys(%servers)) {
3942: %{$personnel{$tryserver}}=();
3943: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
3944: &escape($startdate).':'.
3945: &escape($enddate).':'.
3946: &escape($rolelist), $tryserver))) {
3947: my ($key,$value) = split(/\=/,$line,2);
3948: if (($key) && ($value)) {
3949: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
3950: }
3951: }
1.662 raeburn 3952: }
3953: return %personnel;
3954: }
1.658 raeburn 3955:
1.1057 www 3956: # ----------------------------------------------------------- Interval timing
1.149 www 3957:
1.1153 www 3958: {
3959: # Caches needed for speedup of navmaps
3960: # We don't want to cache this for very long at all (5 seconds at most)
3961: #
3962: # The user for whom we cache
3963: my $cachedkey='';
3964: # The cached times for this user
3965: my %cachedtimes=();
3966: # When this was last done
3967: my $cachedtime=();
3968:
3969: sub load_all_first_access {
1.1154 raeburn 3970: my ($uname,$udom)=@_;
1.1156 www 3971: if (($cachedkey eq $uname.':'.$udom) &&
1.1154 raeburn 3972: (abs($cachedtime-time)<5)) {
3973: return;
3974: }
3975: $cachedtime=time;
3976: $cachedkey=$uname.':'.$udom;
3977: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153 www 3978: }
3979:
1.504 albertel 3980: sub get_first_access {
1.1162 raeburn 3981: my ($type,$argsymb,$argmap)=@_;
1.790 albertel 3982: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 3983: if ($argsymb) { $symb=$argsymb; }
3984: my ($map,$id,$res)=&decode_symb($symb);
1.1162 raeburn 3985: if ($argmap) { $map = $argmap; }
1.926 albertel 3986: if ($type eq 'course') {
3987: $res='course';
3988: } elsif ($type eq 'map') {
1.588 albertel 3989: $res=&symbread($map);
3990: } else {
3991: $res=$symb;
3992: }
1.1153 www 3993: &load_all_first_access($uname,$udom);
3994: return $cachedtimes{"$courseid\0$res"};
1.504 albertel 3995: }
3996:
3997: sub set_first_access {
1.1162 raeburn 3998: my ($type,$interval)=@_;
1.790 albertel 3999: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4000: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 4001: if ($type eq 'course') {
4002: $res='course';
4003: } elsif ($type eq 'map') {
1.588 albertel 4004: $res=&symbread($map);
4005: } else {
4006: $res=$symb;
4007: }
1.1153 www 4008: $cachedkey='';
1.1162 raeburn 4009: my $firstaccess=&get_first_access($type,$symb,$map);
1.505 albertel 4010: if (!$firstaccess) {
1.1162 raeburn 4011: my $start = time;
4012: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
4013: $udom,$uname);
4014: if ($putres eq 'ok') {
4015: &put('timerinterval',{"$courseid\0$res"=>$interval},
4016: $udom,$uname);
4017: &appenv(
4018: {
4019: 'course.'.$courseid.'.firstaccess.'.$res => $start,
4020: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
4021: }
4022: );
4023: }
4024: return $putres;
1.505 albertel 4025: }
4026: return 'already_set';
1.504 albertel 4027: }
1.1153 www 4028: }
1.110 www 4029: # --------------------------------------------- Set Expire Date for Spreadsheet
4030:
4031: sub expirespread {
4032: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 4033: my $cid=$env{'request.course.id'};
1.110 www 4034: if ($cid) {
4035: my $now=time;
4036: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 4037: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
4038: $env{'course.'.$cid.'.num'}.
1.110 www 4039: ':nohist_expirationdates:'.
4040: &escape($key).'='.$now,
1.620 albertel 4041: $env{'course.'.$cid.'.home'})
1.110 www 4042: }
4043: return 'ok';
1.14 www 4044: }
4045:
1.109 www 4046: # ----------------------------------------------------- Devalidate Spreadsheets
4047:
4048: sub devalidate {
1.325 www 4049: my ($symb,$uname,$udom)=@_;
1.620 albertel 4050: my $cid=$env{'request.course.id'};
1.109 www 4051: if ($cid) {
1.391 matthew 4052: # delete the stored spreadsheets for
4053: # - the student level sheet of this user in course's homespace
4054: # - the assessment level sheet for this resource
4055: # for this user in user's homespace
1.553 albertel 4056: # - current conditional state info
1.325 www 4057: my $key=$uname.':'.$udom.':';
1.109 www 4058: my $status=
1.299 matthew 4059: &del('nohist_calculatedsheets',
1.391 matthew 4060: [$key.'studentcalc:'],
1.620 albertel 4061: $env{'course.'.$cid.'.domain'},
4062: $env{'course.'.$cid.'.num'})
1.133 albertel 4063: .' '.
4064: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 4065: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 4066: unless ($status eq 'ok ok') {
4067: &logthis('Could not devalidate spreadsheet '.
1.325 www 4068: $uname.' at '.$udom.' for '.
1.109 www 4069: $symb.': '.$status);
1.133 albertel 4070: }
1.553 albertel 4071: &delenv('user.state.'.$cid);
1.109 www 4072: }
4073: }
4074:
1.265 albertel 4075: sub get_scalar {
4076: my ($string,$end) = @_;
4077: my $value;
4078: if ($$string =~ s/^([^&]*?)($end)/$2/) {
4079: $value = $1;
4080: } elsif ($$string =~ s/^([^&]*?)&//) {
4081: $value = $1;
4082: }
4083: return &unescape($value);
4084: }
4085:
4086: sub array2str {
4087: my (@array) = @_;
4088: my $result=&arrayref2str(\@array);
4089: $result=~s/^__ARRAY_REF__//;
4090: $result=~s/__END_ARRAY_REF__$//;
4091: return $result;
4092: }
4093:
1.204 albertel 4094: sub arrayref2str {
4095: my ($arrayref) = @_;
1.265 albertel 4096: my $result='__ARRAY_REF__';
1.204 albertel 4097: foreach my $elem (@$arrayref) {
1.265 albertel 4098: if(ref($elem) eq 'ARRAY') {
4099: $result.=&arrayref2str($elem).'&';
4100: } elsif(ref($elem) eq 'HASH') {
4101: $result.=&hashref2str($elem).'&';
4102: } elsif(ref($elem)) {
4103: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 4104: } else {
4105: $result.=&escape($elem).'&';
4106: }
4107: }
4108: $result=~s/\&$//;
1.265 albertel 4109: $result .= '__END_ARRAY_REF__';
1.204 albertel 4110: return $result;
4111: }
4112:
1.168 albertel 4113: sub hash2str {
1.204 albertel 4114: my (%hash) = @_;
4115: my $result=&hashref2str(\%hash);
1.265 albertel 4116: $result=~s/^__HASH_REF__//;
4117: $result=~s/__END_HASH_REF__$//;
1.204 albertel 4118: return $result;
4119: }
4120:
4121: sub hashref2str {
4122: my ($hashref)=@_;
1.265 albertel 4123: my $result='__HASH_REF__';
1.800 albertel 4124: foreach my $key (sort(keys(%$hashref))) {
4125: if (ref($key) eq 'ARRAY') {
4126: $result.=&arrayref2str($key).'=';
4127: } elsif (ref($key) eq 'HASH') {
4128: $result.=&hashref2str($key).'=';
4129: } elsif (ref($key)) {
1.265 albertel 4130: $result.='=';
1.800 albertel 4131: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 4132: } else {
1.1132 raeburn 4133: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 4134: }
4135:
1.800 albertel 4136: if(ref($hashref->{$key}) eq 'ARRAY') {
4137: $result.=&arrayref2str($hashref->{$key}).'&';
4138: } elsif(ref($hashref->{$key}) eq 'HASH') {
4139: $result.=&hashref2str($hashref->{$key}).'&';
4140: } elsif(ref($hashref->{$key})) {
1.265 albertel 4141: $result.='&';
1.800 albertel 4142: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 4143: } else {
1.800 albertel 4144: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 4145: }
4146: }
1.168 albertel 4147: $result=~s/\&$//;
1.265 albertel 4148: $result .= '__END_HASH_REF__';
1.168 albertel 4149: return $result;
4150: }
4151:
4152: sub str2hash {
1.265 albertel 4153: my ($string)=@_;
4154: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
4155: return %$hash;
4156: }
4157:
4158: sub str2hashref {
1.168 albertel 4159: my ($string) = @_;
1.265 albertel 4160:
4161: my %hash;
4162:
4163: if($string !~ /^__HASH_REF__/) {
4164: if (! ($string eq '' || !defined($string))) {
4165: $hash{'error'}='Not hash reference';
4166: }
4167: return (\%hash, $string);
4168: }
4169:
4170: $string =~ s/^__HASH_REF__//;
4171:
4172: while($string !~ /^__END_HASH_REF__/) {
4173: #key
4174: my $key='';
4175: if($string =~ /^__HASH_REF__/) {
4176: ($key, $string)=&str2hashref($string);
4177: if(defined($key->{'error'})) {
4178: $hash{'error'}='Bad data';
4179: return (\%hash, $string);
4180: }
4181: } elsif($string =~ /^__ARRAY_REF__/) {
4182: ($key, $string)=&str2arrayref($string);
4183: if($key->[0] eq 'Array reference error') {
4184: $hash{'error'}='Bad data';
4185: return (\%hash, $string);
4186: }
4187: } else {
4188: $string =~ s/^(.*?)=//;
1.267 albertel 4189: $key=&unescape($1);
1.265 albertel 4190: }
4191: $string =~ s/^=//;
4192:
4193: #value
4194: my $value='';
4195: if($string =~ /^__HASH_REF__/) {
4196: ($value, $string)=&str2hashref($string);
4197: if(defined($value->{'error'})) {
4198: $hash{'error'}='Bad data';
4199: return (\%hash, $string);
4200: }
4201: } elsif($string =~ /^__ARRAY_REF__/) {
4202: ($value, $string)=&str2arrayref($string);
4203: if($value->[0] eq 'Array reference error') {
4204: $hash{'error'}='Bad data';
4205: return (\%hash, $string);
4206: }
4207: } else {
4208: $value=&get_scalar(\$string,'__END_HASH_REF__');
4209: }
4210: $string =~ s/^&//;
4211:
4212: $hash{$key}=$value;
1.204 albertel 4213: }
1.265 albertel 4214:
4215: $string =~ s/^__END_HASH_REF__//;
4216:
4217: return (\%hash, $string);
1.204 albertel 4218: }
4219:
4220: sub str2array {
1.265 albertel 4221: my ($string)=@_;
4222: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
4223: return @$array;
4224: }
4225:
4226: sub str2arrayref {
1.204 albertel 4227: my ($string) = @_;
1.265 albertel 4228: my @array;
4229:
4230: if($string !~ /^__ARRAY_REF__/) {
4231: if (! ($string eq '' || !defined($string))) {
4232: $array[0]='Array reference error';
4233: }
4234: return (\@array, $string);
4235: }
4236:
4237: $string =~ s/^__ARRAY_REF__//;
4238:
4239: while($string !~ /^__END_ARRAY_REF__/) {
4240: my $value='';
4241: if($string =~ /^__HASH_REF__/) {
4242: ($value, $string)=&str2hashref($string);
4243: if(defined($value->{'error'})) {
4244: $array[0] ='Array reference error';
4245: return (\@array, $string);
4246: }
4247: } elsif($string =~ /^__ARRAY_REF__/) {
4248: ($value, $string)=&str2arrayref($string);
4249: if($value->[0] eq 'Array reference error') {
4250: $array[0] ='Array reference error';
4251: return (\@array, $string);
4252: }
4253: } else {
4254: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
4255: }
4256: $string =~ s/^&//;
4257:
4258: push(@array, $value);
1.191 harris41 4259: }
1.265 albertel 4260:
4261: $string =~ s/^__END_ARRAY_REF__//;
4262:
4263: return (\@array, $string);
1.168 albertel 4264: }
4265:
1.167 albertel 4266: # -------------------------------------------------------------------Temp Store
4267:
1.168 albertel 4268: sub tmpreset {
4269: my ($symb,$namespace,$domain,$stuname) = @_;
4270: if (!$symb) {
4271: $symb=&symbread();
1.620 albertel 4272: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4273: }
4274: $symb=escape($symb);
4275:
1.620 albertel 4276: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 4277: $namespace=~s/\//\_/g;
4278: $namespace=~s/\W//g;
4279:
1.620 albertel 4280: if (!$domain) { $domain=$env{'user.domain'}; }
4281: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4282: if ($domain eq 'public' && $stuname eq 'public') {
4283: $stuname=$ENV{'REMOTE_ADDR'};
4284: }
1.1117 foxr 4285: my $path=LONCAPA::tempdir();
1.168 albertel 4286: my %hash;
4287: if (tie(%hash,'GDBM_File',
4288: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4289: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 4290: foreach my $key (keys(%hash)) {
1.180 albertel 4291: if ($key=~ /:$symb/) {
1.168 albertel 4292: delete($hash{$key});
4293: }
4294: }
4295: }
4296: }
4297:
1.167 albertel 4298: sub tmpstore {
1.168 albertel 4299: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4300:
4301: if (!$symb) {
4302: $symb=&symbread();
1.620 albertel 4303: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4304: }
4305: $symb=escape($symb);
4306:
4307: if (!$namespace) {
4308: # I don't think we would ever want to store this for a course.
4309: # it seems this will only be used if we don't have a course.
1.620 albertel 4310: #$namespace=$env{'request.course.id'};
1.168 albertel 4311: #if (!$namespace) {
1.620 albertel 4312: $namespace=$env{'request.state'};
1.168 albertel 4313: #}
4314: }
4315: $namespace=~s/\//\_/g;
4316: $namespace=~s/\W//g;
1.620 albertel 4317: if (!$domain) { $domain=$env{'user.domain'}; }
4318: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4319: if ($domain eq 'public' && $stuname eq 'public') {
4320: $stuname=$ENV{'REMOTE_ADDR'};
4321: }
1.168 albertel 4322: my $now=time;
4323: my %hash;
1.1117 foxr 4324: my $path=LONCAPA::tempdir();
1.168 albertel 4325: if (tie(%hash,'GDBM_File',
4326: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4327: &GDBM_WRCREAT(),0640)) {
1.168 albertel 4328: $hash{"version:$symb"}++;
4329: my $version=$hash{"version:$symb"};
4330: my $allkeys='';
4331: foreach my $key (keys(%$storehash)) {
4332: $allkeys.=$key.':';
1.591 albertel 4333: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 4334: }
4335: $hash{"$version:$symb:timestamp"}=$now;
4336: $allkeys.='timestamp';
4337: $hash{"$version:keys:$symb"}=$allkeys;
4338: if (untie(%hash)) {
4339: return 'ok';
4340: } else {
4341: return "error:$!";
4342: }
4343: } else {
4344: return "error:$!";
4345: }
4346: }
1.167 albertel 4347:
1.168 albertel 4348: # -----------------------------------------------------------------Temp Restore
1.167 albertel 4349:
1.168 albertel 4350: sub tmprestore {
4351: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 4352:
1.168 albertel 4353: if (!$symb) {
4354: $symb=&symbread();
1.620 albertel 4355: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4356: }
4357: $symb=escape($symb);
4358:
1.620 albertel 4359: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 4360:
1.620 albertel 4361: if (!$domain) { $domain=$env{'user.domain'}; }
4362: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4363: if ($domain eq 'public' && $stuname eq 'public') {
4364: $stuname=$ENV{'REMOTE_ADDR'};
4365: }
1.168 albertel 4366: my %returnhash;
4367: $namespace=~s/\//\_/g;
4368: $namespace=~s/\W//g;
4369: my %hash;
1.1117 foxr 4370: my $path=LONCAPA::tempdir();
1.168 albertel 4371: if (tie(%hash,'GDBM_File',
4372: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4373: &GDBM_READER(),0640)) {
1.168 albertel 4374: my $version=$hash{"version:$symb"};
4375: $returnhash{'version'}=$version;
4376: my $scope;
4377: for ($scope=1;$scope<=$version;$scope++) {
4378: my $vkeys=$hash{"$scope:keys:$symb"};
4379: my @keys=split(/:/,$vkeys);
4380: my $key;
4381: $returnhash{"$scope:keys"}=$vkeys;
4382: foreach $key (@keys) {
1.591 albertel 4383: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
4384: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 4385: }
4386: }
1.168 albertel 4387: if (!(untie(%hash))) {
4388: return "error:$!";
4389: }
4390: } else {
4391: return "error:$!";
4392: }
4393: return %returnhash;
1.167 albertel 4394: }
4395:
1.9 www 4396: # ----------------------------------------------------------------------- Store
4397:
4398: sub store {
1.124 www 4399: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4400: my $home='';
4401:
1.168 albertel 4402: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4403:
1.213 www 4404: $symb=&symbclean($symb);
1.122 albertel 4405: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 4406:
1.620 albertel 4407: if (!$domain) { $domain=$env{'user.domain'}; }
4408: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 4409:
4410: &devalidate($symb,$stuname,$domain);
1.109 www 4411:
4412: $symb=escape($symb);
1.187 www 4413: if (!$namespace) {
1.620 albertel 4414: unless ($namespace=$env{'request.course.id'}) {
1.187 www 4415: return '';
4416: }
4417: }
1.620 albertel 4418: if (!$home) { $home=$env{'user.home'}; }
1.447 www 4419:
4420: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4421: $$storehash{'host'}=$perlvar{'lonHostID'};
4422:
1.12 www 4423: my $namevalue='';
1.800 albertel 4424: foreach my $key (keys(%$storehash)) {
4425: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 4426: }
1.12 www 4427: $namevalue=~s/\&$//;
1.187 www 4428: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124 www 4429: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9 www 4430: }
4431:
1.47 www 4432: # -------------------------------------------------------------- Critical Store
4433:
4434: sub cstore {
1.124 www 4435: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4436: my $home='';
4437:
1.168 albertel 4438: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4439:
1.213 www 4440: $symb=&symbclean($symb);
1.122 albertel 4441: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 4442:
1.620 albertel 4443: if (!$domain) { $domain=$env{'user.domain'}; }
4444: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 4445:
4446: &devalidate($symb,$stuname,$domain);
1.109 www 4447:
4448: $symb=escape($symb);
1.187 www 4449: if (!$namespace) {
1.620 albertel 4450: unless ($namespace=$env{'request.course.id'}) {
1.187 www 4451: return '';
4452: }
4453: }
1.620 albertel 4454: if (!$home) { $home=$env{'user.home'}; }
1.447 www 4455:
4456: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4457: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 4458:
1.47 www 4459: my $namevalue='';
1.800 albertel 4460: foreach my $key (keys(%$storehash)) {
4461: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 4462: }
1.47 www 4463: $namevalue=~s/\&$//;
1.187 www 4464: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 4465: return critical
4466: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47 www 4467: }
4468:
1.9 www 4469: # --------------------------------------------------------------------- Restore
4470:
4471: sub restore {
1.124 www 4472: my ($symb,$namespace,$domain,$stuname) = @_;
4473: my $home='';
4474:
1.168 albertel 4475: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4476:
1.122 albertel 4477: if (!$symb) {
4478: unless ($symb=escape(&symbread())) { return ''; }
4479: } else {
1.213 www 4480: $symb=&escape(&symbclean($symb));
1.122 albertel 4481: }
1.188 www 4482: if (!$namespace) {
1.620 albertel 4483: unless ($namespace=$env{'request.course.id'}) {
1.188 www 4484: return '';
4485: }
4486: }
1.620 albertel 4487: if (!$domain) { $domain=$env{'user.domain'}; }
4488: if (!$stuname) { $stuname=$env{'user.name'}; }
4489: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 4490: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
4491:
1.12 www 4492: my %returnhash=();
1.800 albertel 4493: foreach my $line (split(/\&/,$answer)) {
4494: my ($name,$value)=split(/\=/,$line);
1.591 albertel 4495: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 4496: }
1.75 www 4497: my $version;
4498: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 4499: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
4500: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 4501: }
1.75 www 4502: }
1.13 www 4503: return %returnhash;
1.34 www 4504: }
4505:
4506: # ---------------------------------------------------------- Course Description
1.1118 foxr 4507: #
4508: #
1.34 www 4509:
4510: sub coursedescription {
1.731 albertel 4511: my ($courseid,$args)=@_;
1.34 www 4512: $courseid=~s/^\///;
1.49 www 4513: $courseid=~s/\_/\//g;
1.34 www 4514: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 4515: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 4516: my $normalid=$cdomain.'_'.$cnum;
4517: # need to always cache even if we get errors otherwise we keep
4518: # trying and trying and trying to get the course description.
4519: my %envhash=();
4520: my %returnhash=();
1.731 albertel 4521:
4522: my $expiretime=600;
4523: if ($env{'request.course.id'} eq $normalid) {
4524: $expiretime=120;
4525: }
4526:
4527: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
4528: if (!$args->{'freshen_cache'}
4529: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
4530: foreach my $key (keys(%env)) {
4531: next if ($key !~ /^\Q$prefix\E(.*)/);
4532: my ($setting) = $1;
4533: $returnhash{$setting} = $env{$key};
4534: }
4535: return %returnhash;
4536: }
4537:
1.1118 foxr 4538: # get the data again
4539:
1.731 albertel 4540: if (!$args->{'one_time'}) {
4541: $envhash{'course.'.$normalid.'.last_cache'}=time;
4542: }
1.811 albertel 4543:
1.34 www 4544: if ($chome ne 'no_host') {
1.302 albertel 4545: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 4546: if (!exists($returnhash{'con_lost'})) {
1.1118 foxr 4547: my $username = $env{'user.name'}; # Defult username
4548: if(defined $args->{'user'}) {
4549: $username = $args->{'user'};
4550: }
1.129 albertel 4551: $returnhash{'home'}= $chome;
4552: $returnhash{'domain'} = $cdomain;
4553: $returnhash{'num'} = $cnum;
1.741 raeburn 4554: if (!defined($returnhash{'type'})) {
4555: $returnhash{'type'} = 'Course';
4556: }
1.130 albertel 4557: while (my ($name,$value) = each %returnhash) {
1.53 www 4558: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 4559: }
1.270 www 4560: $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117 foxr 4561: $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118 foxr 4562: $username.'_'.$cdomain.'_'.$cnum;
1.60 www 4563: $envhash{'course.'.$normalid.'.home'}=$chome;
4564: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
4565: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 4566: }
4567: }
1.731 albertel 4568: if (!$args->{'one_time'}) {
1.949 raeburn 4569: &appenv(\%envhash);
1.731 albertel 4570: }
1.302 albertel 4571: return %returnhash;
1.461 www 4572: }
4573:
1.1080 raeburn 4574: sub update_released_required {
4575: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
4576: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
4577: $cid = $env{'request.course.id'};
4578: $cdom = $env{'course.'.$cid.'.domain'};
4579: $cnum = $env{'course.'.$cid.'.num'};
4580: $chome = $env{'course.'.$cid.'.home'};
4581: }
4582: if ($needsrelease) {
4583: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
4584: my $needsupdate;
4585: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
4586: $needsupdate = 1;
4587: } else {
4588: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
4589: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
4590: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
4591: $needsupdate = 1;
4592: }
4593: }
4594: if ($needsupdate) {
4595: my %needshash = (
4596: 'internal.releaserequired' => $needsrelease,
4597: );
4598: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
4599: if ($putresult eq 'ok') {
4600: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
4601: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
4602: if (ref($crsinfo{$cid}) eq 'HASH') {
4603: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
4604: &courseidput($cdom,\%crsinfo,$chome,'notime');
4605: }
4606: }
4607: }
4608: }
4609: return;
4610: }
4611:
1.461 www 4612: # -------------------------------------------------See if a user is privileged
4613:
4614: sub privileged {
4615: my ($username,$domain)=@_;
4616: my $rolesdump=&reply("dump:$domain:$username:roles",
4617: &homeserver($username,$domain));
1.1033 raeburn 4618: if (($rolesdump eq 'con_lost') || ($rolesdump eq '') ||
4619: ($rolesdump =~ /^error:/)) {
4620: return 0;
4621: }
1.461 www 4622: my $now=time;
4623: if ($rolesdump ne '') {
1.800 albertel 4624: foreach my $entry (split(/&/,$rolesdump)) {
4625: if ($entry!~/^rolesdef_/) {
4626: my ($area,$role)=split(/=/,$entry);
1.461 www 4627: $area=~s/\_\w\w$//;
4628: my ($trole,$tend,$tstart)=split(/_/,$role);
4629: if (($trole eq 'dc') || ($trole eq 'su')) {
4630: my $active=1;
4631: if ($tend) {
4632: if ($tend<$now) { $active=0; }
4633: }
4634: if ($tstart) {
4635: if ($tstart>$now) { $active=0; }
4636: }
4637: if ($active) { return 1; }
4638: }
4639: }
4640: }
4641: }
4642: return 0;
1.9 www 4643: }
1.1 albertel 4644:
1.103 harris41 4645: # -------------------------------------------------------- Get user privileges
1.11 www 4646:
4647: sub rolesinit {
4648: my ($domain,$username,$authhost)=@_;
1.1034 raeburn 4649: my $now=time;
4650: my %userroles = ('user.login.time' => $now);
1.1166 raeburn 4651: my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.1033 raeburn 4652: if (($rolesdump eq 'con_lost') || ($rolesdump eq '') ||
1.1078 raeburn 4653: ($rolesdump =~ /^error:/)) {
1.1033 raeburn 4654: return \%userroles;
4655: }
1.1162 raeburn 4656: my %firstaccess = &dump('firstaccesstimes',$domain,$username);
4657: my %timerinterval = &dump('timerinterval',$domain,$username);
4658: my (%coursetimerstarts,%firstaccchk,%firstaccenv,
4659: %coursetimerintervals,%timerintchk,%timerintenv);
4660: foreach my $key (keys(%firstaccess)) {
4661: my ($cid,$rest) = split(/\0/,$key);
4662: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
4663: }
4664: foreach my $key (keys(%timerinterval)) {
4665: my ($cid,$rest) = split(/\0/,$key);
4666: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
4667: }
1.11 www 4668: my %allroles=();
1.1162 raeburn 4669: my %allgroups=();
1.11 www 4670:
4671: if ($rolesdump ne '') {
1.800 albertel 4672: foreach my $entry (split(/&/,$rolesdump)) {
4673: if ($entry!~/^rolesdef_/) {
4674: my ($area,$role)=split(/=/,$entry);
1.587 albertel 4675: $area=~s/\_\w\w$//;
1.678 raeburn 4676: my ($trole,$tend,$tstart,$group_privs);
1.1168 ! www 4677: if ($role=~/^cr/) {
! 4678: # Custom role, defined by a user
! 4679: # e.g., user.role.cr/msu/smith/mynewrole
1.807 albertel 4680: if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
4681: ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655 albertel 4682: ($tend,$tstart)=split('_',$trest);
4683: } else {
4684: $trole=$role;
4685: }
1.678 raeburn 4686: } elsif ($role =~ m|^gr/|) {
1.1168 ! www 4687: # Role of member in a group, defined within a course/community
! 4688: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
1.678 raeburn 4689: ($trole,$tend,$tstart) = split(/_/,$role);
1.1104 raeburn 4690: next if ($tstart eq '-1');
1.678 raeburn 4691: ($trole,$group_privs) = split(/\//,$trole);
4692: $group_privs = &unescape($group_privs);
1.587 albertel 4693: } else {
1.1168 ! www 4694: # Just a normal role, defined in roles.tab
1.587 albertel 4695: ($trole,$tend,$tstart)=split(/_/,$role);
4696: }
1.743 albertel 4697: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
4698: $username);
4699: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567 raeburn 4700: if (($tend!=0) && ($tend<$now)) { $trole=''; }
4701: if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11 www 4702: if (($area ne '') && ($trole ne '')) {
1.347 albertel 4703: my $spec=$trole.'.'.$area;
4704: my ($tdummy,$tdomain,$trest)=split(/\//,$area);
4705: if ($trole =~ /^cr\//) {
1.1168 ! www 4706: # Custom role, defined by a user
1.567 raeburn 4707: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678 raeburn 4708: } elsif ($trole eq 'gr') {
1.1168 ! www 4709: # Role of a member in a group, defined within a course/community
1.678 raeburn 4710: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347 albertel 4711: } else {
1.1168 ! www 4712: # Normal role, defined in roles.tab
1.567 raeburn 4713: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347 albertel 4714: }
1.1162 raeburn 4715: if ($trole ne 'gr') {
4716: my $cid = $tdomain.'_'.$trest;
4717: unless ($firstaccchk{$cid}) {
4718: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
4719: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
4720: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
4721: $coursetimerstarts{$cid}{$item};
4722: }
4723: }
4724: $firstaccchk{$cid} = 1;
4725: }
4726: unless ($timerintchk{$cid}) {
4727: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
4728: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
4729: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
4730: $coursetimerintervals{$cid}{$item};
4731: }
4732: }
4733: $timerintchk{$cid} = 1;
4734: }
4735: }
1.12 www 4736: }
1.662 raeburn 4737: }
1.191 harris41 4738: }
1.743 albertel 4739: my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
4740: $userroles{'user.adv'} = $adv;
4741: $userroles{'user.author'} = $author;
1.620 albertel 4742: $env{'user.adv'}=$adv;
1.11 www 4743: }
1.1162 raeburn 4744: return (\%userroles,\%firstaccenv,\%timerintenv);
1.11 www 4745: }
4746:
1.567 raeburn 4747: sub set_arearole {
4748: my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
4749: # log the associated role with the area
4750: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743 albertel 4751: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 4752: }
4753:
4754: sub custom_roleprivs {
4755: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
4756: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
4757: my $homsvr=homeserver($rauthor,$rdomain);
1.838 albertel 4758: if (&hostname($homsvr) ne '') {
1.567 raeburn 4759: my ($rdummy,$roledef)=
4760: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
4761: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
4762: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
4763: if (defined($syspriv)) {
1.1043 raeburn 4764: if ($trest =~ /^$match_community$/) {
4765: $syspriv =~ s/bre\&S//;
4766: }
1.567 raeburn 4767: $$allroles{'cm./'}.=':'.$syspriv;
4768: $$allroles{$spec.'./'}.=':'.$syspriv;
4769: }
4770: if ($tdomain ne '') {
4771: if (defined($dompriv)) {
4772: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
4773: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
4774: }
4775: if (($trest ne '') && (defined($coursepriv))) {
4776: $$allroles{'cm.'.$area}.=':'.$coursepriv;
4777: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
4778: }
4779: }
4780: }
4781: }
4782: }
4783:
1.678 raeburn 4784: sub group_roleprivs {
4785: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
4786: my $access = 1;
4787: my $now = time;
4788: if (($tend!=0) && ($tend<$now)) { $access = 0; }
4789: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
4790: if ($access) {
1.811 albertel 4791: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 4792: $$allgroups{$course}{$group} .=':'.$group_privs;
4793: }
4794: }
1.567 raeburn 4795:
4796: sub standard_roleprivs {
4797: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
4798: if (defined($pr{$trole.':s'})) {
4799: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
4800: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
4801: }
4802: if ($tdomain ne '') {
4803: if (defined($pr{$trole.':d'})) {
4804: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
4805: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
4806: }
4807: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
4808: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
4809: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
4810: }
4811: }
4812: }
4813:
4814: sub set_userprivs {
1.1064 raeburn 4815: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 4816: my $author=0;
4817: my $adv=0;
1.678 raeburn 4818: my %grouproles = ();
4819: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 4820: my @groupkeys;
1.1000 raeburn 4821: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 4822: push(@groupkeys,$role);
4823: }
4824: if (ref($groups_roles) eq 'HASH') {
4825: foreach my $key (keys(%{$groups_roles})) {
4826: unless (grep(/^\Q$key\E$/,@groupkeys)) {
4827: push(@groupkeys,$key);
4828: }
4829: }
4830: }
4831: if (@groupkeys > 0) {
4832: foreach my $role (@groupkeys) {
4833: my ($trole,$area,$sec,$extendedarea);
4834: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
4835: $trole = $1;
4836: $area = $2;
4837: $sec = $3;
4838: $extendedarea = $area.$sec;
4839: if (exists($$allgroups{$area})) {
4840: foreach my $group (keys(%{$$allgroups{$area}})) {
4841: my $spec = $trole.'.'.$extendedarea;
4842: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 4843: $$allgroups{$area}{$group};
1.1064 raeburn 4844: }
1.678 raeburn 4845: }
4846: }
4847: }
4848: }
4849: }
1.800 albertel 4850: foreach my $group (keys(%grouproles)) {
4851: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 4852: }
1.800 albertel 4853: foreach my $role (keys(%{$allroles})) {
4854: my %thesepriv;
1.941 raeburn 4855: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 4856: foreach my $item (split(/:/,$$allroles{$role})) {
4857: if ($item ne '') {
4858: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 4859: if ($restrictions eq '') {
4860: $thesepriv{$privilege}='F';
4861: } elsif ($thesepriv{$privilege} ne 'F') {
4862: $thesepriv{$privilege}.=$restrictions;
4863: }
4864: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
4865: }
4866: }
4867: my $thesestr='';
1.1104 raeburn 4868: foreach my $priv (sort(keys(%thesepriv))) {
1.800 albertel 4869: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
4870: }
4871: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 4872: }
4873: return ($author,$adv);
4874: }
4875:
1.994 raeburn 4876: sub role_status {
1.1104 raeburn 4877: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 4878: my @pwhere = ();
4879: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
4880: (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
4881: unless (!defined($$role) || $$role eq '') {
4882: $$where=join('.',@pwhere);
4883: $$trolecode=$$role.'.'.$$where;
4884: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
4885: $$tstatus='is';
1.1104 raeburn 4886: if ($$tstart && $$tstart>$update) {
1.994 raeburn 4887: $$tstatus='future';
1.1034 raeburn 4888: if ($$tstart<$now) {
4889: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 4890: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 4891: my (%allroles,%allgroups,$group_privs,
4892: %groups_roles,@rolecodes);
1.1002 raeburn 4893: my %userroles = (
4894: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
4895: );
1.1064 raeburn 4896: @rolecodes = ('cm');
1.1002 raeburn 4897: my $spec=$$role.'.'.$$where;
4898: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
4899: if ($$role =~ /^cr\//) {
4900: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 4901: push(@rolecodes,'cr');
1.1002 raeburn 4902: } elsif ($$role eq 'gr') {
1.1064 raeburn 4903: push(@rolecodes,$$role);
1.1002 raeburn 4904: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
4905: $env{'user.name'});
1.1064 raeburn 4906: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 4907: (undef,my $group_privs) = split(/\//,$trole);
4908: $group_privs = &unescape($group_privs);
4909: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 4910: 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 4911: &get_groups_roles($tdomain,$trest,
4912: \%course_roles,\@rolecodes,
4913: \%groups_roles);
1.1002 raeburn 4914: } else {
1.1064 raeburn 4915: push(@rolecodes,$$role);
1.1002 raeburn 4916: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
4917: }
1.1064 raeburn 4918: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
4919: &appenv(\%userroles,\@rolecodes);
1.1002 raeburn 4920: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
4921: }
4922: }
1.1034 raeburn 4923: $$tstatus = 'is';
1.1002 raeburn 4924: }
1.994 raeburn 4925: }
4926: if ($$tend) {
1.1104 raeburn 4927: if ($$tend<$update) {
1.994 raeburn 4928: $$tstatus='expired';
4929: } elsif ($$tend<$now) {
4930: $$tstatus='will_not';
4931: }
4932: }
4933: }
4934: }
4935: }
4936:
1.1104 raeburn 4937: sub get_groups_roles {
4938: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
4939: return unless((ref($cdom_courseroles) eq 'HASH') &&
4940: (ref($rolecodes) eq 'ARRAY') &&
4941: (ref($groups_roles) eq 'HASH'));
4942: if (keys(%{$cdom_courseroles}) > 0) {
4943: my ($cnum) = ($rest =~ /^($match_courseid)/);
4944: if ($cdom ne '' && $cnum ne '') {
4945: foreach my $key (keys(%{$cdom_courseroles})) {
4946: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
4947: my $crsrole = $1;
4948: my $crssec = $2;
4949: if ($crsrole =~ /^cr/) {
4950: unless (grep(/^cr$/,@{$rolecodes})) {
4951: push(@{$rolecodes},'cr');
4952: }
4953: } else {
4954: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
4955: push(@{$rolecodes},$crsrole);
4956: }
4957: }
4958: my $rolekey = "$crsrole./$cdom/$cnum";
4959: if ($crssec ne '') {
4960: $rolekey .= "/$crssec";
4961: }
4962: $rolekey .= './';
4963: $groups_roles->{$rolekey} = $rolecodes;
4964: }
4965: }
4966: }
4967: }
4968: return;
4969: }
4970:
4971: sub delete_env_groupprivs {
4972: my ($where,$courseroles,$possroles) = @_;
4973: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
4974: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
4975: unless (ref($courseroles->{$udom}) eq 'HASH') {
4976: %{$courseroles->{$udom}} =
4977: &get_my_roles('','','userroles',['active'],
4978: $possroles,[$udom],1);
4979: }
4980: if (ref($courseroles->{$udom}) eq 'HASH') {
4981: foreach my $item (keys(%{$courseroles->{$udom}})) {
4982: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
4983: my $area = '/'.$cdom.'/'.$cnum;
4984: my $privkey = "user.priv.$crsrole.$area";
4985: if ($crssec ne '') {
4986: $privkey .= '/'.$crssec;
4987: }
4988: $privkey .= ".$area/$group";
4989: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
4990: }
4991: }
4992: return;
4993: }
4994:
1.994 raeburn 4995: sub check_adhoc_privs {
1.1104 raeburn 4996: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994 raeburn 4997: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
4998: if ($env{$cckey}) {
4999: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104 raeburn 5000: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 5001: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088 raeburn 5002: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994 raeburn 5003: }
5004: } else {
1.1088 raeburn 5005: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994 raeburn 5006: }
5007: }
5008:
5009: sub set_adhoc_privileges {
5010: # role can be cc or ca
1.1088 raeburn 5011: my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994 raeburn 5012: my $area = '/'.$dcdom.'/'.$pickedcourse;
5013: my $spec = $role.'.'.$area;
5014: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
5015: $env{'user.name'});
5016: my %ccrole = ();
5017: &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
5018: my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
5019: &appenv(\%userroles,[$role,'cm']);
5020: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088 raeburn 5021: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
5022: &appenv( {'request.role' => $spec,
5023: 'request.role.domain' => $dcdom,
5024: 'request.course.sec' => ''
5025: }
5026: );
5027: my $tadv=0;
5028: if (&allowed('adv') eq 'F') { $tadv=1; }
5029: &appenv({'request.role.adv' => $tadv});
5030: }
1.994 raeburn 5031: }
5032:
1.12 www 5033: # --------------------------------------------------------------- get interface
5034:
5035: sub get {
1.131 albertel 5036: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 5037: my $items='';
1.800 albertel 5038: foreach my $item (@$storearr) {
5039: $items.=&escape($item).'&';
1.191 harris41 5040: }
1.12 www 5041: $items=~s/\&$//;
1.620 albertel 5042: if (!$udomain) { $udomain=$env{'user.domain'}; }
5043: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 5044: my $uhome=&homeserver($uname,$udomain);
5045:
1.133 albertel 5046: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 5047: my @pairs=split(/\&/,$rep);
1.273 albertel 5048: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
5049: return @pairs;
5050: }
1.15 www 5051: my %returnhash=();
1.42 www 5052: my $i=0;
1.800 albertel 5053: foreach my $item (@$storearr) {
5054: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 5055: $i++;
1.191 harris41 5056: }
1.15 www 5057: return %returnhash;
1.27 www 5058: }
5059:
5060: # --------------------------------------------------------------- del interface
5061:
5062: sub del {
1.133 albertel 5063: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 5064: my $items='';
1.800 albertel 5065: foreach my $item (@$storearr) {
5066: $items.=&escape($item).'&';
1.191 harris41 5067: }
1.984 neumanie 5068:
1.27 www 5069: $items=~s/\&$//;
1.620 albertel 5070: if (!$udomain) { $udomain=$env{'user.domain'}; }
5071: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 5072: my $uhome=&homeserver($uname,$udomain);
5073: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 5074: }
5075:
5076: # -------------------------------------------------------------- dump interface
5077:
5078: sub dump {
1.1166 raeburn 5079: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.755 albertel 5080: if (!$udomain) { $udomain=$env{'user.domain'}; }
5081: if (!$uname) { $uname=$env{'user.name'}; }
5082: my $uhome=&homeserver($uname,$udomain);
1.1167 droeschl 5083:
1.755 albertel 5084: if ($regexp) {
5085: $regexp=&escape($regexp);
5086: } else {
5087: $regexp='.';
5088: }
1.1166 raeburn 5089: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755 albertel 5090: my @pairs=split(/\&/,$rep);
5091: my %returnhash=();
1.1098 foxr 5092: if (!($rep =~ /^error/ )) {
5093: foreach my $item (@pairs) {
5094: my ($key,$value)=split(/=/,$item,2);
5095: $key = &unescape($key);
5096: next if ($key =~ /^error: 2 /);
5097: $returnhash{$key}=&thaw_unescape($value);
5098: }
1.755 albertel 5099: }
5100: return %returnhash;
1.407 www 5101: }
5102:
1.1098 foxr 5103:
1.717 albertel 5104: # --------------------------------------------------------- dumpstore interface
5105:
5106: sub dumpstore {
5107: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822 albertel 5108: if (!$udomain) { $udomain=$env{'user.domain'}; }
5109: if (!$uname) { $uname=$env{'user.name'}; }
5110: my $uhome=&homeserver($uname,$udomain);
5111: if ($regexp) {
5112: $regexp=&escape($regexp);
5113: } else {
5114: $regexp='.';
5115: }
5116: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
5117: my @pairs=split(/\&/,$rep);
5118: my %returnhash=();
5119: foreach my $item (@pairs) {
5120: my ($key,$value)=split(/=/,$item,2);
5121: next if ($key =~ /^error: 2 /);
5122: $returnhash{$key}=&thaw_unescape($value);
5123: }
5124: return %returnhash;
1.717 albertel 5125: }
5126:
1.407 www 5127: # -------------------------------------------------------------- keys interface
5128:
5129: sub getkeys {
5130: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 5131: if (!$udomain) { $udomain=$env{'user.domain'}; }
5132: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 5133: my $uhome=&homeserver($uname,$udomain);
5134: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
5135: my @keyarray=();
1.800 albertel 5136: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 5137: next if ($key =~ /^error: 2 /);
1.800 albertel 5138: push(@keyarray,&unescape($key));
1.407 www 5139: }
5140: return @keyarray;
1.318 matthew 5141: }
5142:
1.319 matthew 5143: # --------------------------------------------------------------- currentdump
5144: sub currentdump {
1.328 matthew 5145: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 5146: $courseid = $env{'request.course.id'} if (! defined($courseid));
5147: $sdom = $env{'user.domain'} if (! defined($sdom));
5148: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 5149: my $uhome = &homeserver($sname,$sdom);
5150: my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318 matthew 5151: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 5152: #
1.318 matthew 5153: my %returnhash=();
1.319 matthew 5154: #
5155: if ($rep eq "unknown_cmd") {
5156: # an old lond will not know currentdump
5157: # Do a dump and make it look like a currentdump
1.822 albertel 5158: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 5159: return if ($tmp[0] =~ /^(error:|no_such_host)/);
5160: my %hash = @tmp;
5161: @tmp=();
1.424 matthew 5162: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 5163: } else {
5164: my @pairs=split(/\&/,$rep);
1.800 albertel 5165: foreach my $pair (@pairs) {
5166: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 5167: my ($symb,$param) = split(/:/,$key);
5168: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 5169: &thaw_unescape($value);
1.319 matthew 5170: }
1.191 harris41 5171: }
1.12 www 5172: return %returnhash;
1.424 matthew 5173: }
5174:
5175: sub convert_dump_to_currentdump{
5176: my %hash = %{shift()};
5177: my %returnhash;
5178: # Code ripped from lond, essentially. The only difference
5179: # here is the unescaping done by lonnet::dump(). Conceivably
5180: # we might run in to problems with parameter names =~ /^v\./
5181: while (my ($key,$value) = each(%hash)) {
5182: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 5183: $symb = &unescape($symb);
5184: $param = &unescape($param);
1.424 matthew 5185: next if ($v eq 'version' || $symb eq 'keys');
5186: next if (exists($returnhash{$symb}) &&
5187: exists($returnhash{$symb}->{$param}) &&
5188: $returnhash{$symb}->{'v.'.$param} > $v);
5189: $returnhash{$symb}->{$param}=$value;
5190: $returnhash{$symb}->{'v.'.$param}=$v;
5191: }
5192: #
5193: # Remove all of the keys in the hashes which keep track of
5194: # the version of the parameter.
5195: while (my ($symb,$param_hash) = each(%returnhash)) {
5196: # use a foreach because we are going to delete from the hash.
5197: foreach my $key (keys(%$param_hash)) {
5198: delete($param_hash->{$key}) if ($key =~ /^v\./);
5199: }
5200: }
5201: return \%returnhash;
1.12 www 5202: }
5203:
1.627 albertel 5204: # ------------------------------------------------------ critical inc interface
5205:
5206: sub cinc {
5207: return &inc(@_,'critical');
5208: }
5209:
1.449 matthew 5210: # --------------------------------------------------------------- inc interface
5211:
5212: sub inc {
1.627 albertel 5213: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 5214: if (!$udomain) { $udomain=$env{'user.domain'}; }
5215: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 5216: my $uhome=&homeserver($uname,$udomain);
5217: my $items='';
5218: if (! ref($store)) {
5219: # got a single value, so use that instead
5220: $items = &escape($store).'=&';
5221: } elsif (ref($store) eq 'SCALAR') {
5222: $items = &escape($$store).'=&';
5223: } elsif (ref($store) eq 'ARRAY') {
5224: $items = join('=&',map {&escape($_);} @{$store});
5225: } elsif (ref($store) eq 'HASH') {
5226: while (my($key,$value) = each(%{$store})) {
5227: $items.= &escape($key).'='.&escape($value).'&';
5228: }
5229: }
5230: $items=~s/\&$//;
1.627 albertel 5231: if ($critical) {
5232: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
5233: } else {
5234: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
5235: }
1.449 matthew 5236: }
5237:
1.12 www 5238: # --------------------------------------------------------------- put interface
5239:
5240: sub put {
1.134 albertel 5241: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 5242: if (!$udomain) { $udomain=$env{'user.domain'}; }
5243: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 5244: my $uhome=&homeserver($uname,$udomain);
1.12 www 5245: my $items='';
1.800 albertel 5246: foreach my $item (keys(%$storehash)) {
5247: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 5248: }
1.12 www 5249: $items=~s/\&$//;
1.134 albertel 5250: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 5251: }
5252:
1.631 albertel 5253: # ------------------------------------------------------------ newput interface
5254:
5255: sub newput {
5256: my ($namespace,$storehash,$udomain,$uname)=@_;
5257: if (!$udomain) { $udomain=$env{'user.domain'}; }
5258: if (!$uname) { $uname=$env{'user.name'}; }
5259: my $uhome=&homeserver($uname,$udomain);
5260: my $items='';
5261: foreach my $key (keys(%$storehash)) {
5262: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
5263: }
5264: $items=~s/\&$//;
5265: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
5266: }
5267:
5268: # --------------------------------------------------------- putstore interface
5269:
1.524 raeburn 5270: sub putstore {
1.715 albertel 5271: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620 albertel 5272: if (!$udomain) { $udomain=$env{'user.domain'}; }
5273: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 5274: my $uhome=&homeserver($uname,$udomain);
5275: my $items='';
1.715 albertel 5276: foreach my $key (keys(%$storehash)) {
5277: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 5278: }
1.715 albertel 5279: $items=~s/\&$//;
1.716 albertel 5280: my $esc_symb=&escape($symb);
5281: my $esc_v=&escape($version);
1.715 albertel 5282: my $reply =
1.716 albertel 5283: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 5284: $uhome);
5285: if ($reply eq 'unknown_cmd') {
1.716 albertel 5286: # gfall back to way things use to be done
1.715 albertel 5287: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
5288: $uname);
1.524 raeburn 5289: }
1.715 albertel 5290: return $reply;
5291: }
5292:
5293: sub old_putstore {
1.716 albertel 5294: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
5295: if (!$udomain) { $udomain=$env{'user.domain'}; }
5296: if (!$uname) { $uname=$env{'user.name'}; }
5297: my $uhome=&homeserver($uname,$udomain);
5298: my %newstorehash;
1.800 albertel 5299: foreach my $item (keys(%$storehash)) {
5300: my $key = $version.':'.&escape($symb).':'.$item;
5301: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 5302: }
5303: my $items='';
5304: my %allitems = ();
1.800 albertel 5305: foreach my $item (keys(%newstorehash)) {
5306: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 5307: my $key = $1.':keys:'.$2;
5308: $allitems{$key} .= $3.':';
5309: }
1.800 albertel 5310: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 5311: }
1.800 albertel 5312: foreach my $item (keys(%allitems)) {
5313: $allitems{$item} =~ s/\:$//;
5314: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 5315: }
5316: $items=~s/\&$//;
5317: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 5318: }
5319:
1.47 www 5320: # ------------------------------------------------------ critical put interface
5321:
5322: sub cput {
1.134 albertel 5323: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 5324: if (!$udomain) { $udomain=$env{'user.domain'}; }
5325: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 5326: my $uhome=&homeserver($uname,$udomain);
1.47 www 5327: my $items='';
1.800 albertel 5328: foreach my $item (keys(%$storehash)) {
5329: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 5330: }
1.47 www 5331: $items=~s/\&$//;
1.134 albertel 5332: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 5333: }
5334:
5335: # -------------------------------------------------------------- eget interface
5336:
5337: sub eget {
1.133 albertel 5338: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 5339: my $items='';
1.800 albertel 5340: foreach my $item (@$storearr) {
5341: $items.=&escape($item).'&';
1.191 harris41 5342: }
1.12 www 5343: $items=~s/\&$//;
1.620 albertel 5344: if (!$udomain) { $udomain=$env{'user.domain'}; }
5345: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 5346: my $uhome=&homeserver($uname,$udomain);
5347: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 5348: my @pairs=split(/\&/,$rep);
5349: my %returnhash=();
1.42 www 5350: my $i=0;
1.800 albertel 5351: foreach my $item (@$storearr) {
5352: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 5353: $i++;
1.191 harris41 5354: }
1.12 www 5355: return %returnhash;
5356: }
5357:
1.667 albertel 5358: # ------------------------------------------------------------ tmpput interface
5359: sub tmpput {
1.802 raeburn 5360: my ($storehash,$server,$context)=@_;
1.667 albertel 5361: my $items='';
1.800 albertel 5362: foreach my $item (keys(%$storehash)) {
5363: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 5364: }
5365: $items=~s/\&$//;
1.802 raeburn 5366: if (defined($context)) {
5367: $items .= ':'.&escape($context);
5368: }
1.667 albertel 5369: return &reply("tmpput:$items",$server);
5370: }
5371:
5372: # ------------------------------------------------------------ tmpget interface
5373: sub tmpget {
1.688 albertel 5374: my ($token,$server)=@_;
5375: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5376: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 5377: my %returnhash;
5378: foreach my $item (split(/\&/,$rep)) {
5379: my ($key,$value)=split(/=/,$item);
1.951 raeburn 5380: next if ($key =~ /^error: 2 /);
1.667 albertel 5381: $returnhash{&unescape($key)}=&thaw_unescape($value);
5382: }
5383: return %returnhash;
5384: }
5385:
1.1113 raeburn 5386: # ------------------------------------------------------------ tmpdel interface
1.688 albertel 5387: sub tmpdel {
5388: my ($token,$server)=@_;
5389: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5390: return &reply("tmpdel:$token",$server);
5391: }
5392:
1.765 albertel 5393: # -------------------------------------------------- portfolio access checking
5394:
5395: sub portfolio_access {
1.766 albertel 5396: my ($requrl) = @_;
1.765 albertel 5397: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
5398: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814 raeburn 5399: if ($result) {
5400: my %setters;
5401: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
5402: my ($startblock,$endblock) =
5403: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
5404: if ($startblock && $endblock) {
5405: return 'B';
5406: }
5407: } else {
5408: my ($startblock,$endblock) =
5409: &Apache::loncommon::blockcheck(\%setters,'port');
5410: if ($startblock && $endblock) {
5411: return 'B';
5412: }
5413: }
5414: }
1.765 albertel 5415: if ($result eq 'ok') {
1.766 albertel 5416: return 'F';
1.765 albertel 5417: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 5418: return 'A';
1.765 albertel 5419: }
1.766 albertel 5420: return '';
1.765 albertel 5421: }
5422:
5423: sub get_portfolio_access {
1.767 albertel 5424: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
5425:
5426: if (!ref($access_hash)) {
5427: my $current_perms = &get_portfile_permissions($udom,$unum);
5428: my %access_controls = &get_access_controls($current_perms,$group,
5429: $file_name);
5430: $access_hash = $access_controls{$file_name};
5431: }
5432:
1.765 albertel 5433: my ($public,$guest,@domains,@users,@courses,@groups);
5434: my $now = time;
5435: if (ref($access_hash) eq 'HASH') {
5436: foreach my $key (keys(%{$access_hash})) {
5437: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
5438: if ($start > $now) {
5439: next;
5440: }
5441: if ($end && $end<$now) {
5442: next;
5443: }
5444: if ($scope eq 'public') {
5445: $public = $key;
5446: last;
5447: } elsif ($scope eq 'guest') {
5448: $guest = $key;
5449: } elsif ($scope eq 'domains') {
5450: push(@domains,$key);
5451: } elsif ($scope eq 'users') {
5452: push(@users,$key);
5453: } elsif ($scope eq 'course') {
5454: push(@courses,$key);
5455: } elsif ($scope eq 'group') {
5456: push(@groups,$key);
5457: }
5458: }
5459: if ($public) {
5460: return 'ok';
5461: }
5462: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
5463: if ($guest) {
5464: return $guest;
5465: }
5466: } else {
5467: if (@domains > 0) {
5468: foreach my $domkey (@domains) {
5469: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
5470: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
5471: return 'ok';
5472: }
5473: }
5474: }
5475: }
5476: if (@users > 0) {
5477: foreach my $userkey (@users) {
1.865 raeburn 5478: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
5479: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
5480: if (ref($item) eq 'HASH') {
5481: if (($item->{'uname'} eq $env{'user.name'}) &&
5482: ($item->{'udom'} eq $env{'user.domain'})) {
5483: return 'ok';
5484: }
5485: }
5486: }
5487: }
1.765 albertel 5488: }
5489: }
5490: my %roleshash;
5491: my @courses_and_groups = @courses;
5492: push(@courses_and_groups,@groups);
5493: if (@courses_and_groups > 0) {
5494: my (%allgroups,%allroles);
5495: my ($start,$end,$role,$sec,$group);
5496: foreach my $envkey (%env) {
1.1060 raeburn 5497: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 5498: my $cid = $2.'_'.$3;
5499: if ($1 eq 'gr') {
5500: $group = $4;
5501: $allgroups{$cid}{$group} = $env{$envkey};
5502: } else {
5503: if ($4 eq '') {
5504: $sec = 'none';
5505: } else {
5506: $sec = $4;
5507: }
5508: $allroles{$cid}{$1}{$sec} = $env{$envkey};
5509: }
1.811 albertel 5510: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 5511: my $cid = $2.'_'.$3;
5512: if ($4 eq '') {
5513: $sec = 'none';
5514: } else {
5515: $sec = $4;
5516: }
5517: $allroles{$cid}{$1}{$sec} = $env{$envkey};
5518: }
5519: }
5520: if (keys(%allroles) == 0) {
5521: return;
5522: }
5523: foreach my $key (@courses_and_groups) {
5524: my %content = %{$$access_hash{$key}};
5525: my $cnum = $content{'number'};
5526: my $cdom = $content{'domain'};
5527: my $cid = $cdom.'_'.$cnum;
5528: if (!exists($allroles{$cid})) {
5529: next;
5530: }
5531: foreach my $role_id (keys(%{$content{'roles'}})) {
5532: my @sections = @{$content{'roles'}{$role_id}{'section'}};
5533: my @groups = @{$content{'roles'}{$role_id}{'group'}};
5534: my @status = @{$content{'roles'}{$role_id}{'access'}};
5535: my @roles = @{$content{'roles'}{$role_id}{'role'}};
5536: foreach my $role (keys(%{$allroles{$cid}})) {
5537: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
5538: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
5539: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
5540: if (grep/^all$/,@sections) {
5541: return 'ok';
5542: } else {
5543: if (grep/^$sec$/,@sections) {
5544: return 'ok';
5545: }
5546: }
5547: }
5548: }
5549: if (keys(%{$allgroups{$cid}}) == 0) {
5550: if (grep/^none$/,@groups) {
5551: return 'ok';
5552: }
5553: } else {
5554: if (grep/^all$/,@groups) {
5555: return 'ok';
5556: }
5557: foreach my $group (keys(%{$allgroups{$cid}})) {
5558: if (grep/^$group$/,@groups) {
5559: return 'ok';
5560: }
5561: }
5562: }
5563: }
5564: }
5565: }
5566: }
5567: }
5568: if ($guest) {
5569: return $guest;
5570: }
5571: }
5572: }
5573: return;
5574: }
5575:
5576: sub course_group_datechecker {
5577: my ($dates,$now,$status) = @_;
5578: my ($start,$end) = split(/\./,$dates);
5579: if (!$start && !$end) {
5580: return 'ok';
5581: }
5582: if (grep/^active$/,@{$status}) {
5583: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
5584: return 'ok';
5585: }
5586: }
5587: if (grep/^previous$/,@{$status}) {
5588: if ($end > $now ) {
5589: return 'ok';
5590: }
5591: }
5592: if (grep/^future$/,@{$status}) {
5593: if ($start > $now) {
5594: return 'ok';
5595: }
5596: }
5597: return;
5598: }
5599:
5600: sub parse_portfolio_url {
5601: my ($url) = @_;
5602:
5603: my ($type,$udom,$unum,$group,$file_name);
5604:
1.823 albertel 5605: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 5606: $type = 1;
5607: $udom = $1;
5608: $unum = $2;
5609: $file_name = $3;
1.823 albertel 5610: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 5611: $type = 2;
5612: $udom = $1;
5613: $unum = $2;
5614: $group = $3;
5615: $file_name = $3.'/'.$4;
5616: }
5617: if (wantarray) {
5618: return ($type,$udom,$unum,$file_name,$group);
5619: }
5620: return $type;
5621: }
5622:
5623: sub is_portfolio_url {
5624: my ($url) = @_;
5625: return scalar(&parse_portfolio_url($url));
5626: }
5627:
1.798 raeburn 5628: sub is_portfolio_file {
5629: my ($file) = @_;
1.820 raeburn 5630: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 5631: return 1;
5632: }
5633: return;
5634: }
5635:
1.976 raeburn 5636: sub usertools_access {
1.1084 raeburn 5637: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 5638: my ($access,%tools);
5639: if ($context eq '') {
5640: $context = 'tools';
5641: }
5642: if ($context eq 'requestcourses') {
5643: %tools = (
5644: official => 1,
5645: unofficial => 1,
1.1006 raeburn 5646: community => 1,
1.985 raeburn 5647: );
5648: } else {
5649: %tools = (
5650: aboutme => 1,
5651: blog => 1,
5652: portfolio => 1,
5653: );
5654: }
1.976 raeburn 5655: return if (!defined($tools{$tool}));
5656:
5657: if ((!defined($udom)) || (!defined($uname))) {
5658: $udom = $env{'user.domain'};
5659: $uname = $env{'user.name'};
5660: }
5661:
1.978 raeburn 5662: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
5663: if ($action ne 'reload') {
1.985 raeburn 5664: if ($context eq 'requestcourses') {
5665: return $env{'environment.canrequest.'.$tool};
5666: } else {
5667: return $env{'environment.availabletools.'.$tool};
5668: }
5669: }
1.976 raeburn 5670: }
5671:
5672: my ($toolstatus,$inststatus);
5673:
1.985 raeburn 5674: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
5675: ($action ne 'reload')) {
5676: $toolstatus = $env{'environment.'.$context.'.'.$tool};
1.976 raeburn 5677: $inststatus = $env{'environment.inststatus'};
5678: } else {
1.1084 raeburn 5679: if (ref($userenvref) eq 'HASH') {
5680: $toolstatus = $userenvref->{$context.'.'.$tool};
5681: $inststatus = $userenvref->{'inststatus'};
5682: } else {
5683: my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
5684: $toolstatus = $userenv{$context.'.'.$tool};
5685: $inststatus = $userenv{'inststatus'};
5686: }
1.976 raeburn 5687: }
5688:
5689: if ($toolstatus ne '') {
5690: if ($toolstatus) {
5691: $access = 1;
5692: } else {
5693: $access = 0;
5694: }
5695: return $access;
5696: }
5697:
1.1084 raeburn 5698: my ($is_adv,%domdef);
5699: if (ref($is_advref) eq 'HASH') {
5700: $is_adv = $is_advref->{'is_adv'};
5701: } else {
5702: $is_adv = &is_advanced_user($udom,$uname);
5703: }
5704: if (ref($domdefref) eq 'HASH') {
5705: %domdef = %{$domdefref};
5706: } else {
5707: %domdef = &get_domain_defaults($udom);
5708: }
1.976 raeburn 5709: if (ref($domdef{$tool}) eq 'HASH') {
5710: if ($is_adv) {
5711: if ($domdef{$tool}{'_LC_adv'} ne '') {
5712: if ($domdef{$tool}{'_LC_adv'}) {
5713: $access = 1;
5714: } else {
5715: $access = 0;
5716: }
5717: return $access;
5718: }
5719: }
5720: if ($inststatus ne '') {
5721: my ($hasaccess,$hasnoaccess);
5722: foreach my $affiliation (split(/:/,$inststatus)) {
5723: if ($domdef{$tool}{$affiliation} ne '') {
5724: if ($domdef{$tool}{$affiliation}) {
5725: $hasaccess = 1;
5726: } else {
5727: $hasnoaccess = 1;
5728: }
5729: }
5730: }
5731: if ($hasaccess || $hasnoaccess) {
5732: if ($hasaccess) {
5733: $access = 1;
5734: } elsif ($hasnoaccess) {
5735: $access = 0;
5736: }
5737: return $access;
5738: }
5739: } else {
5740: if ($domdef{$tool}{'default'} ne '') {
5741: if ($domdef{$tool}{'default'}) {
5742: $access = 1;
5743: } elsif ($domdef{$tool}{'default'} == 0) {
5744: $access = 0;
5745: }
5746: return $access;
5747: }
5748: }
5749: } else {
1.985 raeburn 5750: if ($context eq 'tools') {
5751: $access = 1;
5752: } else {
5753: $access = 0;
5754: }
1.976 raeburn 5755: return $access;
5756: }
5757: }
5758:
1.1050 raeburn 5759: sub is_course_owner {
5760: my ($cdom,$cnum,$udom,$uname) = @_;
5761: if (($udom eq '') || ($uname eq '')) {
5762: $udom = $env{'user.domain'};
5763: $uname = $env{'user.name'};
5764: }
5765: unless (($udom eq '') || ($uname eq '')) {
5766: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
5767: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
5768: return 1;
5769: } else {
5770: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
5771: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
5772: return 1;
5773: }
5774: }
5775: }
5776: }
5777: return;
5778: }
5779:
1.976 raeburn 5780: sub is_advanced_user {
5781: my ($udom,$uname) = @_;
1.1085 raeburn 5782: if ($udom ne '' && $uname ne '') {
5783: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128 raeburn 5784: if (wantarray) {
5785: return ($env{'user.adv'},$env{'user.author'});
5786: } else {
5787: return $env{'user.adv'};
5788: }
1.1085 raeburn 5789: }
5790: }
1.976 raeburn 5791: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
5792: my %allroles;
1.1128 raeburn 5793: my ($is_adv,$is_author);
1.976 raeburn 5794: foreach my $role (keys(%roleshash)) {
5795: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
5796: my $area = '/'.$tdomain.'/'.$trest;
5797: if ($sec ne '') {
5798: $area .= '/'.$sec;
5799: }
5800: if (($area ne '') && ($trole ne '')) {
5801: my $spec=$trole.'.'.$area;
5802: if ($trole =~ /^cr\//) {
5803: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5804: } elsif ($trole ne 'gr') {
5805: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5806: }
1.1128 raeburn 5807: if ($trole eq 'au') {
5808: $is_author = 1;
5809: }
1.976 raeburn 5810: }
5811: }
5812: foreach my $role (keys(%allroles)) {
5813: last if ($is_adv);
5814: foreach my $item (split(/:/,$allroles{$role})) {
5815: if ($item ne '') {
5816: my ($privilege,$restrictions)=split(/&/,$item);
5817: if ($privilege eq 'adv') {
5818: $is_adv = 1;
5819: last;
5820: }
5821: }
5822: }
5823: }
1.1128 raeburn 5824: if (wantarray) {
5825: return ($is_adv,$is_author);
5826: }
1.976 raeburn 5827: return $is_adv;
5828: }
1.798 raeburn 5829:
1.1035 raeburn 5830: sub check_can_request {
1.1036 raeburn 5831: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 5832: my $canreq = 0;
5833: my ($types,$typename) = &Apache::loncommon::course_types();
5834: my @options = ('approval','validate','autolimit');
5835: my $optregex = join('|',@options);
5836: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
5837: foreach my $type (@{$types}) {
5838: if (&usertools_access($env{'user.name'},
5839: $env{'user.domain'},
5840: $type,undef,'requestcourses')) {
5841: $canreq ++;
1.1036 raeburn 5842: if (ref($request_domains) eq 'HASH') {
5843: push(@{$request_domains->{$type}},$env{'user.domain'});
5844: }
1.1035 raeburn 5845: if ($dom eq $env{'user.domain'}) {
5846: $can_request->{$type} = 1;
5847: }
5848: }
5849: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
5850: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
5851: if (@curr > 0) {
1.1036 raeburn 5852: foreach my $item (@curr) {
5853: if (ref($request_domains) eq 'HASH') {
5854: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
5855: if ($otherdom ne '') {
5856: if (ref($request_domains->{$type}) eq 'ARRAY') {
5857: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
5858: push(@{$request_domains->{$type}},$otherdom);
5859: }
5860: } else {
5861: push(@{$request_domains->{$type}},$otherdom);
5862: }
5863: }
5864: }
5865: }
5866: unless($dom eq $env{'user.domain'}) {
5867: $canreq ++;
1.1035 raeburn 5868: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
5869: $can_request->{$type} = 1;
5870: }
5871: }
5872: }
5873: }
5874: }
5875: }
5876: return $canreq;
5877: }
5878:
1.341 www 5879: # ---------------------------------------------- Custom access rule evaluation
5880:
5881: sub customaccess {
5882: my ($priv,$uri)=@_;
1.807 albertel 5883: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 5884: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 5885: $udom = &LONCAPA::clean_domain($udom);
5886: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 5887: my $access=0;
1.800 albertel 5888: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 5889: my ($effect,$realm,$role,$type)=split(/\:/,$right);
5890: if ($type eq 'user') {
5891: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 5892: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 5893: if ($tdom) {
5894: if ($tdom ne $env{'user.domain'}) { next; }
5895: }
1.896 albertel 5896: if ($tuname) {
5897: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 5898: }
5899: $access=($effect eq 'allow');
5900: last;
5901: }
5902: } else {
5903: if ($role) {
5904: if ($role ne $urole) { next; }
5905: }
5906: foreach my $scope (split(/\s*\,\s*/,$realm)) {
5907: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
5908: if ($tdom) {
5909: if ($tdom ne $udom) { next; }
5910: }
5911: if ($tcrs) {
5912: if ($tcrs ne $ucrs) { next; }
5913: }
5914: if ($tsec) {
5915: if ($tsec ne $usec) { next; }
5916: }
5917: $access=($effect eq 'allow');
5918: last;
5919: }
5920: if ($realm eq '' && $role eq '') {
5921: $access=($effect eq 'allow');
5922: }
1.402 bowersj2 5923: }
1.341 www 5924: }
5925: return $access;
5926: }
5927:
1.103 harris41 5928: # ------------------------------------------------- Check for a user privilege
1.12 www 5929:
5930: sub allowed {
1.810 raeburn 5931: my ($priv,$uri,$symb,$role)=@_;
1.705 albertel 5932: my $ver_orguri=$uri;
1.439 www 5933: $uri=&deversion($uri);
1.152 www 5934: my $orguri=$uri;
1.52 www 5935: $uri=&declutter($uri);
1.809 raeburn 5936:
1.810 raeburn 5937: if ($priv eq 'evb') {
5938: # Evade communication block restrictions for specified role in a course
5939: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
5940: return $1;
5941: } else {
5942: return;
5943: }
5944: }
5945:
1.620 albertel 5946: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 5947: # Free bre access to adm and meta resources
1.775 albertel 5948: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 5949: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
5950: && ($priv eq 'bre')) {
1.14 www 5951: return 'F';
1.159 www 5952: }
5953:
1.545 banghart 5954: # Free bre access to user's own portfolio contents
1.714 raeburn 5955: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 5956: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 5957: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 5958: my %setters;
5959: my ($startblock,$endblock) =
5960: &Apache::loncommon::blockcheck(\%setters,'port');
5961: if ($startblock && $endblock) {
5962: return 'B';
5963: } else {
5964: return 'F';
5965: }
1.545 banghart 5966: }
5967:
1.762 raeburn 5968: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 5969: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
5970: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
5971: if (exists($env{'request.course.id'})) {
5972: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
5973: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
5974: if (($domain eq $cdom) && ($name eq $cnum)) {
5975: my $courseprivid=$env{'request.course.id'};
5976: $courseprivid=~s/\_/\//;
5977: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
5978: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
5979: return $1;
1.762 raeburn 5980: } else {
5981: if ($env{'request.course.sec'}) {
5982: $courseprivid.='/'.$env{'request.course.sec'};
5983: }
5984: if ($env{'user.priv.'.$env{'request.role'}.'./'.
5985: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
5986: return $2;
5987: }
1.714 raeburn 5988: }
5989: }
5990: }
5991: }
5992:
1.159 www 5993: # Free bre to public access
5994:
5995: if ($priv eq 'bre') {
1.238 www 5996: my $copyright=&metadata($uri,'copyright');
1.620 albertel 5997: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 5998: return 'F';
5999: }
1.238 www 6000: if ($copyright eq 'priv') {
6001: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 6002: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 6003: return '';
6004: }
6005: }
6006: if ($copyright eq 'domain') {
6007: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 6008: unless (($env{'user.domain'} eq $1) ||
6009: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 6010: return '';
6011: }
1.262 matthew 6012: }
1.620 albertel 6013: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 6014: # Library role, so allow browsing of resources in this domain.
6015: return 'F';
1.238 www 6016: }
1.341 www 6017: if ($copyright eq 'custom') {
6018: unless (&customaccess($priv,$uri)) { return ''; }
6019: }
1.14 www 6020: }
1.264 matthew 6021: # Domain coordinator is trying to create a course
1.620 albertel 6022: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 6023: # uri is the requested domain in this case.
6024: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 6025: # a role of dc for the domain in question.
1.620 albertel 6026: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 6027: }
1.29 www 6028:
1.52 www 6029: my $thisallowed='';
6030: my $statecond=0;
6031: my $courseprivid='';
6032:
1.1039 raeburn 6033: my $ownaccess;
1.1043 raeburn 6034: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 6035: if (($priv eq 'bro') && ($env{'user.author'})) {
6036: if ($uri eq '') {
6037: $ownaccess = 1;
6038: } else {
6039: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
6040: my $udom = $env{'user.domain'};
6041: my $uname = $env{'user.name'};
6042: if ($uri =~ m{^\Q$udom\E/?$}) {
6043: $ownaccess = 1;
1.1040 raeburn 6044: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 6045: unless ($uri =~ m{\.\./}) {
6046: $ownaccess = 1;
6047: }
6048: } elsif (($udom ne 'public') && ($uname ne 'public')) {
6049: my $now = time;
6050: if ($uri =~ m{^([^/]+)/?$}) {
6051: my $adom = $1;
6052: foreach my $key (keys(%env)) {
1.1042 raeburn 6053: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 6054: my ($start,$end) = split('.',$env{$key});
6055: if (($now >= $start) && (!$end || $end < $now)) {
6056: $ownaccess = 1;
6057: last;
6058: }
6059: }
6060: }
6061: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
6062: my $adom = $1;
6063: my $aname = $2;
1.1042 raeburn 6064: foreach my $role ('ca','aa') {
6065: if ($env{"user.role.$role./$adom/$aname"}) {
6066: my ($start,$end) =
6067: split('.',$env{"user.role.$role./$adom/$aname"});
6068: if (($now >= $start) && (!$end || $end < $now)) {
6069: $ownaccess = 1;
6070: last;
6071: }
1.1039 raeburn 6072: }
6073: }
6074: }
6075: }
6076: }
6077: }
6078: }
6079:
1.52 www 6080: # Course
6081:
1.620 albertel 6082: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6083: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6084: $thisallowed.=$1;
6085: }
1.52 www 6086: }
1.29 www 6087:
1.52 www 6088: # Domain
6089:
1.620 albertel 6090: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 6091: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6092: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6093: $thisallowed.=$1;
6094: }
1.12 www 6095: }
1.52 www 6096:
1.1141 raeburn 6097: # User who is not author or co-author might still be able to edit
6098: # resource of an author in the domain (e.g., if Domain Coordinator).
6099: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
6100: (&allowed('mdc',$env{'request.course.id'}))) {
6101: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
6102: $thisallowed.=$1;
6103: }
6104: }
6105:
1.52 www 6106: # Course: uri itself is a course
1.66 www 6107: my $courseuri=$uri;
6108: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 6109: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 6110:
1.620 albertel 6111: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 6112: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6113: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6114: $thisallowed.=$1;
6115: }
1.12 www 6116: }
1.29 www 6117:
1.665 albertel 6118: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 6119: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 6120: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 6121: $thisallowed='';
1.671 raeburn 6122: my ($match)=&is_on_map($uri);
6123: if ($match) {
6124: if ($env{'user.priv.'.$env{'request.role'}.'./'}
6125: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6126: my @blockers = &has_comm_blocking($priv,$symb,$uri);
6127: if (@blockers > 0) {
6128: $thisallowed = 'B';
6129: } else {
6130: $thisallowed.=$1;
6131: }
1.671 raeburn 6132: }
6133: } else {
1.705 albertel 6134: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 6135: if ($refuri) {
6136: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 6137: $thisallowed='F';
1.671 raeburn 6138: } else {
6139: $refuri=&declutter($refuri);
6140: my ($match) = &is_on_map($refuri);
6141: if ($match) {
1.1162 raeburn 6142: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
6143: if (@blockers > 0) {
6144: $thisallowed = 'B';
6145: } else {
6146: $thisallowed='F';
6147: }
1.671 raeburn 6148: }
1.669 raeburn 6149: }
1.671 raeburn 6150: }
6151: }
1.314 www 6152: }
1.492 albertel 6153:
1.766 albertel 6154: if ($priv eq 'bre'
6155: && $thisallowed ne 'F'
6156: && $thisallowed ne '2'
6157: && &is_portfolio_url($uri)) {
6158: $thisallowed = &portfolio_access($uri);
6159: }
6160:
1.52 www 6161: # Full access at system, domain or course-wide level? Exit.
1.29 www 6162: if ($thisallowed=~/F/) {
6163: return 'F';
6164: }
6165:
1.52 www 6166: # If this is generating or modifying users, exit with special codes
1.29 www 6167:
1.643 www 6168: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
6169: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 6170: my ($audom,$auname)=split('/',$uri);
1.643 www 6171: # no author name given, so this just checks on the general right to make a co-author in this domain
6172: unless ($auname) { return $thisallowed; }
6173: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 6174: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
6175: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
6176: ($audom ne $env{'request.role.domain'}))) { return ''; }
6177: }
1.52 www 6178: return $thisallowed;
6179: }
6180: #
1.103 harris41 6181: # Gathered so far: system, domain and course wide privileges
1.52 www 6182: #
6183: # Course: See if uri or referer is an individual resource that is part of
6184: # the course
6185:
1.620 albertel 6186: if ($env{'request.course.id'}) {
1.232 www 6187:
1.620 albertel 6188: $courseprivid=$env{'request.course.id'};
6189: if ($env{'request.course.sec'}) {
6190: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 6191: }
6192: $courseprivid=~s/\_/\//;
6193: my $checkreferer=1;
1.232 www 6194: my ($match,$cond)=&is_on_map($uri);
6195: if ($match) {
6196: $statecond=$cond;
1.620 albertel 6197: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 6198: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6199: my $value = $1;
6200: if ($priv eq 'bre') {
6201: my @blockers = &has_comm_blocking($priv,$symb,$uri);
6202: if (@blockers > 0) {
6203: $thisallowed = 'B';
6204: } else {
6205: $thisallowed.=$value;
6206: }
6207: } else {
6208: $thisallowed.=$value;
6209: }
1.52 www 6210: $checkreferer=0;
6211: }
1.29 www 6212: }
1.83 www 6213:
1.148 www 6214: if ($checkreferer) {
1.620 albertel 6215: my $refuri=$env{'httpref.'.$orguri};
1.148 www 6216: unless ($refuri) {
1.800 albertel 6217: foreach my $key (keys(%env)) {
6218: if ($key=~/^httpref\..*\*/) {
6219: my $pattern=$key;
1.156 www 6220: $pattern=~s/^httpref\.\/res\///;
1.148 www 6221: $pattern=~s/\*/\[\^\/\]\+/g;
6222: $pattern=~s/\//\\\//g;
1.152 www 6223: if ($orguri=~/$pattern/) {
1.800 albertel 6224: $refuri=$env{$key};
1.148 www 6225: }
6226: }
1.191 harris41 6227: }
1.148 www 6228: }
1.232 www 6229:
1.148 www 6230: if ($refuri) {
1.152 www 6231: $refuri=&declutter($refuri);
1.232 www 6232: my ($match,$cond)=&is_on_map($refuri);
6233: if ($match) {
6234: my $refstatecond=$cond;
1.620 albertel 6235: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 6236: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6237: my $value = $1;
6238: if ($priv eq 'bre') {
6239: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
6240: if (@blockers > 0) {
6241: $thisallowed = 'B';
6242: } else {
6243: $thisallowed.=$value;
6244: }
6245: } else {
6246: $thisallowed.=$value;
6247: }
1.53 www 6248: $uri=$refuri;
6249: $statecond=$refstatecond;
1.52 www 6250: }
6251: }
1.148 www 6252: }
1.29 www 6253: }
1.52 www 6254: }
1.29 www 6255:
1.52 www 6256: #
1.103 harris41 6257: # Gathered now: all privileges that could apply, and condition number
1.52 www 6258: #
6259: #
6260: # Full or no access?
6261: #
1.29 www 6262:
1.52 www 6263: if ($thisallowed=~/F/) {
6264: return 'F';
6265: }
1.29 www 6266:
1.52 www 6267: unless ($thisallowed) {
6268: return '';
6269: }
1.29 www 6270:
1.52 www 6271: # Restrictions exist, deal with them
6272: #
6273: # C:according to course preferences
6274: # R:according to resource settings
6275: # L:unless locked
6276: # X:according to user session state
6277: #
6278:
6279: # Possibly locked functionality, check all courses
1.54 www 6280: # Locks might take effect only after 10 minutes cache expiration for other
6281: # courses, and 2 minutes for current course
1.52 www 6282:
6283: my $envkey;
6284: if ($thisallowed=~/L/) {
1.1000 raeburn 6285: foreach $envkey (keys(%env)) {
1.54 www 6286: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
6287: my $courseid=$2;
6288: my $roleid=$1.'.'.$2;
1.92 www 6289: $courseid=~s/^\///;
1.54 www 6290: my $expiretime=600;
1.620 albertel 6291: if ($env{'request.role'} eq $roleid) {
1.54 www 6292: $expiretime=120;
6293: }
6294: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
6295: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 6296: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 6297: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 6298: }
1.620 albertel 6299: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
6300: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
6301: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
6302: &log($env{'user.domain'},$env{'user.name'},
6303: $env{'user.home'},
1.57 www 6304: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 6305: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 6306: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 6307: return '';
6308: }
6309: }
1.620 albertel 6310: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
6311: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
6312: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
6313: &log($env{'user.domain'},$env{'user.name'},
6314: $env{'user.home'},
1.57 www 6315: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 6316: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 6317: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 6318: return '';
6319: }
6320: }
6321: }
1.29 www 6322: }
1.52 www 6323: }
6324:
6325: #
6326: # Rest of the restrictions depend on selected course
6327: #
6328:
1.620 albertel 6329: unless ($env{'request.course.id'}) {
1.766 albertel 6330: if ($thisallowed eq 'A') {
6331: return 'A';
1.814 raeburn 6332: } elsif ($thisallowed eq 'B') {
6333: return 'B';
1.766 albertel 6334: } else {
6335: return '1';
6336: }
1.52 www 6337: }
1.29 www 6338:
1.52 www 6339: #
6340: # Now user is definitely in a course
6341: #
1.53 www 6342:
6343:
6344: # Course preferences
6345:
6346: if ($thisallowed=~/C/) {
1.620 albertel 6347: my $rolecode=(split(/\./,$env{'request.role'}))[0];
6348: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
6349: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 6350: =~/\Q$rolecode\E/) {
1.1103 raeburn 6351: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 6352: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
6353: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
6354: $env{'request.course.id'});
6355: }
1.237 www 6356: return '';
6357: }
6358:
1.620 albertel 6359: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 6360: =~/\Q$unamedom\E/) {
1.1103 raeburn 6361: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 6362: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
6363: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
6364: $env{'request.course.id'});
6365: }
1.54 www 6366: return '';
6367: }
1.53 www 6368: }
6369:
6370: # Resource preferences
6371:
6372: if ($thisallowed=~/R/) {
1.620 albertel 6373: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 6374: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103 raeburn 6375: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 6376: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
6377: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
6378: }
6379: return '';
1.54 www 6380: }
1.53 www 6381: }
1.30 www 6382:
1.246 www 6383: # Restricted by state or randomout?
1.30 www 6384:
1.52 www 6385: if ($thisallowed=~/X/) {
1.620 albertel 6386: if ($env{'acc.randomout'}) {
1.579 albertel 6387: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 6388: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 6389: return '';
6390: }
1.247 www 6391: }
6392: if (&condval($statecond)) {
1.52 www 6393: return '2';
6394: } else {
6395: return '';
6396: }
6397: }
1.30 www 6398:
1.766 albertel 6399: if ($thisallowed eq 'A') {
6400: return 'A';
1.814 raeburn 6401: } elsif ($thisallowed eq 'B') {
6402: return 'B';
1.766 albertel 6403: }
1.52 www 6404: return 'F';
1.232 www 6405: }
1.1162 raeburn 6406:
6407: sub get_comm_blocks {
6408: my ($cdom,$cnum) = @_;
6409: if ($cdom eq '' || $cnum eq '') {
6410: return unless ($env{'request.course.id'});
6411: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6412: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6413: }
6414: my %commblocks;
6415: my $hashid=$cdom.'_'.$cnum;
6416: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
6417: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
6418: %commblocks = %{$blocksref};
6419: } else {
6420: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
6421: my $cachetime = 600;
6422: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
6423: }
6424: return %commblocks;
6425: }
6426:
6427: sub has_comm_blocking {
6428: my ($priv,$symb,$uri,$blocks) = @_;
6429: return unless ($env{'request.course.id'});
6430: return unless ($priv eq 'bre');
6431: return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
6432: my %commblocks;
6433: if (ref($blocks) eq 'HASH') {
6434: %commblocks = %{$blocks};
6435: } else {
6436: %commblocks = &get_comm_blocks();
6437: }
6438: return unless (keys(%commblocks) > 0);
6439: if (!$symb) { $symb=&symbread($uri,1); }
6440: my ($map,$resid,undef)=&decode_symb($symb);
6441: my %tocheck = (
6442: maps => $map,
6443: resources => $symb,
6444: );
6445: my @blockers;
6446: my $now = time;
1.1163 raeburn 6447: my $navmap = Apache::lonnavmaps::navmap->new();
1.1162 raeburn 6448: foreach my $block (keys(%commblocks)) {
6449: if ($block =~ /^(\d+)____(\d+)$/) {
6450: my ($start,$end) = ($1,$2);
6451: if ($start <= $now && $end >= $now) {
6452: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
6453: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
6454: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
6455: if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
6456: unless (grep(/^\Q$block\E$/,@blockers)) {
6457: push(@blockers,$block);
6458: }
6459: }
6460: }
6461: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
6462: if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
6463: unless (grep(/^\Q$block\E$/,@blockers)) {
6464: push(@blockers,$block);
6465: }
6466: }
6467: }
6468: }
6469: }
6470: }
6471: } elsif ($block =~ /^firstaccess____(.+)$/) {
6472: my $item = $1;
1.1163 raeburn 6473: my @to_test;
1.1162 raeburn 6474: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
6475: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
6476: my $check_interval;
6477: if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
6478: my @interval;
6479: my $type = 'map';
6480: if ($item eq 'course') {
6481: $type = 'course';
6482: @interval=&EXT("resource.0.interval");
6483: } else {
6484: if ($item =~ /___\d+___/) {
6485: $type = 'resource';
6486: @interval=&EXT("resource.0.interval",$item);
1.1163 raeburn 6487: if (ref($navmap)) {
6488: my $res = $navmap->getBySymb($item);
6489: push(@to_test,$res);
6490: }
1.1162 raeburn 6491: } else {
6492: my $mapsymb = &symbread($item,1);
6493: if ($mapsymb) {
6494: if (ref($navmap)) {
6495: my $mapres = $navmap->getBySymb($mapsymb);
1.1163 raeburn 6496: @to_test = $mapres->retrieveResources($mapres,undef,0,1);
6497: foreach my $res (@to_test) {
1.1162 raeburn 6498: my $symb = $res->symb();
6499: next if ($symb eq $mapsymb);
6500: if ($symb ne '') {
6501: @interval=&EXT("resource.0.interval",$symb);
6502: last;
6503: }
6504: }
6505: }
6506: }
6507: }
6508: }
6509: if ($interval[0] =~ /\d+/) {
6510: my $first_access;
6511: if ($type eq 'resource') {
6512: $first_access=&get_first_access($interval[1],$item);
6513: } elsif ($type eq 'map') {
6514: $first_access=&get_first_access($interval[1],undef,$item);
6515: } else {
6516: $first_access=&get_first_access($interval[1]);
6517: }
6518: if ($first_access) {
6519: my $timesup = $first_access+$interval[0];
6520: if ($timesup > $now) {
1.1163 raeburn 6521: foreach my $res (@to_test) {
6522: if ($res->is_problem()) {
6523: if ($res->completable()) {
6524: unless (grep(/^\Q$block\E$/,@blockers)) {
6525: push(@blockers,$block);
6526: }
6527: last;
6528: }
6529: }
1.1162 raeburn 6530: }
6531: }
6532: }
6533: }
6534: }
6535: }
6536: }
6537: }
6538: }
6539: return @blockers;
6540: }
6541:
6542: sub check_docs_block {
6543: my ($docsblock,$tocheck) =@_;
6544: if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
6545: return;
6546: }
6547: if (ref($docsblock->{'maps'}) eq 'HASH') {
6548: if ($tocheck->{'maps'}) {
6549: if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
6550: return 1;
6551: }
6552: }
6553: }
6554: if (ref($docsblock->{'resources'}) eq 'HASH') {
6555: if ($tocheck->{'resources'}) {
6556: if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
6557: return 1;
6558: }
6559: }
6560: }
6561: return;
6562: }
6563:
1.1133 foxr 6564: #
6565: # Removes the versino from a URI and
6566: # splits it in to its filename and path to the filename.
6567: # Seems like File::Basename could have done this more clearly.
6568: # Parameters:
6569: # $uri - input URI
6570: # Returns:
6571: # Two element list consisting of
6572: # $pathname - the URI up to and excluding the trailing /
6573: # $filename - The part of the URI following the last /
6574: # NOTE:
6575: # Another realization of this is simply:
6576: # use File::Basename;
6577: # ...
6578: # $uri = shift;
6579: # $filename = basename($uri);
6580: # $path = dirname($uri);
6581: # return ($filename, $path);
6582: #
6583: # The implementation below is probably faster however.
6584: #
1.710 albertel 6585: sub split_uri_for_cond {
6586: my $uri=&deversion(&declutter(shift));
6587: my @uriparts=split(/\//,$uri);
6588: my $filename=pop(@uriparts);
6589: my $pathname=join('/',@uriparts);
6590: return ($pathname,$filename);
6591: }
1.232 www 6592: # --------------------------------------------------- Is a resource on the map?
6593:
6594: sub is_on_map {
1.710 albertel 6595: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 6596: #Trying to find the conditional for the file
1.620 albertel 6597: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 6598: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 6599: if ($match) {
1.289 bowersj2 6600: return (1,$1);
6601: } else {
1.434 www 6602: return (0,0);
1.289 bowersj2 6603: }
1.12 www 6604: }
6605:
1.427 www 6606: # --------------------------------------------------------- Get symb from alias
6607:
6608: sub get_symb_from_alias {
6609: my $symb=shift;
6610: my ($map,$resid,$url)=&decode_symb($symb);
6611: # Already is a symb
6612: if ($url) { return $symb; }
6613: # Must be an alias
6614: my $aliassymb='';
6615: my %bighash;
1.620 albertel 6616: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 6617: &GDBM_READER(),0640)) {
6618: my $rid=$bighash{'mapalias_'.$symb};
6619: if ($rid) {
6620: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 6621: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
6622: $resid,$bighash{'src_'.$rid});
1.427 www 6623: }
6624: untie %bighash;
6625: }
6626: return $aliassymb;
6627: }
6628:
1.12 www 6629: # ----------------------------------------------------------------- Define Role
6630:
6631: sub definerole {
6632: if (allowed('mcr','/')) {
6633: my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800 albertel 6634: foreach my $role (split(':',$sysrole)) {
6635: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 6636: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
6637: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
6638: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 6639: return "refused:s:$crole&$cqual";
6640: }
6641: }
1.191 harris41 6642: }
1.800 albertel 6643: foreach my $role (split(':',$domrole)) {
6644: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 6645: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
6646: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
6647: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 6648: return "refused:d:$crole&$cqual";
6649: }
6650: }
1.191 harris41 6651: }
1.800 albertel 6652: foreach my $role (split(':',$courole)) {
6653: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 6654: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
6655: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
6656: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 6657: return "refused:c:$crole&$cqual";
6658: }
6659: }
1.191 harris41 6660: }
1.620 albertel 6661: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
6662: "$env{'user.domain'}:$env{'user.name'}:".
1.21 www 6663: "rolesdef_$rolename=".
6664: escape($sysrole.'_'.$domrole.'_'.$courole);
1.620 albertel 6665: return reply($command,$env{'user.home'});
1.12 www 6666: } else {
6667: return 'refused';
6668: }
1.105 harris41 6669: }
6670:
6671: # ---------------- Make a metadata query against the network of library servers
6672:
6673: sub metadata_query {
1.244 matthew 6674: my ($query,$custom,$customshow,$server_array)=@_;
1.120 harris41 6675: my %rhash;
1.845 albertel 6676: my %libserv = &all_library();
1.244 matthew 6677: my @server_list = (defined($server_array) ? @$server_array
6678: : keys(%libserv) );
6679: for my $server (@server_list) {
1.118 harris41 6680: unless ($custom or $customshow) {
6681: my $reply=&reply("querysend:".&escape($query),$server);
6682: $rhash{$server}=$reply;
6683: }
6684: else {
6685: my $reply=&reply("querysend:".&escape($query).':'.
6686: &escape($custom).':'.&escape($customshow),
6687: $server);
6688: $rhash{$server}=$reply;
6689: }
1.112 harris41 6690: }
1.118 harris41 6691: return \%rhash;
1.240 www 6692: }
6693:
6694: # ----------------------------------------- Send log queries and wait for reply
6695:
6696: sub log_query {
6697: my ($uname,$udom,$query,%filters)=@_;
6698: my $uhome=&homeserver($uname,$udom);
6699: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 6700: my $uhost=&hostname($uhome);
1.800 albertel 6701: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 6702: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
6703: $uhome);
1.479 albertel 6704: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 6705: return get_query_reply($queryid);
6706: }
6707:
1.818 raeburn 6708: # -------------------------- Update MySQL table for portfolio file
6709:
6710: sub update_portfolio_table {
1.821 raeburn 6711: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 6712: if ($group ne '') {
6713: $file_name =~s /^\Q$group\E//;
6714: }
1.818 raeburn 6715: my $homeserver = &homeserver($uname,$udom);
6716: my $queryid=
1.821 raeburn 6717: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
6718: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 6719: my $reply = &get_query_reply($queryid);
6720: return $reply;
6721: }
6722:
1.899 raeburn 6723: # -------------------------- Update MySQL allusers table
6724:
6725: sub update_allusers_table {
6726: my ($uname,$udom,$names) = @_;
6727: my $homeserver = &homeserver($uname,$udom);
6728: my $queryid=
6729: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
6730: 'lastname='.&escape($names->{'lastname'}).'%%'.
6731: 'firstname='.&escape($names->{'firstname'}).'%%'.
6732: 'middlename='.&escape($names->{'middlename'}).'%%'.
6733: 'generation='.&escape($names->{'generation'}).'%%'.
6734: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
6735: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 6736: return;
1.899 raeburn 6737: }
6738:
1.508 raeburn 6739: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 6740:
6741: sub fetch_enrollment_query {
1.511 raeburn 6742: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508 raeburn 6743: my $homeserver;
1.547 raeburn 6744: my $maxtries = 1;
1.508 raeburn 6745: if ($context eq 'automated') {
6746: $homeserver = $perlvar{'lonHostID'};
1.547 raeburn 6747: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 6748: } else {
6749: $homeserver = &homeserver($cnum,$dom);
6750: }
1.838 albertel 6751: my $host=&hostname($homeserver);
1.506 raeburn 6752: my $cmd = '';
1.1000 raeburn 6753: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 6754: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 6755: }
6756: $cmd =~ s/%%$//;
6757: $cmd = &escape($cmd);
6758: my $query = 'fetchenrollment';
1.620 albertel 6759: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 6760: unless ($queryid=~/^\Q$host\E\_/) {
6761: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
6762: return 'error: '.$queryid;
6763: }
1.506 raeburn 6764: my $reply = &get_query_reply($queryid);
1.547 raeburn 6765: my $tries = 1;
6766: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
6767: $reply = &get_query_reply($queryid);
6768: $tries ++;
6769: }
1.526 raeburn 6770: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 6771: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 6772: } else {
1.901 albertel 6773: my @responses = split(/:/,$reply);
1.515 raeburn 6774: if ($homeserver eq $perlvar{'lonHostID'}) {
1.800 albertel 6775: foreach my $line (@responses) {
6776: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 6777: $$replyref{$key} = $value;
6778: }
6779: } else {
1.1117 foxr 6780: my $pathname = LONCAPA::tempdir();
1.800 albertel 6781: foreach my $line (@responses) {
6782: my ($key,$value) = split(/=/,$line);
1.506 raeburn 6783: $$replyref{$key} = $value;
6784: if ($value > 0) {
1.800 albertel 6785: foreach my $item (@{$$affiliatesref{$key}}) {
6786: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 6787: my $destname = $pathname.'/'.$filename;
6788: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 6789: if ($xml_classlist =~ /^error/) {
6790: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
6791: } else {
1.506 raeburn 6792: if ( open(FILE,">$destname") ) {
6793: print FILE &unescape($xml_classlist);
6794: close(FILE);
1.526 raeburn 6795: } else {
6796: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 6797: }
6798: }
6799: }
6800: }
6801: }
6802: }
6803: return 'ok';
6804: }
6805: return 'error';
6806: }
6807:
1.242 www 6808: sub get_query_reply {
6809: my $queryid=shift;
1.1117 foxr 6810: my $replyfile=LONCAPA::tempdir().$queryid;
1.240 www 6811: my $reply='';
6812: for (1..100) {
6813: sleep 2;
6814: if (-e $replyfile.'.end') {
1.448 albertel 6815: if (open(my $fh,$replyfile)) {
1.904 albertel 6816: $reply = join('',<$fh>);
6817: close($fh);
1.240 www 6818: } else { return 'error: reply_file_error'; }
1.242 www 6819: return &unescape($reply);
6820: }
1.240 www 6821: }
1.242 www 6822: return 'timeout:'.$queryid;
1.240 www 6823: }
6824:
6825: sub courselog_query {
1.241 www 6826: #
6827: # possible filters:
6828: # url: url or symb
6829: # username
6830: # domain
6831: # action: view, submit, grade
6832: # start: timestamp
6833: # end: timestamp
6834: #
1.240 www 6835: my (%filters)=@_;
1.620 albertel 6836: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 6837: if ($filters{'url'}) {
6838: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
6839: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
6840: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
6841: }
1.620 albertel 6842: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
6843: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 6844: return &log_query($cname,$cdom,'courselog',%filters);
6845: }
6846:
6847: sub userlog_query {
1.858 raeburn 6848: #
6849: # possible filters:
6850: # action: log check role
6851: # start: timestamp
6852: # end: timestamp
6853: #
1.240 www 6854: my ($uname,$udom,%filters)=@_;
6855: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 6856: }
6857:
1.506 raeburn 6858: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
6859:
6860: sub auto_run {
1.508 raeburn 6861: my ($cnum,$cdom) = @_;
1.876 raeburn 6862: my $response = 0;
6863: my $settings;
6864: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
6865: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
6866: $settings = $domconfig{'autoenroll'};
6867: if ($settings->{'run'} eq '1') {
6868: $response = 1;
6869: }
6870: } else {
1.934 raeburn 6871: my $homeserver;
6872: if (&is_course($cdom,$cnum)) {
6873: $homeserver = &homeserver($cnum,$cdom);
6874: } else {
6875: $homeserver = &domain($cdom,'primary');
6876: }
6877: if ($homeserver ne 'no_host') {
6878: $response = &reply('autorun:'.$cdom,$homeserver);
6879: }
1.876 raeburn 6880: }
1.506 raeburn 6881: return $response;
6882: }
1.776 albertel 6883:
1.506 raeburn 6884: sub auto_get_sections {
1.508 raeburn 6885: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 6886: my $homeserver;
6887: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6888: $homeserver = &homeserver($cnum,$cdom);
6889: }
6890: if (!defined($homeserver)) {
6891: if ($cdom =~ /^$match_domain$/) {
6892: $homeserver = &domain($cdom,'primary');
6893: }
6894: }
6895: my @secs;
6896: if (defined($homeserver)) {
6897: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
6898: unless ($response eq 'refused') {
6899: @secs = split(/:/,$response);
6900: }
1.506 raeburn 6901: }
6902: return @secs;
6903: }
1.776 albertel 6904:
1.506 raeburn 6905: sub auto_new_course {
1.1099 raeburn 6906: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 6907: my $homeserver = &homeserver($cnum,$cdom);
1.1099 raeburn 6908: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 6909: return $response;
6910: }
1.776 albertel 6911:
1.506 raeburn 6912: sub auto_validate_courseID {
1.508 raeburn 6913: my ($cnum,$cdom,$inst_course_id) = @_;
6914: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 6915: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 6916: return $response;
6917: }
1.776 albertel 6918:
1.1007 raeburn 6919: sub auto_validate_instcode {
1.1020 raeburn 6920: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 6921: my ($homeserver,$response);
6922: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6923: $homeserver = &homeserver($cnum,$cdom);
6924: }
6925: if (!defined($homeserver)) {
6926: if ($cdom =~ /^$match_domain$/) {
6927: $homeserver = &domain($cdom,'primary');
6928: }
6929: }
1.1065 raeburn 6930: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
6931: &escape($instcode).':'.&escape($owner),$homeserver));
1.1027 raeburn 6932: my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
6933: return ($outcome,$description);
1.1007 raeburn 6934: }
6935:
1.506 raeburn 6936: sub auto_create_password {
1.873 raeburn 6937: my ($cnum,$cdom,$authparam,$udom) = @_;
6938: my ($homeserver,$response);
1.506 raeburn 6939: my $create_passwd = 0;
6940: my $authchk = '';
1.873 raeburn 6941: if ($udom =~ /^$match_domain$/) {
6942: $homeserver = &domain($udom,'primary');
6943: }
6944: if ($homeserver eq '') {
6945: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6946: $homeserver = &homeserver($cnum,$cdom);
6947: }
6948: }
6949: if ($homeserver eq '') {
6950: $authchk = 'nodomain';
1.506 raeburn 6951: } else {
1.873 raeburn 6952: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
6953: if ($response eq 'refused') {
6954: $authchk = 'refused';
6955: } else {
1.901 albertel 6956: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 6957: }
1.506 raeburn 6958: }
6959: return ($authparam,$create_passwd,$authchk);
6960: }
6961:
1.706 raeburn 6962: sub auto_photo_permission {
6963: my ($cnum,$cdom,$students) = @_;
6964: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 6965: my ($outcome,$perm_reqd,$conditions) =
6966: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 6967: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6968: return (undef,undef);
6969: }
1.706 raeburn 6970: return ($outcome,$perm_reqd,$conditions);
6971: }
6972:
6973: sub auto_checkphotos {
6974: my ($uname,$udom,$pid) = @_;
6975: my $homeserver = &homeserver($uname,$udom);
6976: my ($result,$resulttype);
6977: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 6978: &escape($uname).':'.&escape($pid),
6979: $homeserver));
1.709 albertel 6980: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6981: return (undef,undef);
6982: }
1.706 raeburn 6983: if ($outcome) {
6984: ($result,$resulttype) = split(/:/,$outcome);
6985: }
6986: return ($result,$resulttype);
6987: }
6988:
6989: sub auto_photochoice {
6990: my ($cnum,$cdom) = @_;
6991: my $homeserver = &homeserver($cnum,$cdom);
6992: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 6993: &escape($cdom),
6994: $homeserver)));
1.709 albertel 6995: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6996: return (undef,undef);
6997: }
1.706 raeburn 6998: return ($update,$comment);
6999: }
7000:
7001: sub auto_photoupdate {
7002: my ($affiliatesref,$dom,$cnum,$photo) = @_;
7003: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 7004: my $host=&hostname($homeserver);
1.706 raeburn 7005: my $cmd = '';
7006: my $maxtries = 1;
1.800 albertel 7007: foreach my $affiliate (keys(%{$affiliatesref})) {
7008: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 7009: }
7010: $cmd =~ s/%%$//;
7011: $cmd = &escape($cmd);
7012: my $query = 'institutionalphotos';
7013: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
7014: unless ($queryid=~/^\Q$host\E\_/) {
7015: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
7016: return 'error: '.$queryid;
7017: }
7018: my $reply = &get_query_reply($queryid);
7019: my $tries = 1;
7020: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
7021: $reply = &get_query_reply($queryid);
7022: $tries ++;
7023: }
7024: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
7025: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
7026: } else {
7027: my @responses = split(/:/,$reply);
7028: my $outcome = shift(@responses);
7029: foreach my $item (@responses) {
7030: my ($key,$value) = split(/=/,$item);
7031: $$photo{$key} = $value;
7032: }
7033: return $outcome;
7034: }
7035: return 'error';
7036: }
7037:
1.521 raeburn 7038: sub auto_instcode_format {
1.793 albertel 7039: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
7040: $cat_order) = @_;
1.521 raeburn 7041: my $courses = '';
1.772 raeburn 7042: my @homeservers;
1.521 raeburn 7043: if ($caller eq 'global') {
1.841 albertel 7044: my %servers = &get_servers($codedom,'library');
7045: foreach my $tryserver (keys(%servers)) {
7046: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7047: push(@homeservers,$tryserver);
7048: }
1.584 raeburn 7049: }
1.1022 raeburn 7050: } elsif ($caller eq 'requests') {
7051: if ($codedom =~ /^$match_domain$/) {
7052: my $chome = &domain($codedom,'primary');
7053: unless ($chome eq 'no_host') {
7054: push(@homeservers,$chome);
7055: }
7056: }
1.521 raeburn 7057: } else {
1.772 raeburn 7058: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 7059: }
1.793 albertel 7060: foreach my $code (keys(%{$instcodes})) {
7061: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 7062: }
7063: chop($courses);
1.772 raeburn 7064: my $ok_response = 0;
7065: my $response;
7066: while (@homeservers > 0 && $ok_response == 0) {
7067: my $server = shift(@homeservers);
7068: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
7069: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
7070: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 7071: split(/:/,$response);
1.772 raeburn 7072: %{$codes} = (%{$codes},&str2hash($codes_str));
7073: push(@{$codetitles},&str2array($codetitles_str));
7074: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
7075: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
7076: $ok_response = 1;
7077: }
7078: }
7079: if ($ok_response) {
1.521 raeburn 7080: return 'ok';
1.772 raeburn 7081: } else {
7082: return $response;
1.521 raeburn 7083: }
7084: }
7085:
1.792 raeburn 7086: sub auto_instcode_defaults {
7087: my ($domain,$returnhash,$code_order) = @_;
7088: my @homeservers;
1.841 albertel 7089:
7090: my %servers = &get_servers($domain,'library');
7091: foreach my $tryserver (keys(%servers)) {
7092: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7093: push(@homeservers,$tryserver);
7094: }
1.792 raeburn 7095: }
1.841 albertel 7096:
1.792 raeburn 7097: my $response;
1.841 albertel 7098: foreach my $server (@homeservers) {
1.792 raeburn 7099: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 7100: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
7101:
7102: foreach my $pair (split(/\&/,$response)) {
7103: my ($name,$value)=split(/\=/,$pair);
7104: if ($name eq 'code_order') {
7105: @{$code_order} = split(/\&/,&unescape($value));
7106: } else {
7107: $returnhash->{&unescape($name)}=&unescape($value);
7108: }
7109: }
7110: return 'ok';
1.792 raeburn 7111: }
1.841 albertel 7112:
7113: return $response;
1.1003 raeburn 7114: }
7115:
7116: sub auto_possible_instcodes {
1.1007 raeburn 7117: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
7118: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
7119: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
7120: return;
7121: }
1.1003 raeburn 7122: my (@homeservers,$uhome);
7123: if (defined(&domain($domain,'primary'))) {
7124: $uhome=&domain($domain,'primary');
7125: push(@homeservers,&domain($domain,'primary'));
7126: } else {
7127: my %servers = &get_servers($domain,'library');
7128: foreach my $tryserver (keys(%servers)) {
7129: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7130: push(@homeservers,$tryserver);
7131: }
7132: }
7133: }
7134: my $response;
7135: foreach my $server (@homeservers) {
7136: $response=&reply('autopossibleinstcodes:'.$domain,$server);
7137: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 7138: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
7139: split(':',$response);
7140: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
7141: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 7142: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 7143: my ($name,$value)=split('=',$item);
7144: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 7145: }
7146: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 7147: my ($name,$value)=split('=',$item);
7148: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 7149: }
7150: return 'ok';
7151: }
7152: return $response;
7153: }
1.792 raeburn 7154:
1.1010 raeburn 7155: sub auto_courserequest_checks {
7156: my ($dom) = @_;
1.1020 raeburn 7157: my ($homeserver,%validations);
7158: if ($dom =~ /^$match_domain$/) {
7159: $homeserver = &domain($dom,'primary');
7160: }
7161: unless ($homeserver eq 'no_host') {
7162: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
7163: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
7164: my @items = split(/&/,$response);
7165: foreach my $item (@items) {
7166: my ($key,$value) = split('=',$item);
7167: $validations{&unescape($key)} = &thaw_unescape($value);
7168: }
7169: }
7170: }
1.1010 raeburn 7171: return %validations;
7172: }
7173:
1.1020 raeburn 7174: sub auto_courserequest_validation {
7175: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
7176: my ($homeserver,$response);
7177: if ($dom =~ /^$match_domain$/) {
7178: $homeserver = &domain($dom,'primary');
7179: }
7180: unless ($homeserver eq 'no_host') {
1.1021 raeburn 7181:
1.1020 raeburn 7182: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 7183: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020 raeburn 7184: ':'.&escape($instcode).':'.&escape($instseclist),
7185: $homeserver));
7186: }
7187: return $response;
7188: }
7189:
1.777 albertel 7190: sub auto_validate_class_sec {
1.918 raeburn 7191: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 7192: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 7193: my $ownerlist;
7194: if (ref($owners) eq 'ARRAY') {
7195: $ownerlist = join(',',@{$owners});
7196: } else {
7197: $ownerlist = $owners;
7198: }
1.773 raeburn 7199: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 7200: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 7201: return $response;
7202: }
7203:
1.679 raeburn 7204: # ------------------------------------------------------- Course Group routines
7205:
7206: sub get_coursegroups {
1.809 raeburn 7207: my ($cdom,$cnum,$group,$namespace) = @_;
7208: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 7209: }
7210:
1.679 raeburn 7211: sub modify_coursegroup {
7212: my ($cdom,$cnum,$groupsettings) = @_;
7213: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
7214: }
7215:
1.809 raeburn 7216: sub toggle_coursegroup_status {
7217: my ($cdom,$cnum,$group,$action) = @_;
7218: my ($from_namespace,$to_namespace);
7219: if ($action eq 'delete') {
7220: $from_namespace = 'coursegroups';
7221: $to_namespace = 'deleted_groups';
7222: } else {
7223: $from_namespace = 'deleted_groups';
7224: $to_namespace = 'coursegroups';
7225: }
7226: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 7227: if (my $tmp = &error(%curr_group)) {
7228: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
7229: return ('read error',$tmp);
7230: } else {
7231: my %savedsettings = %curr_group;
1.809 raeburn 7232: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 7233: my $deloutcome;
7234: if ($result eq 'ok') {
1.809 raeburn 7235: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 7236: } else {
7237: return ('write error',$result);
7238: }
7239: if ($deloutcome eq 'ok') {
7240: return 'ok';
7241: } else {
7242: return ('delete error',$deloutcome);
7243: }
7244: }
7245: }
7246:
1.679 raeburn 7247: sub modify_group_roles {
1.957 raeburn 7248: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 7249: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
7250: my $role = 'gr/'.&escape($userprivs);
7251: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 7252: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 7253: if ($result eq 'ok') {
7254: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
7255: }
1.679 raeburn 7256: return $result;
7257: }
7258:
7259: sub modify_coursegroup_membership {
7260: my ($cdom,$cnum,$membership) = @_;
7261: my $result = &put('groupmembership',$membership,$cdom,$cnum);
7262: return $result;
7263: }
7264:
1.682 raeburn 7265: sub get_active_groups {
7266: my ($udom,$uname,$cdom,$cnum) = @_;
7267: my $now = time;
7268: my %groups = ();
7269: foreach my $key (keys(%env)) {
1.811 albertel 7270: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 7271: my ($start,$end) = split(/\./,$env{$key});
7272: if (($end!=0) && ($end<$now)) { next; }
7273: if (($start!=0) && ($start>$now)) { next; }
7274: if ($1 eq $cdom && $2 eq $cnum) {
7275: $groups{$3} = $env{$key} ;
7276: }
7277: }
7278: }
7279: return %groups;
7280: }
7281:
1.683 raeburn 7282: sub get_group_membership {
7283: my ($cdom,$cnum,$group) = @_;
7284: return(&dump('groupmembership',$cdom,$cnum,$group));
7285: }
7286:
7287: sub get_users_groups {
7288: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 7289: my @usersgroups;
1.683 raeburn 7290: my $cachetime=1800;
7291:
7292: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 7293: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
7294: if (defined($cached)) {
1.734 albertel 7295: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 7296: } else {
7297: $grouplist = '';
1.816 raeburn 7298: my $courseurl = &courseid_to_courseurl($courseid);
1.1166 raeburn 7299: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 7300: my $access_end = $env{'course.'.$courseid.
7301: '.default_enrollment_end_date'};
7302: my $now = time;
7303: foreach my $key (keys(%roleshash)) {
7304: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
7305: my $group = $1;
7306: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
7307: my $start = $2;
7308: my $end = $1;
7309: if ($start == -1) { next; } # deleted from group
7310: if (($start!=0) && ($start>$now)) { next; }
7311: if (($end!=0) && ($end<$now)) {
7312: if ($access_end && $access_end < $now) {
7313: if ($access_end - $end < 86400) {
7314: push(@usersgroups,$group);
1.733 raeburn 7315: }
7316: }
1.817 raeburn 7317: next;
1.733 raeburn 7318: }
1.817 raeburn 7319: push(@usersgroups,$group);
1.683 raeburn 7320: }
7321: }
7322: }
1.817 raeburn 7323: @usersgroups = &sort_course_groups($courseid,@usersgroups);
7324: $grouplist = join(':',@usersgroups);
7325: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 7326: }
1.733 raeburn 7327: return @usersgroups;
1.683 raeburn 7328: }
7329:
7330: sub devalidate_getgroups_cache {
7331: my ($udom,$uname,$cdom,$cnum)=@_;
7332: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 7333:
1.683 raeburn 7334: my $hashid="$udom:$uname:$courseid";
7335: &devalidate_cache_new('getgroups',$hashid);
7336: }
7337:
1.12 www 7338: # ------------------------------------------------------------------ Plain Text
7339:
7340: sub plaintext {
1.988 raeburn 7341: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 7342: if ($short =~ m{^cr/}) {
1.758 albertel 7343: return (split('/',$short))[-1];
7344: }
1.742 raeburn 7345: if (!defined($cid)) {
7346: $cid = $env{'request.course.id'};
7347: }
7348: my %rolenames = (
1.1008 raeburn 7349: Course => 'std',
7350: Community => 'alt1',
1.742 raeburn 7351: );
1.1037 raeburn 7352: if ($cid ne '') {
7353: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
7354: unless ($forcedefault) {
7355: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
7356: &Apache::lonlocal::mt_escape(\$roletext);
7357: return &Apache::lonlocal::mt($roletext);
7358: }
7359: }
7360: }
7361: if ((defined($type)) && (defined($rolenames{$type})) &&
7362: (defined($rolenames{$type})) &&
7363: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 7364: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 7365: } elsif ($cid ne '') {
7366: my $crstype = $env{'course.'.$cid.'.type'};
7367: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
7368: (defined($prp{$short}{$rolenames{$crstype}}))) {
7369: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
7370: }
1.742 raeburn 7371: }
1.1037 raeburn 7372: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 7373: }
7374:
7375: # ----------------------------------------------------------------- Assign Role
7376:
7377: sub assignrole {
1.957 raeburn 7378: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
7379: $context)=@_;
1.21 www 7380: my $mrole;
7381: if ($role =~ /^cr\//) {
1.393 www 7382: my $cwosec=$url;
1.811 albertel 7383: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 7384: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 7385: my $refused = 1;
7386: if ($context eq 'requestcourses') {
7387: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
7388: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
7389: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
7390: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
7391: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
7392: if ($crsenv{'internal.courseowner'} eq
7393: $env{'user.name'}.':'.$env{'user.domain'}) {
7394: $refused = '';
7395: }
7396: }
7397: }
7398: }
7399: }
7400: if ($refused) {
7401: &logthis('Refused custom assignrole: '.
7402: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
7403: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
7404: return 'refused';
7405: }
1.104 www 7406: }
1.21 www 7407: $mrole='cr';
1.678 raeburn 7408: } elsif ($role =~ /^gr\//) {
7409: my $cwogrp=$url;
1.811 albertel 7410: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 7411: unless (&allowed('mdg',$cwogrp)) {
7412: &logthis('Refused group assignrole: '.
7413: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
7414: $env{'user.name'}.' at '.$env{'user.domain'});
7415: return 'refused';
7416: }
7417: $mrole='gr';
1.21 www 7418: } else {
1.82 www 7419: my $cwosec=$url;
1.811 albertel 7420: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 7421: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
7422: my $refused;
7423: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
7424: if (!(&allowed('c'.$role,$url))) {
7425: $refused = 1;
7426: }
7427: } else {
7428: $refused = 1;
7429: }
1.947 raeburn 7430: if ($refused) {
1.1045 raeburn 7431: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
7432: if (!$selfenroll && $context eq 'course') {
7433: my %crsenv;
7434: if ($role eq 'cc' || $role eq 'co') {
7435: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
7436: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
7437: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
7438: if ($crsenv{'internal.courseowner'} eq
7439: $env{'user.name'}.':'.$env{'user.domain'}) {
7440: $refused = '';
7441: }
7442: }
7443: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
7444: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
7445: if ($crsenv{'internal.courseowner'} eq
7446: $env{'user.name'}.':'.$env{'user.domain'}) {
7447: $refused = '';
7448: }
7449: }
7450: }
7451: }
7452: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 7453: $refused = '';
1.1017 raeburn 7454: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 7455: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 7456: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 7457: my $wrongcc;
7458: if ($cnum =~ /^$match_community$/) {
7459: $wrongcc = 1 if ($role eq 'cc');
7460: } else {
7461: $wrongcc = 1 if ($role eq 'co');
7462: }
7463: unless ($wrongcc) {
7464: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
7465: if ($crsenv{'internal.courseowner'} eq
7466: $env{'user.name'}.':'.$env{'user.domain'}) {
7467: $refused = '';
7468: }
1.1017 raeburn 7469: }
7470: }
7471: }
7472: if ($refused) {
1.947 raeburn 7473: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
7474: ' '.$role.' '.$end.' '.$start.' by '.
7475: $env{'user.name'}.' at '.$env{'user.domain'});
7476: return 'refused';
7477: }
1.932 raeburn 7478: }
1.1131 raeburn 7479: } elsif ($role eq 'au') {
7480: if ($url ne '/'.$udom.'/') {
7481: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
7482: ' to assign author role for '.$uname.':'.$udom.
7483: ' in domain: '.$url.' refused (wrong domain).');
7484: return 'refused';
7485: }
1.104 www 7486: }
1.21 www 7487: $mrole=$role;
7488: }
1.620 albertel 7489: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 7490: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 7491: if ($end) { $command.='_'.$end; }
1.21 www 7492: if ($start) {
7493: if ($end) {
1.81 www 7494: $command.='_'.$start;
1.21 www 7495: } else {
1.81 www 7496: $command.='_0_'.$start;
1.21 www 7497: }
7498: }
1.739 raeburn 7499: my $origstart = $start;
7500: my $origend = $end;
1.957 raeburn 7501: my $delflag;
1.357 www 7502: # actually delete
7503: if ($deleteflag) {
1.373 www 7504: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 7505: # modify command to delete the role
1.620 albertel 7506: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 7507: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 7508: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 7509: # set start and finish to negative values for userrolelog
7510: $start=-1;
7511: $end=-1;
1.957 raeburn 7512: $delflag = 1;
1.357 www 7513: }
7514: }
7515: # send command
1.349 www 7516: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 7517: # log new user role if status is ok
1.349 www 7518: if ($answer eq 'ok') {
1.663 raeburn 7519: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.739 raeburn 7520: # for course roles, perform group memberships changes triggered by role change.
1.957 raeburn 7521: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739 raeburn 7522: unless ($role =~ /^gr/) {
7523: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957 raeburn 7524: $origstart,$selfenroll,$context);
1.739 raeburn 7525: }
1.1053 raeburn 7526: if ($role eq 'cc') {
7527: &autoupdate_coowners($url,$end,$start,$uname,$udom);
7528: }
1.349 www 7529: }
7530: return $answer;
1.169 harris41 7531: }
7532:
1.1053 raeburn 7533: sub autoupdate_coowners {
7534: my ($url,$end,$start,$uname,$udom) = @_;
7535: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
7536: if (($cdom ne '') && ($cnum ne '')) {
7537: my $now = time;
7538: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
7539: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
7540: my %coursehash = &coursedescription($cdom.'_'.$cnum);
7541: my $instcode = $coursehash{'internal.coursecode'};
7542: if ($instcode ne '') {
1.1056 raeburn 7543: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
7544: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 7545: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 7546: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
7547: if ($result eq 'valid') {
7548: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 7549: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
7550: push(@newcoowners,$coowner);
7551: }
7552: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
7553: push(@newcoowners,$uname.':'.$udom);
7554: }
7555: @newcoowners = sort(@newcoowners);
7556: } else {
7557: push(@newcoowners,$uname.':'.$udom);
7558: }
7559: } else {
7560: if ($coursehash{'internal.co-owners'}) {
7561: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
7562: unless ($coowner eq $uname.':'.$udom) {
7563: push(@newcoowners,$coowner);
7564: }
7565: }
7566: unless (@newcoowners > 0) {
7567: $delcoowners = 1;
7568: $coowners = '';
7569: }
7570: }
7571: }
7572: if (@newcoowners || $delcoowners) {
7573: &store_coowners($cdom,$cnum,$coursehash{'home'},
7574: $delcoowners,@newcoowners);
7575: }
7576: }
7577: }
7578: }
7579: }
7580: }
7581: }
7582:
7583: sub store_coowners {
7584: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
7585: my $cid = $cdom.'_'.$cnum;
7586: my ($coowners,$delresult,$putresult);
7587: if (@newcoowners) {
7588: $coowners = join(',',@newcoowners);
7589: my %coownershash = (
7590: 'internal.co-owners' => $coowners,
7591: );
7592: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
7593: if ($putresult eq 'ok') {
7594: if ($env{'course.'.$cid.'.num'} eq $cnum) {
7595: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
7596: }
7597: }
7598: }
7599: if ($delcoowners) {
7600: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
7601: if ($delresult eq 'ok') {
7602: if ($env{'course.'.$cid.'.internal.co-owners'}) {
7603: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
7604: }
7605: }
7606: }
7607: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
7608: my %crsinfo =
7609: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
7610: if (ref($crsinfo{$cid}) eq 'HASH') {
7611: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
7612: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
7613: }
7614: }
7615: }
7616:
1.169 harris41 7617: # -------------------------------------------------- Modify user authentication
1.197 www 7618: # Overrides without validation
7619:
1.169 harris41 7620: sub modifyuserauth {
7621: my ($udom,$uname,$umode,$upass)=@_;
7622: my $uhome=&homeserver($uname,$udom);
1.197 www 7623: unless (&allowed('mau',$udom)) { return 'refused'; }
7624: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 7625: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
7626: ' in domain '.$env{'request.role.domain'});
1.169 harris41 7627: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
7628: &escape($upass),$uhome);
1.620 albertel 7629: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 7630: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
7631: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
7632: &log($udom,,$uname,$uhome,
1.620 albertel 7633: 'Authentication changed by '.$env{'user.domain'}.', '.
7634: $env{'user.name'}.', '.$umode.
1.197 www 7635: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 7636: unless ($reply eq 'ok') {
1.197 www 7637: &logthis('Authentication mode error: '.$reply);
1.169 harris41 7638: return 'error: '.$reply;
7639: }
1.170 harris41 7640: return 'ok';
1.80 www 7641: }
7642:
1.81 www 7643: # --------------------------------------------------------------- Modify a user
1.80 www 7644:
1.81 www 7645: sub modifyuser {
1.206 matthew 7646: my ($udom, $uname, $uid,
7647: $umode, $upass, $first,
7648: $middle, $last, $gene,
1.1058 raeburn 7649: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 7650: $udom= &LONCAPA::clean_domain($udom);
7651: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 7652: my $showcandelete = 'none';
7653: if (ref($candelete) eq 'ARRAY') {
7654: if (@{$candelete} > 0) {
7655: $showcandelete = join(', ',@{$candelete});
7656: }
7657: }
1.81 www 7658: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 7659: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 7660: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 7661: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
7662: ' desiredhome not specified').
1.620 albertel 7663: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
7664: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 7665: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 7666: my $newuser;
7667: if ($uhome eq 'no_host') {
7668: $newuser = 1;
7669: }
1.80 www 7670: # ----------------------------------------------------------------- Create User
1.406 albertel 7671: if (($uhome eq 'no_host') &&
7672: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 7673: my $unhome='';
1.844 albertel 7674: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 7675: $unhome = $desiredhome;
1.620 albertel 7676: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
7677: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 7678: } else { # load balancing routine for determining $unhome
1.81 www 7679: my $loadm=10000000;
1.841 albertel 7680: my %servers = &get_servers($udom,'library');
7681: foreach my $tryserver (keys(%servers)) {
7682: my $answer=reply('load',$tryserver);
7683: if (($answer=~/\d+/) && ($answer<$loadm)) {
7684: $loadm=$answer;
7685: $unhome=$tryserver;
7686: }
1.80 www 7687: }
7688: }
7689: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 7690: return 'error: unable to find a home server for '.$uname.
7691: ' in domain '.$udom;
1.80 www 7692: }
7693: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
7694: &escape($upass),$unhome);
7695: unless ($reply eq 'ok') {
7696: return 'error: '.$reply;
7697: }
1.230 stredwic 7698: $uhome=&homeserver($uname,$udom,'true');
1.80 www 7699: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 7700: return 'error: unable verify users home machine.';
1.80 www 7701: }
1.209 matthew 7702: } # End of creation of new user
1.80 www 7703: # ---------------------------------------------------------------------- Add ID
7704: if ($uid) {
7705: $uid=~tr/A-Z/a-z/;
7706: my %uidhash=&idrget($udom,$uname);
1.196 www 7707: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
7708: && (!$forceid)) {
1.80 www 7709: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 7710: return 'error: user id "'.$uid.'" does not match '.
7711: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 7712: }
7713: } else {
7714: &idput($udom,($uname => $uid));
7715: }
7716: }
7717: # -------------------------------------------------------------- Add names, etc
1.313 matthew 7718: my @tmp=&get('environment',
1.899 raeburn 7719: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 7720: 'permanentemail','inststatus'],
1.134 albertel 7721: $udom,$uname);
1.1075 raeburn 7722: my (%names,%oldnames);
1.313 matthew 7723: if ($tmp[0] =~ m/^error:.*/) {
7724: %names=();
7725: } else {
7726: %names = @tmp;
1.1075 raeburn 7727: %oldnames = %names;
1.313 matthew 7728: }
1.388 www 7729: #
1.1058 raeburn 7730: # If name, email and/or uid are blank (e.g., because an uploaded file
7731: # of users did not contain them), do not overwrite existing values
7732: # unless field is in $candelete array ref.
7733: #
7734:
7735: my @fields = ('firstname','middlename','lastname','generation',
7736: 'permanentemail','id');
7737: my %newvalues;
7738: if (ref($candelete) eq 'ARRAY') {
7739: foreach my $field (@fields) {
7740: if (grep(/^\Q$field\E$/,@{$candelete})) {
7741: if ($field eq 'firstname') {
7742: $names{$field} = $first;
7743: } elsif ($field eq 'middlename') {
7744: $names{$field} = $middle;
7745: } elsif ($field eq 'lastname') {
7746: $names{$field} = $last;
7747: } elsif ($field eq 'generation') {
7748: $names{$field} = $gene;
7749: } elsif ($field eq 'permanentemail') {
7750: $names{$field} = $email;
7751: } elsif ($field eq 'id') {
7752: $names{$field} = $uid;
7753: }
7754: }
7755: }
7756: }
1.388 www 7757: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 7758: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 7759: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 7760: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 7761: if ($email) {
7762: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 7763: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 7764: }
1.899 raeburn 7765: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 7766: if (defined($inststatus)) {
7767: $names{'inststatus'} = '';
7768: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
7769: if (ref($usertypes) eq 'HASH') {
7770: my @okstatuses;
7771: foreach my $item (split(/:/,$inststatus)) {
7772: if (defined($usertypes->{$item})) {
7773: push(@okstatuses,$item);
7774: }
7775: }
7776: if (@okstatuses) {
7777: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
7778: }
7779: }
7780: }
1.1075 raeburn 7781: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 7782: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 7783: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 7784: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
7785: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
7786: } else {
7787: $logmsg .= ' during self creation';
7788: }
1.1075 raeburn 7789: my $changed;
7790: if ($newuser) {
7791: $changed = 1;
7792: } else {
7793: foreach my $field (@fields) {
7794: if ($names{$field} ne $oldnames{$field}) {
7795: $changed = 1;
7796: last;
7797: }
7798: }
7799: }
7800: unless ($changed) {
7801: $logmsg = 'No changes in user information needed for: '.$logmsg;
7802: &logthis($logmsg);
7803: return 'ok';
7804: }
7805: my $reply = &put('environment', \%names, $udom,$uname);
7806: if ($reply ne 'ok') {
7807: return 'error: '.$reply;
7808: }
1.1087 raeburn 7809: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
7810: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
7811: }
1.1075 raeburn 7812: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
7813: &devalidate_cache_new('namescache',$uname.':'.$udom);
7814: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 7815: &logthis($logmsg);
1.134 albertel 7816: return 'ok';
1.80 www 7817: }
7818:
1.81 www 7819: # -------------------------------------------------------------- Modify student
1.80 www 7820:
1.81 www 7821: sub modifystudent {
7822: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 7823: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.990 raeburn 7824: $selfenroll,$context,$inststatus)=@_;
1.455 albertel 7825: if (!$cid) {
1.620 albertel 7826: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 7827: return 'not_in_class';
7828: }
1.80 www 7829: }
7830: # --------------------------------------------------------------- Make the user
1.81 www 7831: my $reply=&modifyuser
1.209 matthew 7832: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 7833: $desiredhome,$email,$inststatus);
1.80 www 7834: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 7835: # This will cause &modify_student_enrollment to get the uid from the
7836: # students environment
7837: $uid = undef if (!$forceid);
1.455 albertel 7838: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957 raeburn 7839: $gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297 matthew 7840: return $reply;
7841: }
7842:
7843: sub modify_student_enrollment {
1.957 raeburn 7844: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455 albertel 7845: my ($cdom,$cnum,$chome);
7846: if (!$cid) {
1.620 albertel 7847: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 7848: return 'not_in_class';
7849: }
1.620 albertel 7850: $cdom=$env{'course.'.$cid.'.domain'};
7851: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 7852: } else {
7853: ($cdom,$cnum)=split(/_/,$cid);
7854: }
1.620 albertel 7855: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 7856: if (!$chome) {
1.457 raeburn 7857: $chome=&homeserver($cnum,$cdom);
1.297 matthew 7858: }
1.455 albertel 7859: if (!$chome) { return 'unknown_course'; }
1.297 matthew 7860: # Make sure the user exists
1.81 www 7861: my $uhome=&homeserver($uname,$udom);
7862: if (($uhome eq '') || ($uhome eq 'no_host')) {
7863: return 'error: no such user';
7864: }
1.297 matthew 7865: # Get student data if we were not given enough information
7866: if (!defined($first) || $first eq '' ||
7867: !defined($last) || $last eq '' ||
7868: !defined($uid) || $uid eq '' ||
7869: !defined($middle) || $middle eq '' ||
7870: !defined($gene) || $gene eq '') {
1.294 matthew 7871: # They did not supply us with enough data to enroll the student, so
7872: # we need to pick up more information.
1.297 matthew 7873: my %tmp = &get('environment',
1.294 matthew 7874: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 7875: ,$udom,$uname);
7876:
1.800 albertel 7877: #foreach my $key (keys(%tmp)) {
7878: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 7879: #}
1.294 matthew 7880: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
7881: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
7882: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 7883: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 7884: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
7885: }
1.556 albertel 7886: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148 raeburn 7887: my $user = "$uname:$udom";
7888: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487 albertel 7889: my $reply=cput('classlist',
1.1148 raeburn 7890: {$user =>
1.515 raeburn 7891: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487 albertel 7892: $cdom,$cnum);
1.1148 raeburn 7893: if (($reply eq 'ok') || ($reply eq 'delayed')) {
7894: &devalidate_getsection_cache($udom,$uname,$cid);
7895: } else {
1.81 www 7896: return 'error: '.$reply;
7897: }
1.297 matthew 7898: # Add student role to user
1.83 www 7899: my $uurl='/'.$cid;
1.81 www 7900: $uurl=~s/\_/\//g;
7901: if ($usec) {
7902: $uurl.='/'.$usec;
7903: }
1.1148 raeburn 7904: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
7905: $selfenroll,$context);
7906: if ($result ne 'ok') {
7907: if ($old_entry{$user} ne '') {
7908: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
7909: } else {
7910: $reply = &del('classlist',[$user],$cdom,$cnum);
7911: }
7912: }
7913: return $result;
1.21 www 7914: }
7915:
1.556 albertel 7916: sub format_name {
7917: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
7918: my $name;
7919: if ($first ne 'lastname') {
7920: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
7921: } else {
7922: if ($lastname=~/\S/) {
7923: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
7924: $name=~s/\s+,/,/;
7925: } else {
7926: $name.= $firstname.' '.$middlename.' '.$generation;
7927: }
7928: }
7929: $name=~s/^\s+//;
7930: $name=~s/\s+$//;
7931: $name=~s/\s+/ /g;
7932: return $name;
7933: }
7934:
1.84 www 7935: # ------------------------------------------------- Write to course preferences
7936:
7937: sub writecoursepref {
7938: my ($courseid,%prefs)=@_;
7939: $courseid=~s/^\///;
7940: $courseid=~s/\_/\//g;
7941: my ($cdomain,$cnum)=split(/\//,$courseid);
7942: my $chome=homeserver($cnum,$cdomain);
7943: if (($chome eq '') || ($chome eq 'no_host')) {
7944: return 'error: no such course';
7945: }
7946: my $cstring='';
1.800 albertel 7947: foreach my $pref (keys(%prefs)) {
7948: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 7949: }
1.84 www 7950: $cstring=~s/\&$//;
7951: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
7952: }
7953:
7954: # ---------------------------------------------------------- Make/modify course
7955:
7956: sub createcourse {
1.741 raeburn 7957: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 7958: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 7959: $url=&declutter($url);
7960: my $cid='';
1.1028 raeburn 7961: if ($context eq 'requestcourses') {
7962: my $can_create = 0;
7963: my ($ownername,$ownerdom) = split(':',$course_owner);
7964: if ($udom eq $ownerdom) {
7965: if (&usertools_access($ownername,$ownerdom,$category,undef,
7966: $context)) {
7967: $can_create = 1;
7968: }
7969: } else {
7970: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
7971: $category);
7972: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
7973: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
7974: if (@curr > 0) {
7975: my @options = qw(approval validate autolimit);
7976: my $optregex = join('|',@options);
7977: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
7978: $can_create = 1;
7979: }
7980: }
7981: }
7982: }
7983: if ($can_create) {
7984: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
7985: unless (&allowed('ccc',$udom)) {
7986: return 'refused';
7987: }
1.1017 raeburn 7988: }
7989: } else {
7990: return 'refused';
7991: }
1.1028 raeburn 7992: } elsif (!&allowed('ccc',$udom)) {
7993: return 'refused';
1.84 www 7994: }
1.1011 raeburn 7995: # --------------------------------------------------------------- Get Unique ID
7996: my $uname;
7997: if ($cnum =~ /^$match_courseid$/) {
7998: my $chome=&homeserver($cnum,$udom,'true');
7999: if (($chome eq '') || ($chome eq 'no_host')) {
8000: $uname = $cnum;
8001: } else {
1.1038 raeburn 8002: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 8003: }
8004: } else {
1.1038 raeburn 8005: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 8006: }
8007: return $uname if ($uname =~ /^error/);
8008: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 8009: if (!defined($course_server)) {
8010: if (defined(&domain($udom,'primary'))) {
8011: $course_server = &domain($udom,'primary');
8012: } else {
8013: $course_server = $env{'user.home'};
8014: }
8015: }
8016: my %host_servers =
8017: &Apache::lonnet::get_servers($udom,'library');
8018: unless ($host_servers{$course_server}) {
8019: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 8020: }
1.84 www 8021: # ------------------------------------------------------------- Make the course
8022: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 8023: $course_server);
1.84 www 8024: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 8025: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 8026: if (($uhome eq '') || ($uhome eq 'no_host')) {
8027: return 'error: no such course';
8028: }
1.271 www 8029: # ----------------------------------------------------------------- Course made
1.516 raeburn 8030: # log existence
1.1029 raeburn 8031: my $now = time;
1.918 raeburn 8032: my $newcourse = {
8033: $udom.'_'.$uname => {
1.921 raeburn 8034: description => $description,
8035: inst_code => $inst_code,
8036: owner => $course_owner,
8037: type => $crstype,
1.1029 raeburn 8038: creator => $env{'user.name'}.':'.
8039: $env{'user.domain'},
8040: created => $now,
8041: context => $context,
1.918 raeburn 8042: },
8043: };
1.921 raeburn 8044: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 8045: # set toplevel url
1.271 www 8046: my $topurl=$url;
8047: unless ($nonstandard) {
8048: # ------------------------------------------ For standard courses, make top url
8049: my $mapurl=&clutter($url);
1.278 www 8050: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 8051: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 8052: <map>
8053: <resource id="1" type="start"></resource>
8054: <resource id="2" src="$mapurl"></resource>
8055: <resource id="3" type="finish"></resource>
8056: <link index="1" from="1" to="2"></link>
8057: <link index="2" from="2" to="3"></link>
8058: </map>
8059: ENDINITMAP
8060: $topurl=&declutter(
1.638 albertel 8061: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 8062: );
8063: }
8064: # ----------------------------------------------------------- Write preferences
1.84 www 8065: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 8066: ('description' => $description,
8067: 'url' => $topurl,
8068: 'internal.creator' => $env{'user.name'}.':'.
8069: $env{'user.domain'},
8070: 'internal.created' => $now,
8071: 'internal.creationcontext' => $context)
8072: );
1.84 www 8073: return '/'.$udom.'/'.$uname;
8074: }
8075:
1.1011 raeburn 8076: # ------------------------------------------------------------------- Create ID
8077: sub generate_coursenum {
1.1038 raeburn 8078: my ($udom,$crstype) = @_;
1.1011 raeburn 8079: my $domdesc = &domain($udom);
8080: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 8081: my $first;
8082: if ($crstype eq 'Community') {
8083: $first = '0';
8084: } else {
8085: $first = int(1+rand(9));
8086: }
8087: my $uname=$first.
1.1011 raeburn 8088: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
8089: substr($$.time,0,5).unpack("H8",pack("I32",time)).
8090: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
8091: # ----------------------------------------------- Make sure that does not exist
8092: my $uhome=&homeserver($uname,$udom,'true');
8093: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 8094: if ($crstype eq 'Community') {
8095: $first = '0';
8096: } else {
8097: $first = int(1+rand(9));
8098: }
8099: $uname=$first.
1.1011 raeburn 8100: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
8101: substr($$.time,0,5).unpack("H8",pack("I32",time)).
8102: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
8103: $uhome=&homeserver($uname,$udom,'true');
8104: unless (($uhome eq '') || ($uhome eq 'no_host')) {
8105: return 'error: unable to generate unique course-ID';
8106: }
8107: }
8108: return $uname;
8109: }
8110:
1.813 albertel 8111: sub is_course {
1.1167 droeschl 8112: my ($cdom, $cnum) = scalar(@_) == 1 ?
8113: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
8114:
8115: return unless $cdom and $cnum;
8116:
8117: my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
8118: '.');
8119:
8120: return unless exists($courses{$cdom.'_'.$cnum});
8121: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813 albertel 8122: }
8123:
1.1015 raeburn 8124: sub store_userdata {
8125: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 8126: my $result;
1.1016 raeburn 8127: if ($datakey ne '') {
1.1013 raeburn 8128: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 8129: if ($udom eq '' || $uname eq '') {
8130: $udom = $env{'user.domain'};
8131: $uname = $env{'user.name'};
8132: }
8133: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 8134: if (($uhome eq '') || ($uhome eq 'no_host')) {
8135: $result = 'error: no_host';
8136: } else {
8137: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
8138: $storehash->{'host'} = $perlvar{'lonHostID'};
8139:
8140: my $namevalue='';
8141: foreach my $key (keys(%{$storehash})) {
8142: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
8143: }
8144: $namevalue=~s/\&$//;
1.1105 raeburn 8145: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
8146: $namevalue,$uhome);
1.1013 raeburn 8147: }
8148: } else {
8149: $result = 'error: data to store was not a hash reference';
8150: }
8151: } else {
8152: $result= 'error: invalid requestkey';
8153: }
8154: return $result;
8155: }
8156:
1.21 www 8157: # ---------------------------------------------------------- Assign Custom Role
8158:
8159: sub assigncustomrole {
1.957 raeburn 8160: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 8161: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 8162: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 8163: }
8164:
8165: # ----------------------------------------------------------------- Revoke Role
8166:
8167: sub revokerole {
1.957 raeburn 8168: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 8169: my $now=time;
1.965 raeburn 8170: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 8171: }
8172:
8173: # ---------------------------------------------------------- Revoke Custom Role
8174:
8175: sub revokecustomrole {
1.957 raeburn 8176: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 8177: my $now=time;
1.357 www 8178: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 8179: $deleteflag,$selfenroll,$context);
1.17 www 8180: }
8181:
1.533 banghart 8182: # ------------------------------------------------------------ Disk usage
1.535 albertel 8183: sub diskusage {
1.955 raeburn 8184: my ($udom,$uname,$directorypath,$getpropath)=@_;
8185: $directorypath =~ s/\/$//;
8186: my $listing=&reply('du2:'.&escape($directorypath).':'
8187: .&escape($getpropath).':'.&escape($uname).':'
8188: .&escape($udom),homeserver($uname,$udom));
8189: if ($listing eq 'unknown_cmd') {
8190: if ($getpropath) {
8191: $directorypath = &propath($udom,$uname).'/'.$directorypath;
8192: }
8193: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
8194: }
1.514 albertel 8195: return $listing;
1.512 banghart 8196: }
8197:
1.566 banghart 8198: sub is_locked {
1.1096 raeburn 8199: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 8200: my @check;
8201: my $is_locked;
1.1093 raeburn 8202: push (@check,$file_name);
1.613 albertel 8203: my %locked = &get('file_permissions',\@check,
1.620 albertel 8204: $env{'user.domain'},$env{'user.name'});
1.615 albertel 8205: my ($tmp)=keys(%locked);
8206: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 8207:
1.566 banghart 8208: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 8209: $is_locked = 'false';
8210: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 8211: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 8212: $is_locked = 'true';
1.1096 raeburn 8213: if (ref($which) eq 'ARRAY') {
8214: push(@{$which},$entry);
8215: } else {
8216: last;
8217: }
1.745 raeburn 8218: }
8219: }
1.566 banghart 8220: } else {
8221: $is_locked = 'false';
8222: }
1.1093 raeburn 8223: return $is_locked;
1.566 banghart 8224: }
8225:
1.759 albertel 8226: sub declutter_portfile {
8227: my ($file) = @_;
1.833 albertel 8228: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 8229: return $file;
8230: }
8231:
1.559 banghart 8232: # ------------------------------------------------------------- Mark as Read Only
8233:
8234: sub mark_as_readonly {
8235: my ($domain,$user,$files,$what) = @_;
1.613 albertel 8236: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 8237: my ($tmp)=keys(%current_permissions);
8238: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 8239: foreach my $file (@{$files}) {
1.759 albertel 8240: $file = &declutter_portfile($file);
1.561 banghart 8241: push(@{$current_permissions{$file}},$what);
1.559 banghart 8242: }
1.613 albertel 8243: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 8244: return;
8245: }
8246:
1.572 banghart 8247: # ------------------------------------------------------------Save Selected Files
8248:
8249: sub save_selected_files {
8250: my ($user, $path, @files) = @_;
8251: my $filename = $user."savedfiles";
1.573 banghart 8252: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 8253: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 8254: foreach my $file (@files) {
1.620 albertel 8255: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 8256: }
8257: foreach my $file (@other_files) {
1.574 banghart 8258: print (OUT $file."\n");
1.572 banghart 8259: }
1.574 banghart 8260: close (OUT);
1.572 banghart 8261: return 'ok';
8262: }
8263:
1.574 banghart 8264: sub clear_selected_files {
8265: my ($user) = @_;
8266: my $filename = $user."savedfiles";
1.1117 foxr 8267: open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574 banghart 8268: print (OUT undef);
8269: close (OUT);
8270: return ("ok");
8271: }
8272:
1.572 banghart 8273: sub files_in_path {
8274: my ($user, $path) = @_;
8275: my $filename = $user."savedfiles";
8276: my %return_files;
1.1117 foxr 8277: open (IN, '<'.LONCAPA::tempdir().$filename);
1.573 banghart 8278: while (my $line_in = <IN>) {
1.574 banghart 8279: chomp ($line_in);
8280: my @paths_and_file = split (m!/!, $line_in);
8281: my $file_part = pop (@paths_and_file);
8282: my $path_part = join ('/', @paths_and_file);
1.573 banghart 8283: $path_part.='/';
8284: my $path_and_file = $path_part.$file_part;
8285: if ($path_part eq $path) {
8286: $return_files{$file_part}= 'selected';
8287: }
8288: }
1.574 banghart 8289: close (IN);
8290: return (\%return_files);
1.572 banghart 8291: }
8292:
8293: # called in portfolio select mode, to show files selected NOT in current directory
8294: sub files_not_in_path {
8295: my ($user, $path) = @_;
8296: my $filename = $user."savedfiles";
8297: my @return_files;
8298: my $path_part;
1.1117 foxr 8299: open(IN, '<'.LONCAPA::.$filename);
1.800 albertel 8300: while (my $line = <IN>) {
1.572 banghart 8301: #ok, I know it's clunky, but I want it to work
1.800 albertel 8302: my @paths_and_file = split(m|/|, $line);
8303: my $file_part = pop(@paths_and_file);
8304: chomp($file_part);
8305: my $path_part = join('/', @paths_and_file);
1.572 banghart 8306: $path_part .= '/';
8307: my $path_and_file = $path_part.$file_part;
8308: if ($path_part ne $path) {
1.800 albertel 8309: push(@return_files, ($path_and_file));
1.572 banghart 8310: }
8311: }
1.800 albertel 8312: close(OUT);
1.574 banghart 8313: return (@return_files);
1.572 banghart 8314: }
8315:
1.745 raeburn 8316: #----------------------------------------------Get portfolio file permissions
1.629 banghart 8317:
1.745 raeburn 8318: sub get_portfile_permissions {
8319: my ($domain,$user) = @_;
1.613 albertel 8320: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 8321: my ($tmp)=keys(%current_permissions);
8322: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 8323: return \%current_permissions;
8324: }
8325:
8326: #---------------------------------------------Get portfolio file access controls
8327:
1.749 raeburn 8328: sub get_access_controls {
1.745 raeburn 8329: my ($current_permissions,$group,$file) = @_;
1.769 albertel 8330: my %access;
8331: my $real_file = $file;
8332: $file =~ s/\.meta$//;
1.745 raeburn 8333: if (defined($file)) {
1.749 raeburn 8334: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
8335: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 8336: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 8337: }
8338: }
1.745 raeburn 8339: } else {
1.749 raeburn 8340: foreach my $key (keys(%{$current_permissions})) {
8341: if ($key =~ /\0accesscontrol$/) {
8342: if (defined($group)) {
8343: if ($key !~ m-^\Q$group\E/-) {
8344: next;
8345: }
8346: }
8347: my ($fullpath) = split(/\0/,$key);
8348: if (ref($$current_permissions{$key}) eq 'HASH') {
8349: foreach my $control (keys(%{$$current_permissions{$key}})) {
8350: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
8351: }
8352: }
8353: }
8354: }
8355: }
8356: return %access;
8357: }
8358:
8359: sub modify_access_controls {
8360: my ($file_name,$changes,$domain,$user)=@_;
8361: my ($outcome,$deloutcome);
8362: my %store_permissions;
8363: my %new_values;
8364: my %new_control;
8365: my %translation;
8366: my @deletions = ();
8367: my $now = time;
8368: if (exists($$changes{'activate'})) {
8369: if (ref($$changes{'activate'}) eq 'HASH') {
8370: my @newitems = sort(keys(%{$$changes{'activate'}}));
8371: my $numnew = scalar(@newitems);
8372: for (my $i=0; $i<$numnew; $i++) {
8373: my $newkey = $newitems[$i];
8374: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 8375: if ($newkey =~ /^\d+:/) {
8376: $newkey =~ s/^(\d+)/$newid/;
8377: $translation{$1} = $newid;
8378: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
8379: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
8380: $translation{$1} = $newid;
8381: }
1.749 raeburn 8382: $new_values{$file_name."\0".$newkey} =
8383: $$changes{'activate'}{$newitems[$i]};
8384: $new_control{$newkey} = $now;
8385: }
8386: }
8387: }
8388: my %todelete;
8389: my %changed_items;
8390: foreach my $action ('delete','update') {
8391: if (exists($$changes{$action})) {
8392: if (ref($$changes{$action}) eq 'HASH') {
8393: foreach my $key (keys(%{$$changes{$action}})) {
8394: my ($itemnum) = ($key =~ /^([^:]+):/);
8395: if ($action eq 'delete') {
8396: $todelete{$itemnum} = 1;
8397: } else {
8398: $changed_items{$itemnum} = $key;
8399: }
8400: }
1.745 raeburn 8401: }
8402: }
1.749 raeburn 8403: }
8404: # get lock on access controls for file.
8405: my $lockhash = {
8406: $file_name."\0".'locked_access_records' => $env{'user.name'}.
8407: ':'.$env{'user.domain'},
8408: };
8409: my $tries = 0;
8410: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
8411:
8412: while (($gotlock ne 'ok') && $tries <3) {
8413: $tries ++;
8414: sleep 1;
8415: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
8416: }
8417: if ($gotlock eq 'ok') {
8418: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
8419: my ($tmp)=keys(%curr_permissions);
8420: if ($tmp=~/^error:/) { undef(%curr_permissions); }
8421: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
8422: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
8423: if (ref($curr_controls) eq 'HASH') {
8424: foreach my $control_item (keys(%{$curr_controls})) {
8425: my ($itemnum) = ($control_item =~ /^([^:]+):/);
8426: if (defined($todelete{$itemnum})) {
8427: push(@deletions,$file_name."\0".$control_item);
8428: } else {
8429: if (defined($changed_items{$itemnum})) {
8430: $new_control{$changed_items{$itemnum}} = $now;
8431: push(@deletions,$file_name."\0".$control_item);
8432: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
8433: } else {
8434: $new_control{$control_item} = $$curr_controls{$control_item};
8435: }
8436: }
1.745 raeburn 8437: }
8438: }
8439: }
1.970 raeburn 8440: my ($group);
8441: if (&is_course($domain,$user)) {
8442: ($group,my $file) = split(/\//,$file_name,2);
8443: }
1.749 raeburn 8444: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
8445: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
8446: $outcome = &put('file_permissions',\%new_values,$domain,$user);
8447: # remove lock
8448: my @del_lock = ($file_name."\0".'locked_access_records');
8449: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 8450: my $sqlresult =
1.970 raeburn 8451: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 8452: $group);
1.749 raeburn 8453: } else {
8454: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 8455: }
1.749 raeburn 8456: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 8457: }
8458:
1.827 raeburn 8459: sub make_public_indefinitely {
8460: my ($requrl) = @_;
8461: my $now = time;
8462: my $action = 'activate';
8463: my $aclnum = 0;
8464: if (&is_portfolio_url($requrl)) {
8465: my (undef,$udom,$unum,$file_name,$group) =
8466: &parse_portfolio_url($requrl);
8467: my $current_perms = &get_portfile_permissions($udom,$unum);
8468: my %access_controls = &get_access_controls($current_perms,
8469: $group,$file_name);
8470: foreach my $key (keys(%{$access_controls{$file_name}})) {
8471: my ($num,$scope,$end,$start) =
8472: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
8473: if ($scope eq 'public') {
8474: if ($start <= $now && $end == 0) {
8475: $action = 'none';
8476: } else {
8477: $action = 'update';
8478: $aclnum = $num;
8479: }
8480: last;
8481: }
8482: }
8483: if ($action eq 'none') {
8484: return 'ok';
8485: } else {
8486: my %changes;
8487: my $newend = 0;
8488: my $newstart = $now;
8489: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
8490: $changes{$action}{$newkey} = {
8491: type => 'public',
8492: time => {
8493: start => $newstart,
8494: end => $newend,
8495: },
8496: };
8497: my ($outcome,$deloutcome,$new_values,$translation) =
8498: &modify_access_controls($file_name,\%changes,$udom,$unum);
8499: return $outcome;
8500: }
8501: } else {
8502: return 'invalid';
8503: }
8504: }
8505:
1.745 raeburn 8506: #------------------------------------------------------Get Marked as Read Only
8507:
8508: sub get_marked_as_readonly {
8509: my ($domain,$user,$what,$group) = @_;
8510: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 8511: my @readonly_files;
1.629 banghart 8512: my $cmp1=$what;
8513: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 8514: while (my ($file_name,$value) = each(%{$current_permissions})) {
8515: if (defined($group)) {
8516: if ($file_name !~ m-^\Q$group\E/-) {
8517: next;
8518: }
8519: }
1.561 banghart 8520: if (ref($value) eq "ARRAY"){
8521: foreach my $stored_what (@{$value}) {
1.629 banghart 8522: my $cmp2=$stored_what;
1.759 albertel 8523: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 8524: $cmp2=join('',@{$stored_what});
1.745 raeburn 8525: }
1.629 banghart 8526: if ($cmp1 eq $cmp2) {
1.561 banghart 8527: push(@readonly_files, $file_name);
1.745 raeburn 8528: last;
1.563 banghart 8529: } elsif (!defined($what)) {
8530: push(@readonly_files, $file_name);
1.745 raeburn 8531: last;
1.561 banghart 8532: }
8533: }
1.745 raeburn 8534: }
1.561 banghart 8535: }
8536: return @readonly_files;
8537: }
1.577 banghart 8538: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 8539:
1.577 banghart 8540: sub get_marked_as_readonly_hash {
1.745 raeburn 8541: my ($current_permissions,$group,$what) = @_;
1.577 banghart 8542: my %readonly_files;
1.745 raeburn 8543: while (my ($file_name,$value) = each(%{$current_permissions})) {
8544: if (defined($group)) {
8545: if ($file_name !~ m-^\Q$group\E/-) {
8546: next;
8547: }
8548: }
1.577 banghart 8549: if (ref($value) eq "ARRAY"){
8550: foreach my $stored_what (@{$value}) {
1.745 raeburn 8551: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 8552: foreach my $lock_descriptor(@{$stored_what}) {
8553: if ($lock_descriptor eq 'graded') {
8554: $readonly_files{$file_name} = 'graded';
8555: } elsif ($lock_descriptor eq 'handback') {
8556: $readonly_files{$file_name} = 'handback';
8557: } else {
8558: if (!exists($readonly_files{$file_name})) {
8559: $readonly_files{$file_name} = 'locked';
8560: }
8561: }
1.745 raeburn 8562: }
1.750 banghart 8563: }
1.577 banghart 8564: }
8565: }
8566: }
8567: return %readonly_files;
8568: }
1.559 banghart 8569: # ------------------------------------------------------------ Unmark as Read Only
8570:
8571: sub unmark_as_readonly {
1.629 banghart 8572: # unmarks $file_name (if $file_name is defined), or all files locked by $what
8573: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 8574: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 8575: $file_name = &declutter_portfile($file_name);
1.634 albertel 8576: my $symb_crs = $what;
8577: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 8578: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 8579: my ($tmp)=keys(%current_permissions);
8580: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 8581: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 8582: foreach my $file (@readonly_files) {
1.759 albertel 8583: my $clean_file = &declutter_portfile($file);
8584: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 8585: my $current_locks = $current_permissions{$file};
1.563 banghart 8586: my @new_locks;
8587: my @del_keys;
8588: if (ref($current_locks) eq "ARRAY"){
8589: foreach my $locker (@{$current_locks}) {
1.632 albertel 8590: my $compare=$locker;
1.749 raeburn 8591: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 8592: $compare=join('',@{$locker});
1.746 raeburn 8593: if ($compare ne $symb_crs) {
8594: push(@new_locks, $locker);
8595: }
1.563 banghart 8596: }
8597: }
1.650 albertel 8598: if (scalar(@new_locks) > 0) {
1.563 banghart 8599: $current_permissions{$file} = \@new_locks;
8600: } else {
8601: push(@del_keys, $file);
1.613 albertel 8602: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 8603: delete($current_permissions{$file});
1.563 banghart 8604: }
8605: }
1.561 banghart 8606: }
1.613 albertel 8607: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 8608: return;
8609: }
1.512 banghart 8610:
1.17 www 8611: # ------------------------------------------------------------ Directory lister
8612:
8613: sub dirlist {
1.955 raeburn 8614: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 8615: $uri=~s/^\///;
8616: $uri=~s/\/$//;
1.253 stredwic 8617: my ($udom, $uname);
1.955 raeburn 8618: if ($getuserdir) {
1.253 stredwic 8619: $udom = $userdomain;
8620: $uname = $username;
1.955 raeburn 8621: } else {
8622: (undef,$udom,$uname)=split(/\//,$uri);
8623: if(defined($userdomain)) {
8624: $udom = $userdomain;
8625: }
8626: if(defined($username)) {
8627: $uname = $username;
8628: }
1.253 stredwic 8629: }
1.955 raeburn 8630: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 8631:
1.955 raeburn 8632: $dirRoot = $perlvar{'lonDocRoot'};
8633: if (defined($getpropath)) {
8634: $dirRoot = &propath($udom,$uname);
1.253 stredwic 8635: $dirRoot =~ s/\/$//;
1.955 raeburn 8636: } elsif (defined($getuserdir)) {
8637: my $subdir=$uname.'__';
8638: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
8639: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
8640: ."/$udom/$subdir/$uname";
8641: } elsif (defined($alternateRoot)) {
8642: $dirRoot = $alternateRoot;
1.751 banghart 8643: }
1.253 stredwic 8644:
8645: if($udom) {
8646: if($uname) {
1.1135 raeburn 8647: my $uhome = &homeserver($uname,$udom);
1.1136 raeburn 8648: if ($uhome eq 'no_host') {
8649: return ([],'no_host');
8650: }
1.955 raeburn 8651: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 8652: .$getuserdir.':'.&escape($dirRoot)
1.1135 raeburn 8653: .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955 raeburn 8654: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 8655: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955 raeburn 8656: } else {
8657: @listing_results = map { &unescape($_); } split(/:/,$listing);
8658: }
1.605 matthew 8659: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 8660: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605 matthew 8661: @listing_results = split(/:/,$listing);
8662: } else {
8663: @listing_results = map { &unescape($_); } split(/:/,$listing);
8664: }
1.1135 raeburn 8665: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
1.1136 raeburn 8666: ($listing eq 'rejected') || ($listing eq 'refused') ||
8667: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
8668: return ([],$listing);
8669: } else {
8670: return (\@listing_results);
1.1135 raeburn 8671: }
1.955 raeburn 8672: } elsif(!$alternateRoot) {
1.1136 raeburn 8673: my (%allusers,%listerror);
1.841 albertel 8674: my %servers = &get_servers($udom,'library');
1.955 raeburn 8675: foreach my $tryserver (keys(%servers)) {
8676: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
8677: &escape($udom),$tryserver);
8678: if ($listing eq 'unknown_cmd') {
8679: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
8680: $udom, $tryserver);
8681: } else {
8682: @listing_results = map { &unescape($_); } split(/:/,$listing);
8683: }
1.841 albertel 8684: if ($listing eq 'unknown_cmd') {
8685: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
8686: $udom, $tryserver);
8687: @listing_results = split(/:/,$listing);
8688: } else {
8689: @listing_results =
8690: map { &unescape($_); } split(/:/,$listing);
8691: }
1.1136 raeburn 8692: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
8693: ($listing eq 'rejected') || ($listing eq 'refused') ||
8694: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
8695: $listerror{$tryserver} = $listing;
8696: } else {
1.841 albertel 8697: foreach my $line (@listing_results) {
8698: my ($entry) = split(/&/,$line,2);
8699: $allusers{$entry} = 1;
8700: }
8701: }
1.253 stredwic 8702: }
1.1136 raeburn 8703: my @alluserslist=();
1.800 albertel 8704: foreach my $user (sort(keys(%allusers))) {
1.1136 raeburn 8705: push(@alluserslist,$user.'&user');
1.253 stredwic 8706: }
1.1136 raeburn 8707: return (\@alluserslist);
1.253 stredwic 8708: } else {
1.1136 raeburn 8709: return ([],'missing username');
1.253 stredwic 8710: }
1.955 raeburn 8711: } elsif(!defined($getpropath)) {
1.1136 raeburn 8712: my $path = $perlvar{'lonDocRoot'}.'/res/';
8713: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
8714: return (\@all_domains);
1.955 raeburn 8715: } else {
1.1136 raeburn 8716: return ([],'missing domain');
1.275 stredwic 8717: }
8718: }
8719:
8720: # --------------------------------------------- GetFileTimestamp
8721: # This function utilizes dirlist and returns the date stamp for
8722: # when it was last modified. It will also return an error of -1
8723: # if an error occurs
8724:
8725: sub GetFileTimestamp {
1.955 raeburn 8726: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 8727: $studentDomain = &LONCAPA::clean_domain($studentDomain);
8728: $studentName = &LONCAPA::clean_username($studentName);
1.1136 raeburn 8729: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
8730: undef,$getuserdir);
8731: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
8732: return -1;
8733: }
8734: if (ref($fileref) eq 'ARRAY') {
8735: my @stats = split('&',$fileref->[0]);
1.375 matthew 8736: # @stats contains first the filename, then the stat output
8737: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 8738: } else {
8739: return -1;
1.253 stredwic 8740: }
1.26 www 8741: }
8742:
1.712 albertel 8743: sub stat_file {
8744: my ($uri) = @_;
1.787 albertel 8745: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 8746:
1.955 raeburn 8747: my ($udom,$uname,$file);
1.712 albertel 8748: if ($uri =~ m-^/(uploaded|editupload)/-) {
8749: ($udom,$uname,$file) =
1.811 albertel 8750: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 8751: $file = 'userfiles/'.$file;
8752: }
8753: if ($uri =~ m-^/res/-) {
8754: ($udom,$uname) =
1.807 albertel 8755: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 8756: $file = $uri;
8757: }
8758:
8759: if (!$udom || !$uname || !$file) {
8760: # unable to handle the uri
8761: return ();
8762: }
1.956 raeburn 8763: my $getpropath;
8764: if ($file =~ /^userfiles\//) {
8765: $getpropath = 1;
8766: }
1.1136 raeburn 8767: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
8768: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
8769: return ();
8770: } else {
8771: if (ref($listref) eq 'ARRAY') {
8772: my @stats = split('&',$listref->[0]);
8773: shift(@stats); #filename is first
8774: return @stats;
8775: }
1.712 albertel 8776: }
8777: return ();
8778: }
8779:
1.26 www 8780: # -------------------------------------------------------- Value of a Condition
8781:
1.713 albertel 8782: # gets the value of a specific preevaluated condition
8783: # stored in the string $env{user.state.<cid>}
8784: # or looks up a condition reference in the bighash and if if hasn't
8785: # already been evaluated recurses into docondval to get the value of
8786: # the condition, then memoizing it to
8787: # $env{user.state.<cid>.<condition>}
1.40 www 8788: sub directcondval {
8789: my $number=shift;
1.620 albertel 8790: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 8791: &Apache::lonuserstate::evalstate();
8792: }
1.713 albertel 8793: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
8794: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
8795: } elsif ($number =~ /^_/) {
8796: my $sub_condition;
8797: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
8798: &GDBM_READER(),0640)) {
8799: $sub_condition=$bighash{'conditions'.$number};
8800: untie(%bighash);
8801: }
8802: my $value = &docondval($sub_condition);
1.949 raeburn 8803: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 8804: return $value;
8805: }
1.620 albertel 8806: if ($env{'user.state.'.$env{'request.course.id'}}) {
8807: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 8808: } else {
8809: return 2;
8810: }
8811: }
8812:
1.713 albertel 8813: # get the collection of conditions for this resource
1.26 www 8814: sub condval {
8815: my $condidx=shift;
1.54 www 8816: my $allpathcond='';
1.713 albertel 8817: foreach my $cond (split(/\|/,$condidx)) {
8818: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
8819: $allpathcond.=
8820: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
8821: }
1.191 harris41 8822: }
1.54 www 8823: $allpathcond=~s/\|$//;
1.713 albertel 8824: return &docondval($allpathcond);
8825: }
8826:
8827: #evaluates an expression of conditions
8828: sub docondval {
8829: my ($allpathcond) = @_;
8830: my $result=0;
8831: if ($env{'request.course.id'}
8832: && defined($allpathcond)) {
8833: my $operand='|';
8834: my @stack;
8835: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
8836: if ($chunk eq '(') {
8837: push @stack,($operand,$result);
8838: } elsif ($chunk eq ')') {
8839: my $before=pop @stack;
8840: if (pop @stack eq '&') {
8841: $result=$result>$before?$before:$result;
8842: } else {
8843: $result=$result>$before?$result:$before;
8844: }
8845: } elsif (($chunk eq '&') || ($chunk eq '|')) {
8846: $operand=$chunk;
8847: } else {
8848: my $new=directcondval($chunk);
8849: if ($operand eq '&') {
8850: $result=$result>$new?$new:$result;
8851: } else {
8852: $result=$result>$new?$result:$new;
8853: }
8854: }
8855: }
1.26 www 8856: }
8857: return $result;
1.421 albertel 8858: }
8859:
8860: # ---------------------------------------------------- Devalidate courseresdata
8861:
8862: sub devalidatecourseresdata {
8863: my ($coursenum,$coursedomain)=@_;
8864: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 8865: &devalidate_cache_new('courseres',$hashid);
1.28 www 8866: }
8867:
1.763 www 8868:
1.200 www 8869: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 8870: #
8871: # Parameters:
8872: # $coursenum - Number of the course.
8873: # $coursedomain - Domain at which the course was created.
8874: # Returns:
8875: # A hash of the course parameters along (I think) with timestamps
8876: # and version info.
1.877 foxr 8877:
1.624 albertel 8878: sub get_courseresdata {
8879: my ($coursenum,$coursedomain)=@_;
1.200 www 8880: my $coursehom=&homeserver($coursenum,$coursedomain);
8881: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 8882: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 8883: my %dumpreply;
1.417 albertel 8884: unless (defined($cached)) {
1.624 albertel 8885: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 8886: $result=\%dumpreply;
1.251 albertel 8887: my ($tmp) = keys(%dumpreply);
8888: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 8889: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 8890: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
8891: return $tmp;
1.416 albertel 8892: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 8893: $result=undef;
1.599 albertel 8894: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 8895: }
8896: }
1.624 albertel 8897: return $result;
8898: }
8899:
1.633 albertel 8900: sub devalidateuserresdata {
8901: my ($uname,$udom)=@_;
8902: my $hashid="$udom:$uname";
8903: &devalidate_cache_new('userres',$hashid);
8904: }
8905:
1.624 albertel 8906: sub get_userresdata {
8907: my ($uname,$udom)=@_;
8908: #most student don\'t have any data set, check if there is some data
8909: if (&EXT_cache_status($udom,$uname)) { return undef; }
8910:
8911: my $hashid="$udom:$uname";
8912: my ($result,$cached)=&is_cached_new('userres',$hashid);
8913: if (!defined($cached)) {
8914: my %resourcedata=&dump('resourcedata',$udom,$uname);
8915: $result=\%resourcedata;
8916: &do_cache_new('userres',$hashid,$result,600);
8917: }
8918: my ($tmp)=keys(%$result);
8919: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
8920: return $result;
8921: }
8922: #error 2 occurs when the .db doesn't exist
8923: if ($tmp!~/error: 2 /) {
1.672 albertel 8924: &logthis("<font color=\"blue\">WARNING:".
1.624 albertel 8925: " Trying to get resource data for ".
8926: $uname." at ".$udom.": ".
8927: $tmp."</font>");
8928: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 8929: #&EXT_cache_set($udom,$uname);
8930: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 8931: undef($tmp); # not really an error so don't send it back
1.624 albertel 8932: }
8933: return $tmp;
8934: }
1.879 foxr 8935: #----------------------------------------------- resdata - return resource data
8936: # Purpose:
8937: # Return resource data for either users or for a course.
8938: # Parameters:
8939: # $name - Course/user name.
8940: # $domain - Name of the domain the user/course is registered on.
8941: # $type - Type of thing $name is (must be 'course' or 'user'
8942: # @which - Array of names of resources desired.
8943: # Returns:
8944: # The value of the first reasource in @which that is found in the
8945: # resource hash.
8946: # Exceptional Conditions:
8947: # If the $type passed in is not valid (not the string 'course' or
8948: # 'user', an undefined reference is returned.
8949: # If none of the resources are found, an undef is returned
1.624 albertel 8950: sub resdata {
8951: my ($name,$domain,$type,@which)=@_;
8952: my $result;
8953: if ($type eq 'course') {
8954: $result=&get_courseresdata($name,$domain);
8955: } elsif ($type eq 'user') {
8956: $result=&get_userresdata($name,$domain);
8957: }
8958: if (!ref($result)) { return $result; }
1.251 albertel 8959: foreach my $item (@which) {
1.927 albertel 8960: if (defined($result->{$item->[0]})) {
8961: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 8962: }
1.250 albertel 8963: }
1.291 albertel 8964: return undef;
1.200 www 8965: }
8966:
1.379 matthew 8967: #
8968: # EXT resource caching routines
8969: #
8970:
8971: sub clear_EXT_cache_status {
1.383 albertel 8972: &delenv('cache.EXT.');
1.379 matthew 8973: }
8974:
8975: sub EXT_cache_status {
8976: my ($target_domain,$target_user) = @_;
1.383 albertel 8977: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 8978: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 8979: # We know already the user has no data
8980: return 1;
8981: } else {
8982: return 0;
8983: }
8984: }
8985:
8986: sub EXT_cache_set {
8987: my ($target_domain,$target_user) = @_;
1.383 albertel 8988: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 8989: #&appenv({$cachename => time});
1.379 matthew 8990: }
8991:
1.28 www 8992: # --------------------------------------------------------- Value of a Variable
1.58 www 8993: sub EXT {
1.715 albertel 8994:
1.395 albertel 8995: my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68 www 8996: unless ($varname) { return ''; }
1.218 albertel 8997: #get real user name/domain, courseid and symb
8998: my $courseid;
1.359 albertel 8999: my $publicuser;
1.427 www 9000: if ($symbparm) {
9001: $symbparm=&get_symb_from_alias($symbparm);
9002: }
1.218 albertel 9003: if (!($uname && $udom)) {
1.790 albertel 9004: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 9005: if (!$symbparm) { $symbparm=$cursymb; }
9006: } else {
1.620 albertel 9007: $courseid=$env{'request.course.id'};
1.218 albertel 9008: }
1.48 www 9009: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
9010: my $rest;
1.320 albertel 9011: if (defined($therest[0])) {
1.48 www 9012: $rest=join('.',@therest);
9013: } else {
9014: $rest='';
9015: }
1.320 albertel 9016:
1.57 www 9017: my $qualifierrest=$qualifier;
9018: if ($rest) { $qualifierrest.='.'.$rest; }
9019: my $spacequalifierrest=$space;
9020: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 9021: if ($realm eq 'user') {
1.48 www 9022: # --------------------------------------------------------------- user.resource
9023: if ($space eq 'resource') {
1.651 albertel 9024: if ( (defined($Apache::lonhomework::parsing_a_problem)
9025: || defined($Apache::lonhomework::parsing_a_task))
9026: &&
1.744 albertel 9027: ($symbparm eq &symbread()) ) {
9028: # if we are in the middle of processing the resource the
9029: # get the value we are planning on committing
9030: if (defined($Apache::lonhomework::results{$qualifierrest})) {
9031: return $Apache::lonhomework::results{$qualifierrest};
9032: } else {
9033: return $Apache::lonhomework::history{$qualifierrest};
9034: }
1.335 albertel 9035: } else {
1.359 albertel 9036: my %restored;
1.620 albertel 9037: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 9038: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
9039: } else {
9040: %restored=&restore($symbparm,$courseid,$udom,$uname);
9041: }
1.335 albertel 9042: return $restored{$qualifierrest};
9043: }
1.48 www 9044: # ----------------------------------------------------------------- user.access
9045: } elsif ($space eq 'access') {
1.218 albertel 9046: # FIXME - not supporting calls for a specific user
1.48 www 9047: return &allowed($qualifier,$rest);
9048: # ------------------------------------------ user.preferences, user.environment
9049: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 9050: if (($uname eq $env{'user.name'}) &&
9051: ($udom eq $env{'user.domain'})) {
9052: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 9053: } else {
1.359 albertel 9054: my %returnhash;
9055: if (!$publicuser) {
9056: %returnhash=&userenvironment($udom,$uname,
9057: $qualifierrest);
9058: }
1.218 albertel 9059: return $returnhash{$qualifierrest};
9060: }
1.48 www 9061: # ----------------------------------------------------------------- user.course
9062: } elsif ($space eq 'course') {
1.218 albertel 9063: # FIXME - not supporting calls for a specific user
1.620 albertel 9064: return $env{join('.',('request.course',$qualifier))};
1.48 www 9065: # ------------------------------------------------------------------- user.role
9066: } elsif ($space eq 'role') {
1.218 albertel 9067: # FIXME - not supporting calls for a specific user
1.620 albertel 9068: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 9069: if ($qualifier eq 'value') {
9070: return $role;
9071: } elsif ($qualifier eq 'extent') {
9072: return $where;
9073: }
9074: # ----------------------------------------------------------------- user.domain
9075: } elsif ($space eq 'domain') {
1.218 albertel 9076: return $udom;
1.48 www 9077: # ------------------------------------------------------------------- user.name
9078: } elsif ($space eq 'name') {
1.218 albertel 9079: return $uname;
1.48 www 9080: # ---------------------------------------------------- Any other user namespace
1.29 www 9081: } else {
1.359 albertel 9082: my %reply;
9083: if (!$publicuser) {
9084: %reply=&get($space,[$qualifierrest],$udom,$uname);
9085: }
9086: return $reply{$qualifierrest};
1.48 www 9087: }
1.236 www 9088: } elsif ($realm eq 'query') {
9089: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 9090: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
9091: [$spacequalifierrest]);
1.620 albertel 9092: return $env{'form.'.$spacequalifierrest};
1.236 www 9093: } elsif ($realm eq 'request') {
1.48 www 9094: # ------------------------------------------------------------- request.browser
9095: if ($space eq 'browser') {
1.1145 bisitz 9096: return $env{'browser.'.$qualifier};
1.57 www 9097: # ------------------------------------------------------------ request.filename
9098: } else {
1.620 albertel 9099: return $env{'request.'.$spacequalifierrest};
1.29 www 9100: }
1.28 www 9101: } elsif ($realm eq 'course') {
1.48 www 9102: # ---------------------------------------------------------- course.description
1.620 albertel 9103: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 9104: } elsif ($realm eq 'resource') {
1.165 www 9105:
1.620 albertel 9106: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 9107: if (!$symbparm) { $symbparm=&symbread(); }
9108: }
1.693 albertel 9109:
9110: if ($space eq 'title') {
9111: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
9112: return &gettitle($symbparm);
9113: }
9114:
9115: if ($space eq 'map') {
9116: my ($map) = &decode_symb($symbparm);
9117: return &symbread($map);
9118: }
1.905 albertel 9119: if ($space eq 'filename') {
9120: if ($symbparm) {
9121: return &clutter((&decode_symb($symbparm))[2]);
9122: }
9123: return &hreflocation('',$env{'request.filename'});
9124: }
1.693 albertel 9125:
9126: my ($section, $group, @groups);
1.593 albertel 9127: my ($courselevelm,$courselevel);
1.539 albertel 9128: if ($symbparm && defined($courseid) &&
1.620 albertel 9129: $courseid eq $env{'request.course.id'}) {
1.165 www 9130:
1.218 albertel 9131: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 9132:
1.60 www 9133: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 9134: my $symbp=$symbparm;
1.735 albertel 9135: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 9136:
9137: my $symbparm=$symbp.'.'.$spacequalifierrest;
9138: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
9139:
1.620 albertel 9140: if (($env{'user.name'} eq $uname) &&
9141: ($env{'user.domain'} eq $udom)) {
9142: $section=$env{'request.course.sec'};
1.733 raeburn 9143: @groups = split(/:/,$env{'request.course.groups'});
9144: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 9145: } else {
1.539 albertel 9146: if (! defined($usection)) {
1.551 albertel 9147: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 9148: } else {
9149: $section = $usection;
9150: }
1.733 raeburn 9151: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 9152: }
9153:
9154: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
9155: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
9156: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
9157:
1.593 albertel 9158: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 9159: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 9160: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 9161:
1.60 www 9162: # ----------------------------------------------------------- first, check user
1.624 albertel 9163:
9164: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 9165: ([$courselevelr,'resource'],
9166: [$courselevelm,'map' ],
9167: [$courselevel, 'course' ]));
1.931 albertel 9168: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 9169:
1.594 albertel 9170: # ------------------------------------------------ second, check some of course
1.684 raeburn 9171: my $coursereply;
1.691 raeburn 9172: if (@groups > 0) {
9173: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
9174: $mapparm,$spacequalifierrest);
1.927 albertel 9175: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 9176: }
1.96 www 9177:
1.684 raeburn 9178: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 9179: $env{'course.'.$courseid.'.domain'},
9180: 'course',
9181: ([$seclevelr, 'resource'],
9182: [$seclevelm, 'map' ],
9183: [$seclevel, 'course' ],
9184: [$courselevelr,'resource']));
9185: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 9186:
1.60 www 9187: # ------------------------------------------------------ third, check map parms
1.218 albertel 9188: my %parmhash=();
9189: my $thisparm='';
9190: if (tie(%parmhash,'GDBM_File',
1.620 albertel 9191: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 9192: &GDBM_READER(),0640)) {
1.218 albertel 9193: $thisparm=$parmhash{$symbparm};
9194: untie(%parmhash);
9195: }
1.927 albertel 9196: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 9197: }
1.594 albertel 9198: # ------------------------------------------ fourth, look in resource metadata
1.71 www 9199:
1.218 albertel 9200: $spacequalifierrest=~s/\./\_/;
1.282 albertel 9201: my $filename;
9202: if (!$symbparm) { $symbparm=&symbread(); }
9203: if ($symbparm) {
1.409 www 9204: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 9205: } else {
1.620 albertel 9206: $filename=$env{'request.filename'};
1.282 albertel 9207: }
9208: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 9209: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 9210: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 9211: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 9212:
1.927 albertel 9213: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 9214: if ($symbparm && defined($courseid) &&
1.620 albertel 9215: $courseid eq $env{'request.course.id'}) {
1.624 albertel 9216: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
9217: $env{'course.'.$courseid.'.domain'},
9218: 'course',
1.927 albertel 9219: ([$courselevelm,'map' ],
9220: [$courselevel, 'course']));
9221: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 9222: }
1.145 www 9223: # ------------------------------------------------------------------ Cascade up
1.218 albertel 9224: unless ($space eq '0') {
1.336 albertel 9225: my @parts=split(/_/,$space);
9226: my $id=pop(@parts);
9227: my $part=join('_',@parts);
9228: if ($part eq '') { $part='0'; }
1.927 albertel 9229: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 9230: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 9231: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 9232: }
1.395 albertel 9233: if ($recurse) { return undef; }
9234: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 9235: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 9236: # ---------------------------------------------------- Any other user namespace
9237: } elsif ($realm eq 'environment') {
9238: # ----------------------------------------------------------------- environment
1.620 albertel 9239: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
9240: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 9241: } else {
1.770 albertel 9242: if ($uname eq 'anonymous' && $udom eq '') {
9243: return '';
9244: }
1.219 albertel 9245: my %returnhash=&userenvironment($udom,$uname,
9246: $spacequalifierrest);
9247: return $returnhash{$spacequalifierrest};
9248: }
1.28 www 9249: } elsif ($realm eq 'system') {
1.48 www 9250: # ----------------------------------------------------------------- system.time
9251: if ($space eq 'time') {
9252: return time;
9253: }
1.696 albertel 9254: } elsif ($realm eq 'server') {
9255: # ----------------------------------------------------------------- system.time
9256: if ($space eq 'name') {
9257: return $ENV{'SERVER_NAME'};
9258: }
1.28 www 9259: }
1.48 www 9260: return '';
1.61 www 9261: }
9262:
1.927 albertel 9263: sub get_reply {
9264: my ($reply_value) = @_;
1.940 raeburn 9265: if (ref($reply_value) eq 'ARRAY') {
9266: if (wantarray) {
9267: return @$reply_value;
9268: }
9269: return $reply_value->[0];
9270: } else {
9271: return $reply_value;
1.927 albertel 9272: }
9273: }
9274:
1.691 raeburn 9275: sub check_group_parms {
9276: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
9277: my @groupitems = ();
9278: my $resultitem;
1.927 albertel 9279: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 9280: foreach my $group (@{$groups}) {
9281: foreach my $level (@levels) {
1.927 albertel 9282: my $item = $courseid.'.['.$group.'].'.$level->[0];
9283: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 9284: }
9285: }
9286: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
9287: $env{'course.'.$courseid.'.domain'},
9288: 'course',@groupitems);
9289: return $coursereply;
9290: }
9291:
9292: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 9293: my ($courseid,@groups) = @_;
9294: @groups = sort(@groups);
1.691 raeburn 9295: return @groups;
9296: }
9297:
1.395 albertel 9298: sub packages_tab_default {
9299: my ($uri,$varname)=@_;
9300: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 9301:
9302: my (@extension,@specifics,$do_default);
9303: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 9304: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 9305: if ($pack_type eq 'default') {
9306: $do_default=1;
9307: } elsif ($pack_type eq 'extension') {
9308: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 9309: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 9310: # only look at packages defaults for packages that this id is
1.738 albertel 9311: push(@specifics,[$package,$pack_type,$pack_part]);
9312: }
9313: }
9314: # first look for a package that matches the requested part id
9315: foreach my $package (@specifics) {
9316: my (undef,$pack_type,$pack_part)=@{$package};
9317: next if ($pack_part ne $part);
9318: if (defined($packagetab{"$pack_type&$name&default"})) {
9319: return $packagetab{"$pack_type&$name&default"};
9320: }
9321: }
9322: # look for any possible matching non extension_ package
9323: foreach my $package (@specifics) {
9324: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 9325: if (defined($packagetab{"$pack_type&$name&default"})) {
9326: return $packagetab{"$pack_type&$name&default"};
9327: }
1.585 albertel 9328: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 9329: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
9330: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 9331: }
9332: }
1.738 albertel 9333: # look for any posible extension_ match
9334: foreach my $package (@extension) {
9335: my ($package,$pack_type)=@{$package};
9336: if (defined($packagetab{"$pack_type&$name&default"})) {
9337: return $packagetab{"$pack_type&$name&default"};
9338: }
9339: if (defined($packagetab{$package."&$name&default"})) {
9340: return $packagetab{$package."&$name&default"};
9341: }
9342: }
9343: # look for a global default setting
9344: if ($do_default && defined($packagetab{"default&$name&default"})) {
9345: return $packagetab{"default&$name&default"};
9346: }
1.395 albertel 9347: return undef;
9348: }
9349:
1.334 albertel 9350: sub add_prefix_and_part {
9351: my ($prefix,$part)=@_;
9352: my $keyroot;
9353: if (defined($prefix) && $prefix !~ /^__/) {
9354: # prefix that has a part already
9355: $keyroot=$prefix;
9356: } elsif (defined($prefix)) {
9357: # prefix that is missing a part
9358: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
9359: } else {
9360: # no prefix at all
9361: if (defined($part)) { $keyroot='_'.$part; }
9362: }
9363: return $keyroot;
9364: }
9365:
1.71 www 9366: # ---------------------------------------------------------------- Get metadata
9367:
1.599 albertel 9368: my %metaentry;
1.1070 www 9369: my %importedpartids;
1.71 www 9370: sub metadata {
1.176 www 9371: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 9372: $uri=&declutter($uri);
1.288 albertel 9373: # if it is a non metadata possible uri return quickly
1.529 albertel 9374: if (($uri eq '') ||
9375: (($uri =~ m|^/*adm/|) &&
1.698 albertel 9376: ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.1108 raeburn 9377: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 9378: return undef;
9379: }
1.1140 www 9380: if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/)
1.924 albertel 9381: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 9382: return undef;
1.288 albertel 9383: }
1.73 www 9384: my $filename=$uri;
9385: $uri=~s/\.meta$//;
1.172 www 9386: #
9387: # Is the metadata already cached?
1.177 www 9388: # Look at timestamp of caching
1.172 www 9389: # Everything is cached by the main uri, libraries are never directly cached
9390: #
1.428 albertel 9391: if (!defined($liburi)) {
1.599 albertel 9392: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 9393: if (defined($cached)) { return $result->{':'.$what}; }
9394: }
9395: {
1.1069 www 9396: # Imported parts would go here
1.1070 www 9397: my %importedids=();
9398: my @origfileimportpartids=();
1.1069 www 9399: my $importedparts=0;
1.172 www 9400: #
9401: # Is this a recursive call for a library?
9402: #
1.599 albertel 9403: # if (! exists($metacache{$uri})) {
9404: # $metacache{$uri}={};
9405: # }
1.924 albertel 9406: my $cachetime = 60*60;
1.171 www 9407: if ($liburi) {
9408: $liburi=&declutter($liburi);
9409: $filename=$liburi;
1.401 bowersj2 9410: } else {
1.599 albertel 9411: &devalidate_cache_new('meta',$uri);
9412: undef(%metaentry);
1.401 bowersj2 9413: }
1.140 www 9414: my %metathesekeys=();
1.73 www 9415: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 9416: my $metastring;
1.1140 www 9417: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929 albertel 9418: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 9419: $metastring =
1.929 albertel 9420: &Apache::lonnet::ssi_body($which,
1.924 albertel 9421: ('grade_target' => 'meta'));
9422: $cachetime = 1; # only want this cached in the child not long term
1.1108 raeburn 9423: } elsif (($uri !~ m -^(editupload)/-) &&
9424: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 9425: my $file=&filelocation('',&clutter($filename));
1.599 albertel 9426: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 9427: $metastring=&getfile($file);
1.489 albertel 9428: }
1.208 albertel 9429: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 9430: my $token;
1.140 www 9431: undef %metathesekeys;
1.71 www 9432: while ($token=$parser->get_token) {
1.339 albertel 9433: if ($token->[0] eq 'S') {
9434: if (defined($token->[2]->{'package'})) {
1.172 www 9435: #
9436: # This is a package - get package info
9437: #
1.339 albertel 9438: my $package=$token->[2]->{'package'};
9439: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
9440: if (defined($token->[2]->{'id'})) {
9441: $keyroot.='_'.$token->[2]->{'id'};
9442: }
1.599 albertel 9443: if ($metaentry{':packages'}) {
9444: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 9445: } else {
1.599 albertel 9446: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 9447: }
1.736 albertel 9448: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 9449: my $part=$keyroot;
9450: $part=~s/^\_//;
1.736 albertel 9451: if ($pack_entry=~/^\Q$package\E\&/ ||
9452: $pack_entry=~/^\Q$package\E_0\&/) {
9453: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 9454: # ignore package.tab specified default values
9455: # here &package_tab_default() will fetch those
9456: if ($subp eq 'default') { next; }
1.736 albertel 9457: my $value=$packagetab{$pack_entry};
1.432 albertel 9458: my $unikey;
9459: if ($pack =~ /_0$/) {
9460: $unikey='parameter_0_'.$name;
9461: $part=0;
9462: } else {
9463: $unikey='parameter'.$keyroot.'_'.$name;
9464: }
1.339 albertel 9465: if ($subp eq 'display') {
9466: $value.=' [Part: '.$part.']';
9467: }
1.599 albertel 9468: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 9469: $metathesekeys{$unikey}=1;
1.599 albertel 9470: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
9471: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 9472: }
1.599 albertel 9473: if (defined($metaentry{':'.$unikey.'.default'})) {
9474: $metaentry{':'.$unikey}=
9475: $metaentry{':'.$unikey.'.default'};
1.356 albertel 9476: }
1.339 albertel 9477: }
9478: }
9479: } else {
1.172 www 9480: #
9481: # This is not a package - some other kind of start tag
1.339 albertel 9482: #
9483: my $entry=$token->[1];
1.1068 www 9484: my $unikey='';
1.175 www 9485:
1.339 albertel 9486: if ($entry eq 'import') {
1.175 www 9487: #
9488: # Importing a library here
1.339 albertel 9489: #
1.1067 www 9490: my $location=$parser->get_text('/import');
9491: my $dir=$filename;
9492: $dir=~s|[^/]*$||;
9493: $location=&filelocation($dir,$location);
1.1069 www 9494:
1.1068 www 9495: my $importmode=$token->[2]->{'importmode'};
9496: if ($importmode eq 'problem') {
1.1069 www 9497: # Import as problem/response
1.1068 www 9498: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
9499: } elsif ($importmode eq 'part') {
9500: # Import as part(s)
1.1069 www 9501: $importedparts=1;
9502: # We need to get the original file and the imported file to get the part order correct
9503: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
9504: # Load and inspect original file
1.1070 www 9505: if ($#origfileimportpartids<0) {
9506: undef(%importedpartids);
9507: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
9508: my $origfile=&getfile($origfilelocation);
9509: @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
9510: }
9511:
1.1069 www 9512: # Load and inspect imported file
9513: my $impfile=&getfile($location);
9514: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
9515: if ($#impfilepartids>=0) {
9516: # This problem had parts
1.1070 www 9517: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 9518: } else {
9519: # Importing by turning a single problem into a problem part
9520: # It gets the import-tags ID as part-ID
9521: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 9522: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 9523: }
1.1068 www 9524: } else {
9525: # Normal import
9526: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
9527: if (defined($token->[2]->{'id'})) {
9528: $unikey.='_'.$token->[2]->{'id'};
9529: }
1.1067 www 9530: }
9531:
1.339 albertel 9532: if ($depthcount<20) {
1.736 albertel 9533: my $metadata =
9534: &metadata($uri,'keys', $location,$unikey,
9535: $depthcount+1);
9536: foreach my $meta (split(',',$metadata)) {
9537: $metaentry{':'.$meta}=$metaentry{':'.$meta};
9538: $metathesekeys{$meta}=1;
1.339 albertel 9539: }
1.1068 www 9540:
9541: }
1.1067 www 9542: } else {
9543: #
9544: # Not importing, some other kind of non-package, non-library start tag
9545: #
9546: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
9547: if (defined($token->[2]->{'id'})) {
9548: $unikey.='_'.$token->[2]->{'id'};
9549: }
1.339 albertel 9550: if (defined($token->[2]->{'name'})) {
9551: $unikey.='_'.$token->[2]->{'name'};
9552: }
9553: $metathesekeys{$unikey}=1;
1.736 albertel 9554: foreach my $param (@{$token->[3]}) {
9555: $metaentry{':'.$unikey.'.'.$param} =
9556: $token->[2]->{$param};
1.339 albertel 9557: }
9558: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 9559: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 9560: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
9561: # only ws inside the tag, and not in default, so use default
9562: # as value
1.599 albertel 9563: $metaentry{':'.$unikey}=$default;
1.908 albertel 9564: } elsif ( $internaltext =~ /\S/ ) {
9565: # something interesting inside the tag
9566: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 9567: } else {
1.908 albertel 9568: # no interesting values, don't set a default
1.339 albertel 9569: }
1.172 www 9570: # end of not-a-package not-a-library import
1.339 albertel 9571: }
1.172 www 9572: # end of not-a-package start tag
1.339 albertel 9573: }
1.172 www 9574: # the next is the end of "start tag"
1.339 albertel 9575: }
9576: }
1.483 albertel 9577: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 9578: $extension = lc($extension);
9579: if ($extension eq 'htm') { $extension='html'; }
9580:
1.737 albertel 9581: foreach my $key (keys(%packagetab)) {
1.483 albertel 9582: #no specific packages #how's our extension
9583: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 9584: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 9585: \%metathesekeys);
9586: }
1.883 albertel 9587:
9588: if (!exists($metaentry{':packages'})
9589: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 9590: foreach my $key (keys(%packagetab)) {
1.483 albertel 9591: #no specific packages well let's get default then
9592: if ($key!~/^default&/) { next; }
1.488 albertel 9593: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 9594: \%metathesekeys);
9595: }
9596: }
1.338 www 9597: # are there custom rights to evaluate
1.599 albertel 9598: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 9599:
1.338 www 9600: #
9601: # Importing a rights file here
1.339 albertel 9602: #
9603: unless ($depthcount) {
1.599 albertel 9604: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 9605: my $dir=$filename;
9606: $dir=~s|[^/]*$||;
9607: $location=&filelocation($dir,$location);
1.736 albertel 9608: my $rights_metadata =
9609: &metadata($uri,'keys',$location,'_rights',
9610: $depthcount+1);
9611: foreach my $rights (split(',',$rights_metadata)) {
9612: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
9613: $metathesekeys{$rights}=1;
1.339 albertel 9614: }
9615: }
9616: }
1.737 albertel 9617: # uniqifiy package listing
9618: my %seen;
9619: my @uniq_packages =
9620: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
9621: $metaentry{':packages'} = join(',',@uniq_packages);
9622:
1.1070 www 9623: if ($importedparts) {
9624: # We had imported parts and need to rebuild partorder
9625: $metaentry{':partorder'}='';
9626: $metathesekeys{'partorder'}=1;
9627: for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
9628: if ($origfileimportpartids[$index] eq 'part') {
9629: # original part, part of the problem
9630: $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
9631: } else {
9632: # we have imported parts at this position
9633: $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
9634: }
9635: }
9636: $metaentry{':partorder'}=~s/^\,//;
9637: }
9638:
1.737 albertel 9639: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 9640: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
9641: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924 albertel 9642: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 9643: # this is the end of "was not already recently cached
1.71 www 9644: }
1.599 albertel 9645: return $metaentry{':'.$what};
1.261 albertel 9646: }
9647:
1.488 albertel 9648: sub metadata_create_package_def {
1.483 albertel 9649: my ($uri,$key,$package,$metathesekeys)=@_;
9650: my ($pack,$name,$subp)=split(/\&/,$key);
9651: if ($subp eq 'default') { next; }
9652:
1.599 albertel 9653: if (defined($metaentry{':packages'})) {
9654: $metaentry{':packages'}.=','.$package;
1.483 albertel 9655: } else {
1.599 albertel 9656: $metaentry{':packages'}=$package;
1.483 albertel 9657: }
9658: my $value=$packagetab{$key};
9659: my $unikey;
9660: $unikey='parameter_0_'.$name;
1.599 albertel 9661: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 9662: $$metathesekeys{$unikey}=1;
1.599 albertel 9663: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
9664: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 9665: }
1.599 albertel 9666: if (defined($metaentry{':'.$unikey.'.default'})) {
9667: $metaentry{':'.$unikey}=
9668: $metaentry{':'.$unikey.'.default'};
1.483 albertel 9669: }
9670: }
9671:
1.261 albertel 9672: sub metadata_generate_part0 {
9673: my ($metadata,$metacache,$uri) = @_;
9674: my %allnames;
1.737 albertel 9675: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 9676: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 9677: my $part=$$metacache{':'.$metakey.'.part'};
9678: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 9679: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 9680: $allnames{$name}=$part;
9681: }
9682: }
9683: }
9684: foreach my $name (keys(%allnames)) {
9685: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 9686: my $key=":parameter_0_$name";
1.261 albertel 9687: $$metacache{"$key.part"}='0';
9688: $$metacache{"$key.name"}=$name;
1.428 albertel 9689: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 9690: $allnames{$name}.'_'.$name.
9691: '.type'};
1.428 albertel 9692: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 9693: '.display'};
1.644 www 9694: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 9695: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 9696: $$metacache{"$key.display"}=$olddis;
9697: }
1.71 www 9698: }
9699:
1.764 albertel 9700: # ------------------------------------------------------ Devalidate title cache
9701:
9702: sub devalidate_title_cache {
9703: my ($url)=@_;
9704: if (!$env{'request.course.id'}) { return; }
9705: my $symb=&symbread($url);
9706: if (!$symb) { return; }
9707: my $key=$env{'request.course.id'}."\0".$symb;
9708: &devalidate_cache_new('title',$key);
9709: }
9710:
1.1014 droeschl 9711: # ------------------------------------------------- Get the title of a course
9712:
9713: sub current_course_title {
9714: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
9715: }
1.301 www 9716: # ------------------------------------------------- Get the title of a resource
9717:
9718: sub gettitle {
9719: my $urlsymb=shift;
9720: my $symb=&symbread($urlsymb);
1.534 albertel 9721: if ($symb) {
1.620 albertel 9722: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 9723: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 9724: if (defined($cached)) {
9725: return $result;
9726: }
1.534 albertel 9727: my ($map,$resid,$url)=&decode_symb($symb);
9728: my $title='';
1.907 albertel 9729: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
9730: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
9731: } else {
9732: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
9733: &GDBM_READER(),0640)) {
9734: my $mapid=$bighash{'map_pc_'.&clutter($map)};
9735: $title=$bighash{'title_'.$mapid.'.'.$resid};
9736: untie(%bighash);
9737: }
1.534 albertel 9738: }
9739: $title=~s/\&colon\;/\:/gs;
9740: if ($title) {
1.1159 www 9741: # Remember both $symb and $title for dynamic metadata
9742: $accesshash{$symb.'___crstitle'}=$title;
1.1161 www 9743: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159 www 9744: # Cache this title and then return it
1.599 albertel 9745: return &do_cache_new('title',$key,$title,600);
1.534 albertel 9746: }
9747: $urlsymb=$url;
9748: }
9749: my $title=&metadata($urlsymb,'title');
9750: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
9751: return $title;
1.301 www 9752: }
1.613 albertel 9753:
1.614 albertel 9754: sub get_slot {
9755: my ($which,$cnum,$cdom)=@_;
9756: if (!$cnum || !$cdom) {
1.790 albertel 9757: (undef,my $courseid)=&whichuser();
1.620 albertel 9758: $cdom=$env{'course.'.$courseid.'.domain'};
9759: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 9760: }
1.703 albertel 9761: my $key=join("\0",'slots',$cdom,$cnum,$which);
9762: my %slotinfo;
9763: if (exists($remembered{$key})) {
9764: $slotinfo{$which} = $remembered{$key};
9765: } else {
9766: %slotinfo=&get('slots',[$which],$cdom,$cnum);
9767: &Apache::lonhomework::showhash(%slotinfo);
9768: my ($tmp)=keys(%slotinfo);
9769: if ($tmp=~/^error:/) { return (); }
9770: $remembered{$key} = $slotinfo{$which};
9771: }
1.616 albertel 9772: if (ref($slotinfo{$which}) eq 'HASH') {
9773: return %{$slotinfo{$which}};
9774: }
9775: return $slotinfo{$which};
1.614 albertel 9776: }
1.1150 raeburn 9777:
9778: sub get_reservable_slots {
9779: my ($cnum,$cdom,$uname,$udom) = @_;
9780: my $now = time;
9781: my $reservable_info;
9782: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
9783: if (exists($remembered{$key})) {
9784: $reservable_info = $remembered{$key};
9785: } else {
9786: my %resv;
9787: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
9788: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
9789: $reservable_info = \%resv;
9790: $remembered{$key} = $reservable_info;
9791: }
9792: return $reservable_info;
9793: }
9794:
9795: sub get_course_slots {
9796: my ($cnum,$cdom) = @_;
9797: my $hashid=$cnum.':'.$cdom;
9798: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
9799: if (defined($cached)) {
9800: if (ref($result) eq 'HASH') {
9801: return %{$result};
9802: }
9803: } else {
9804: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
9805: my ($tmp) = keys(%slots);
9806: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
9807: &Apache::lonnet::do_cache_new('allslots',$hashid,\%slots,600);
9808: return %slots;
9809: }
9810: }
9811: return;
9812: }
9813:
9814: sub devalidate_slots_cache {
9815: my ($cnum,$cdom)=@_;
9816: my $hashid=$cnum.':'.$cdom;
9817: &devalidate_cache_new('allslots',$hashid);
9818: }
9819:
1.31 www 9820: # ------------------------------------------------- Update symbolic store links
9821:
9822: sub symblist {
9823: my ($mapname,%newhash)=@_;
1.438 www 9824: $mapname=&deversion(&declutter($mapname));
1.31 www 9825: my %hash;
1.620 albertel 9826: if (($env{'request.course.fn'}) && (%newhash)) {
9827: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 9828: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 9829: foreach my $url (keys(%newhash)) {
1.711 albertel 9830: next if ($url eq 'last_known'
9831: && $env{'form.no_update_last_known'});
9832: $hash{declutter($url)}=&encode_symb($mapname,
9833: $newhash{$url}->[1],
9834: $newhash{$url}->[0]);
1.191 harris41 9835: }
1.31 www 9836: if (untie(%hash)) {
9837: return 'ok';
9838: }
9839: }
9840: }
9841: return 'error';
1.212 www 9842: }
9843:
9844: # --------------------------------------------------------------- Verify a symb
9845:
9846: sub symbverify {
1.510 www 9847: my ($symb,$thisurl)=@_;
9848: my $thisfn=$thisurl;
1.439 www 9849: $thisfn=&declutter($thisfn);
1.215 www 9850: # direct jump to resource in page or to a sequence - will construct own symbs
9851: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
9852: # check URL part
1.409 www 9853: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 9854:
1.431 www 9855: unless ($url eq $thisfn) { return 0; }
1.213 www 9856:
1.216 www 9857: $symb=&symbclean($symb);
1.510 www 9858: $thisurl=&deversion($thisurl);
1.439 www 9859: $thisfn=&deversion($thisfn);
1.213 www 9860:
9861: my %bighash;
9862: my $okay=0;
1.431 www 9863:
1.620 albertel 9864: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 9865: &GDBM_READER(),0640)) {
1.1032 raeburn 9866: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
9867: $thisurl =~ s/\?.+$//;
9868: }
1.510 www 9869: my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1102 raeburn 9870: unless ($ids) {
9871: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
9872: $ids=$bighash{$idkey};
1.216 www 9873: }
9874: if ($ids) {
9875: # ------------------------------------------------------------------- Has ID(s)
1.800 albertel 9876: foreach my $id (split(/\,/,$ids)) {
9877: my ($mapid,$resid)=split(/\./,$id);
1.1032 raeburn 9878: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
9879: $symb =~ s/\?.+$//;
9880: }
1.216 www 9881: if (
9882: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
9883: eq $symb) {
1.620 albertel 9884: if (($env{'request.role.adv'}) ||
1.1101 raeburn 9885: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
9886: ($thisurl eq '/adm/navmaps')) {
1.582 albertel 9887: $okay=1;
9888: }
9889: }
1.216 www 9890: }
9891: }
1.213 www 9892: untie(%bighash);
9893: }
9894: return $okay;
1.31 www 9895: }
9896:
1.210 www 9897: # --------------------------------------------------------------- Clean-up symb
9898:
9899: sub symbclean {
9900: my $symb=shift;
1.568 albertel 9901: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 9902: # remove version from map
9903: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 9904:
1.210 www 9905: # remove version from URL
9906: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 9907:
1.507 www 9908: # remove wrapper
9909:
1.510 www 9910: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 9911: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 9912: return $symb;
1.409 www 9913: }
9914:
9915: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 9916:
9917: sub encode_symb {
9918: my ($map,$resid,$url)=@_;
9919: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
9920: }
1.409 www 9921:
9922: sub decode_symb {
1.568 albertel 9923: my $symb=shift;
9924: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
9925: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 9926: return (&fixversion($map),$resid,&fixversion($url));
9927: }
9928:
9929: sub fixversion {
9930: my $fn=shift;
1.609 banghart 9931: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 9932: my %bighash;
9933: my $uri=&clutter($fn);
1.620 albertel 9934: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 9935: # is this cached?
1.599 albertel 9936: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 9937: if (defined($cached)) { return $result; }
9938: # unfortunately not cached, or expired
1.620 albertel 9939: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 9940: &GDBM_READER(),0640)) {
9941: if ($bighash{'version_'.$uri}) {
9942: my $version=$bighash{'version_'.$uri};
1.444 www 9943: unless (($version eq 'mostrecent') ||
9944: ($version==&getversion($uri))) {
1.440 www 9945: $uri=~s/\.(\w+)$/\.$version\.$1/;
9946: }
9947: }
9948: untie %bighash;
1.413 www 9949: }
1.599 albertel 9950: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 9951: }
9952:
9953: sub deversion {
9954: my $url=shift;
9955: $url=~s/\.\d+\.(\w+)$/\.$1/;
9956: return $url;
1.210 www 9957: }
9958:
1.31 www 9959: # ------------------------------------------------------ Return symb list entry
9960:
9961: sub symbread {
1.249 www 9962: my ($thisfn,$donotrecurse)=@_;
1.542 albertel 9963: my $cache_str='request.symbread.cached.'.$thisfn;
1.620 albertel 9964: if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242 www 9965: # no filename provided? try from environment
1.44 www 9966: unless ($thisfn) {
1.620 albertel 9967: if ($env{'request.symb'}) {
9968: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 9969: }
1.620 albertel 9970: $thisfn=$env{'request.filename'};
1.44 www 9971: }
1.569 albertel 9972: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 9973: # is that filename actually a symb? Verify, clean, and return
9974: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 9975: if (&symbverify($thisfn,$1)) {
1.620 albertel 9976: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 9977: }
1.242 www 9978: }
1.44 www 9979: $thisfn=declutter($thisfn);
1.31 www 9980: my %hash;
1.37 www 9981: my %bighash;
9982: my $syval='';
1.620 albertel 9983: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 9984: my $targetfn = $thisfn;
1.609 banghart 9985: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 9986: $targetfn = 'adm/wrapper/'.$thisfn;
9987: }
1.687 albertel 9988: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
9989: $targetfn=$1;
9990: }
1.620 albertel 9991: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 9992: &GDBM_READER(),0640)) {
1.481 raeburn 9993: $syval=$hash{$targetfn};
1.37 www 9994: untie(%hash);
9995: }
9996: # ---------------------------------------------------------- There was an entry
9997: if ($syval) {
1.601 albertel 9998: #unless ($syval=~/\_\d+$/) {
1.620 albertel 9999: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 10000: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 10001: #return $env{$cache_str}='';
1.601 albertel 10002: #}
10003: #$syval.=$1;
10004: #}
1.37 www 10005: } else {
10006: # ------------------------------------------------------- Was not in symb table
1.620 albertel 10007: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 10008: &GDBM_READER(),0640)) {
1.37 www 10009: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 10010: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 10011: unless ($ids) {
10012: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 10013: }
10014: unless ($ids) {
10015: # alias?
10016: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 10017: }
1.37 www 10018: if ($ids) {
10019: # ------------------------------------------------------------------- Has ID(s)
10020: my @possibilities=split(/\,/,$ids);
1.39 www 10021: if ($#possibilities==0) {
10022: # ----------------------------------------------- There is only one possibility
1.37 www 10023: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 10024: $syval=&encode_symb($bighash{'map_id_'.$mapid},
10025: $resid,$thisfn);
1.249 www 10026: } elsif (!$donotrecurse) {
1.39 www 10027: # ------------------------------------------ There is more than one possibility
10028: my $realpossible=0;
1.800 albertel 10029: foreach my $id (@possibilities) {
10030: my $file=$bighash{'src_'.$id};
1.39 www 10031: if (&allowed('bre',$file)) {
1.800 albertel 10032: my ($mapid,$resid)=split(/\./,$id);
1.39 www 10033: if ($bighash{'map_type_'.$mapid} ne 'page') {
10034: $realpossible++;
1.626 albertel 10035: $syval=&encode_symb($bighash{'map_id_'.$mapid},
10036: $resid,$thisfn);
1.39 www 10037: }
10038: }
1.191 harris41 10039: }
1.39 www 10040: if ($realpossible!=1) { $syval=''; }
1.249 www 10041: } else {
10042: $syval='';
1.37 www 10043: }
10044: }
10045: untie(%bighash)
1.481 raeburn 10046: }
1.31 www 10047: }
1.62 www 10048: if ($syval) {
1.620 albertel 10049: return $env{$cache_str}=$syval;
1.62 www 10050: }
1.31 www 10051: }
1.949 raeburn 10052: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 10053: return $env{$cache_str}='';
1.31 www 10054: }
10055:
10056: # ---------------------------------------------------------- Return random seed
10057:
1.32 www 10058: sub numval {
10059: my $txt=shift;
10060: $txt=~tr/A-J/0-9/;
10061: $txt=~tr/a-j/0-9/;
10062: $txt=~tr/K-T/0-9/;
10063: $txt=~tr/k-t/0-9/;
10064: $txt=~tr/U-Z/0-5/;
10065: $txt=~tr/u-z/0-5/;
10066: $txt=~s/\D//g;
1.564 albertel 10067: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 10068: return int($txt);
1.368 albertel 10069: }
10070:
1.484 albertel 10071: sub numval2 {
10072: my $txt=shift;
10073: $txt=~tr/A-J/0-9/;
10074: $txt=~tr/a-j/0-9/;
10075: $txt=~tr/K-T/0-9/;
10076: $txt=~tr/k-t/0-9/;
10077: $txt=~tr/U-Z/0-5/;
10078: $txt=~tr/u-z/0-5/;
10079: $txt=~s/\D//g;
10080: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10081: my $total;
10082: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 10083: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 10084: return int($total);
10085: }
10086:
1.575 albertel 10087: sub numval3 {
10088: use integer;
10089: my $txt=shift;
10090: $txt=~tr/A-J/0-9/;
10091: $txt=~tr/a-j/0-9/;
10092: $txt=~tr/K-T/0-9/;
10093: $txt=~tr/k-t/0-9/;
10094: $txt=~tr/U-Z/0-5/;
10095: $txt=~tr/u-z/0-5/;
10096: $txt=~s/\D//g;
10097: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10098: my $total;
10099: foreach my $val (@txts) { $total+=$val; }
10100: if ($_64bit) { $total=(($total<<32)>>32); }
10101: return $total;
10102: }
10103:
1.675 albertel 10104: sub digest {
10105: my ($data)=@_;
10106: my $digest=&Digest::MD5::md5($data);
10107: my ($a,$b,$c,$d)=unpack("iiii",$digest);
10108: my ($e,$f);
10109: {
10110: use integer;
10111: $e=($a+$b);
10112: $f=($c+$d);
10113: if ($_64bit) {
10114: $e=(($e<<32)>>32);
10115: $f=(($f<<32)>>32);
10116: }
10117: }
10118: if (wantarray) {
10119: return ($e,$f);
10120: } else {
10121: my $g;
10122: {
10123: use integer;
10124: $g=($e+$f);
10125: if ($_64bit) {
10126: $g=(($g<<32)>>32);
10127: }
10128: }
10129: return $g;
10130: }
10131: }
10132:
1.368 albertel 10133: sub latest_rnd_algorithm_id {
1.675 albertel 10134: return '64bit5';
1.366 albertel 10135: }
1.32 www 10136:
1.503 albertel 10137: sub get_rand_alg {
10138: my ($courseid)=@_;
1.790 albertel 10139: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 10140: if ($courseid) {
1.620 albertel 10141: return $env{"course.$courseid.rndseed"};
1.503 albertel 10142: }
10143: return &latest_rnd_algorithm_id();
10144: }
10145:
1.562 albertel 10146: sub validCODE {
10147: my ($CODE)=@_;
10148: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
10149: return 0;
10150: }
10151:
1.491 albertel 10152: sub getCODE {
1.620 albertel 10153: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 10154: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
10155: defined($Apache::lonhomework::parsing_a_task) ) &&
10156: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 10157: return $Apache::lonhomework::history{'resource.CODE'};
10158: }
10159: return undef;
10160: }
1.1133 foxr 10161: #
10162: # Determines the random seed for a specific context:
10163: #
10164: # parameters:
10165: # symb - in course context the symb for the seed.
10166: # course_id - The course id of the form domain_coursenum.
10167: # domain - Domain for the user.
10168: # course - Course for the user.
10169: # cenv - environment of the course.
10170: #
10171: # NOTE:
10172: # All parameters are picked out of the environment if missing
10173: # or not defined.
10174: # If a symb cannot be determined the current time is used instead.
10175: #
10176: # For a given well defined symb, courside, domain, username,
10177: # and course environment, the seed is reproducible.
10178: #
1.31 www 10179: sub rndseed {
1.1133 foxr 10180: my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790 albertel 10181: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 10182: if (!defined($symb)) {
1.366 albertel 10183: unless ($symb=$wsymb) { return time; }
10184: }
1.1146 foxr 10185: if (!defined $courseid) {
10186: $courseid=$wcourseid;
10187: }
10188: if (!defined $domain) { $domain=$wdomain; }
10189: if (!defined $username) { $username=$wusername }
1.1133 foxr 10190:
10191: my $which;
10192: if (defined($cenv->{'rndseed'})) {
10193: $which = $cenv->{'rndseed'};
10194: } else {
10195: $which =&get_rand_alg($courseid);
10196: }
1.491 albertel 10197: if (defined(&getCODE())) {
1.1133 foxr 10198:
1.675 albertel 10199: if ($which eq '64bit5') {
10200: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
10201: } elsif ($which eq '64bit4') {
1.575 albertel 10202: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
10203: } else {
10204: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
10205: }
1.675 albertel 10206: } elsif ($which eq '64bit5') {
10207: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 10208: } elsif ($which eq '64bit4') {
10209: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 10210: } elsif ($which eq '64bit3') {
10211: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 10212: } elsif ($which eq '64bit2') {
10213: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 10214: } elsif ($which eq '64bit') {
10215: return &rndseed_64bit($symb,$courseid,$domain,$username);
10216: }
10217: return &rndseed_32bit($symb,$courseid,$domain,$username);
10218: }
10219:
10220: sub rndseed_32bit {
10221: my ($symb,$courseid,$domain,$username)=@_;
10222: {
10223: use integer;
10224: my $symbchck=unpack("%32C*",$symb) << 27;
10225: my $symbseed=numval($symb) << 22;
10226: my $namechck=unpack("%32C*",$username) << 17;
10227: my $nameseed=numval($username) << 12;
10228: my $domainseed=unpack("%32C*",$domain) << 7;
10229: my $courseseed=unpack("%32C*",$courseid);
10230: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 10231: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10232: #&logthis("rndseed :$num:$symb");
1.564 albertel 10233: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 10234: return $num;
10235: }
10236: }
10237:
10238: sub rndseed_64bit {
10239: my ($symb,$courseid,$domain,$username)=@_;
10240: {
10241: use integer;
10242: my $symbchck=unpack("%32S*",$symb) << 21;
10243: my $symbseed=numval($symb) << 10;
10244: my $namechck=unpack("%32S*",$username);
10245:
10246: my $nameseed=numval($username) << 21;
10247: my $domainseed=unpack("%32S*",$domain) << 10;
10248: my $courseseed=unpack("%32S*",$courseid);
10249:
10250: my $num1=$symbchck+$symbseed+$namechck;
10251: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 10252: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10253: #&logthis("rndseed :$num:$symb");
1.564 albertel 10254: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 10255: return "$num1,$num2";
1.155 albertel 10256: }
1.366 albertel 10257: }
10258:
1.443 albertel 10259: sub rndseed_64bit2 {
10260: my ($symb,$courseid,$domain,$username)=@_;
10261: {
10262: use integer;
10263: # strings need to be an even # of cahracters long, it it is odd the
10264: # last characters gets thrown away
10265: my $symbchck=unpack("%32S*",$symb.' ') << 21;
10266: my $symbseed=numval($symb) << 10;
10267: my $namechck=unpack("%32S*",$username.' ');
10268:
10269: my $nameseed=numval($username) << 21;
1.501 albertel 10270: my $domainseed=unpack("%32S*",$domain.' ') << 10;
10271: my $courseseed=unpack("%32S*",$courseid.' ');
10272:
10273: my $num1=$symbchck+$symbseed+$namechck;
10274: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 10275: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10276: #&logthis("rndseed :$num:$symb");
1.803 albertel 10277: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 10278: return "$num1,$num2";
10279: }
10280: }
10281:
10282: sub rndseed_64bit3 {
10283: my ($symb,$courseid,$domain,$username)=@_;
10284: {
10285: use integer;
10286: # strings need to be an even # of cahracters long, it it is odd the
10287: # last characters gets thrown away
10288: my $symbchck=unpack("%32S*",$symb.' ') << 21;
10289: my $symbseed=numval2($symb) << 10;
10290: my $namechck=unpack("%32S*",$username.' ');
10291:
10292: my $nameseed=numval2($username) << 21;
1.443 albertel 10293: my $domainseed=unpack("%32S*",$domain.' ') << 10;
10294: my $courseseed=unpack("%32S*",$courseid.' ');
10295:
10296: my $num1=$symbchck+$symbseed+$namechck;
10297: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 10298: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10299: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 10300: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 10301:
1.503 albertel 10302: return "$num1:$num2";
1.443 albertel 10303: }
10304: }
10305:
1.575 albertel 10306: sub rndseed_64bit4 {
10307: my ($symb,$courseid,$domain,$username)=@_;
10308: {
10309: use integer;
10310: # strings need to be an even # of cahracters long, it it is odd the
10311: # last characters gets thrown away
10312: my $symbchck=unpack("%32S*",$symb.' ') << 21;
10313: my $symbseed=numval3($symb) << 10;
10314: my $namechck=unpack("%32S*",$username.' ');
10315:
10316: my $nameseed=numval3($username) << 21;
10317: my $domainseed=unpack("%32S*",$domain.' ') << 10;
10318: my $courseseed=unpack("%32S*",$courseid.' ');
10319:
10320: my $num1=$symbchck+$symbseed+$namechck;
10321: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 10322: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10323: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 10324: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 10325:
1.575 albertel 10326: return "$num1:$num2";
10327: }
10328: }
10329:
1.675 albertel 10330: sub rndseed_64bit5 {
10331: my ($symb,$courseid,$domain,$username)=@_;
10332: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
10333: return "$num1:$num2";
10334: }
10335:
1.366 albertel 10336: sub rndseed_CODE_64bit {
10337: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 10338: {
1.366 albertel 10339: use integer;
1.443 albertel 10340: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 10341: my $symbseed=numval2($symb);
1.491 albertel 10342: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
10343: my $CODEseed=numval(&getCODE());
1.443 albertel 10344: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 10345: my $num1=$symbseed+$CODEchck;
10346: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 10347: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
10348: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 10349: if ($_64bit) { $num1=(($num1<<32)>>32); }
10350: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 10351: return "$num1:$num2";
1.366 albertel 10352: }
10353: }
10354:
1.575 albertel 10355: sub rndseed_CODE_64bit4 {
10356: my ($symb,$courseid,$domain,$username)=@_;
10357: {
10358: use integer;
10359: my $symbchck=unpack("%32S*",$symb.' ') << 16;
10360: my $symbseed=numval3($symb);
10361: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
10362: my $CODEseed=numval3(&getCODE());
10363: my $courseseed=unpack("%32S*",$courseid.' ');
10364: my $num1=$symbseed+$CODEchck;
10365: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 10366: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
10367: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 10368: if ($_64bit) { $num1=(($num1<<32)>>32); }
10369: if ($_64bit) { $num2=(($num2<<32)>>32); }
10370: return "$num1:$num2";
10371: }
10372: }
10373:
1.675 albertel 10374: sub rndseed_CODE_64bit5 {
10375: my ($symb,$courseid,$domain,$username)=@_;
10376: my $code = &getCODE();
10377: my ($num1,$num2)=&digest("$symb,$courseid,$code");
10378: return "$num1:$num2";
10379: }
10380:
1.366 albertel 10381: sub setup_random_from_rndseed {
10382: my ($rndseed)=@_;
1.503 albertel 10383: if ($rndseed =~/([,:])/) {
10384: my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366 albertel 10385: &Math::Random::random_set_seed(abs($num1),abs($num2));
10386: } else {
10387: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 10388: }
1.36 albertel 10389: }
10390:
1.474 albertel 10391: sub latest_receipt_algorithm_id {
1.835 albertel 10392: return 'receipt3';
1.474 albertel 10393: }
10394:
1.480 www 10395: sub recunique {
10396: my $fucourseid=shift;
10397: my $unique;
1.835 albertel 10398: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
10399: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 10400: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 10401: } else {
10402: $unique=$perlvar{'lonReceipt'};
10403: }
10404: return unpack("%32C*",$unique);
10405: }
10406:
10407: sub recprefix {
10408: my $fucourseid=shift;
10409: my $prefix;
1.835 albertel 10410: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
10411: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 10412: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 10413: } else {
10414: $prefix=$perlvar{'lonHostID'};
10415: }
10416: return unpack("%32C*",$prefix);
10417: }
10418:
1.76 www 10419: sub ireceipt {
1.474 albertel 10420: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 10421:
10422: my $return =&recprefix($fucourseid).'-';
10423:
10424: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
10425: $env{'request.state'} eq 'construct') {
10426: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
10427: return $return;
10428: }
10429:
1.76 www 10430: my $cuname=unpack("%32C*",$funame);
10431: my $cudom=unpack("%32C*",$fudom);
10432: my $cucourseid=unpack("%32C*",$fucourseid);
10433: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 10434: my $cunique=&recunique($fucourseid);
1.474 albertel 10435: my $cpart=unpack("%32S*",$part);
1.835 albertel 10436: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
10437:
1.790 albertel 10438: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 10439:
10440: $return.= ($cunique%$cuname+
10441: $cunique%$cudom+
10442: $cusymb%$cuname+
10443: $cusymb%$cudom+
10444: $cucourseid%$cuname+
10445: $cucourseid%$cudom+
10446: $cpart%$cuname+
10447: $cpart%$cudom);
10448: } else {
10449: $return.= ($cunique%$cuname+
10450: $cunique%$cudom+
10451: $cusymb%$cuname+
10452: $cusymb%$cudom+
10453: $cucourseid%$cuname+
10454: $cucourseid%$cudom);
10455: }
10456: return $return;
1.76 www 10457: }
10458:
10459: sub receipt {
1.474 albertel 10460: my ($part)=@_;
1.790 albertel 10461: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 10462: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 10463: }
1.260 ng 10464:
1.790 albertel 10465: sub whichuser {
10466: my ($passedsymb)=@_;
10467: my ($symb,$courseid,$domain,$name,$publicuser);
10468: if (defined($env{'form.grade_symb'})) {
10469: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
10470: my $allowed=&allowed('vgr',$tmp_courseid);
10471: if (!$allowed &&
10472: exists($env{'request.course.sec'}) &&
10473: $env{'request.course.sec'} !~ /^\s*$/) {
10474: $allowed=&allowed('vgr',$tmp_courseid.
10475: '/'.$env{'request.course.sec'});
10476: }
10477: if ($allowed) {
10478: ($symb)=&get_env_multiple('form.grade_symb');
10479: $courseid=$tmp_courseid;
10480: ($domain)=&get_env_multiple('form.grade_domain');
10481: ($name)=&get_env_multiple('form.grade_username');
10482: return ($symb,$courseid,$domain,$name,$publicuser);
10483: }
10484: }
10485: if (!$passedsymb) {
10486: $symb=&symbread();
10487: } else {
10488: $symb=$passedsymb;
10489: }
10490: $courseid=$env{'request.course.id'};
10491: $domain=$env{'user.domain'};
10492: $name=$env{'user.name'};
10493: if ($name eq 'public' && $domain eq 'public') {
10494: if (!defined($env{'form.username'})) {
10495: $env{'form.username'}.=time.rand(10000000);
10496: }
10497: $name.=$env{'form.username'};
10498: }
10499: return ($symb,$courseid,$domain,$name,$publicuser);
10500:
10501: }
10502:
1.36 albertel 10503: # ------------------------------------------------------------ Serves up a file
1.472 albertel 10504: # returns either the contents of the file or
10505: # -1 if the file doesn't exist
1.481 raeburn 10506: #
10507: # if the target is a file that was uploaded via DOCS,
10508: # a check will be made to see if a current copy exists on the local server,
10509: # if it does this will be served, otherwise a copy will be retrieved from
10510: # the home server for the course and stored in /home/httpd/html/userfiles on
10511: # the local server.
1.472 albertel 10512:
1.36 albertel 10513: sub getfile {
1.538 albertel 10514: my ($file) = @_;
1.609 banghart 10515: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 10516: &repcopy($file);
10517: return &readfile($file);
10518: }
10519:
10520: sub repcopy_userfile {
10521: my ($file)=@_;
1.1142 raeburn 10522: my $londocroot = $perlvar{'lonDocRoot'};
10523: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164 raeburn 10524: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538 albertel 10525: my ($cdom,$cnum,$filename) =
1.811 albertel 10526: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 10527: my $uri="/uploaded/$cdom/$cnum/$filename";
10528: if (-e "$file") {
1.828 www 10529: # we already have a local copy, check it out
1.538 albertel 10530: my @fileinfo = stat($file);
1.828 www 10531: my $rtncode;
10532: my $info;
1.538 albertel 10533: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 10534: if ($lwpresp ne 'ok') {
1.828 www 10535: # there is no such file anymore, even though we had a local copy
1.482 albertel 10536: if ($rtncode eq '404') {
1.538 albertel 10537: unlink($file);
1.482 albertel 10538: }
10539: return -1;
10540: }
10541: if ($info < $fileinfo[9]) {
1.828 www 10542: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 10543: return 'ok';
1.828 www 10544: } else {
10545: # the file is outdated, get rid of it
10546: unlink($file);
1.482 albertel 10547: }
1.828 www 10548: }
10549: # one way or the other, at this point, we don't have the file
10550: # construct the correct path for the file
10551: my @parts = ($cdom,$cnum);
10552: if ($filename =~ m|^(.+)/[^/]+$|) {
10553: push @parts, split(/\//,$1);
10554: }
10555: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
10556: foreach my $part (@parts) {
10557: $path .= '/'.$part;
10558: if (!-e $path) {
10559: mkdir($path,0770);
1.482 albertel 10560: }
10561: }
1.828 www 10562: # now the path exists for sure
10563: # get a user agent
10564: my $ua=new LWP::UserAgent;
10565: my $transferfile=$file.'.in.transfer';
10566: # FIXME: this should flock
10567: if (-e $transferfile) { return 'ok'; }
10568: my $request;
10569: $uri=~s/^\///;
1.980 raeburn 10570: my $homeserver = &homeserver($cnum,$cdom);
10571: my $protocol = $protocol{$homeserver};
10572: $protocol = 'http' if ($protocol ne 'https');
10573: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 10574: my $response=$ua->request($request,$transferfile);
10575: # did it work?
10576: if ($response->is_error()) {
10577: unlink($transferfile);
10578: &logthis("Userfile repcopy failed for $uri");
10579: return -1;
10580: }
10581: # worked, rename the transfer file
10582: rename($transferfile,$file);
1.607 raeburn 10583: return 'ok';
1.481 raeburn 10584: }
10585:
1.517 albertel 10586: sub tokenwrapper {
10587: my $uri=shift;
1.980 raeburn 10588: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 10589: $uri=~s|^/||;
1.620 albertel 10590: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 10591: my $token=$1;
1.552 albertel 10592: my (undef,$udom,$uname,$file)=split('/',$uri,4);
10593: if ($udom && $uname && $file) {
10594: $file=~s|(\?\.*)*$||;
1.949 raeburn 10595: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 10596: my $homeserver = &homeserver($uname,$udom);
10597: my $protocol = $protocol{$homeserver};
10598: $protocol = 'http' if ($protocol ne 'https');
10599: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 10600: (($uri=~/\?/)?'&':'?').'token='.$token.
10601: '&tokenissued='.$perlvar{'lonHostID'};
10602: } else {
10603: return '/adm/notfound.html';
10604: }
10605: }
10606:
1.828 www 10607: # call with reqtype HEAD: get last modification time
10608: # call with reqtype GET: get the file contents
10609: # Do not call this with reqtype GET for large files! It loads everything into memory
10610: #
1.481 raeburn 10611: sub getuploaded {
10612: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
10613: $uri=~s/^\///;
1.980 raeburn 10614: my $homeserver = &homeserver($cnum,$cdom);
10615: my $protocol = $protocol{$homeserver};
10616: $protocol = 'http' if ($protocol ne 'https');
10617: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 10618: my $ua=new LWP::UserAgent;
10619: my $request=new HTTP::Request($reqtype,$uri);
10620: my $response=$ua->request($request);
10621: $$rtncode = $response->code;
1.482 albertel 10622: if (! $response->is_success()) {
10623: return 'failed';
10624: }
10625: if ($reqtype eq 'HEAD') {
1.486 www 10626: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 10627: } elsif ($reqtype eq 'GET') {
10628: $$info = $response->content;
1.472 albertel 10629: }
1.482 albertel 10630: return 'ok';
1.36 albertel 10631: }
10632:
1.481 raeburn 10633: sub readfile {
10634: my $file = shift;
10635: if ( (! -e $file ) || ($file eq '') ) { return -1; };
10636: my $fh;
10637: open($fh,"<$file");
10638: my $a='';
1.800 albertel 10639: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 10640: return $a;
10641: }
10642:
1.36 albertel 10643: sub filelocation {
1.590 banghart 10644: my ($dir,$file) = @_;
10645: my $location;
10646: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 10647:
10648: if ($file =~ m-^/adm/-) {
10649: $file=~s-^/adm/wrapper/-/-;
10650: $file=~s-^/adm/coursedocs/showdoc/-/-;
10651: }
1.882 albertel 10652:
1.1139 www 10653: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956 raeburn 10654: $location = $file;
1.609 banghart 10655: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 10656: my ($udom,$uname,$filename)=
1.811 albertel 10657: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 10658: my $home=&homeserver($uname,$udom);
10659: my $is_me=0;
10660: my @ids=¤t_machine_ids();
10661: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
10662: if ($is_me) {
1.1117 foxr 10663: $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 10664: } else {
10665: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
10666: $udom.'/'.$uname.'/'.$filename;
10667: }
1.882 albertel 10668: } elsif ($file =~ m-^/adm/-) {
10669: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 10670: } else {
10671: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139 www 10672: $file=~s:^/(res|priv)/:/:;
10673: my $space=$1;
1.590 banghart 10674: if ( !( $file =~ m:^/:) ) {
10675: $location = $dir. '/'.$file;
10676: } else {
1.1142 raeburn 10677: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590 banghart 10678: }
1.59 albertel 10679: }
1.590 banghart 10680: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 10681: while ($location=~m{/\.\./}) {
10682: if ($location =~ m{/[^/]+/\.\./}) {
10683: $location=~ s{/[^/]+/\.\./}{/}g;
10684: } else {
10685: $location=~ s{/\.\./}{/}g;
10686: }
10687: } #remove dir/..
1.590 banghart 10688: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
10689: return $location;
1.46 www 10690: }
1.36 albertel 10691:
1.46 www 10692: sub hreflocation {
10693: my ($dir,$file)=@_;
1.980 raeburn 10694: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 10695: $file=filelocation($dir,$file);
1.700 albertel 10696: } elsif ($file=~m-^/adm/-) {
10697: $file=~s-^/adm/wrapper/-/-;
10698: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 10699: }
10700: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
10701: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
10702: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143 raeburn 10703: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
10704: {/uploaded/$1/$2/}x;
1.46 www 10705: }
1.913 albertel 10706: if ($file=~ m{^/userfiles/}) {
10707: $file =~ s{^/userfiles/}{/uploaded/};
10708: }
1.462 albertel 10709: return $file;
1.465 albertel 10710: }
10711:
1.1139 www 10712:
10713:
10714:
10715:
1.465 albertel 10716: sub current_machine_domains {
1.853 albertel 10717: return &machine_domains(&hostname($perlvar{'lonHostID'}));
10718: }
10719:
10720: sub machine_domains {
10721: my ($hostname) = @_;
1.465 albertel 10722: my @domains;
1.838 albertel 10723: my %hostname = &all_hostnames();
1.465 albertel 10724: while( my($id, $name) = each(%hostname)) {
1.467 matthew 10725: # &logthis("-$id-$name-$hostname-");
1.465 albertel 10726: if ($hostname eq $name) {
1.844 albertel 10727: push(@domains,&host_domain($id));
1.465 albertel 10728: }
10729: }
10730: return @domains;
10731: }
10732:
10733: sub current_machine_ids {
1.853 albertel 10734: return &machine_ids(&hostname($perlvar{'lonHostID'}));
10735: }
10736:
10737: sub machine_ids {
10738: my ($hostname) = @_;
10739: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 10740: my @ids;
1.888 albertel 10741: my %name_to_host = &all_names();
1.889 albertel 10742: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
10743: return @{ $name_to_host{$hostname} };
10744: }
10745: return;
1.31 www 10746: }
10747:
1.824 raeburn 10748: sub additional_machine_domains {
10749: my @domains;
10750: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
10751: while( my $line = <$fh>) {
10752: $line =~ s/\s//g;
10753: push(@domains,$line);
10754: }
10755: return @domains;
10756: }
10757:
10758: sub default_login_domain {
10759: my $domain = $perlvar{'lonDefDomain'};
10760: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
10761: foreach my $posdom (¤t_machine_domains(),
10762: &additional_machine_domains()) {
10763: if (lc($posdom) eq lc($testdomain)) {
10764: $domain=$posdom;
10765: last;
10766: }
10767: }
10768: return $domain;
10769: }
10770:
1.31 www 10771: # ------------------------------------------------------------- Declutters URLs
10772:
10773: sub declutter {
10774: my $thisfn=shift;
1.569 albertel 10775: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479 albertel 10776: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31 www 10777: $thisfn=~s/^\///;
1.697 albertel 10778: $thisfn=~s|^adm/wrapper/||;
10779: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 10780: $thisfn=~s/^res\///;
1.1032 raeburn 10781: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
10782: $thisfn=~s/\?.+$//;
10783: }
1.268 www 10784: return $thisfn;
10785: }
10786:
10787: # ------------------------------------------------------------- Clutter up URLs
10788:
10789: sub clutter {
10790: my $thisfn='/'.&declutter(shift);
1.887 albertel 10791: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 10792: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 10793: $thisfn='/res'.$thisfn;
10794: }
1.1031 raeburn 10795: if ($thisfn !~m|^/adm|) {
10796: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 10797: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 10798: } else {
10799: my ($ext) = ($thisfn =~ /\.(\w+)$/);
10800: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 10801: if ($embstyle eq 'ssi'
10802: || ($embstyle eq 'hdn')
10803: || ($embstyle eq 'rat')
10804: || ($embstyle eq 'prv')
10805: || ($embstyle eq 'ign')) {
10806: #do nothing with these
10807: } elsif (($embstyle eq 'img')
1.695 albertel 10808: || ($embstyle eq 'emb')
10809: || ($embstyle eq 'wrp')) {
10810: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 10811: } elsif ($embstyle eq 'unk'
10812: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 10813: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 10814: } else {
1.718 www 10815: # &logthis("Got a blank emb style");
1.695 albertel 10816: }
1.694 albertel 10817: }
10818: }
1.31 www 10819: return $thisfn;
1.12 www 10820: }
10821:
1.787 albertel 10822: sub clutter_with_no_wrapper {
10823: my $uri = &clutter(shift);
10824: if ($uri =~ m-^/adm/-) {
10825: $uri =~ s-^/adm/wrapper/-/-;
10826: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
10827: }
10828: return $uri;
10829: }
10830:
1.557 albertel 10831: sub freeze_escape {
10832: my ($value)=@_;
10833: if (ref($value)) {
10834: $value=&nfreeze($value);
10835: return '__FROZEN__'.&escape($value);
10836: }
10837: return &escape($value);
10838: }
10839:
1.11 www 10840:
1.557 albertel 10841: sub thaw_unescape {
10842: my ($value)=@_;
10843: if ($value =~ /^__FROZEN__/) {
10844: substr($value,0,10,undef);
10845: $value=&unescape($value);
10846: return &thaw($value);
10847: }
10848: return &unescape($value);
10849: }
10850:
1.436 albertel 10851: sub correct_line_ends {
10852: my ($result)=@_;
10853: $$result =~s/\r\n/\n/mg;
10854: $$result =~s/\r/\n/mg;
1.415 albertel 10855: }
1.1 albertel 10856: # ================================================================ Main Program
10857:
1.184 www 10858: sub goodbye {
1.204 albertel 10859: &logthis("Starting Shut down");
1.443 albertel 10860: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 10861: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 10862: #converted
1.599 albertel 10863: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 10864: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
10865: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
10866: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 10867: #1.1 only
1.870 albertel 10868: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
10869: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
10870: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
10871: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
10872: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 10873: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
10874: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 10875: &flushcourselogs();
10876: &logthis("Shutting down");
10877: }
10878:
1.852 albertel 10879: sub get_dns {
1.869 albertel 10880: my ($url,$func,$ignore_cache) = @_;
10881: if (!$ignore_cache) {
10882: my ($content,$cached)=
10883: &Apache::lonnet::is_cached_new('dns',$url);
10884: if ($cached) {
10885: &$func($content);
10886: return;
10887: }
10888: }
10889:
10890: my %alldns;
1.852 albertel 10891: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
10892: foreach my $dns (<$config>) {
10893: next if ($dns !~ /^\^(\S*)/x);
1.979 raeburn 10894: my $line = $1;
10895: my ($host,$protocol) = split(/:/,$line);
10896: if ($protocol ne 'https') {
10897: $protocol = 'http';
10898: }
10899: $alldns{$host} = $protocol;
1.869 albertel 10900: }
10901: while (%alldns) {
10902: my ($dns) = keys(%alldns);
1.852 albertel 10903: my $ua=new LWP::UserAgent;
1.1134 raeburn 10904: $ua->timeout(30);
1.979 raeburn 10905: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 10906: my $response=$ua->request($request);
1.979 raeburn 10907: delete($alldns{$dns});
1.852 albertel 10908: next if ($response->is_error());
10909: my @content = split("\n",$response->content);
1.869 albertel 10910: &Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852 albertel 10911: &$func(\@content);
1.869 albertel 10912: return;
1.852 albertel 10913: }
10914: close($config);
1.871 albertel 10915: my $which = (split('/',$url))[3];
10916: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
10917: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 10918: my @content = <$config>;
10919: &$func(\@content);
10920: return;
1.852 albertel 10921: }
1.327 albertel 10922: # ------------------------------------------------------------ Read domain file
10923: {
1.852 albertel 10924: my $loaded;
1.846 albertel 10925: my %domain;
10926:
1.852 albertel 10927: sub parse_domain_tab {
10928: my ($lines) = @_;
10929: foreach my $line (@$lines) {
10930: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 10931:
1.846 albertel 10932: chomp($line);
1.852 albertel 10933: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 10934: my %this_domain;
10935: foreach my $field ('description', 'auth_def', 'auth_arg_def',
10936: 'lang_def', 'city', 'longi', 'lati',
10937: 'primary') {
10938: $this_domain{$field} = shift(@elements);
10939: }
10940: $domain{$name} = \%this_domain;
1.852 albertel 10941: }
10942: }
1.864 albertel 10943:
10944: sub reset_domain_info {
10945: undef($loaded);
10946: undef(%domain);
10947: }
10948:
1.852 albertel 10949: sub load_domain_tab {
1.869 albertel 10950: my ($ignore_cache) = @_;
10951: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852 albertel 10952: my $fh;
10953: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
10954: my @lines = <$fh>;
10955: &parse_domain_tab(\@lines);
1.448 albertel 10956: }
1.852 albertel 10957: close($fh);
10958: $loaded = 1;
1.327 albertel 10959: }
1.846 albertel 10960:
10961: sub domain {
1.852 albertel 10962: &load_domain_tab() if (!$loaded);
10963:
1.846 albertel 10964: my ($name,$what) = @_;
10965: return if ( !exists($domain{$name}) );
10966:
10967: if (!$what) {
10968: return $domain{$name}{'description'};
10969: }
10970: return $domain{$name}{$what};
10971: }
1.974 raeburn 10972:
10973: sub domain_info {
10974: &load_domain_tab() if (!$loaded);
10975: return %domain;
10976: }
10977:
1.327 albertel 10978: }
10979:
10980:
1.1 albertel 10981: # ------------------------------------------------------------- Read hosts file
10982: {
1.838 albertel 10983: my %hostname;
1.844 albertel 10984: my %hostdom;
1.845 albertel 10985: my %libserv;
1.852 albertel 10986: my $loaded;
1.888 albertel 10987: my %name_to_host;
1.1074 raeburn 10988: my %internetdom;
1.1107 raeburn 10989: my %LC_dns_serv;
1.852 albertel 10990:
10991: sub parse_hosts_tab {
10992: my ($file) = @_;
10993: foreach my $configline (@$file) {
10994: next if ($configline =~ /^(\#|\s*$ )/x);
1.1107 raeburn 10995: chomp($configline);
10996: if ($configline =~ /^\^/) {
10997: if ($configline =~ /^\^([\w.\-]+)/) {
10998: $LC_dns_serv{$1} = 1;
10999: }
11000: next;
11001: }
1.1074 raeburn 11002: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 11003: $name=~s/\s//g;
11004: if ($id && $domain && $role && $name) {
11005: $hostname{$id}=$name;
1.888 albertel 11006: push(@{$name_to_host{$name}}, $id);
1.852 albertel 11007: $hostdom{$id}=$domain;
11008: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 11009: if (defined($protocol)) {
11010: if ($protocol eq 'https') {
11011: $protocol{$id} = $protocol;
11012: } else {
11013: $protocol{$id} = 'http';
11014: }
1.968 raeburn 11015: } else {
1.969 raeburn 11016: $protocol{$id} = 'http';
1.968 raeburn 11017: }
1.1074 raeburn 11018: if (defined($intdom)) {
11019: $internetdom{$id} = $intdom;
11020: }
1.852 albertel 11021: }
11022: }
11023: }
1.864 albertel 11024:
11025: sub reset_hosts_info {
1.897 albertel 11026: &purge_remembered();
1.864 albertel 11027: &reset_domain_info();
11028: &reset_hosts_ip_info();
1.892 albertel 11029: undef(%name_to_host);
1.864 albertel 11030: undef(%hostname);
11031: undef(%hostdom);
11032: undef(%libserv);
11033: undef($loaded);
11034: }
1.1 albertel 11035:
1.852 albertel 11036: sub load_hosts_tab {
1.869 albertel 11037: my ($ignore_cache) = @_;
11038: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852 albertel 11039: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11040: my @config = <$config>;
11041: &parse_hosts_tab(\@config);
11042: close($config);
11043: $loaded=1;
1.1 albertel 11044: }
1.852 albertel 11045:
1.838 albertel 11046: sub hostname {
1.852 albertel 11047: &load_hosts_tab() if (!$loaded);
11048:
1.838 albertel 11049: my ($lonid) = @_;
11050: return $hostname{$lonid};
11051: }
1.845 albertel 11052:
1.838 albertel 11053: sub all_hostnames {
1.852 albertel 11054: &load_hosts_tab() if (!$loaded);
11055:
1.838 albertel 11056: return %hostname;
11057: }
1.845 albertel 11058:
1.888 albertel 11059: sub all_names {
11060: &load_hosts_tab() if (!$loaded);
11061:
11062: return %name_to_host;
11063: }
11064:
1.974 raeburn 11065: sub all_host_domain {
11066: &load_hosts_tab() if (!$loaded);
11067: return %hostdom;
11068: }
11069:
1.845 albertel 11070: sub is_library {
1.852 albertel 11071: &load_hosts_tab() if (!$loaded);
11072:
1.845 albertel 11073: return exists($libserv{$_[0]});
11074: }
11075:
11076: sub all_library {
1.852 albertel 11077: &load_hosts_tab() if (!$loaded);
11078:
1.845 albertel 11079: return %libserv;
11080: }
11081:
1.1062 droeschl 11082: sub unique_library {
11083: #2x reverse removes all hostnames that appear more than once
11084: my %unique = reverse &all_library();
11085: return reverse %unique;
11086: }
11087:
1.841 albertel 11088: sub get_servers {
1.852 albertel 11089: &load_hosts_tab() if (!$loaded);
11090:
1.841 albertel 11091: my ($domain,$type) = @_;
11092: my %possible_hosts = ($type eq 'library') ? %libserv
11093: : %hostname;
11094: my %result;
1.842 albertel 11095: if (ref($domain) eq 'ARRAY') {
11096: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 11097: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 11098: $result{$host} = $hostname;
11099: }
11100: }
11101: } else {
11102: while ( my ($host,$hostname) = each(%possible_hosts)) {
11103: if ($hostdom{$host} eq $domain) {
11104: $result{$host} = $hostname;
11105: }
1.841 albertel 11106: }
11107: }
11108: return %result;
11109: }
1.845 albertel 11110:
1.1062 droeschl 11111: sub get_unique_servers {
11112: my %unique = reverse &get_servers(@_);
11113: return reverse %unique;
11114: }
11115:
1.844 albertel 11116: sub host_domain {
1.852 albertel 11117: &load_hosts_tab() if (!$loaded);
11118:
1.844 albertel 11119: my ($lonid) = @_;
11120: return $hostdom{$lonid};
11121: }
11122:
1.841 albertel 11123: sub all_domains {
1.852 albertel 11124: &load_hosts_tab() if (!$loaded);
11125:
1.841 albertel 11126: my %seen;
11127: my @uniq = grep(!$seen{$_}++, values(%hostdom));
11128: return @uniq;
11129: }
1.1074 raeburn 11130:
11131: sub internet_dom {
11132: &load_hosts_tab() if (!$loaded);
11133:
11134: my ($lonid) = @_;
11135: return $internetdom{$lonid};
11136: }
1.1107 raeburn 11137:
11138: sub is_LC_dns {
11139: &load_hosts_tab() if (!$loaded);
11140:
11141: my ($hostname) = @_;
11142: return exists($LC_dns_serv{$hostname});
11143: }
11144:
1.1 albertel 11145: }
11146:
1.847 albertel 11147: {
11148: my %iphost;
1.856 albertel 11149: my %name_to_ip;
11150: my %lonid_to_ip;
1.869 albertel 11151:
1.847 albertel 11152: sub get_hosts_from_ip {
11153: my ($ip) = @_;
11154: my %iphosts = &get_iphost();
11155: if (ref($iphosts{$ip})) {
11156: return @{$iphosts{$ip}};
11157: }
11158: return;
1.839 albertel 11159: }
1.864 albertel 11160:
11161: sub reset_hosts_ip_info {
11162: undef(%iphost);
11163: undef(%name_to_ip);
11164: undef(%lonid_to_ip);
11165: }
1.856 albertel 11166:
11167: sub get_host_ip {
11168: my ($lonid) = @_;
11169: if (exists($lonid_to_ip{$lonid})) {
11170: return $lonid_to_ip{$lonid};
11171: }
11172: my $name=&hostname($lonid);
11173: my $ip = gethostbyname($name);
11174: return if (!$ip || length($ip) ne 4);
11175: $ip=inet_ntoa($ip);
11176: $name_to_ip{$name} = $ip;
11177: $lonid_to_ip{$lonid} = $ip;
11178: return $ip;
11179: }
1.847 albertel 11180:
11181: sub get_iphost {
1.869 albertel 11182: my ($ignore_cache) = @_;
1.894 albertel 11183:
1.869 albertel 11184: if (!$ignore_cache) {
11185: if (%iphost) {
11186: return %iphost;
11187: }
11188: my ($ip_info,$cached)=
11189: &Apache::lonnet::is_cached_new('iphost','iphost');
11190: if ($cached) {
11191: %iphost = %{$ip_info->[0]};
11192: %name_to_ip = %{$ip_info->[1]};
11193: %lonid_to_ip = %{$ip_info->[2]};
11194: return %iphost;
11195: }
11196: }
1.894 albertel 11197:
11198: # get yesterday's info for fallback
11199: my %old_name_to_ip;
11200: my ($ip_info,$cached)=
11201: &Apache::lonnet::is_cached_new('iphost','iphost');
11202: if ($cached) {
11203: %old_name_to_ip = %{$ip_info->[1]};
11204: }
11205:
1.888 albertel 11206: my %name_to_host = &all_names();
11207: foreach my $name (keys(%name_to_host)) {
1.847 albertel 11208: my $ip;
11209: if (!exists($name_to_ip{$name})) {
11210: $ip = gethostbyname($name);
11211: if (!$ip || length($ip) ne 4) {
1.894 albertel 11212: if (defined($old_name_to_ip{$name})) {
11213: $ip = $old_name_to_ip{$name};
11214: &logthis("Can't find $name defaulting to old $ip");
11215: } else {
11216: &logthis("Name $name no IP found");
11217: next;
11218: }
11219: } else {
11220: $ip=inet_ntoa($ip);
1.847 albertel 11221: }
11222: $name_to_ip{$name} = $ip;
11223: } else {
11224: $ip = $name_to_ip{$name};
1.653 albertel 11225: }
1.888 albertel 11226: foreach my $id (@{ $name_to_host{$name} }) {
11227: $lonid_to_ip{$id} = $ip;
11228: }
11229: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 11230: }
1.869 albertel 11231: &Apache::lonnet::do_cache_new('iphost','iphost',
11232: [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894 albertel 11233: 48*60*60);
1.869 albertel 11234:
1.847 albertel 11235: return %iphost;
1.598 albertel 11236: }
11237:
1.992 raeburn 11238: #
11239: # Given a DNS returns the loncapa host name for that DNS
11240: #
11241: sub host_from_dns {
11242: my ($dns) = @_;
11243: my @hosts;
11244: my $ip;
11245:
1.993 raeburn 11246: if (exists($name_to_ip{$dns})) {
1.992 raeburn 11247: $ip = $name_to_ip{$dns};
11248: }
11249: if (!$ip) {
11250: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
11251: if (length($ip) == 4) {
11252: $ip = &IO::Socket::inet_ntoa($ip);
11253: }
11254: }
11255: if ($ip) {
11256: @hosts = get_hosts_from_ip($ip);
11257: return $hosts[0];
11258: }
11259: return undef;
1.986 foxr 11260: }
1.992 raeburn 11261:
1.1074 raeburn 11262: sub get_internet_names {
11263: my ($lonid) = @_;
11264: return if ($lonid eq '');
11265: my ($idnref,$cached)=
11266: &Apache::lonnet::is_cached_new('internetnames',$lonid);
11267: if ($cached) {
11268: return $idnref;
11269: }
11270: my $ip = &get_host_ip($lonid);
11271: my @hosts = &get_hosts_from_ip($ip);
11272: my %iphost = &get_iphost();
11273: my (@idns,%seen);
11274: foreach my $id (@hosts) {
11275: my $dom = &host_domain($id);
11276: my $prim_id = &domain($dom,'primary');
11277: my $prim_ip = &get_host_ip($prim_id);
11278: next if ($seen{$prim_ip});
11279: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
11280: foreach my $id (@{$iphost{$prim_ip}}) {
11281: my $intdom = &internet_dom($id);
11282: unless (grep(/^\Q$intdom\E$/,@idns)) {
11283: push(@idns,$intdom);
11284: }
11285: }
11286: }
11287: $seen{$prim_ip} = 1;
11288: }
11289: return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
11290: }
11291:
1.986 foxr 11292: }
11293:
1.1079 raeburn 11294: sub all_loncaparevs {
11295: 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);
11296: }
11297:
1.862 albertel 11298: BEGIN {
11299:
11300: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
11301: unless ($readit) {
11302: {
11303: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
11304: %perlvar = (%perlvar,%{$configvars});
11305: }
11306:
11307:
1.1 albertel 11308: # ------------------------------------------------------ Read spare server file
11309: {
1.448 albertel 11310: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 11311:
11312: while (my $configline=<$config>) {
11313: chomp($configline);
1.284 matthew 11314: if ($configline) {
1.784 albertel 11315: my ($host,$type) = split(':',$configline,2);
1.785 albertel 11316: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 11317: push(@{ $spareid{$type} }, $host);
1.1 albertel 11318: }
11319: }
1.448 albertel 11320: close($config);
1.1 albertel 11321: }
1.11 www 11322: # ------------------------------------------------------------ Read permissions
11323: {
1.448 albertel 11324: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 11325:
11326: while (my $configline=<$config>) {
1.448 albertel 11327: chomp($configline);
11328: if ($configline) {
11329: my ($role,$perm)=split(/ /,$configline);
11330: if ($perm ne '') { $pr{$role}=$perm; }
11331: }
1.11 www 11332: }
1.448 albertel 11333: close($config);
1.11 www 11334: }
11335:
11336: # -------------------------------------------- Read plain texts for permissions
11337: {
1.448 albertel 11338: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 11339:
11340: while (my $configline=<$config>) {
1.448 albertel 11341: chomp($configline);
11342: if ($configline) {
1.742 raeburn 11343: my ($short,@plain)=split(/:/,$configline);
11344: %{$prp{$short}} = ();
11345: if (@plain > 0) {
11346: $prp{$short}{'std'} = $plain[0];
11347: for (my $i=1; $i<@plain; $i++) {
11348: $prp{$short}{'alt'.$i} = $plain[$i];
11349: }
11350: }
1.448 albertel 11351: }
1.135 www 11352: }
1.448 albertel 11353: close($config);
1.135 www 11354: }
11355:
11356: # ---------------------------------------------------------- Read package table
11357: {
1.448 albertel 11358: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 11359:
11360: while (my $configline=<$config>) {
1.483 albertel 11361: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 11362: chomp($configline);
11363: my ($short,$plain)=split(/:/,$configline);
11364: my ($pack,$name)=split(/\&/,$short);
11365: if ($plain ne '') {
11366: $packagetab{$pack.'&'.$name.'&name'}=$name;
11367: $packagetab{$short}=$plain;
11368: }
1.11 www 11369: }
1.448 albertel 11370: close($config);
1.329 matthew 11371: }
11372:
1.1073 raeburn 11373: # ---------------------------------------------------------- Read loncaparev table
11374: {
11375: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
11376: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
11377: while (my $configline=<$config>) {
11378: chomp($configline);
11379: my ($hostid,$loncaparev)=split(/:/,$configline);
11380: $loncaparevs{$hostid}=$loncaparev;
11381: }
11382: close($config);
11383: }
11384: }
11385: }
11386:
1.1074 raeburn 11387: # ---------------------------------------------------------- Read serverhostID table
11388: {
11389: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
11390: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
11391: while (my $configline=<$config>) {
11392: chomp($configline);
11393: my ($name,$id)=split(/:/,$configline);
11394: $serverhomeIDs{$name}=$id;
11395: }
11396: close($config);
11397: }
11398: }
11399: }
11400:
1.1079 raeburn 11401: {
11402: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
11403: if (-e $file) {
11404: my $parser = HTML::LCParser->new($file);
11405: while (my $token = $parser->get_token()) {
11406: if ($token->[0] eq 'S') {
11407: my $item = $token->[1];
11408: my $name = $token->[2]{'name'};
11409: my $value = $token->[2]{'value'};
11410: if ($item ne '' && $name ne '' && $value ne '') {
11411: my $release = $parser->get_text();
11412: $release =~ s/(^\s*|\s*$ )//gx;
11413: $needsrelease{$item.':'.$name.':'.$value} = $release;
11414: }
11415: }
11416: }
11417: }
1.1073 raeburn 11418: }
11419:
1.1138 raeburn 11420: # ---------------------------------------------------------- Read managers table
11421: {
11422: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
11423: if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
11424: while (my $configline=<$config>) {
11425: chomp($configline);
11426: next if ($configline =~ /^\#/);
11427: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
11428: $managerstab{$configline} = 1;
11429: }
11430: }
11431: close($config);
11432: }
11433: }
11434: }
11435:
1.329 matthew 11436: # ------------- set up temporary directory
11437: {
1.1117 foxr 11438: $tmpdir = LONCAPA::tempdir();
1.329 matthew 11439:
1.11 www 11440: }
11441:
1.794 albertel 11442: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
11443: 'compress_threshold'=> 20_000,
11444: });
1.185 www 11445:
1.281 www 11446: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 11447: $dumpcount=0;
1.958 www 11448: $locknum=0;
1.22 www 11449:
1.163 harris41 11450: &logtouch();
1.672 albertel 11451: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 11452: $readit=1;
1.564 albertel 11453: {
11454: use integer;
11455: my $test=(2**32)+1;
1.568 albertel 11456: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 11457: &logthis(" Detected 64bit platform ($_64bit)");
11458: }
1.195 www 11459: }
1.1 albertel 11460: }
1.179 www 11461:
1.1 albertel 11462: 1;
1.191 harris41 11463: __END__
11464:
1.243 albertel 11465: =pod
11466:
1.191 harris41 11467: =head1 NAME
11468:
1.243 albertel 11469: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 11470:
11471: =head1 SYNOPSIS
11472:
1.243 albertel 11473: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 11474:
11475: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
11476:
1.243 albertel 11477: Common parameters:
11478:
11479: =over 4
11480:
11481: =item *
11482:
11483: $uname : an internal username (if $cname expecting a course Id specifically)
11484:
11485: =item *
11486:
11487: $udom : a domain (if $cdom expecting a course's domain specifically)
11488:
11489: =item *
11490:
11491: $symb : a resource instance identifier
11492:
11493: =item *
11494:
11495: $namespace : the name of a .db file that contains the data needed or
11496: being set.
11497:
11498: =back
11499:
1.394 bowersj2 11500: =head1 OVERVIEW
1.191 harris41 11501:
1.394 bowersj2 11502: lonnet provides subroutines which interact with the
11503: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
11504: about classes, users, and resources.
1.243 albertel 11505:
11506: For many of these objects you can also use this to store data about
11507: them or modify them in various ways.
1.191 harris41 11508:
1.394 bowersj2 11509: =head2 Symbs
1.191 harris41 11510:
1.394 bowersj2 11511: To identify a specific instance of a resource, LON-CAPA uses symbols
11512: or "symbs"X<symb>. These identifiers are built from the URL of the
11513: map, the resource number of the resource in the map, and the URL of
11514: the resource itself. The latter is somewhat redundant, but might help
11515: if maps change.
11516:
11517: An example is
11518:
11519: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
11520:
11521: The respective map entry is
11522:
11523: <resource id="19" src="/res/msu/korte/tests/part12.problem"
11524: title="Problem 2">
11525: </resource>
11526:
11527: Symbs are used by the random number generator, as well as to store and
11528: restore data specific to a certain instance of for example a problem.
11529:
11530: =head2 Storing And Retrieving Data
11531:
11532: X<store()>X<cstore()>X<restore()>Three of the most important functions
11533: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
11534: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
11535: is is the non-critical message twin of cstore. These functions are for
11536: handlers to store a perl hash to a user's permanent data space in an
11537: easy manner, and to retrieve it again on another call. It is expected
11538: that a handler would use this once at the beginning to retrieve data,
11539: and then again once at the end to send only the new data back.
11540:
11541: The data is stored in the user's data directory on the user's
11542: homeserver under the ID of the course.
11543:
11544: The hash that is returned by restore will have all of the previous
11545: value for all of the elements of the hash.
11546:
11547: Example:
11548:
11549: #creating a hash
11550: my %hash;
11551: $hash{'foo'}='bar';
11552:
11553: #storing it
11554: &Apache::lonnet::cstore(\%hash);
11555:
11556: #changing a value
11557: $hash{'foo'}='notbar';
11558:
11559: #adding a new value
11560: $hash{'bar'}='foo';
11561: &Apache::lonnet::cstore(\%hash);
11562:
11563: #retrieving the hash
11564: my %history=&Apache::lonnet::restore();
11565:
11566: #print the hash
11567: foreach my $key (sort(keys(%history))) {
11568: print("\%history{$key} = $history{$key}");
11569: }
11570:
11571: Will print out:
1.191 harris41 11572:
1.394 bowersj2 11573: %history{1:foo} = bar
11574: %history{1:keys} = foo:timestamp
11575: %history{1:timestamp} = 990455579
11576: %history{2:bar} = foo
11577: %history{2:foo} = notbar
11578: %history{2:keys} = foo:bar:timestamp
11579: %history{2:timestamp} = 990455580
11580: %history{bar} = foo
11581: %history{foo} = notbar
11582: %history{timestamp} = 990455580
11583: %history{version} = 2
11584:
11585: Note that the special hash entries C<keys>, C<version> and
11586: C<timestamp> were added to the hash. C<version> will be equal to the
11587: total number of versions of the data that have been stored. The
11588: C<timestamp> attribute will be the UNIX time the hash was
11589: stored. C<keys> is available in every historical section to list which
11590: keys were added or changed at a specific historical revision of a
11591: hash.
11592:
11593: B<Warning>: do not store the hash that restore returns directly. This
11594: will cause a mess since it will restore the historical keys as if the
11595: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 11596:
1.394 bowersj2 11597: Calling convention:
1.191 harris41 11598:
1.394 bowersj2 11599: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
11600: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191 harris41 11601:
1.394 bowersj2 11602: For more detailed information, see lonnet specific documentation.
1.191 harris41 11603:
1.394 bowersj2 11604: =head1 RETURN MESSAGES
1.191 harris41 11605:
1.394 bowersj2 11606: =over 4
1.191 harris41 11607:
1.394 bowersj2 11608: =item * B<con_lost>: unable to contact remote host
1.191 harris41 11609:
1.394 bowersj2 11610: =item * B<con_delayed>: unable to contact remote host, message will be delivered
11611: when the connection is brought back up
1.191 harris41 11612:
1.394 bowersj2 11613: =item * B<con_failed>: unable to contact remote host and unable to save message
11614: for later delivery
1.191 harris41 11615:
1.967 bisitz 11616: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 11617:
1.394 bowersj2 11618: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 11619: that was requested
1.191 harris41 11620:
1.243 albertel 11621: =back
1.191 harris41 11622:
1.243 albertel 11623: =head1 PUBLIC SUBROUTINES
1.191 harris41 11624:
1.243 albertel 11625: =head2 Session Environment Functions
1.191 harris41 11626:
1.243 albertel 11627: =over 4
1.191 harris41 11628:
1.394 bowersj2 11629: =item *
11630: X<appenv()>
1.949 raeburn 11631: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 11632: the user envirnoment file, and will be restored for each access this
1.620 albertel 11633: user makes during this session, also modifies the %env for the current
1.949 raeburn 11634: process. Optional rolesarrayref - if defined contains a reference to an array
11635: of roles which are exempt from the restriction on modifying user.role entries
11636: in the user's environment.db and in %env.
1.191 harris41 11637:
11638: =item *
1.394 bowersj2 11639: X<delenv()>
1.987 raeburn 11640: B<delenv($delthis,$regexp)>: removes all items from the session
11641: environment file that begin with $delthis. If the
11642: optional second arg - $regexp - is true, $delthis is treated as a
11643: regular expression, otherwise \Q$delthis\E is used.
11644: The values are also deleted from the current processes %env.
1.191 harris41 11645:
1.795 albertel 11646: =item * get_env_multiple($name)
11647:
11648: gets $name from the %env hash, it seemlessly handles the cases where multiple
11649: values may be defined and end up as an array ref.
11650:
11651: returns an array of values
11652:
1.243 albertel 11653: =back
11654:
11655: =head2 User Information
1.191 harris41 11656:
1.243 albertel 11657: =over 4
1.191 harris41 11658:
11659: =item *
1.394 bowersj2 11660: X<queryauthenticate()>
11661: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 11662: authentication scheme
11663:
11664: =item *
1.394 bowersj2 11665: X<authenticate()>
1.1073 raeburn 11666: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 11667: authenticate user from domain's lib servers (first use the current
11668: one). C<$upass> should be the users password.
1.1073 raeburn 11669: $checkdefauth is optional (value is 1 if a check should be made to
11670: authenticate user using default authentication method, and allow
11671: account creation if username does not have account in the domain).
11672: $clientcancheckhost is optional (value is 1 if checking whether the
11673: server can host will occur on the client side in lonauth.pm).
1.191 harris41 11674:
11675: =item *
1.394 bowersj2 11676: X<homeserver()>
11677: B<homeserver($uname,$udom)>: find the server which has
11678: the user's directory and files (there must be only one), this caches
11679: the answer, and also caches if there is a borken connection.
1.191 harris41 11680:
11681: =item *
1.394 bowersj2 11682: X<idget()>
11683: B<idget($udom,@ids)>: find the usernames behind a list of IDs
11684: (IDs are a unique resource in a domain, there must be only 1 ID per
11685: username, and only 1 username per ID in a specific domain) (returns
11686: hash: id=>name,id=>name)
1.191 harris41 11687:
11688: =item *
1.394 bowersj2 11689: X<idrget()>
11690: B<idrget($udom,@unames)>: find the IDs behind a list of
11691: usernames (returns hash: name=>id,name=>id)
1.191 harris41 11692:
11693: =item *
1.394 bowersj2 11694: X<idput()>
11695: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 11696:
11697: =item *
1.394 bowersj2 11698: X<rolesinit()>
11699: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243 albertel 11700:
11701: =item *
1.551 albertel 11702: X<getsection()>
11703: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 11704: course $cname, return section name/number or '' for "not in course"
11705: and '-1' for "no section"
11706:
11707: =item *
1.394 bowersj2 11708: X<userenvironment()>
11709: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 11710: passed in @what from the requested user's environment, returns a hash
11711:
1.858 raeburn 11712: =item *
11713: X<userlog_query()>
1.859 albertel 11714: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
11715: activity.log file. %filters defines filters applied when parsing the
11716: log file. These can be start or end timestamps, or the type of action
11717: - log to look for Login or Logout events, check for Checkin or
11718: Checkout, role for role selection. The response is in the form
11719: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
11720: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 11721:
1.243 albertel 11722: =back
11723:
11724: =head2 User Roles
11725:
11726: =over 4
11727:
11728: =item *
11729:
1.810 raeburn 11730: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243 albertel 11731: F: full access
11732: U,I,K: authentication modes (cxx only)
11733: '': forbidden
11734: 1: user needs to choose course
11735: 2: browse allowed
1.766 albertel 11736: A: passphrase authentication needed
1.243 albertel 11737:
11738: =item *
11739:
11740: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
11741: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
11742: and course level
11743:
11744: =item *
11745:
1.988 raeburn 11746: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
11747: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 11748: $type is Course (default) or Community.
1.988 raeburn 11749: If $forcedefault evaluates to true, text returned will be default
11750: text for $type. Otherwise, if this is a course, the text returned
11751: will be a custom name for the role (if defined in the course's
11752: environment). If no custom name is defined the default is returned.
11753:
1.832 raeburn 11754: =item *
11755:
1.935 raeburn 11756: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858 raeburn 11757: All arguments are optional. Returns a hash of a roles, either for
11758: co-author/assistant author roles for a user's Construction Space
1.906 albertel 11759: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 11760: In the hash, keys are set to colon-separated $uname,$udom,$role, and
11761: (optionally) if $withsec is true, a fourth colon-separated item - $section.
11762: For each key, value is set to colon-separated start and end times for
11763: the role. If no username and domain are specified, will default to
1.934 raeburn 11764: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 11765: of role statuses (active, future or previous), roles
11766: (e.g., cc,in, st etc.) and domains of the roles which can be used
11767: to restrict the list of roles reported. If no array ref is
11768: provided for types, will default to return only active roles.
1.834 albertel 11769:
1.243 albertel 11770: =back
11771:
11772: =head2 User Modification
11773:
11774: =over 4
11775:
11776: =item *
11777:
1.957 raeburn 11778: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 11779: user for the level given by URL. Optional start and end dates (leave empty
11780: string or zero for "no date")
1.191 harris41 11781:
11782: =item *
11783:
1.243 albertel 11784: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
11785: change a users, password, possible return values are: ok,
11786: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
11787: refused
1.191 harris41 11788:
11789: =item *
11790:
1.243 albertel 11791: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 11792:
11793: =item *
11794:
1.1058 raeburn 11795: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
11796: $forceid,$desiredhome,$email,$inststatus,$candelete) :
11797:
11798: will update user information (firstname,middlename,lastname,generation,
11799: permanentemail), and if forceid is true, student/employee ID also.
11800: A user's institutional affiliation(s) can also be updated.
11801: User information fields will not be overwritten with empty entries
11802: unless the field is included in the $candelete array reference.
11803: This array is included when a single user is modified via "Manage Users",
11804: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 11805:
11806: =item *
11807:
1.286 matthew 11808: modifystudent
11809:
1.957 raeburn 11810: modify a student's enrollment and identification information.
1.286 matthew 11811: The course id is resolved based on the current users environment.
11812: This means the envoking user must be a course coordinator or otherwise
11813: associated with a course.
11814:
1.297 matthew 11815: This call is essentially a wrapper for lonnet::modifyuser and
11816: lonnet::modify_student_enrollment
1.286 matthew 11817:
11818: Inputs:
11819:
11820: =over 4
11821:
1.957 raeburn 11822: =item B<$udom> Student's loncapa domain
1.286 matthew 11823:
1.957 raeburn 11824: =item B<$uname> Student's loncapa login name
1.286 matthew 11825:
1.964 bisitz 11826: =item B<$uid> Student/Employee ID
1.286 matthew 11827:
1.957 raeburn 11828: =item B<$umode> Student's authentication mode
1.286 matthew 11829:
1.957 raeburn 11830: =item B<$upass> Student's password
1.286 matthew 11831:
1.957 raeburn 11832: =item B<$first> Student's first name
1.286 matthew 11833:
1.957 raeburn 11834: =item B<$middle> Student's middle name
1.286 matthew 11835:
1.957 raeburn 11836: =item B<$last> Student's last name
1.286 matthew 11837:
1.957 raeburn 11838: =item B<$gene> Student's generation
1.286 matthew 11839:
1.957 raeburn 11840: =item B<$usec> Student's section in course
1.286 matthew 11841:
11842: =item B<$end> Unix time of the roles expiration
11843:
11844: =item B<$start> Unix time of the roles start date
11845:
11846: =item B<$forceid> If defined, allow $uid to be changed
11847:
11848: =item B<$desiredhome> server to use as home server for student
11849:
1.957 raeburn 11850: =item B<$email> Student's permanent e-mail address
11851:
11852: =item B<$type> Type of enrollment (auto or manual)
11853:
1.963 raeburn 11854: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
11855:
11856: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 11857:
1.963 raeburn 11858: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 11859:
1.963 raeburn 11860: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 11861:
1.963 raeburn 11862: =item B<$inststatus> institutional status of user - : separated string of escaped status types
1.957 raeburn 11863:
1.286 matthew 11864: =back
1.297 matthew 11865:
11866: =item *
11867:
11868: modify_student_enrollment
11869:
11870: Change a students enrollment status in a class. The environment variable
11871: 'role.request.course' must be defined for this function to proceed.
11872:
11873: Inputs:
11874:
11875: =over 4
11876:
11877: =item $udom, students domain
11878:
11879: =item $uname, students name
11880:
11881: =item $uid, students user id
11882:
11883: =item $first, students first name
11884:
11885: =item $middle
11886:
11887: =item $last
11888:
11889: =item $gene
11890:
11891: =item $usec
11892:
11893: =item $end
11894:
11895: =item $start
11896:
1.957 raeburn 11897: =item $type
11898:
11899: =item $locktype
11900:
11901: =item $cid
11902:
11903: =item $selfenroll
11904:
11905: =item $context
11906:
1.297 matthew 11907: =back
11908:
1.191 harris41 11909:
11910: =item *
11911:
1.243 albertel 11912: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
11913: custom role; give a custom role to a user for the level given by URL. Specify
11914: name and domain of role author, and role name
1.191 harris41 11915:
11916: =item *
11917:
1.243 albertel 11918: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 11919:
11920: =item *
11921:
1.243 albertel 11922: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
11923:
11924: =back
11925:
11926: =head2 Course Infomation
11927:
11928: =over 4
1.191 harris41 11929:
11930: =item *
11931:
1.1118 foxr 11932: coursedescription($courseid,$options) : returns a hash of information about the
1.631 albertel 11933: specified course id, including all environment settings for the
11934: course, the description of the course will be in the hash under the
11935: key 'description'
1.191 harris41 11936:
1.1118 foxr 11937: $options is an optional parameter that if supplied is a hash reference that controls
11938: what how this function works. It has the following key/values:
11939:
11940: =over 4
11941:
11942: =item freshen_cache
11943:
11944: If defined, and the environment cache for the course is valid, it is
11945: returned in the returned hash.
11946:
11947: =item one_time
11948:
11949: If defined, the last cache time is set to _now_
11950:
11951: =item user
11952:
11953: If defined, the supplied username is used instead of the current user.
11954:
11955:
11956: =back
11957:
1.191 harris41 11958: =item *
11959:
1.624 albertel 11960: resdata($name,$domain,$type,@which) : request for current parameter
11961: setting for a specific $type, where $type is either 'course' or 'user',
11962: @what should be a list of parameters to ask about. This routine caches
11963: answers for 5 minutes.
1.243 albertel 11964:
1.877 foxr 11965: =item *
11966:
11967: get_courseresdata($courseid, $domain) : dump the entire course resource
11968: data base, returning a hash that is keyed by the resource name and has
11969: values that are the resource value. I believe that the timestamps and
11970: versions are also returned.
11971:
11972:
1.243 albertel 11973: =back
11974:
11975: =head2 Course Modification
11976:
11977: =over 4
1.191 harris41 11978:
11979: =item *
11980:
1.243 albertel 11981: writecoursepref($courseid,%prefs) : write preferences (environment
11982: database) for a course
1.191 harris41 11983:
11984: =item *
11985:
1.1011 raeburn 11986: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
11987:
11988: =item *
11989:
1.1038 raeburn 11990: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 11991:
1.1167 droeschl 11992: =item *
11993:
11994: is_course($courseid), is_course($cdom, $cnum)
11995:
11996: Accepts either a combined $courseid (in the form of domain_courseid) or the
11997: two component version $cdom, $cnum. It checks if the specified course exists.
11998:
11999: Returns:
12000: undef if the course doesn't exist, otherwise
12001: in scalar context the combined courseid.
12002: in list context the two components of the course identifier, domain and
12003: courseid.
12004:
1.243 albertel 12005: =back
12006:
12007: =head2 Resource Subroutines
12008:
12009: =over 4
1.191 harris41 12010:
12011: =item *
12012:
1.243 albertel 12013: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 12014:
12015: =item *
12016:
1.243 albertel 12017: repcopy($filename) : subscribes to the requested file, and attempts to
12018: replicate from the owning library server, Might return
1.607 raeburn 12019: 'unavailable', 'not_found', 'forbidden', 'ok', or
12020: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 12021: resource. Expects the local filesystem pathname
12022: (/home/httpd/html/res/....)
12023:
12024: =back
12025:
12026: =head2 Resource Information
12027:
12028: =over 4
1.191 harris41 12029:
12030: =item *
12031:
1.243 albertel 12032: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
12033: a vairety of different possible values, $varname should be a request
12034: string, and the other parameters can be used to specify who and what
12035: one is asking about.
12036:
12037: Possible values for $varname are environment.lastname (or other item
12038: from the envirnment hash), user.name (or someother aspect about the
12039: user), resource.0.maxtries (or some other part and parameter of a
12040: resource)
1.204 albertel 12041:
12042: =item *
12043:
1.243 albertel 12044: directcondval($number) : get current value of a condition; reads from a state
12045: string
1.204 albertel 12046:
12047: =item *
12048:
1.243 albertel 12049: condval($condidx) : value of condition index based on state
1.204 albertel 12050:
12051: =item *
12052:
1.243 albertel 12053: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
12054: resource's metadata, $what should be either a specific key, or either
12055: 'keys' (to get a list of possible keys) or 'packages' to get a list of
12056: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
12057:
12058: this function automatically caches all requests
1.191 harris41 12059:
12060: =item *
12061:
1.243 albertel 12062: metadata_query($query,$custom,$customshow) : make a metadata query against the
12063: network of library servers; returns file handle of where SQL and regex results
12064: will be stored for query
1.191 harris41 12065:
12066: =item *
12067:
1.243 albertel 12068: symbread($filename) : return symbolic list entry (filename argument optional);
12069: returns the data handle
1.191 harris41 12070:
12071: =item *
12072:
1.243 albertel 12073: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582 albertel 12074: a possible symb for the URL in $thisfn, and if is an encryypted
12075: resource that the user accessed using /enc/ returns a 1 on success, 0
12076: on failure, user must be in a course, as it assumes the existance of
1.620 albertel 12077: the course initial hash, and uses $env('request.course.id'}
1.243 albertel 12078:
1.191 harris41 12079:
12080: =item *
12081:
1.243 albertel 12082: symbclean($symb) : removes versions numbers from a symb, returns the
12083: cleaned symb
1.191 harris41 12084:
12085: =item *
12086:
1.243 albertel 12087: is_on_map($uri) : checks if the $uri is somewhere on the current
12088: course map, user must be in a course for it to work.
1.191 harris41 12089:
12090: =item *
12091:
1.243 albertel 12092: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 12093:
12094: =item *
12095:
1.243 albertel 12096: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
12097: a random seed, all arguments are optional, if they aren't sent it uses the
12098: environment to derive them. Note: if symb isn't sent and it can't get one
12099: from &symbread it will use the current time as its return value
1.191 harris41 12100:
12101: =item *
12102:
1.243 albertel 12103: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
12104: unfakeable, receipt
1.191 harris41 12105:
12106: =item *
12107:
1.620 albertel 12108: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 12109:
12110: =item *
12111:
1.243 albertel 12112: countacc($url) : count the number of accesses to a given URL
1.191 harris41 12113:
12114: =item *
12115:
1.243 albertel 12116: 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 12117:
12118: =item *
12119:
1.243 albertel 12120: 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 12121:
12122: =item *
12123:
1.243 albertel 12124: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 12125:
12126: =item *
12127:
1.243 albertel 12128: devalidate($symb) : devalidate temporary spreadsheet calculations,
12129: forcing spreadsheet to reevaluate the resource scores next time.
12130:
12131: =back
12132:
12133: =head2 Storing/Retreiving Data
12134:
12135: =over 4
1.191 harris41 12136:
12137: =item *
12138:
1.243 albertel 12139: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
12140: for this url; hashref needs to be given and should be a \%hashname; the
12141: remaining args aren't required and if they aren't passed or are '' they will
1.620 albertel 12142: be derived from the env
1.191 harris41 12143:
12144: =item *
12145:
1.243 albertel 12146: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
12147: uses critical subroutine
1.191 harris41 12148:
12149: =item *
12150:
1.243 albertel 12151: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
12152: all args are optional
1.191 harris41 12153:
12154: =item *
12155:
1.717 albertel 12156: dumpstore($namespace,$udom,$uname,$regexp,$range) :
12157: dumps the complete (or key matching regexp) namespace into a hash
12158: ($udom, $uname, $regexp, $range are optional) for a namespace that is
12159: normally &store()ed into
12160:
12161: $range should be either an integer '100' (give me the first 100
12162: matching records)
12163: or be two integers sperated by a - with no spaces
12164: '30-50' (give me the 30th through the 50th matching
12165: records)
12166:
12167:
12168: =item *
12169:
12170: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
12171: replaces a &store() version of data with a replacement set of data
12172: for a particular resource in a namespace passed in the $storehash hash
12173: reference
12174:
12175: =item *
12176:
1.243 albertel 12177: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
12178: works very similar to store/cstore, but all data is stored in a
12179: temporary location and can be reset using tmpreset, $storehash should
12180: be a hash reference, returns nothing on success
1.191 harris41 12181:
12182: =item *
12183:
1.243 albertel 12184: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
12185: similar to restore, but all data is stored in a temporary location and
12186: can be reset using tmpreset. Returns a hash of values on success,
12187: error string otherwise.
1.191 harris41 12188:
12189: =item *
12190:
1.243 albertel 12191: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
12192: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 12193:
12194: =item *
12195:
1.243 albertel 12196: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
12197: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 12198:
12199: =item *
12200:
1.243 albertel 12201: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
12202: namesp ($udom and $uname are optional)
1.191 harris41 12203:
12204: =item *
12205:
1.702 albertel 12206: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 12207: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 12208: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 12209:
1.702 albertel 12210: $range should be either an integer '100' (give me the first 100
12211: matching records)
12212: or be two integers sperated by a - with no spaces
12213: '30-50' (give me the 30th through the 50th matching
12214: records)
1.449 matthew 12215: =item *
12216:
12217: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
12218: $store can be a scalar, an array reference, or if the amount to be
12219: incremented is > 1, a hash reference.
12220:
12221: ($udom and $uname are optional)
1.191 harris41 12222:
12223: =item *
12224:
1.243 albertel 12225: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
12226: ($udom and $uname are optional)
1.191 harris41 12227:
12228: =item *
12229:
1.243 albertel 12230: cput($namespace,$storehash,$udom,$uname) : critical put
12231: ($udom and $uname are optional)
1.191 harris41 12232:
12233: =item *
12234:
1.748 albertel 12235: newput($namespace,$storehash,$udom,$uname) :
12236:
12237: Attempts to store the items in the $storehash, but only if they don't
12238: currently exist, if this succeeds you can be certain that you have
12239: successfully created a new key value pair in the $namespace db.
12240:
12241:
12242: Args:
12243: $namespace: name of database to store values to
12244: $storehash: hashref to store to the db
12245: $udom: (optional) domain of user containing the db
12246: $uname: (optional) name of user caontaining the db
12247:
12248: Returns:
12249: 'ok' -> succeeded in storing all keys of $storehash
12250: 'key_exists: <key>' -> failed to anything out of $storehash, as at
12251: least <key> already existed in the db (other
12252: requested keys may also already exist)
1.967 bisitz 12253: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 12254: 'con_lost' -> unable to contact request server
12255: 'refused' -> action was not allowed by remote machine
12256:
12257:
12258: =item *
12259:
1.243 albertel 12260: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
12261: reference filled in from namesp (encrypts the return communication)
12262: ($udom and $uname are optional)
1.191 harris41 12263:
12264: =item *
12265:
1.243 albertel 12266: log($udom,$name,$home,$message) : write to permanent log for user; use
12267: critical subroutine
12268:
1.806 raeburn 12269: =item *
12270:
1.860 raeburn 12271: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
12272: array reference filled in from namespace found in domain level on either
12273: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 12274:
12275: =item *
12276:
1.860 raeburn 12277: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
12278: domain level either on specified domain server ($uhome) or primary domain
12279: server ($udom and $uhome are optional)
1.806 raeburn 12280:
1.943 raeburn 12281: =item *
12282:
12283: get_domain_defaults($target_domain) : returns hash with defaults for
12284: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
12285: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
12286: or localauth), initial password or a kerberos realm, language (e.g., en-us).
12287: Values are retrieved from cache (if current), or from domain's configuration.db
12288: (if available), or lastly from values in lonTabs/dns_domain,tab,
12289: or lonTabs/domain.tab.
12290:
12291: %domdefaults = &get_auth_defaults($target_domain);
12292:
1.243 albertel 12293: =back
12294:
12295: =head2 Network Status Functions
12296:
12297: =over 4
1.191 harris41 12298:
12299: =item *
12300:
1.1137 raeburn 12301: dirlist() : return directory list based on URI (first arg).
12302:
12303: Inputs: 1 required, 5 optional.
12304:
12305: =over
12306:
12307: =item
12308: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
12309:
12310: =item
12311: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
12312:
12313: =item
12314: $username - username of user/course to be listed. Extracted from $uri if absent.
12315:
12316: =item
12317: $getpropath - boolean: 1 if prepend path using &propath().
12318:
12319: =item
12320: $getuserdir - boolean: 1 if prepend path for "userfiles".
12321:
12322: =item
12323: $alternateRoot - path to prepend in place of path from $uri.
12324:
12325: =back
12326:
12327: Returns: Array of up to two items.
12328:
12329: =over
12330:
12331: a reference to an array of files/subdirectories
12332:
12333: =over
12334:
12335: Each element in the array of files/subdirectories is a & separated list of
12336: item name and the result of running stat on the item. If dirlist was requested
12337: for a file instead of a directory, the item name will be ''. For a directory
12338: listing, if the item is a metadata file, the element will end &N&M
12339: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
12340: default copyright set (1).
12341:
12342: =back
12343:
12344: a scalar containing error condition (if encountered).
12345:
12346: =over
12347:
12348: =item
12349: no_host (no homeserver identified for $username:$domain).
12350:
12351: =item
12352: no_such_host (server contacted for listing not identified as valid host).
12353:
12354: =item
12355: con_lost (connection to remote server failed).
12356:
12357: =item
12358: refused (invalid $username:$domain received on lond side).
12359:
12360: =item
12361: no_such_dir (directory at specified path on lond side does not exist).
12362:
12363: =item
12364: empty (directory at specified path on lond side is empty).
12365:
12366: =over
12367:
12368: This is currently not encountered because the &ls3, &ls2,
12369: &ls (_handler) routines on the lond side do not filter out
12370: . and .. from a directory listing.
12371:
12372: =back
12373:
12374: =back
12375:
12376: =back
1.191 harris41 12377:
12378: =item *
12379:
1.243 albertel 12380: spareserver() : find server with least workload from spare.tab
12381:
1.986 foxr 12382:
12383: =item *
12384:
12385: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
12386: if there is no corresponding loncapa host.
12387:
1.243 albertel 12388: =back
12389:
1.986 foxr 12390:
1.243 albertel 12391: =head2 Apache Request
12392:
12393: =over 4
1.191 harris41 12394:
12395: =item *
12396:
1.243 albertel 12397: ssi($url,%hash) : server side include, does a complete request cycle on url to
12398: localhost, posts hash
12399:
12400: =back
12401:
12402: =head2 Data to String to Data
12403:
12404: =over 4
1.191 harris41 12405:
12406: =item *
12407:
1.243 albertel 12408: hash2str(%hash) : convert a hash into a string complete with escaping and '='
12409: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 12410:
12411: =item *
12412:
1.243 albertel 12413: hashref2str($hashref) : convert a hashref into a string complete with
12414: escaping and '=' and '&' separators, supports elements that are
12415: arrayrefs and hashrefs
1.191 harris41 12416:
12417: =item *
12418:
1.243 albertel 12419: arrayref2str($arrayref) : convert an arrayref into a string complete
12420: with escaping and '&' separators, supports elements that are arrayrefs
12421: and hashrefs
1.191 harris41 12422:
12423: =item *
12424:
1.243 albertel 12425: str2hash($string) : convert string to hash using unescaping and
12426: splitting on '=' and '&', supports elements that are arrayrefs and
12427: hashrefs
1.191 harris41 12428:
12429: =item *
12430:
1.243 albertel 12431: str2array($string) : convert string to hash using unescaping and
12432: splitting on '&', supports elements that are arrayrefs and hashrefs
12433:
12434: =back
12435:
12436: =head2 Logging Routines
12437:
12438:
12439: These routines allow one to make log messages in the lonnet.log and
12440: lonnet.perm logfiles.
1.191 harris41 12441:
1.1119 foxr 12442: =over 4
12443:
1.191 harris41 12444: =item *
12445:
1.243 albertel 12446: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 12447:
12448: =item *
12449:
1.243 albertel 12450: logthis() : append message to the normal lonnet.log file, it gets
12451: preiodically rolled over and deleted.
1.191 harris41 12452:
12453: =item *
12454:
1.243 albertel 12455: logperm() : append a permanent message to lonnet.perm.log, this log
12456: file never gets deleted by any automated portion of the system, only
12457: messages of critical importance should go in here.
12458:
1.1119 foxr 12459:
1.243 albertel 12460: =back
12461:
12462: =head2 General File Helper Routines
12463:
12464: =over 4
1.191 harris41 12465:
12466: =item *
12467:
1.481 raeburn 12468: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
12469: (a) files in /uploaded
12470: (i) If a local copy of the file exists -
12471: compares modification date of local copy with last-modified date for
12472: definitive version stored on home server for course. If local copy is
12473: stale, requests a new version from the home server and stores it.
12474: If the original has been removed from the home server, then local copy
12475: is unlinked.
12476: (ii) If local copy does not exist -
12477: requests the file from the home server and stores it.
12478:
12479: If $caller is 'uploadrep':
12480: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
12481: for request for files originally uploaded via DOCS.
12482: - returns 'ok' if fresh local copy now available, -1 otherwise.
12483:
12484: Otherwise:
12485: This indicates a call from the content generation phase of the request.
12486: - returns the entire contents of the file or -1.
12487:
12488: (b) files in /res
12489: - returns the entire contents of a file or -1;
12490: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 12491:
1.712 albertel 12492:
12493: =item *
12494:
12495: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
12496: reference
12497:
12498: returns either a stat() list of data about the file or an empty list
12499: if the file doesn't exist or couldn't find out about it (connection
12500: problems or user unknown)
12501:
1.191 harris41 12502: =item *
12503:
1.243 albertel 12504: filelocation($dir,$file) : returns file system location of a file
12505: based on URI; meant to be "fairly clean" absolute reference, $dir is a
12506: directory that relative $file lookups are to looked in ($dir of /a/dir
12507: and a file of ../bob will become /a/bob)
1.191 harris41 12508:
12509: =item *
12510:
12511: hreflocation($dir,$file) : returns file system location or a URL; same as
12512: filelocation except for hrefs
12513:
12514: =item *
12515:
12516: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
12517:
1.243 albertel 12518: =back
12519:
1.608 albertel 12520: =head2 Usererfile file routines (/uploaded*)
12521:
12522: =over 4
12523:
12524: =item *
12525:
12526: userfileupload(): main rotine for putting a file in a user or course's
12527: filespace, arguments are,
12528:
1.620 albertel 12529: formname - required - this is the name of the element in $env where the
1.608 albertel 12530: filename, and the contents of the file to create/modifed exist
1.620 albertel 12531: the filename is in $env{'form.'.$formname.'.filename'} and the
12532: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 12533: context - if coursedoc, store the file in the course of the active role
12534: of the current user;
12535: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
12536: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 12537: subdir - required - subdirectory to put the file in under ../userfiles/
12538: if undefined, it will be placed in "unknown"
12539:
12540: (This routine calls clean_filename() to remove any dangerous
12541: characters from the filename, and then calls finuserfileupload() to
12542: complete the transaction)
12543:
12544: returns either the url of the uploaded file (/uploaded/....) if successful
12545: and /adm/notfound.html if unsuccessful
12546:
12547: =item *
12548:
12549: clean_filename(): routine for cleaing a filename up for storage in
12550: userfile space, argument is:
12551:
12552: filename - proposed filename
12553:
12554: returns: the new clean filename
12555:
12556: =item *
12557:
1.1090 raeburn 12558: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 12559: userspace, probably shouldn't be called directly
12560:
12561: docuname: username or courseid of destination for the file
12562: docudom: domain of user/course of destination for the file
12563: formname: same as for userfileupload()
1.1090 raeburn 12564: fname: filename (including subdirectories) for the file
12565: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
12566: allfiles: reference to hash used to store objects found by parser
12567: codebase: reference to hash used for codebases of java objects found by parser
12568: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
12569: thumbheight: height (pixels) of thumbnail to be created for uploaded image
12570: resizewidth: width to be used to resize image using resizeImage from ImageMagick
12571: resizeheight: height to be used to resize image using resizeImage from ImageMagick
12572: context: if 'overwrite', will move the uploaded file from its temporary location to
12573: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 12574: mimetype: reference to scalar to accommodate mime type determined
12575: from File::MMagic if $parser = parse.
1.608 albertel 12576:
12577: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 12578: and /adm/notfound.html if unsuccessful (or an error message if context
12579: was 'overwrite').
12580:
1.608 albertel 12581:
12582: =item *
12583:
12584: renameuserfile(): renames an existing userfile to a new name
12585:
12586: Args:
12587: docuname: username or courseid of destination for the file
12588: docudom: domain of user/course of destination for the file
12589: old: current file name (including any subdirs under userfiles)
12590: new: desired file name (including any subdirs under userfiles)
12591:
12592: =item *
12593:
12594: mkdiruserfile(): creates a directory is a userfiles dir
12595:
12596: Args:
12597: docuname: username or courseid of destination for the file
12598: docudom: domain of user/course of destination for the file
12599: dir: dir to create (including any subdirs under userfiles)
12600:
12601: =item *
12602:
12603: removeuserfile(): removes a file that exists in userfiles
12604:
12605: Args:
12606: docuname: username or courseid of destination for the file
12607: docudom: domain of user/course of destination for the file
12608: fname: filname to delete (including any subdirs under userfiles)
12609:
12610: =item *
12611:
12612: removeuploadedurl(): convience function for removeuserfile()
12613:
12614: Args:
12615: url: a full /uploaded/... url to delete
12616:
1.747 albertel 12617: =item *
12618:
12619: get_portfile_permissions():
12620: Args:
12621: domain: domain of user or course contain the portfolio files
12622: user: name of user or num of course contain the portfolio files
12623: Returns:
12624: hashref of a dump of the proper file_permissions.db
12625:
12626:
12627: =item *
12628:
12629: get_access_controls():
12630:
12631: Args:
12632: current_permissions: the hash ref returned from get_portfile_permissions()
12633: group: (optional) the group you want the files associated with
12634: file: (optional) the file you want access info on
12635:
12636: Returns:
1.749 raeburn 12637: a hash (keys are file names) of hashes containing
12638: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
12639: values are XML containing access control settings (see below)
1.747 albertel 12640:
12641: Internal notes:
12642:
1.749 raeburn 12643: access controls are stored in file_permissions.db as key=value pairs.
12644: key -> path to file/file_name\0uniqueID:scope_end_start
12645: where scope -> public,guest,course,group,domains or users.
12646: end -> UNIX time for end of access (0 -> no end date)
12647: start -> UNIX time for start of access
12648:
12649: value -> XML description of access control
12650: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
12651: <start></start>
12652: <end></end>
12653:
12654: <password></password> for scope type = guest
12655:
12656: <domain></domain> for scope type = course or group
12657: <number></number>
12658: <roles id="">
12659: <role></role>
12660: <access></access>
12661: <section></section>
12662: <group></group>
12663: </roles>
12664:
12665: <dom></dom> for scope type = domains
12666:
12667: <users> for scope type = users
12668: <user>
12669: <uname></uname>
12670: <udom></udom>
12671: </user>
12672: </users>
12673: </scope>
12674:
12675: Access data is also aggregated for each file in an additional key=value pair:
12676: key -> path to file/file_name\0accesscontrol
12677: value -> reference to hash
12678: hash contains key = value pairs
12679: where key = uniqueID:scope_end_start
12680: value = UNIX time record was last updated
12681:
12682: Used to improve speed of look-ups of access controls for each file.
12683:
12684: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
12685:
12686: modify_access_controls():
12687:
12688: Modifies access controls for a portfolio file
12689: Args
12690: 1. file name
12691: 2. reference to hash of required changes,
12692: 3. domain
12693: 4. username
12694: where domain,username are the domain of the portfolio owner
12695: (either a user or a course)
12696:
12697: Returns:
12698: 1. result of additions or updates ('ok' or 'error', with error message).
12699: 2. result of deletions ('ok' or 'error', with error message).
12700: 3. reference to hash of any new or updated access controls.
12701: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
12702: key = integer (inbound ID)
12703: value = uniqueID
1.747 albertel 12704:
1.608 albertel 12705: =back
12706:
1.243 albertel 12707: =head2 HTTP Helper Routines
12708:
12709: =over 4
12710:
1.191 harris41 12711: =item *
12712:
12713: escape() : unpack non-word characters into CGI-compatible hex codes
12714:
12715: =item *
12716:
12717: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
12718:
1.243 albertel 12719: =back
12720:
12721: =head1 PRIVATE SUBROUTINES
12722:
12723: =head2 Underlying communication routines (Shouldn't call)
12724:
12725: =over 4
12726:
12727: =item *
12728:
12729: subreply() : tries to pass a message to lonc, returns con_lost if incapable
12730:
12731: =item *
12732:
12733: reply() : uses subreply to send a message to remote machine, logs all failures
12734:
12735: =item *
12736:
12737: critical() : passes a critical message to another server; if cannot
12738: get through then place message in connection buffer directory and
12739: returns con_delayed, if incapable of saving message, returns
12740: con_failed
12741:
12742: =item *
12743:
12744: reconlonc() : tries to reconnect lonc client processes.
12745:
12746: =back
12747:
12748: =head2 Resource Access Logging
12749:
12750: =over 4
12751:
12752: =item *
12753:
12754: flushcourselogs() : flush (save) buffer logs and access logs
12755:
12756: =item *
12757:
12758: courselog($what) : save message for course in hash
12759:
12760: =item *
12761:
12762: courseacclog($what) : save message for course using &courselog(). Perform
12763: special processing for specific resource types (problems, exams, quizzes, etc).
12764:
1.191 harris41 12765: =item *
12766:
12767: goodbye() : flush course logs and log shutting down; it is called in srm.conf
12768: as a PerlChildExitHandler
1.243 albertel 12769:
12770: =back
12771:
12772: =head2 Other
12773:
12774: =over 4
12775:
12776: =item *
12777:
12778: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 12779:
12780: =back
12781:
12782: =cut
1.877 foxr 12783:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>