Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1167
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1167 ! droeschl 4: # $Id: lonnet.pm,v 1.1166 2012/04/25 21:22:15 raeburn Exp $
1.178 www 5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27: #
1.169 harris41 28: ###
29:
1.971 jms 30: =pod
31:
1.972 jms 32: =head1 NAME
33:
34: Apache::lonnet.pm
35:
36: =head1 SYNOPSIS
37:
38: This file is an interface to the lonc processes of
39: the LON-CAPA network as well as set of elaborated functions for handling information
40: necessary for navigating through a given cluster of LON-CAPA machines within a
41: domain. There are over 40 specialized functions in this module which handle the
42: reading and transmission of metadata, user information (ids, names, environments, roles,
43: logs), file information (storage, reading, directories, extensions, replication, embedded
44: styles and descriptors), educational resources (course descriptions, section names and
45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
46: and from more descriptive phrases or explanations.
47:
48: This is part of the LearningOnline Network with CAPA project
49: described at http://www.lon-capa.org.
50:
1.971 jms 51: =head1 Package Variables
52:
53: These are largely undocumented, so if you decipher one please note it here.
54:
55: =over 4
56:
57: =item $processmarker
58:
59: Contains the time this process was started and this servers host id.
60:
61: =item $dumpcount
62:
63: Counts the number of times a message log flush has been attempted (regardless
64: of success) by this process. Used as part of the filename when messages are
65: delayed.
66:
67: =back
68:
69: =cut
70:
1.1 albertel 71: package Apache::lonnet;
72:
73: use strict;
1.8 www 74: use LWP::UserAgent();
1.486 www 75: use HTTP::Date;
1.977 amueller 76: use Image::Magick;
77:
1.871 albertel 78: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.1138 raeburn 79: $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
80: %managerstab);
1.871 albertel 81:
82: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
83: %userrolehash, $processmarker, $dumpcount, %coursedombuf,
84: %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958 www 85: %courseownerbuf, %coursetypebuf,$locknum);
1.403 www 86:
1.1 albertel 87: use IO::Socket;
1.31 www 88: use GDBM_File;
1.208 albertel 89: use HTML::LCParser;
1.88 www 90: use Fcntl qw(:flock);
1.870 albertel 91: use Storable qw(thaw nfreeze);
1.539 albertel 92: use Time::HiRes qw( gettimeofday tv_interval );
1.599 albertel 93: use Cache::Memcached;
1.676 albertel 94: use Digest::MD5;
1.790 albertel 95: use Math::Random;
1.1024 raeburn 96: use File::MMagic;
1.807 albertel 97: use LONCAPA qw(:DEFAULT :match);
1.740 www 98: use LONCAPA::Configuration;
1.1160 www 99: use LONCAPA::lonmetadata;
1.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.587 albertel 4677: if ($role=~/^cr/) {
1.807 albertel 4678: if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
4679: ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655 albertel 4680: ($tend,$tstart)=split('_',$trest);
4681: } else {
4682: $trole=$role;
4683: }
1.678 raeburn 4684: } elsif ($role =~ m|^gr/|) {
4685: ($trole,$tend,$tstart) = split(/_/,$role);
1.1104 raeburn 4686: next if ($tstart eq '-1');
1.678 raeburn 4687: ($trole,$group_privs) = split(/\//,$trole);
4688: $group_privs = &unescape($group_privs);
1.587 albertel 4689: } else {
4690: ($trole,$tend,$tstart)=split(/_/,$role);
4691: }
1.743 albertel 4692: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
4693: $username);
4694: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567 raeburn 4695: if (($tend!=0) && ($tend<$now)) { $trole=''; }
4696: if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11 www 4697: if (($area ne '') && ($trole ne '')) {
1.347 albertel 4698: my $spec=$trole.'.'.$area;
4699: my ($tdummy,$tdomain,$trest)=split(/\//,$area);
4700: if ($trole =~ /^cr\//) {
1.567 raeburn 4701: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678 raeburn 4702: } elsif ($trole eq 'gr') {
4703: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347 albertel 4704: } else {
1.567 raeburn 4705: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347 albertel 4706: }
1.1162 raeburn 4707: if ($trole ne 'gr') {
4708: my $cid = $tdomain.'_'.$trest;
4709: unless ($firstaccchk{$cid}) {
4710: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
4711: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
4712: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
4713: $coursetimerstarts{$cid}{$item};
4714: }
4715: }
4716: $firstaccchk{$cid} = 1;
4717: }
4718: unless ($timerintchk{$cid}) {
4719: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
4720: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
4721: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
4722: $coursetimerintervals{$cid}{$item};
4723: }
4724: }
4725: $timerintchk{$cid} = 1;
4726: }
4727: }
1.12 www 4728: }
1.662 raeburn 4729: }
1.191 harris41 4730: }
1.743 albertel 4731: my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
4732: $userroles{'user.adv'} = $adv;
4733: $userroles{'user.author'} = $author;
1.620 albertel 4734: $env{'user.adv'}=$adv;
1.11 www 4735: }
1.1162 raeburn 4736: return (\%userroles,\%firstaccenv,\%timerintenv);
1.11 www 4737: }
4738:
1.567 raeburn 4739: sub set_arearole {
4740: my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
4741: # log the associated role with the area
4742: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743 albertel 4743: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 4744: }
4745:
4746: sub custom_roleprivs {
4747: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
4748: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
4749: my $homsvr=homeserver($rauthor,$rdomain);
1.838 albertel 4750: if (&hostname($homsvr) ne '') {
1.567 raeburn 4751: my ($rdummy,$roledef)=
4752: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
4753: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
4754: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
4755: if (defined($syspriv)) {
1.1043 raeburn 4756: if ($trest =~ /^$match_community$/) {
4757: $syspriv =~ s/bre\&S//;
4758: }
1.567 raeburn 4759: $$allroles{'cm./'}.=':'.$syspriv;
4760: $$allroles{$spec.'./'}.=':'.$syspriv;
4761: }
4762: if ($tdomain ne '') {
4763: if (defined($dompriv)) {
4764: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
4765: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
4766: }
4767: if (($trest ne '') && (defined($coursepriv))) {
4768: $$allroles{'cm.'.$area}.=':'.$coursepriv;
4769: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
4770: }
4771: }
4772: }
4773: }
4774: }
4775:
1.678 raeburn 4776: sub group_roleprivs {
4777: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
4778: my $access = 1;
4779: my $now = time;
4780: if (($tend!=0) && ($tend<$now)) { $access = 0; }
4781: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
4782: if ($access) {
1.811 albertel 4783: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 4784: $$allgroups{$course}{$group} .=':'.$group_privs;
4785: }
4786: }
1.567 raeburn 4787:
4788: sub standard_roleprivs {
4789: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
4790: if (defined($pr{$trole.':s'})) {
4791: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
4792: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
4793: }
4794: if ($tdomain ne '') {
4795: if (defined($pr{$trole.':d'})) {
4796: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
4797: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
4798: }
4799: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
4800: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
4801: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
4802: }
4803: }
4804: }
4805:
4806: sub set_userprivs {
1.1064 raeburn 4807: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 4808: my $author=0;
4809: my $adv=0;
1.678 raeburn 4810: my %grouproles = ();
4811: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 4812: my @groupkeys;
1.1000 raeburn 4813: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 4814: push(@groupkeys,$role);
4815: }
4816: if (ref($groups_roles) eq 'HASH') {
4817: foreach my $key (keys(%{$groups_roles})) {
4818: unless (grep(/^\Q$key\E$/,@groupkeys)) {
4819: push(@groupkeys,$key);
4820: }
4821: }
4822: }
4823: if (@groupkeys > 0) {
4824: foreach my $role (@groupkeys) {
4825: my ($trole,$area,$sec,$extendedarea);
4826: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
4827: $trole = $1;
4828: $area = $2;
4829: $sec = $3;
4830: $extendedarea = $area.$sec;
4831: if (exists($$allgroups{$area})) {
4832: foreach my $group (keys(%{$$allgroups{$area}})) {
4833: my $spec = $trole.'.'.$extendedarea;
4834: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 4835: $$allgroups{$area}{$group};
1.1064 raeburn 4836: }
1.678 raeburn 4837: }
4838: }
4839: }
4840: }
4841: }
1.800 albertel 4842: foreach my $group (keys(%grouproles)) {
4843: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 4844: }
1.800 albertel 4845: foreach my $role (keys(%{$allroles})) {
4846: my %thesepriv;
1.941 raeburn 4847: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 4848: foreach my $item (split(/:/,$$allroles{$role})) {
4849: if ($item ne '') {
4850: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 4851: if ($restrictions eq '') {
4852: $thesepriv{$privilege}='F';
4853: } elsif ($thesepriv{$privilege} ne 'F') {
4854: $thesepriv{$privilege}.=$restrictions;
4855: }
4856: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
4857: }
4858: }
4859: my $thesestr='';
1.1104 raeburn 4860: foreach my $priv (sort(keys(%thesepriv))) {
1.800 albertel 4861: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
4862: }
4863: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 4864: }
4865: return ($author,$adv);
4866: }
4867:
1.994 raeburn 4868: sub role_status {
1.1104 raeburn 4869: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 4870: my @pwhere = ();
4871: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
4872: (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
4873: unless (!defined($$role) || $$role eq '') {
4874: $$where=join('.',@pwhere);
4875: $$trolecode=$$role.'.'.$$where;
4876: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
4877: $$tstatus='is';
1.1104 raeburn 4878: if ($$tstart && $$tstart>$update) {
1.994 raeburn 4879: $$tstatus='future';
1.1034 raeburn 4880: if ($$tstart<$now) {
4881: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 4882: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 4883: my (%allroles,%allgroups,$group_privs,
4884: %groups_roles,@rolecodes);
1.1002 raeburn 4885: my %userroles = (
4886: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
4887: );
1.1064 raeburn 4888: @rolecodes = ('cm');
1.1002 raeburn 4889: my $spec=$$role.'.'.$$where;
4890: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
4891: if ($$role =~ /^cr\//) {
4892: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 4893: push(@rolecodes,'cr');
1.1002 raeburn 4894: } elsif ($$role eq 'gr') {
1.1064 raeburn 4895: push(@rolecodes,$$role);
1.1002 raeburn 4896: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
4897: $env{'user.name'});
1.1064 raeburn 4898: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 4899: (undef,my $group_privs) = split(/\//,$trole);
4900: $group_privs = &unescape($group_privs);
4901: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 4902: 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 4903: &get_groups_roles($tdomain,$trest,
4904: \%course_roles,\@rolecodes,
4905: \%groups_roles);
1.1002 raeburn 4906: } else {
1.1064 raeburn 4907: push(@rolecodes,$$role);
1.1002 raeburn 4908: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
4909: }
1.1064 raeburn 4910: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
4911: &appenv(\%userroles,\@rolecodes);
1.1002 raeburn 4912: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
4913: }
4914: }
1.1034 raeburn 4915: $$tstatus = 'is';
1.1002 raeburn 4916: }
1.994 raeburn 4917: }
4918: if ($$tend) {
1.1104 raeburn 4919: if ($$tend<$update) {
1.994 raeburn 4920: $$tstatus='expired';
4921: } elsif ($$tend<$now) {
4922: $$tstatus='will_not';
4923: }
4924: }
4925: }
4926: }
4927: }
4928:
1.1104 raeburn 4929: sub get_groups_roles {
4930: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
4931: return unless((ref($cdom_courseroles) eq 'HASH') &&
4932: (ref($rolecodes) eq 'ARRAY') &&
4933: (ref($groups_roles) eq 'HASH'));
4934: if (keys(%{$cdom_courseroles}) > 0) {
4935: my ($cnum) = ($rest =~ /^($match_courseid)/);
4936: if ($cdom ne '' && $cnum ne '') {
4937: foreach my $key (keys(%{$cdom_courseroles})) {
4938: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
4939: my $crsrole = $1;
4940: my $crssec = $2;
4941: if ($crsrole =~ /^cr/) {
4942: unless (grep(/^cr$/,@{$rolecodes})) {
4943: push(@{$rolecodes},'cr');
4944: }
4945: } else {
4946: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
4947: push(@{$rolecodes},$crsrole);
4948: }
4949: }
4950: my $rolekey = "$crsrole./$cdom/$cnum";
4951: if ($crssec ne '') {
4952: $rolekey .= "/$crssec";
4953: }
4954: $rolekey .= './';
4955: $groups_roles->{$rolekey} = $rolecodes;
4956: }
4957: }
4958: }
4959: }
4960: return;
4961: }
4962:
4963: sub delete_env_groupprivs {
4964: my ($where,$courseroles,$possroles) = @_;
4965: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
4966: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
4967: unless (ref($courseroles->{$udom}) eq 'HASH') {
4968: %{$courseroles->{$udom}} =
4969: &get_my_roles('','','userroles',['active'],
4970: $possroles,[$udom],1);
4971: }
4972: if (ref($courseroles->{$udom}) eq 'HASH') {
4973: foreach my $item (keys(%{$courseroles->{$udom}})) {
4974: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
4975: my $area = '/'.$cdom.'/'.$cnum;
4976: my $privkey = "user.priv.$crsrole.$area";
4977: if ($crssec ne '') {
4978: $privkey .= '/'.$crssec;
4979: }
4980: $privkey .= ".$area/$group";
4981: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
4982: }
4983: }
4984: return;
4985: }
4986:
1.994 raeburn 4987: sub check_adhoc_privs {
1.1104 raeburn 4988: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994 raeburn 4989: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
4990: if ($env{$cckey}) {
4991: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104 raeburn 4992: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 4993: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088 raeburn 4994: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994 raeburn 4995: }
4996: } else {
1.1088 raeburn 4997: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994 raeburn 4998: }
4999: }
5000:
5001: sub set_adhoc_privileges {
5002: # role can be cc or ca
1.1088 raeburn 5003: my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994 raeburn 5004: my $area = '/'.$dcdom.'/'.$pickedcourse;
5005: my $spec = $role.'.'.$area;
5006: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
5007: $env{'user.name'});
5008: my %ccrole = ();
5009: &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
5010: my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
5011: &appenv(\%userroles,[$role,'cm']);
5012: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088 raeburn 5013: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
5014: &appenv( {'request.role' => $spec,
5015: 'request.role.domain' => $dcdom,
5016: 'request.course.sec' => ''
5017: }
5018: );
5019: my $tadv=0;
5020: if (&allowed('adv') eq 'F') { $tadv=1; }
5021: &appenv({'request.role.adv' => $tadv});
5022: }
1.994 raeburn 5023: }
5024:
1.12 www 5025: # --------------------------------------------------------------- get interface
5026:
5027: sub get {
1.131 albertel 5028: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 5029: my $items='';
1.800 albertel 5030: foreach my $item (@$storearr) {
5031: $items.=&escape($item).'&';
1.191 harris41 5032: }
1.12 www 5033: $items=~s/\&$//;
1.620 albertel 5034: if (!$udomain) { $udomain=$env{'user.domain'}; }
5035: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 5036: my $uhome=&homeserver($uname,$udomain);
5037:
1.133 albertel 5038: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 5039: my @pairs=split(/\&/,$rep);
1.273 albertel 5040: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
5041: return @pairs;
5042: }
1.15 www 5043: my %returnhash=();
1.42 www 5044: my $i=0;
1.800 albertel 5045: foreach my $item (@$storearr) {
5046: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 5047: $i++;
1.191 harris41 5048: }
1.15 www 5049: return %returnhash;
1.27 www 5050: }
5051:
5052: # --------------------------------------------------------------- del interface
5053:
5054: sub del {
1.133 albertel 5055: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 5056: my $items='';
1.800 albertel 5057: foreach my $item (@$storearr) {
5058: $items.=&escape($item).'&';
1.191 harris41 5059: }
1.984 neumanie 5060:
1.27 www 5061: $items=~s/\&$//;
1.620 albertel 5062: if (!$udomain) { $udomain=$env{'user.domain'}; }
5063: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 5064: my $uhome=&homeserver($uname,$udomain);
5065: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 5066: }
5067:
5068: # -------------------------------------------------------------- dump interface
5069:
5070: sub dump {
1.1166 raeburn 5071: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.755 albertel 5072: if (!$udomain) { $udomain=$env{'user.domain'}; }
5073: if (!$uname) { $uname=$env{'user.name'}; }
5074: my $uhome=&homeserver($uname,$udomain);
1.1167 ! droeschl 5075:
1.755 albertel 5076: if ($regexp) {
5077: $regexp=&escape($regexp);
5078: } else {
5079: $regexp='.';
5080: }
1.1166 raeburn 5081: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755 albertel 5082: my @pairs=split(/\&/,$rep);
5083: my %returnhash=();
1.1098 foxr 5084: if (!($rep =~ /^error/ )) {
5085: foreach my $item (@pairs) {
5086: my ($key,$value)=split(/=/,$item,2);
5087: $key = &unescape($key);
5088: next if ($key =~ /^error: 2 /);
5089: $returnhash{$key}=&thaw_unescape($value);
5090: }
1.755 albertel 5091: }
5092: return %returnhash;
1.407 www 5093: }
5094:
1.1098 foxr 5095:
1.717 albertel 5096: # --------------------------------------------------------- dumpstore interface
5097:
5098: sub dumpstore {
5099: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822 albertel 5100: if (!$udomain) { $udomain=$env{'user.domain'}; }
5101: if (!$uname) { $uname=$env{'user.name'}; }
5102: my $uhome=&homeserver($uname,$udomain);
5103: if ($regexp) {
5104: $regexp=&escape($regexp);
5105: } else {
5106: $regexp='.';
5107: }
5108: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
5109: my @pairs=split(/\&/,$rep);
5110: my %returnhash=();
5111: foreach my $item (@pairs) {
5112: my ($key,$value)=split(/=/,$item,2);
5113: next if ($key =~ /^error: 2 /);
5114: $returnhash{$key}=&thaw_unescape($value);
5115: }
5116: return %returnhash;
1.717 albertel 5117: }
5118:
1.407 www 5119: # -------------------------------------------------------------- keys interface
5120:
5121: sub getkeys {
5122: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 5123: if (!$udomain) { $udomain=$env{'user.domain'}; }
5124: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 5125: my $uhome=&homeserver($uname,$udomain);
5126: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
5127: my @keyarray=();
1.800 albertel 5128: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 5129: next if ($key =~ /^error: 2 /);
1.800 albertel 5130: push(@keyarray,&unescape($key));
1.407 www 5131: }
5132: return @keyarray;
1.318 matthew 5133: }
5134:
1.319 matthew 5135: # --------------------------------------------------------------- currentdump
5136: sub currentdump {
1.328 matthew 5137: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 5138: $courseid = $env{'request.course.id'} if (! defined($courseid));
5139: $sdom = $env{'user.domain'} if (! defined($sdom));
5140: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 5141: my $uhome = &homeserver($sname,$sdom);
5142: my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318 matthew 5143: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 5144: #
1.318 matthew 5145: my %returnhash=();
1.319 matthew 5146: #
5147: if ($rep eq "unknown_cmd") {
5148: # an old lond will not know currentdump
5149: # Do a dump and make it look like a currentdump
1.822 albertel 5150: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 5151: return if ($tmp[0] =~ /^(error:|no_such_host)/);
5152: my %hash = @tmp;
5153: @tmp=();
1.424 matthew 5154: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 5155: } else {
5156: my @pairs=split(/\&/,$rep);
1.800 albertel 5157: foreach my $pair (@pairs) {
5158: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 5159: my ($symb,$param) = split(/:/,$key);
5160: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 5161: &thaw_unescape($value);
1.319 matthew 5162: }
1.191 harris41 5163: }
1.12 www 5164: return %returnhash;
1.424 matthew 5165: }
5166:
5167: sub convert_dump_to_currentdump{
5168: my %hash = %{shift()};
5169: my %returnhash;
5170: # Code ripped from lond, essentially. The only difference
5171: # here is the unescaping done by lonnet::dump(). Conceivably
5172: # we might run in to problems with parameter names =~ /^v\./
5173: while (my ($key,$value) = each(%hash)) {
5174: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 5175: $symb = &unescape($symb);
5176: $param = &unescape($param);
1.424 matthew 5177: next if ($v eq 'version' || $symb eq 'keys');
5178: next if (exists($returnhash{$symb}) &&
5179: exists($returnhash{$symb}->{$param}) &&
5180: $returnhash{$symb}->{'v.'.$param} > $v);
5181: $returnhash{$symb}->{$param}=$value;
5182: $returnhash{$symb}->{'v.'.$param}=$v;
5183: }
5184: #
5185: # Remove all of the keys in the hashes which keep track of
5186: # the version of the parameter.
5187: while (my ($symb,$param_hash) = each(%returnhash)) {
5188: # use a foreach because we are going to delete from the hash.
5189: foreach my $key (keys(%$param_hash)) {
5190: delete($param_hash->{$key}) if ($key =~ /^v\./);
5191: }
5192: }
5193: return \%returnhash;
1.12 www 5194: }
5195:
1.627 albertel 5196: # ------------------------------------------------------ critical inc interface
5197:
5198: sub cinc {
5199: return &inc(@_,'critical');
5200: }
5201:
1.449 matthew 5202: # --------------------------------------------------------------- inc interface
5203:
5204: sub inc {
1.627 albertel 5205: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 5206: if (!$udomain) { $udomain=$env{'user.domain'}; }
5207: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 5208: my $uhome=&homeserver($uname,$udomain);
5209: my $items='';
5210: if (! ref($store)) {
5211: # got a single value, so use that instead
5212: $items = &escape($store).'=&';
5213: } elsif (ref($store) eq 'SCALAR') {
5214: $items = &escape($$store).'=&';
5215: } elsif (ref($store) eq 'ARRAY') {
5216: $items = join('=&',map {&escape($_);} @{$store});
5217: } elsif (ref($store) eq 'HASH') {
5218: while (my($key,$value) = each(%{$store})) {
5219: $items.= &escape($key).'='.&escape($value).'&';
5220: }
5221: }
5222: $items=~s/\&$//;
1.627 albertel 5223: if ($critical) {
5224: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
5225: } else {
5226: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
5227: }
1.449 matthew 5228: }
5229:
1.12 www 5230: # --------------------------------------------------------------- put interface
5231:
5232: sub put {
1.134 albertel 5233: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 5234: if (!$udomain) { $udomain=$env{'user.domain'}; }
5235: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 5236: my $uhome=&homeserver($uname,$udomain);
1.12 www 5237: my $items='';
1.800 albertel 5238: foreach my $item (keys(%$storehash)) {
5239: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 5240: }
1.12 www 5241: $items=~s/\&$//;
1.134 albertel 5242: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 5243: }
5244:
1.631 albertel 5245: # ------------------------------------------------------------ newput interface
5246:
5247: sub newput {
5248: my ($namespace,$storehash,$udomain,$uname)=@_;
5249: if (!$udomain) { $udomain=$env{'user.domain'}; }
5250: if (!$uname) { $uname=$env{'user.name'}; }
5251: my $uhome=&homeserver($uname,$udomain);
5252: my $items='';
5253: foreach my $key (keys(%$storehash)) {
5254: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
5255: }
5256: $items=~s/\&$//;
5257: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
5258: }
5259:
5260: # --------------------------------------------------------- putstore interface
5261:
1.524 raeburn 5262: sub putstore {
1.715 albertel 5263: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620 albertel 5264: if (!$udomain) { $udomain=$env{'user.domain'}; }
5265: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 5266: my $uhome=&homeserver($uname,$udomain);
5267: my $items='';
1.715 albertel 5268: foreach my $key (keys(%$storehash)) {
5269: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 5270: }
1.715 albertel 5271: $items=~s/\&$//;
1.716 albertel 5272: my $esc_symb=&escape($symb);
5273: my $esc_v=&escape($version);
1.715 albertel 5274: my $reply =
1.716 albertel 5275: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 5276: $uhome);
5277: if ($reply eq 'unknown_cmd') {
1.716 albertel 5278: # gfall back to way things use to be done
1.715 albertel 5279: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
5280: $uname);
1.524 raeburn 5281: }
1.715 albertel 5282: return $reply;
5283: }
5284:
5285: sub old_putstore {
1.716 albertel 5286: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
5287: if (!$udomain) { $udomain=$env{'user.domain'}; }
5288: if (!$uname) { $uname=$env{'user.name'}; }
5289: my $uhome=&homeserver($uname,$udomain);
5290: my %newstorehash;
1.800 albertel 5291: foreach my $item (keys(%$storehash)) {
5292: my $key = $version.':'.&escape($symb).':'.$item;
5293: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 5294: }
5295: my $items='';
5296: my %allitems = ();
1.800 albertel 5297: foreach my $item (keys(%newstorehash)) {
5298: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 5299: my $key = $1.':keys:'.$2;
5300: $allitems{$key} .= $3.':';
5301: }
1.800 albertel 5302: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 5303: }
1.800 albertel 5304: foreach my $item (keys(%allitems)) {
5305: $allitems{$item} =~ s/\:$//;
5306: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 5307: }
5308: $items=~s/\&$//;
5309: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 5310: }
5311:
1.47 www 5312: # ------------------------------------------------------ critical put interface
5313:
5314: sub cput {
1.134 albertel 5315: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 5316: if (!$udomain) { $udomain=$env{'user.domain'}; }
5317: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 5318: my $uhome=&homeserver($uname,$udomain);
1.47 www 5319: my $items='';
1.800 albertel 5320: foreach my $item (keys(%$storehash)) {
5321: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 5322: }
1.47 www 5323: $items=~s/\&$//;
1.134 albertel 5324: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 5325: }
5326:
5327: # -------------------------------------------------------------- eget interface
5328:
5329: sub eget {
1.133 albertel 5330: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 5331: my $items='';
1.800 albertel 5332: foreach my $item (@$storearr) {
5333: $items.=&escape($item).'&';
1.191 harris41 5334: }
1.12 www 5335: $items=~s/\&$//;
1.620 albertel 5336: if (!$udomain) { $udomain=$env{'user.domain'}; }
5337: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 5338: my $uhome=&homeserver($uname,$udomain);
5339: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 5340: my @pairs=split(/\&/,$rep);
5341: my %returnhash=();
1.42 www 5342: my $i=0;
1.800 albertel 5343: foreach my $item (@$storearr) {
5344: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 5345: $i++;
1.191 harris41 5346: }
1.12 www 5347: return %returnhash;
5348: }
5349:
1.667 albertel 5350: # ------------------------------------------------------------ tmpput interface
5351: sub tmpput {
1.802 raeburn 5352: my ($storehash,$server,$context)=@_;
1.667 albertel 5353: my $items='';
1.800 albertel 5354: foreach my $item (keys(%$storehash)) {
5355: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 5356: }
5357: $items=~s/\&$//;
1.802 raeburn 5358: if (defined($context)) {
5359: $items .= ':'.&escape($context);
5360: }
1.667 albertel 5361: return &reply("tmpput:$items",$server);
5362: }
5363:
5364: # ------------------------------------------------------------ tmpget interface
5365: sub tmpget {
1.688 albertel 5366: my ($token,$server)=@_;
5367: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5368: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 5369: my %returnhash;
5370: foreach my $item (split(/\&/,$rep)) {
5371: my ($key,$value)=split(/=/,$item);
1.951 raeburn 5372: next if ($key =~ /^error: 2 /);
1.667 albertel 5373: $returnhash{&unescape($key)}=&thaw_unescape($value);
5374: }
5375: return %returnhash;
5376: }
5377:
1.1113 raeburn 5378: # ------------------------------------------------------------ tmpdel interface
1.688 albertel 5379: sub tmpdel {
5380: my ($token,$server)=@_;
5381: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5382: return &reply("tmpdel:$token",$server);
5383: }
5384:
1.765 albertel 5385: # -------------------------------------------------- portfolio access checking
5386:
5387: sub portfolio_access {
1.766 albertel 5388: my ($requrl) = @_;
1.765 albertel 5389: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
5390: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814 raeburn 5391: if ($result) {
5392: my %setters;
5393: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
5394: my ($startblock,$endblock) =
5395: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
5396: if ($startblock && $endblock) {
5397: return 'B';
5398: }
5399: } else {
5400: my ($startblock,$endblock) =
5401: &Apache::loncommon::blockcheck(\%setters,'port');
5402: if ($startblock && $endblock) {
5403: return 'B';
5404: }
5405: }
5406: }
1.765 albertel 5407: if ($result eq 'ok') {
1.766 albertel 5408: return 'F';
1.765 albertel 5409: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 5410: return 'A';
1.765 albertel 5411: }
1.766 albertel 5412: return '';
1.765 albertel 5413: }
5414:
5415: sub get_portfolio_access {
1.767 albertel 5416: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
5417:
5418: if (!ref($access_hash)) {
5419: my $current_perms = &get_portfile_permissions($udom,$unum);
5420: my %access_controls = &get_access_controls($current_perms,$group,
5421: $file_name);
5422: $access_hash = $access_controls{$file_name};
5423: }
5424:
1.765 albertel 5425: my ($public,$guest,@domains,@users,@courses,@groups);
5426: my $now = time;
5427: if (ref($access_hash) eq 'HASH') {
5428: foreach my $key (keys(%{$access_hash})) {
5429: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
5430: if ($start > $now) {
5431: next;
5432: }
5433: if ($end && $end<$now) {
5434: next;
5435: }
5436: if ($scope eq 'public') {
5437: $public = $key;
5438: last;
5439: } elsif ($scope eq 'guest') {
5440: $guest = $key;
5441: } elsif ($scope eq 'domains') {
5442: push(@domains,$key);
5443: } elsif ($scope eq 'users') {
5444: push(@users,$key);
5445: } elsif ($scope eq 'course') {
5446: push(@courses,$key);
5447: } elsif ($scope eq 'group') {
5448: push(@groups,$key);
5449: }
5450: }
5451: if ($public) {
5452: return 'ok';
5453: }
5454: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
5455: if ($guest) {
5456: return $guest;
5457: }
5458: } else {
5459: if (@domains > 0) {
5460: foreach my $domkey (@domains) {
5461: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
5462: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
5463: return 'ok';
5464: }
5465: }
5466: }
5467: }
5468: if (@users > 0) {
5469: foreach my $userkey (@users) {
1.865 raeburn 5470: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
5471: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
5472: if (ref($item) eq 'HASH') {
5473: if (($item->{'uname'} eq $env{'user.name'}) &&
5474: ($item->{'udom'} eq $env{'user.domain'})) {
5475: return 'ok';
5476: }
5477: }
5478: }
5479: }
1.765 albertel 5480: }
5481: }
5482: my %roleshash;
5483: my @courses_and_groups = @courses;
5484: push(@courses_and_groups,@groups);
5485: if (@courses_and_groups > 0) {
5486: my (%allgroups,%allroles);
5487: my ($start,$end,$role,$sec,$group);
5488: foreach my $envkey (%env) {
1.1060 raeburn 5489: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 5490: my $cid = $2.'_'.$3;
5491: if ($1 eq 'gr') {
5492: $group = $4;
5493: $allgroups{$cid}{$group} = $env{$envkey};
5494: } else {
5495: if ($4 eq '') {
5496: $sec = 'none';
5497: } else {
5498: $sec = $4;
5499: }
5500: $allroles{$cid}{$1}{$sec} = $env{$envkey};
5501: }
1.811 albertel 5502: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 5503: my $cid = $2.'_'.$3;
5504: if ($4 eq '') {
5505: $sec = 'none';
5506: } else {
5507: $sec = $4;
5508: }
5509: $allroles{$cid}{$1}{$sec} = $env{$envkey};
5510: }
5511: }
5512: if (keys(%allroles) == 0) {
5513: return;
5514: }
5515: foreach my $key (@courses_and_groups) {
5516: my %content = %{$$access_hash{$key}};
5517: my $cnum = $content{'number'};
5518: my $cdom = $content{'domain'};
5519: my $cid = $cdom.'_'.$cnum;
5520: if (!exists($allroles{$cid})) {
5521: next;
5522: }
5523: foreach my $role_id (keys(%{$content{'roles'}})) {
5524: my @sections = @{$content{'roles'}{$role_id}{'section'}};
5525: my @groups = @{$content{'roles'}{$role_id}{'group'}};
5526: my @status = @{$content{'roles'}{$role_id}{'access'}};
5527: my @roles = @{$content{'roles'}{$role_id}{'role'}};
5528: foreach my $role (keys(%{$allroles{$cid}})) {
5529: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
5530: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
5531: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
5532: if (grep/^all$/,@sections) {
5533: return 'ok';
5534: } else {
5535: if (grep/^$sec$/,@sections) {
5536: return 'ok';
5537: }
5538: }
5539: }
5540: }
5541: if (keys(%{$allgroups{$cid}}) == 0) {
5542: if (grep/^none$/,@groups) {
5543: return 'ok';
5544: }
5545: } else {
5546: if (grep/^all$/,@groups) {
5547: return 'ok';
5548: }
5549: foreach my $group (keys(%{$allgroups{$cid}})) {
5550: if (grep/^$group$/,@groups) {
5551: return 'ok';
5552: }
5553: }
5554: }
5555: }
5556: }
5557: }
5558: }
5559: }
5560: if ($guest) {
5561: return $guest;
5562: }
5563: }
5564: }
5565: return;
5566: }
5567:
5568: sub course_group_datechecker {
5569: my ($dates,$now,$status) = @_;
5570: my ($start,$end) = split(/\./,$dates);
5571: if (!$start && !$end) {
5572: return 'ok';
5573: }
5574: if (grep/^active$/,@{$status}) {
5575: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
5576: return 'ok';
5577: }
5578: }
5579: if (grep/^previous$/,@{$status}) {
5580: if ($end > $now ) {
5581: return 'ok';
5582: }
5583: }
5584: if (grep/^future$/,@{$status}) {
5585: if ($start > $now) {
5586: return 'ok';
5587: }
5588: }
5589: return;
5590: }
5591:
5592: sub parse_portfolio_url {
5593: my ($url) = @_;
5594:
5595: my ($type,$udom,$unum,$group,$file_name);
5596:
1.823 albertel 5597: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 5598: $type = 1;
5599: $udom = $1;
5600: $unum = $2;
5601: $file_name = $3;
1.823 albertel 5602: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 5603: $type = 2;
5604: $udom = $1;
5605: $unum = $2;
5606: $group = $3;
5607: $file_name = $3.'/'.$4;
5608: }
5609: if (wantarray) {
5610: return ($type,$udom,$unum,$file_name,$group);
5611: }
5612: return $type;
5613: }
5614:
5615: sub is_portfolio_url {
5616: my ($url) = @_;
5617: return scalar(&parse_portfolio_url($url));
5618: }
5619:
1.798 raeburn 5620: sub is_portfolio_file {
5621: my ($file) = @_;
1.820 raeburn 5622: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 5623: return 1;
5624: }
5625: return;
5626: }
5627:
1.976 raeburn 5628: sub usertools_access {
1.1084 raeburn 5629: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 5630: my ($access,%tools);
5631: if ($context eq '') {
5632: $context = 'tools';
5633: }
5634: if ($context eq 'requestcourses') {
5635: %tools = (
5636: official => 1,
5637: unofficial => 1,
1.1006 raeburn 5638: community => 1,
1.985 raeburn 5639: );
5640: } else {
5641: %tools = (
5642: aboutme => 1,
5643: blog => 1,
5644: portfolio => 1,
5645: );
5646: }
1.976 raeburn 5647: return if (!defined($tools{$tool}));
5648:
5649: if ((!defined($udom)) || (!defined($uname))) {
5650: $udom = $env{'user.domain'};
5651: $uname = $env{'user.name'};
5652: }
5653:
1.978 raeburn 5654: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
5655: if ($action ne 'reload') {
1.985 raeburn 5656: if ($context eq 'requestcourses') {
5657: return $env{'environment.canrequest.'.$tool};
5658: } else {
5659: return $env{'environment.availabletools.'.$tool};
5660: }
5661: }
1.976 raeburn 5662: }
5663:
5664: my ($toolstatus,$inststatus);
5665:
1.985 raeburn 5666: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
5667: ($action ne 'reload')) {
5668: $toolstatus = $env{'environment.'.$context.'.'.$tool};
1.976 raeburn 5669: $inststatus = $env{'environment.inststatus'};
5670: } else {
1.1084 raeburn 5671: if (ref($userenvref) eq 'HASH') {
5672: $toolstatus = $userenvref->{$context.'.'.$tool};
5673: $inststatus = $userenvref->{'inststatus'};
5674: } else {
5675: my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
5676: $toolstatus = $userenv{$context.'.'.$tool};
5677: $inststatus = $userenv{'inststatus'};
5678: }
1.976 raeburn 5679: }
5680:
5681: if ($toolstatus ne '') {
5682: if ($toolstatus) {
5683: $access = 1;
5684: } else {
5685: $access = 0;
5686: }
5687: return $access;
5688: }
5689:
1.1084 raeburn 5690: my ($is_adv,%domdef);
5691: if (ref($is_advref) eq 'HASH') {
5692: $is_adv = $is_advref->{'is_adv'};
5693: } else {
5694: $is_adv = &is_advanced_user($udom,$uname);
5695: }
5696: if (ref($domdefref) eq 'HASH') {
5697: %domdef = %{$domdefref};
5698: } else {
5699: %domdef = &get_domain_defaults($udom);
5700: }
1.976 raeburn 5701: if (ref($domdef{$tool}) eq 'HASH') {
5702: if ($is_adv) {
5703: if ($domdef{$tool}{'_LC_adv'} ne '') {
5704: if ($domdef{$tool}{'_LC_adv'}) {
5705: $access = 1;
5706: } else {
5707: $access = 0;
5708: }
5709: return $access;
5710: }
5711: }
5712: if ($inststatus ne '') {
5713: my ($hasaccess,$hasnoaccess);
5714: foreach my $affiliation (split(/:/,$inststatus)) {
5715: if ($domdef{$tool}{$affiliation} ne '') {
5716: if ($domdef{$tool}{$affiliation}) {
5717: $hasaccess = 1;
5718: } else {
5719: $hasnoaccess = 1;
5720: }
5721: }
5722: }
5723: if ($hasaccess || $hasnoaccess) {
5724: if ($hasaccess) {
5725: $access = 1;
5726: } elsif ($hasnoaccess) {
5727: $access = 0;
5728: }
5729: return $access;
5730: }
5731: } else {
5732: if ($domdef{$tool}{'default'} ne '') {
5733: if ($domdef{$tool}{'default'}) {
5734: $access = 1;
5735: } elsif ($domdef{$tool}{'default'} == 0) {
5736: $access = 0;
5737: }
5738: return $access;
5739: }
5740: }
5741: } else {
1.985 raeburn 5742: if ($context eq 'tools') {
5743: $access = 1;
5744: } else {
5745: $access = 0;
5746: }
1.976 raeburn 5747: return $access;
5748: }
5749: }
5750:
1.1050 raeburn 5751: sub is_course_owner {
5752: my ($cdom,$cnum,$udom,$uname) = @_;
5753: if (($udom eq '') || ($uname eq '')) {
5754: $udom = $env{'user.domain'};
5755: $uname = $env{'user.name'};
5756: }
5757: unless (($udom eq '') || ($uname eq '')) {
5758: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
5759: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
5760: return 1;
5761: } else {
5762: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
5763: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
5764: return 1;
5765: }
5766: }
5767: }
5768: }
5769: return;
5770: }
5771:
1.976 raeburn 5772: sub is_advanced_user {
5773: my ($udom,$uname) = @_;
1.1085 raeburn 5774: if ($udom ne '' && $uname ne '') {
5775: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128 raeburn 5776: if (wantarray) {
5777: return ($env{'user.adv'},$env{'user.author'});
5778: } else {
5779: return $env{'user.adv'};
5780: }
1.1085 raeburn 5781: }
5782: }
1.976 raeburn 5783: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
5784: my %allroles;
1.1128 raeburn 5785: my ($is_adv,$is_author);
1.976 raeburn 5786: foreach my $role (keys(%roleshash)) {
5787: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
5788: my $area = '/'.$tdomain.'/'.$trest;
5789: if ($sec ne '') {
5790: $area .= '/'.$sec;
5791: }
5792: if (($area ne '') && ($trole ne '')) {
5793: my $spec=$trole.'.'.$area;
5794: if ($trole =~ /^cr\//) {
5795: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5796: } elsif ($trole ne 'gr') {
5797: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5798: }
1.1128 raeburn 5799: if ($trole eq 'au') {
5800: $is_author = 1;
5801: }
1.976 raeburn 5802: }
5803: }
5804: foreach my $role (keys(%allroles)) {
5805: last if ($is_adv);
5806: foreach my $item (split(/:/,$allroles{$role})) {
5807: if ($item ne '') {
5808: my ($privilege,$restrictions)=split(/&/,$item);
5809: if ($privilege eq 'adv') {
5810: $is_adv = 1;
5811: last;
5812: }
5813: }
5814: }
5815: }
1.1128 raeburn 5816: if (wantarray) {
5817: return ($is_adv,$is_author);
5818: }
1.976 raeburn 5819: return $is_adv;
5820: }
1.798 raeburn 5821:
1.1035 raeburn 5822: sub check_can_request {
1.1036 raeburn 5823: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 5824: my $canreq = 0;
5825: my ($types,$typename) = &Apache::loncommon::course_types();
5826: my @options = ('approval','validate','autolimit');
5827: my $optregex = join('|',@options);
5828: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
5829: foreach my $type (@{$types}) {
5830: if (&usertools_access($env{'user.name'},
5831: $env{'user.domain'},
5832: $type,undef,'requestcourses')) {
5833: $canreq ++;
1.1036 raeburn 5834: if (ref($request_domains) eq 'HASH') {
5835: push(@{$request_domains->{$type}},$env{'user.domain'});
5836: }
1.1035 raeburn 5837: if ($dom eq $env{'user.domain'}) {
5838: $can_request->{$type} = 1;
5839: }
5840: }
5841: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
5842: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
5843: if (@curr > 0) {
1.1036 raeburn 5844: foreach my $item (@curr) {
5845: if (ref($request_domains) eq 'HASH') {
5846: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
5847: if ($otherdom ne '') {
5848: if (ref($request_domains->{$type}) eq 'ARRAY') {
5849: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
5850: push(@{$request_domains->{$type}},$otherdom);
5851: }
5852: } else {
5853: push(@{$request_domains->{$type}},$otherdom);
5854: }
5855: }
5856: }
5857: }
5858: unless($dom eq $env{'user.domain'}) {
5859: $canreq ++;
1.1035 raeburn 5860: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
5861: $can_request->{$type} = 1;
5862: }
5863: }
5864: }
5865: }
5866: }
5867: }
5868: return $canreq;
5869: }
5870:
1.341 www 5871: # ---------------------------------------------- Custom access rule evaluation
5872:
5873: sub customaccess {
5874: my ($priv,$uri)=@_;
1.807 albertel 5875: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 5876: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 5877: $udom = &LONCAPA::clean_domain($udom);
5878: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 5879: my $access=0;
1.800 albertel 5880: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 5881: my ($effect,$realm,$role,$type)=split(/\:/,$right);
5882: if ($type eq 'user') {
5883: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 5884: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 5885: if ($tdom) {
5886: if ($tdom ne $env{'user.domain'}) { next; }
5887: }
1.896 albertel 5888: if ($tuname) {
5889: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 5890: }
5891: $access=($effect eq 'allow');
5892: last;
5893: }
5894: } else {
5895: if ($role) {
5896: if ($role ne $urole) { next; }
5897: }
5898: foreach my $scope (split(/\s*\,\s*/,$realm)) {
5899: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
5900: if ($tdom) {
5901: if ($tdom ne $udom) { next; }
5902: }
5903: if ($tcrs) {
5904: if ($tcrs ne $ucrs) { next; }
5905: }
5906: if ($tsec) {
5907: if ($tsec ne $usec) { next; }
5908: }
5909: $access=($effect eq 'allow');
5910: last;
5911: }
5912: if ($realm eq '' && $role eq '') {
5913: $access=($effect eq 'allow');
5914: }
1.402 bowersj2 5915: }
1.341 www 5916: }
5917: return $access;
5918: }
5919:
1.103 harris41 5920: # ------------------------------------------------- Check for a user privilege
1.12 www 5921:
5922: sub allowed {
1.810 raeburn 5923: my ($priv,$uri,$symb,$role)=@_;
1.705 albertel 5924: my $ver_orguri=$uri;
1.439 www 5925: $uri=&deversion($uri);
1.152 www 5926: my $orguri=$uri;
1.52 www 5927: $uri=&declutter($uri);
1.809 raeburn 5928:
1.810 raeburn 5929: if ($priv eq 'evb') {
5930: # Evade communication block restrictions for specified role in a course
5931: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
5932: return $1;
5933: } else {
5934: return;
5935: }
5936: }
5937:
1.620 albertel 5938: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 5939: # Free bre access to adm and meta resources
1.775 albertel 5940: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 5941: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
5942: && ($priv eq 'bre')) {
1.14 www 5943: return 'F';
1.159 www 5944: }
5945:
1.545 banghart 5946: # Free bre access to user's own portfolio contents
1.714 raeburn 5947: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 5948: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 5949: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 5950: my %setters;
5951: my ($startblock,$endblock) =
5952: &Apache::loncommon::blockcheck(\%setters,'port');
5953: if ($startblock && $endblock) {
5954: return 'B';
5955: } else {
5956: return 'F';
5957: }
1.545 banghart 5958: }
5959:
1.762 raeburn 5960: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 5961: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
5962: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
5963: if (exists($env{'request.course.id'})) {
5964: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
5965: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
5966: if (($domain eq $cdom) && ($name eq $cnum)) {
5967: my $courseprivid=$env{'request.course.id'};
5968: $courseprivid=~s/\_/\//;
5969: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
5970: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
5971: return $1;
1.762 raeburn 5972: } else {
5973: if ($env{'request.course.sec'}) {
5974: $courseprivid.='/'.$env{'request.course.sec'};
5975: }
5976: if ($env{'user.priv.'.$env{'request.role'}.'./'.
5977: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
5978: return $2;
5979: }
1.714 raeburn 5980: }
5981: }
5982: }
5983: }
5984:
1.159 www 5985: # Free bre to public access
5986:
5987: if ($priv eq 'bre') {
1.238 www 5988: my $copyright=&metadata($uri,'copyright');
1.620 albertel 5989: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 5990: return 'F';
5991: }
1.238 www 5992: if ($copyright eq 'priv') {
5993: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 5994: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 5995: return '';
5996: }
5997: }
5998: if ($copyright eq 'domain') {
5999: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 6000: unless (($env{'user.domain'} eq $1) ||
6001: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 6002: return '';
6003: }
1.262 matthew 6004: }
1.620 albertel 6005: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 6006: # Library role, so allow browsing of resources in this domain.
6007: return 'F';
1.238 www 6008: }
1.341 www 6009: if ($copyright eq 'custom') {
6010: unless (&customaccess($priv,$uri)) { return ''; }
6011: }
1.14 www 6012: }
1.264 matthew 6013: # Domain coordinator is trying to create a course
1.620 albertel 6014: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 6015: # uri is the requested domain in this case.
6016: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 6017: # a role of dc for the domain in question.
1.620 albertel 6018: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 6019: }
1.29 www 6020:
1.52 www 6021: my $thisallowed='';
6022: my $statecond=0;
6023: my $courseprivid='';
6024:
1.1039 raeburn 6025: my $ownaccess;
1.1043 raeburn 6026: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 6027: if (($priv eq 'bro') && ($env{'user.author'})) {
6028: if ($uri eq '') {
6029: $ownaccess = 1;
6030: } else {
6031: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
6032: my $udom = $env{'user.domain'};
6033: my $uname = $env{'user.name'};
6034: if ($uri =~ m{^\Q$udom\E/?$}) {
6035: $ownaccess = 1;
1.1040 raeburn 6036: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 6037: unless ($uri =~ m{\.\./}) {
6038: $ownaccess = 1;
6039: }
6040: } elsif (($udom ne 'public') && ($uname ne 'public')) {
6041: my $now = time;
6042: if ($uri =~ m{^([^/]+)/?$}) {
6043: my $adom = $1;
6044: foreach my $key (keys(%env)) {
1.1042 raeburn 6045: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 6046: my ($start,$end) = split('.',$env{$key});
6047: if (($now >= $start) && (!$end || $end < $now)) {
6048: $ownaccess = 1;
6049: last;
6050: }
6051: }
6052: }
6053: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
6054: my $adom = $1;
6055: my $aname = $2;
1.1042 raeburn 6056: foreach my $role ('ca','aa') {
6057: if ($env{"user.role.$role./$adom/$aname"}) {
6058: my ($start,$end) =
6059: split('.',$env{"user.role.$role./$adom/$aname"});
6060: if (($now >= $start) && (!$end || $end < $now)) {
6061: $ownaccess = 1;
6062: last;
6063: }
1.1039 raeburn 6064: }
6065: }
6066: }
6067: }
6068: }
6069: }
6070: }
6071:
1.52 www 6072: # Course
6073:
1.620 albertel 6074: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6075: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6076: $thisallowed.=$1;
6077: }
1.52 www 6078: }
1.29 www 6079:
1.52 www 6080: # Domain
6081:
1.620 albertel 6082: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 6083: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6084: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6085: $thisallowed.=$1;
6086: }
1.12 www 6087: }
1.52 www 6088:
1.1141 raeburn 6089: # User who is not author or co-author might still be able to edit
6090: # resource of an author in the domain (e.g., if Domain Coordinator).
6091: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
6092: (&allowed('mdc',$env{'request.course.id'}))) {
6093: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
6094: $thisallowed.=$1;
6095: }
6096: }
6097:
1.52 www 6098: # Course: uri itself is a course
1.66 www 6099: my $courseuri=$uri;
6100: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 6101: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 6102:
1.620 albertel 6103: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 6104: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6105: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6106: $thisallowed.=$1;
6107: }
1.12 www 6108: }
1.29 www 6109:
1.665 albertel 6110: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 6111: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 6112: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 6113: $thisallowed='';
1.671 raeburn 6114: my ($match)=&is_on_map($uri);
6115: if ($match) {
6116: if ($env{'user.priv.'.$env{'request.role'}.'./'}
6117: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6118: my @blockers = &has_comm_blocking($priv,$symb,$uri);
6119: if (@blockers > 0) {
6120: $thisallowed = 'B';
6121: } else {
6122: $thisallowed.=$1;
6123: }
1.671 raeburn 6124: }
6125: } else {
1.705 albertel 6126: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 6127: if ($refuri) {
6128: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 6129: $thisallowed='F';
1.671 raeburn 6130: } else {
6131: $refuri=&declutter($refuri);
6132: my ($match) = &is_on_map($refuri);
6133: if ($match) {
1.1162 raeburn 6134: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
6135: if (@blockers > 0) {
6136: $thisallowed = 'B';
6137: } else {
6138: $thisallowed='F';
6139: }
1.671 raeburn 6140: }
1.669 raeburn 6141: }
1.671 raeburn 6142: }
6143: }
1.314 www 6144: }
1.492 albertel 6145:
1.766 albertel 6146: if ($priv eq 'bre'
6147: && $thisallowed ne 'F'
6148: && $thisallowed ne '2'
6149: && &is_portfolio_url($uri)) {
6150: $thisallowed = &portfolio_access($uri);
6151: }
6152:
1.52 www 6153: # Full access at system, domain or course-wide level? Exit.
1.29 www 6154: if ($thisallowed=~/F/) {
6155: return 'F';
6156: }
6157:
1.52 www 6158: # If this is generating or modifying users, exit with special codes
1.29 www 6159:
1.643 www 6160: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
6161: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 6162: my ($audom,$auname)=split('/',$uri);
1.643 www 6163: # no author name given, so this just checks on the general right to make a co-author in this domain
6164: unless ($auname) { return $thisallowed; }
6165: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 6166: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
6167: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
6168: ($audom ne $env{'request.role.domain'}))) { return ''; }
6169: }
1.52 www 6170: return $thisallowed;
6171: }
6172: #
1.103 harris41 6173: # Gathered so far: system, domain and course wide privileges
1.52 www 6174: #
6175: # Course: See if uri or referer is an individual resource that is part of
6176: # the course
6177:
1.620 albertel 6178: if ($env{'request.course.id'}) {
1.232 www 6179:
1.620 albertel 6180: $courseprivid=$env{'request.course.id'};
6181: if ($env{'request.course.sec'}) {
6182: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 6183: }
6184: $courseprivid=~s/\_/\//;
6185: my $checkreferer=1;
1.232 www 6186: my ($match,$cond)=&is_on_map($uri);
6187: if ($match) {
6188: $statecond=$cond;
1.620 albertel 6189: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 6190: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6191: my $value = $1;
6192: if ($priv eq 'bre') {
6193: my @blockers = &has_comm_blocking($priv,$symb,$uri);
6194: if (@blockers > 0) {
6195: $thisallowed = 'B';
6196: } else {
6197: $thisallowed.=$value;
6198: }
6199: } else {
6200: $thisallowed.=$value;
6201: }
1.52 www 6202: $checkreferer=0;
6203: }
1.29 www 6204: }
1.83 www 6205:
1.148 www 6206: if ($checkreferer) {
1.620 albertel 6207: my $refuri=$env{'httpref.'.$orguri};
1.148 www 6208: unless ($refuri) {
1.800 albertel 6209: foreach my $key (keys(%env)) {
6210: if ($key=~/^httpref\..*\*/) {
6211: my $pattern=$key;
1.156 www 6212: $pattern=~s/^httpref\.\/res\///;
1.148 www 6213: $pattern=~s/\*/\[\^\/\]\+/g;
6214: $pattern=~s/\//\\\//g;
1.152 www 6215: if ($orguri=~/$pattern/) {
1.800 albertel 6216: $refuri=$env{$key};
1.148 www 6217: }
6218: }
1.191 harris41 6219: }
1.148 www 6220: }
1.232 www 6221:
1.148 www 6222: if ($refuri) {
1.152 www 6223: $refuri=&declutter($refuri);
1.232 www 6224: my ($match,$cond)=&is_on_map($refuri);
6225: if ($match) {
6226: my $refstatecond=$cond;
1.620 albertel 6227: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 6228: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6229: my $value = $1;
6230: if ($priv eq 'bre') {
6231: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
6232: if (@blockers > 0) {
6233: $thisallowed = 'B';
6234: } else {
6235: $thisallowed.=$value;
6236: }
6237: } else {
6238: $thisallowed.=$value;
6239: }
1.53 www 6240: $uri=$refuri;
6241: $statecond=$refstatecond;
1.52 www 6242: }
6243: }
1.148 www 6244: }
1.29 www 6245: }
1.52 www 6246: }
1.29 www 6247:
1.52 www 6248: #
1.103 harris41 6249: # Gathered now: all privileges that could apply, and condition number
1.52 www 6250: #
6251: #
6252: # Full or no access?
6253: #
1.29 www 6254:
1.52 www 6255: if ($thisallowed=~/F/) {
6256: return 'F';
6257: }
1.29 www 6258:
1.52 www 6259: unless ($thisallowed) {
6260: return '';
6261: }
1.29 www 6262:
1.52 www 6263: # Restrictions exist, deal with them
6264: #
6265: # C:according to course preferences
6266: # R:according to resource settings
6267: # L:unless locked
6268: # X:according to user session state
6269: #
6270:
6271: # Possibly locked functionality, check all courses
1.54 www 6272: # Locks might take effect only after 10 minutes cache expiration for other
6273: # courses, and 2 minutes for current course
1.52 www 6274:
6275: my $envkey;
6276: if ($thisallowed=~/L/) {
1.1000 raeburn 6277: foreach $envkey (keys(%env)) {
1.54 www 6278: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
6279: my $courseid=$2;
6280: my $roleid=$1.'.'.$2;
1.92 www 6281: $courseid=~s/^\///;
1.54 www 6282: my $expiretime=600;
1.620 albertel 6283: if ($env{'request.role'} eq $roleid) {
1.54 www 6284: $expiretime=120;
6285: }
6286: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
6287: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 6288: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 6289: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 6290: }
1.620 albertel 6291: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
6292: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
6293: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
6294: &log($env{'user.domain'},$env{'user.name'},
6295: $env{'user.home'},
1.57 www 6296: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 6297: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 6298: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 6299: return '';
6300: }
6301: }
1.620 albertel 6302: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
6303: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
6304: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
6305: &log($env{'user.domain'},$env{'user.name'},
6306: $env{'user.home'},
1.57 www 6307: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 6308: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 6309: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 6310: return '';
6311: }
6312: }
6313: }
1.29 www 6314: }
1.52 www 6315: }
6316:
6317: #
6318: # Rest of the restrictions depend on selected course
6319: #
6320:
1.620 albertel 6321: unless ($env{'request.course.id'}) {
1.766 albertel 6322: if ($thisallowed eq 'A') {
6323: return 'A';
1.814 raeburn 6324: } elsif ($thisallowed eq 'B') {
6325: return 'B';
1.766 albertel 6326: } else {
6327: return '1';
6328: }
1.52 www 6329: }
1.29 www 6330:
1.52 www 6331: #
6332: # Now user is definitely in a course
6333: #
1.53 www 6334:
6335:
6336: # Course preferences
6337:
6338: if ($thisallowed=~/C/) {
1.620 albertel 6339: my $rolecode=(split(/\./,$env{'request.role'}))[0];
6340: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
6341: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 6342: =~/\Q$rolecode\E/) {
1.1103 raeburn 6343: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 6344: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
6345: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
6346: $env{'request.course.id'});
6347: }
1.237 www 6348: return '';
6349: }
6350:
1.620 albertel 6351: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 6352: =~/\Q$unamedom\E/) {
1.1103 raeburn 6353: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 6354: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
6355: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
6356: $env{'request.course.id'});
6357: }
1.54 www 6358: return '';
6359: }
1.53 www 6360: }
6361:
6362: # Resource preferences
6363:
6364: if ($thisallowed=~/R/) {
1.620 albertel 6365: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 6366: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103 raeburn 6367: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 6368: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
6369: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
6370: }
6371: return '';
1.54 www 6372: }
1.53 www 6373: }
1.30 www 6374:
1.246 www 6375: # Restricted by state or randomout?
1.30 www 6376:
1.52 www 6377: if ($thisallowed=~/X/) {
1.620 albertel 6378: if ($env{'acc.randomout'}) {
1.579 albertel 6379: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 6380: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 6381: return '';
6382: }
1.247 www 6383: }
6384: if (&condval($statecond)) {
1.52 www 6385: return '2';
6386: } else {
6387: return '';
6388: }
6389: }
1.30 www 6390:
1.766 albertel 6391: if ($thisallowed eq 'A') {
6392: return 'A';
1.814 raeburn 6393: } elsif ($thisallowed eq 'B') {
6394: return 'B';
1.766 albertel 6395: }
1.52 www 6396: return 'F';
1.232 www 6397: }
1.1162 raeburn 6398:
6399: sub get_comm_blocks {
6400: my ($cdom,$cnum) = @_;
6401: if ($cdom eq '' || $cnum eq '') {
6402: return unless ($env{'request.course.id'});
6403: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6404: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6405: }
6406: my %commblocks;
6407: my $hashid=$cdom.'_'.$cnum;
6408: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
6409: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
6410: %commblocks = %{$blocksref};
6411: } else {
6412: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
6413: my $cachetime = 600;
6414: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
6415: }
6416: return %commblocks;
6417: }
6418:
6419: sub has_comm_blocking {
6420: my ($priv,$symb,$uri,$blocks) = @_;
6421: return unless ($env{'request.course.id'});
6422: return unless ($priv eq 'bre');
6423: return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
6424: my %commblocks;
6425: if (ref($blocks) eq 'HASH') {
6426: %commblocks = %{$blocks};
6427: } else {
6428: %commblocks = &get_comm_blocks();
6429: }
6430: return unless (keys(%commblocks) > 0);
6431: if (!$symb) { $symb=&symbread($uri,1); }
6432: my ($map,$resid,undef)=&decode_symb($symb);
6433: my %tocheck = (
6434: maps => $map,
6435: resources => $symb,
6436: );
6437: my @blockers;
6438: my $now = time;
1.1163 raeburn 6439: my $navmap = Apache::lonnavmaps::navmap->new();
1.1162 raeburn 6440: foreach my $block (keys(%commblocks)) {
6441: if ($block =~ /^(\d+)____(\d+)$/) {
6442: my ($start,$end) = ($1,$2);
6443: if ($start <= $now && $end >= $now) {
6444: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
6445: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
6446: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
6447: if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
6448: unless (grep(/^\Q$block\E$/,@blockers)) {
6449: push(@blockers,$block);
6450: }
6451: }
6452: }
6453: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
6454: if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
6455: unless (grep(/^\Q$block\E$/,@blockers)) {
6456: push(@blockers,$block);
6457: }
6458: }
6459: }
6460: }
6461: }
6462: }
6463: } elsif ($block =~ /^firstaccess____(.+)$/) {
6464: my $item = $1;
1.1163 raeburn 6465: my @to_test;
1.1162 raeburn 6466: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
6467: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
6468: my $check_interval;
6469: if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
6470: my @interval;
6471: my $type = 'map';
6472: if ($item eq 'course') {
6473: $type = 'course';
6474: @interval=&EXT("resource.0.interval");
6475: } else {
6476: if ($item =~ /___\d+___/) {
6477: $type = 'resource';
6478: @interval=&EXT("resource.0.interval",$item);
1.1163 raeburn 6479: if (ref($navmap)) {
6480: my $res = $navmap->getBySymb($item);
6481: push(@to_test,$res);
6482: }
1.1162 raeburn 6483: } else {
6484: my $mapsymb = &symbread($item,1);
6485: if ($mapsymb) {
6486: if (ref($navmap)) {
6487: my $mapres = $navmap->getBySymb($mapsymb);
1.1163 raeburn 6488: @to_test = $mapres->retrieveResources($mapres,undef,0,1);
6489: foreach my $res (@to_test) {
1.1162 raeburn 6490: my $symb = $res->symb();
6491: next if ($symb eq $mapsymb);
6492: if ($symb ne '') {
6493: @interval=&EXT("resource.0.interval",$symb);
6494: last;
6495: }
6496: }
6497: }
6498: }
6499: }
6500: }
6501: if ($interval[0] =~ /\d+/) {
6502: my $first_access;
6503: if ($type eq 'resource') {
6504: $first_access=&get_first_access($interval[1],$item);
6505: } elsif ($type eq 'map') {
6506: $first_access=&get_first_access($interval[1],undef,$item);
6507: } else {
6508: $first_access=&get_first_access($interval[1]);
6509: }
6510: if ($first_access) {
6511: my $timesup = $first_access+$interval[0];
6512: if ($timesup > $now) {
1.1163 raeburn 6513: foreach my $res (@to_test) {
6514: if ($res->is_problem()) {
6515: if ($res->completable()) {
6516: unless (grep(/^\Q$block\E$/,@blockers)) {
6517: push(@blockers,$block);
6518: }
6519: last;
6520: }
6521: }
1.1162 raeburn 6522: }
6523: }
6524: }
6525: }
6526: }
6527: }
6528: }
6529: }
6530: }
6531: return @blockers;
6532: }
6533:
6534: sub check_docs_block {
6535: my ($docsblock,$tocheck) =@_;
6536: if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
6537: return;
6538: }
6539: if (ref($docsblock->{'maps'}) eq 'HASH') {
6540: if ($tocheck->{'maps'}) {
6541: if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
6542: return 1;
6543: }
6544: }
6545: }
6546: if (ref($docsblock->{'resources'}) eq 'HASH') {
6547: if ($tocheck->{'resources'}) {
6548: if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
6549: return 1;
6550: }
6551: }
6552: }
6553: return;
6554: }
6555:
1.1133 foxr 6556: #
6557: # Removes the versino from a URI and
6558: # splits it in to its filename and path to the filename.
6559: # Seems like File::Basename could have done this more clearly.
6560: # Parameters:
6561: # $uri - input URI
6562: # Returns:
6563: # Two element list consisting of
6564: # $pathname - the URI up to and excluding the trailing /
6565: # $filename - The part of the URI following the last /
6566: # NOTE:
6567: # Another realization of this is simply:
6568: # use File::Basename;
6569: # ...
6570: # $uri = shift;
6571: # $filename = basename($uri);
6572: # $path = dirname($uri);
6573: # return ($filename, $path);
6574: #
6575: # The implementation below is probably faster however.
6576: #
1.710 albertel 6577: sub split_uri_for_cond {
6578: my $uri=&deversion(&declutter(shift));
6579: my @uriparts=split(/\//,$uri);
6580: my $filename=pop(@uriparts);
6581: my $pathname=join('/',@uriparts);
6582: return ($pathname,$filename);
6583: }
1.232 www 6584: # --------------------------------------------------- Is a resource on the map?
6585:
6586: sub is_on_map {
1.710 albertel 6587: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 6588: #Trying to find the conditional for the file
1.620 albertel 6589: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 6590: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 6591: if ($match) {
1.289 bowersj2 6592: return (1,$1);
6593: } else {
1.434 www 6594: return (0,0);
1.289 bowersj2 6595: }
1.12 www 6596: }
6597:
1.427 www 6598: # --------------------------------------------------------- Get symb from alias
6599:
6600: sub get_symb_from_alias {
6601: my $symb=shift;
6602: my ($map,$resid,$url)=&decode_symb($symb);
6603: # Already is a symb
6604: if ($url) { return $symb; }
6605: # Must be an alias
6606: my $aliassymb='';
6607: my %bighash;
1.620 albertel 6608: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 6609: &GDBM_READER(),0640)) {
6610: my $rid=$bighash{'mapalias_'.$symb};
6611: if ($rid) {
6612: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 6613: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
6614: $resid,$bighash{'src_'.$rid});
1.427 www 6615: }
6616: untie %bighash;
6617: }
6618: return $aliassymb;
6619: }
6620:
1.12 www 6621: # ----------------------------------------------------------------- Define Role
6622:
6623: sub definerole {
6624: if (allowed('mcr','/')) {
6625: my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800 albertel 6626: foreach my $role (split(':',$sysrole)) {
6627: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 6628: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
6629: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
6630: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 6631: return "refused:s:$crole&$cqual";
6632: }
6633: }
1.191 harris41 6634: }
1.800 albertel 6635: foreach my $role (split(':',$domrole)) {
6636: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 6637: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
6638: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
6639: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 6640: return "refused:d:$crole&$cqual";
6641: }
6642: }
1.191 harris41 6643: }
1.800 albertel 6644: foreach my $role (split(':',$courole)) {
6645: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 6646: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
6647: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
6648: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 6649: return "refused:c:$crole&$cqual";
6650: }
6651: }
1.191 harris41 6652: }
1.620 albertel 6653: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
6654: "$env{'user.domain'}:$env{'user.name'}:".
1.21 www 6655: "rolesdef_$rolename=".
6656: escape($sysrole.'_'.$domrole.'_'.$courole);
1.620 albertel 6657: return reply($command,$env{'user.home'});
1.12 www 6658: } else {
6659: return 'refused';
6660: }
1.105 harris41 6661: }
6662:
6663: # ---------------- Make a metadata query against the network of library servers
6664:
6665: sub metadata_query {
1.244 matthew 6666: my ($query,$custom,$customshow,$server_array)=@_;
1.120 harris41 6667: my %rhash;
1.845 albertel 6668: my %libserv = &all_library();
1.244 matthew 6669: my @server_list = (defined($server_array) ? @$server_array
6670: : keys(%libserv) );
6671: for my $server (@server_list) {
1.118 harris41 6672: unless ($custom or $customshow) {
6673: my $reply=&reply("querysend:".&escape($query),$server);
6674: $rhash{$server}=$reply;
6675: }
6676: else {
6677: my $reply=&reply("querysend:".&escape($query).':'.
6678: &escape($custom).':'.&escape($customshow),
6679: $server);
6680: $rhash{$server}=$reply;
6681: }
1.112 harris41 6682: }
1.118 harris41 6683: return \%rhash;
1.240 www 6684: }
6685:
6686: # ----------------------------------------- Send log queries and wait for reply
6687:
6688: sub log_query {
6689: my ($uname,$udom,$query,%filters)=@_;
6690: my $uhome=&homeserver($uname,$udom);
6691: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 6692: my $uhost=&hostname($uhome);
1.800 albertel 6693: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 6694: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
6695: $uhome);
1.479 albertel 6696: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 6697: return get_query_reply($queryid);
6698: }
6699:
1.818 raeburn 6700: # -------------------------- Update MySQL table for portfolio file
6701:
6702: sub update_portfolio_table {
1.821 raeburn 6703: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 6704: if ($group ne '') {
6705: $file_name =~s /^\Q$group\E//;
6706: }
1.818 raeburn 6707: my $homeserver = &homeserver($uname,$udom);
6708: my $queryid=
1.821 raeburn 6709: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
6710: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 6711: my $reply = &get_query_reply($queryid);
6712: return $reply;
6713: }
6714:
1.899 raeburn 6715: # -------------------------- Update MySQL allusers table
6716:
6717: sub update_allusers_table {
6718: my ($uname,$udom,$names) = @_;
6719: my $homeserver = &homeserver($uname,$udom);
6720: my $queryid=
6721: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
6722: 'lastname='.&escape($names->{'lastname'}).'%%'.
6723: 'firstname='.&escape($names->{'firstname'}).'%%'.
6724: 'middlename='.&escape($names->{'middlename'}).'%%'.
6725: 'generation='.&escape($names->{'generation'}).'%%'.
6726: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
6727: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 6728: return;
1.899 raeburn 6729: }
6730:
1.508 raeburn 6731: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 6732:
6733: sub fetch_enrollment_query {
1.511 raeburn 6734: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508 raeburn 6735: my $homeserver;
1.547 raeburn 6736: my $maxtries = 1;
1.508 raeburn 6737: if ($context eq 'automated') {
6738: $homeserver = $perlvar{'lonHostID'};
1.547 raeburn 6739: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 6740: } else {
6741: $homeserver = &homeserver($cnum,$dom);
6742: }
1.838 albertel 6743: my $host=&hostname($homeserver);
1.506 raeburn 6744: my $cmd = '';
1.1000 raeburn 6745: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 6746: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 6747: }
6748: $cmd =~ s/%%$//;
6749: $cmd = &escape($cmd);
6750: my $query = 'fetchenrollment';
1.620 albertel 6751: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 6752: unless ($queryid=~/^\Q$host\E\_/) {
6753: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
6754: return 'error: '.$queryid;
6755: }
1.506 raeburn 6756: my $reply = &get_query_reply($queryid);
1.547 raeburn 6757: my $tries = 1;
6758: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
6759: $reply = &get_query_reply($queryid);
6760: $tries ++;
6761: }
1.526 raeburn 6762: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 6763: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 6764: } else {
1.901 albertel 6765: my @responses = split(/:/,$reply);
1.515 raeburn 6766: if ($homeserver eq $perlvar{'lonHostID'}) {
1.800 albertel 6767: foreach my $line (@responses) {
6768: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 6769: $$replyref{$key} = $value;
6770: }
6771: } else {
1.1117 foxr 6772: my $pathname = LONCAPA::tempdir();
1.800 albertel 6773: foreach my $line (@responses) {
6774: my ($key,$value) = split(/=/,$line);
1.506 raeburn 6775: $$replyref{$key} = $value;
6776: if ($value > 0) {
1.800 albertel 6777: foreach my $item (@{$$affiliatesref{$key}}) {
6778: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 6779: my $destname = $pathname.'/'.$filename;
6780: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 6781: if ($xml_classlist =~ /^error/) {
6782: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
6783: } else {
1.506 raeburn 6784: if ( open(FILE,">$destname") ) {
6785: print FILE &unescape($xml_classlist);
6786: close(FILE);
1.526 raeburn 6787: } else {
6788: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 6789: }
6790: }
6791: }
6792: }
6793: }
6794: }
6795: return 'ok';
6796: }
6797: return 'error';
6798: }
6799:
1.242 www 6800: sub get_query_reply {
6801: my $queryid=shift;
1.1117 foxr 6802: my $replyfile=LONCAPA::tempdir().$queryid;
1.240 www 6803: my $reply='';
6804: for (1..100) {
6805: sleep 2;
6806: if (-e $replyfile.'.end') {
1.448 albertel 6807: if (open(my $fh,$replyfile)) {
1.904 albertel 6808: $reply = join('',<$fh>);
6809: close($fh);
1.240 www 6810: } else { return 'error: reply_file_error'; }
1.242 www 6811: return &unescape($reply);
6812: }
1.240 www 6813: }
1.242 www 6814: return 'timeout:'.$queryid;
1.240 www 6815: }
6816:
6817: sub courselog_query {
1.241 www 6818: #
6819: # possible filters:
6820: # url: url or symb
6821: # username
6822: # domain
6823: # action: view, submit, grade
6824: # start: timestamp
6825: # end: timestamp
6826: #
1.240 www 6827: my (%filters)=@_;
1.620 albertel 6828: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 6829: if ($filters{'url'}) {
6830: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
6831: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
6832: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
6833: }
1.620 albertel 6834: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
6835: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 6836: return &log_query($cname,$cdom,'courselog',%filters);
6837: }
6838:
6839: sub userlog_query {
1.858 raeburn 6840: #
6841: # possible filters:
6842: # action: log check role
6843: # start: timestamp
6844: # end: timestamp
6845: #
1.240 www 6846: my ($uname,$udom,%filters)=@_;
6847: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 6848: }
6849:
1.506 raeburn 6850: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
6851:
6852: sub auto_run {
1.508 raeburn 6853: my ($cnum,$cdom) = @_;
1.876 raeburn 6854: my $response = 0;
6855: my $settings;
6856: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
6857: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
6858: $settings = $domconfig{'autoenroll'};
6859: if ($settings->{'run'} eq '1') {
6860: $response = 1;
6861: }
6862: } else {
1.934 raeburn 6863: my $homeserver;
6864: if (&is_course($cdom,$cnum)) {
6865: $homeserver = &homeserver($cnum,$cdom);
6866: } else {
6867: $homeserver = &domain($cdom,'primary');
6868: }
6869: if ($homeserver ne 'no_host') {
6870: $response = &reply('autorun:'.$cdom,$homeserver);
6871: }
1.876 raeburn 6872: }
1.506 raeburn 6873: return $response;
6874: }
1.776 albertel 6875:
1.506 raeburn 6876: sub auto_get_sections {
1.508 raeburn 6877: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 6878: my $homeserver;
6879: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6880: $homeserver = &homeserver($cnum,$cdom);
6881: }
6882: if (!defined($homeserver)) {
6883: if ($cdom =~ /^$match_domain$/) {
6884: $homeserver = &domain($cdom,'primary');
6885: }
6886: }
6887: my @secs;
6888: if (defined($homeserver)) {
6889: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
6890: unless ($response eq 'refused') {
6891: @secs = split(/:/,$response);
6892: }
1.506 raeburn 6893: }
6894: return @secs;
6895: }
1.776 albertel 6896:
1.506 raeburn 6897: sub auto_new_course {
1.1099 raeburn 6898: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 6899: my $homeserver = &homeserver($cnum,$cdom);
1.1099 raeburn 6900: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 6901: return $response;
6902: }
1.776 albertel 6903:
1.506 raeburn 6904: sub auto_validate_courseID {
1.508 raeburn 6905: my ($cnum,$cdom,$inst_course_id) = @_;
6906: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 6907: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 6908: return $response;
6909: }
1.776 albertel 6910:
1.1007 raeburn 6911: sub auto_validate_instcode {
1.1020 raeburn 6912: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 6913: my ($homeserver,$response);
6914: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6915: $homeserver = &homeserver($cnum,$cdom);
6916: }
6917: if (!defined($homeserver)) {
6918: if ($cdom =~ /^$match_domain$/) {
6919: $homeserver = &domain($cdom,'primary');
6920: }
6921: }
1.1065 raeburn 6922: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
6923: &escape($instcode).':'.&escape($owner),$homeserver));
1.1027 raeburn 6924: my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
6925: return ($outcome,$description);
1.1007 raeburn 6926: }
6927:
1.506 raeburn 6928: sub auto_create_password {
1.873 raeburn 6929: my ($cnum,$cdom,$authparam,$udom) = @_;
6930: my ($homeserver,$response);
1.506 raeburn 6931: my $create_passwd = 0;
6932: my $authchk = '';
1.873 raeburn 6933: if ($udom =~ /^$match_domain$/) {
6934: $homeserver = &domain($udom,'primary');
6935: }
6936: if ($homeserver eq '') {
6937: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6938: $homeserver = &homeserver($cnum,$cdom);
6939: }
6940: }
6941: if ($homeserver eq '') {
6942: $authchk = 'nodomain';
1.506 raeburn 6943: } else {
1.873 raeburn 6944: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
6945: if ($response eq 'refused') {
6946: $authchk = 'refused';
6947: } else {
1.901 albertel 6948: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 6949: }
1.506 raeburn 6950: }
6951: return ($authparam,$create_passwd,$authchk);
6952: }
6953:
1.706 raeburn 6954: sub auto_photo_permission {
6955: my ($cnum,$cdom,$students) = @_;
6956: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 6957: my ($outcome,$perm_reqd,$conditions) =
6958: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 6959: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6960: return (undef,undef);
6961: }
1.706 raeburn 6962: return ($outcome,$perm_reqd,$conditions);
6963: }
6964:
6965: sub auto_checkphotos {
6966: my ($uname,$udom,$pid) = @_;
6967: my $homeserver = &homeserver($uname,$udom);
6968: my ($result,$resulttype);
6969: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 6970: &escape($uname).':'.&escape($pid),
6971: $homeserver));
1.709 albertel 6972: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6973: return (undef,undef);
6974: }
1.706 raeburn 6975: if ($outcome) {
6976: ($result,$resulttype) = split(/:/,$outcome);
6977: }
6978: return ($result,$resulttype);
6979: }
6980:
6981: sub auto_photochoice {
6982: my ($cnum,$cdom) = @_;
6983: my $homeserver = &homeserver($cnum,$cdom);
6984: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 6985: &escape($cdom),
6986: $homeserver)));
1.709 albertel 6987: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6988: return (undef,undef);
6989: }
1.706 raeburn 6990: return ($update,$comment);
6991: }
6992:
6993: sub auto_photoupdate {
6994: my ($affiliatesref,$dom,$cnum,$photo) = @_;
6995: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 6996: my $host=&hostname($homeserver);
1.706 raeburn 6997: my $cmd = '';
6998: my $maxtries = 1;
1.800 albertel 6999: foreach my $affiliate (keys(%{$affiliatesref})) {
7000: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 7001: }
7002: $cmd =~ s/%%$//;
7003: $cmd = &escape($cmd);
7004: my $query = 'institutionalphotos';
7005: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
7006: unless ($queryid=~/^\Q$host\E\_/) {
7007: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
7008: return 'error: '.$queryid;
7009: }
7010: my $reply = &get_query_reply($queryid);
7011: my $tries = 1;
7012: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
7013: $reply = &get_query_reply($queryid);
7014: $tries ++;
7015: }
7016: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
7017: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
7018: } else {
7019: my @responses = split(/:/,$reply);
7020: my $outcome = shift(@responses);
7021: foreach my $item (@responses) {
7022: my ($key,$value) = split(/=/,$item);
7023: $$photo{$key} = $value;
7024: }
7025: return $outcome;
7026: }
7027: return 'error';
7028: }
7029:
1.521 raeburn 7030: sub auto_instcode_format {
1.793 albertel 7031: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
7032: $cat_order) = @_;
1.521 raeburn 7033: my $courses = '';
1.772 raeburn 7034: my @homeservers;
1.521 raeburn 7035: if ($caller eq 'global') {
1.841 albertel 7036: my %servers = &get_servers($codedom,'library');
7037: foreach my $tryserver (keys(%servers)) {
7038: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7039: push(@homeservers,$tryserver);
7040: }
1.584 raeburn 7041: }
1.1022 raeburn 7042: } elsif ($caller eq 'requests') {
7043: if ($codedom =~ /^$match_domain$/) {
7044: my $chome = &domain($codedom,'primary');
7045: unless ($chome eq 'no_host') {
7046: push(@homeservers,$chome);
7047: }
7048: }
1.521 raeburn 7049: } else {
1.772 raeburn 7050: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 7051: }
1.793 albertel 7052: foreach my $code (keys(%{$instcodes})) {
7053: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 7054: }
7055: chop($courses);
1.772 raeburn 7056: my $ok_response = 0;
7057: my $response;
7058: while (@homeservers > 0 && $ok_response == 0) {
7059: my $server = shift(@homeservers);
7060: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
7061: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
7062: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 7063: split(/:/,$response);
1.772 raeburn 7064: %{$codes} = (%{$codes},&str2hash($codes_str));
7065: push(@{$codetitles},&str2array($codetitles_str));
7066: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
7067: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
7068: $ok_response = 1;
7069: }
7070: }
7071: if ($ok_response) {
1.521 raeburn 7072: return 'ok';
1.772 raeburn 7073: } else {
7074: return $response;
1.521 raeburn 7075: }
7076: }
7077:
1.792 raeburn 7078: sub auto_instcode_defaults {
7079: my ($domain,$returnhash,$code_order) = @_;
7080: my @homeservers;
1.841 albertel 7081:
7082: my %servers = &get_servers($domain,'library');
7083: foreach my $tryserver (keys(%servers)) {
7084: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7085: push(@homeservers,$tryserver);
7086: }
1.792 raeburn 7087: }
1.841 albertel 7088:
1.792 raeburn 7089: my $response;
1.841 albertel 7090: foreach my $server (@homeservers) {
1.792 raeburn 7091: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 7092: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
7093:
7094: foreach my $pair (split(/\&/,$response)) {
7095: my ($name,$value)=split(/\=/,$pair);
7096: if ($name eq 'code_order') {
7097: @{$code_order} = split(/\&/,&unescape($value));
7098: } else {
7099: $returnhash->{&unescape($name)}=&unescape($value);
7100: }
7101: }
7102: return 'ok';
1.792 raeburn 7103: }
1.841 albertel 7104:
7105: return $response;
1.1003 raeburn 7106: }
7107:
7108: sub auto_possible_instcodes {
1.1007 raeburn 7109: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
7110: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
7111: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
7112: return;
7113: }
1.1003 raeburn 7114: my (@homeservers,$uhome);
7115: if (defined(&domain($domain,'primary'))) {
7116: $uhome=&domain($domain,'primary');
7117: push(@homeservers,&domain($domain,'primary'));
7118: } else {
7119: my %servers = &get_servers($domain,'library');
7120: foreach my $tryserver (keys(%servers)) {
7121: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7122: push(@homeservers,$tryserver);
7123: }
7124: }
7125: }
7126: my $response;
7127: foreach my $server (@homeservers) {
7128: $response=&reply('autopossibleinstcodes:'.$domain,$server);
7129: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 7130: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
7131: split(':',$response);
7132: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
7133: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 7134: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 7135: my ($name,$value)=split('=',$item);
7136: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 7137: }
7138: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 7139: my ($name,$value)=split('=',$item);
7140: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 7141: }
7142: return 'ok';
7143: }
7144: return $response;
7145: }
1.792 raeburn 7146:
1.1010 raeburn 7147: sub auto_courserequest_checks {
7148: my ($dom) = @_;
1.1020 raeburn 7149: my ($homeserver,%validations);
7150: if ($dom =~ /^$match_domain$/) {
7151: $homeserver = &domain($dom,'primary');
7152: }
7153: unless ($homeserver eq 'no_host') {
7154: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
7155: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
7156: my @items = split(/&/,$response);
7157: foreach my $item (@items) {
7158: my ($key,$value) = split('=',$item);
7159: $validations{&unescape($key)} = &thaw_unescape($value);
7160: }
7161: }
7162: }
1.1010 raeburn 7163: return %validations;
7164: }
7165:
1.1020 raeburn 7166: sub auto_courserequest_validation {
7167: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
7168: my ($homeserver,$response);
7169: if ($dom =~ /^$match_domain$/) {
7170: $homeserver = &domain($dom,'primary');
7171: }
7172: unless ($homeserver eq 'no_host') {
1.1021 raeburn 7173:
1.1020 raeburn 7174: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 7175: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020 raeburn 7176: ':'.&escape($instcode).':'.&escape($instseclist),
7177: $homeserver));
7178: }
7179: return $response;
7180: }
7181:
1.777 albertel 7182: sub auto_validate_class_sec {
1.918 raeburn 7183: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 7184: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 7185: my $ownerlist;
7186: if (ref($owners) eq 'ARRAY') {
7187: $ownerlist = join(',',@{$owners});
7188: } else {
7189: $ownerlist = $owners;
7190: }
1.773 raeburn 7191: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 7192: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 7193: return $response;
7194: }
7195:
1.679 raeburn 7196: # ------------------------------------------------------- Course Group routines
7197:
7198: sub get_coursegroups {
1.809 raeburn 7199: my ($cdom,$cnum,$group,$namespace) = @_;
7200: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 7201: }
7202:
1.679 raeburn 7203: sub modify_coursegroup {
7204: my ($cdom,$cnum,$groupsettings) = @_;
7205: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
7206: }
7207:
1.809 raeburn 7208: sub toggle_coursegroup_status {
7209: my ($cdom,$cnum,$group,$action) = @_;
7210: my ($from_namespace,$to_namespace);
7211: if ($action eq 'delete') {
7212: $from_namespace = 'coursegroups';
7213: $to_namespace = 'deleted_groups';
7214: } else {
7215: $from_namespace = 'deleted_groups';
7216: $to_namespace = 'coursegroups';
7217: }
7218: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 7219: if (my $tmp = &error(%curr_group)) {
7220: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
7221: return ('read error',$tmp);
7222: } else {
7223: my %savedsettings = %curr_group;
1.809 raeburn 7224: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 7225: my $deloutcome;
7226: if ($result eq 'ok') {
1.809 raeburn 7227: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 7228: } else {
7229: return ('write error',$result);
7230: }
7231: if ($deloutcome eq 'ok') {
7232: return 'ok';
7233: } else {
7234: return ('delete error',$deloutcome);
7235: }
7236: }
7237: }
7238:
1.679 raeburn 7239: sub modify_group_roles {
1.957 raeburn 7240: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 7241: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
7242: my $role = 'gr/'.&escape($userprivs);
7243: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 7244: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 7245: if ($result eq 'ok') {
7246: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
7247: }
1.679 raeburn 7248: return $result;
7249: }
7250:
7251: sub modify_coursegroup_membership {
7252: my ($cdom,$cnum,$membership) = @_;
7253: my $result = &put('groupmembership',$membership,$cdom,$cnum);
7254: return $result;
7255: }
7256:
1.682 raeburn 7257: sub get_active_groups {
7258: my ($udom,$uname,$cdom,$cnum) = @_;
7259: my $now = time;
7260: my %groups = ();
7261: foreach my $key (keys(%env)) {
1.811 albertel 7262: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 7263: my ($start,$end) = split(/\./,$env{$key});
7264: if (($end!=0) && ($end<$now)) { next; }
7265: if (($start!=0) && ($start>$now)) { next; }
7266: if ($1 eq $cdom && $2 eq $cnum) {
7267: $groups{$3} = $env{$key} ;
7268: }
7269: }
7270: }
7271: return %groups;
7272: }
7273:
1.683 raeburn 7274: sub get_group_membership {
7275: my ($cdom,$cnum,$group) = @_;
7276: return(&dump('groupmembership',$cdom,$cnum,$group));
7277: }
7278:
7279: sub get_users_groups {
7280: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 7281: my @usersgroups;
1.683 raeburn 7282: my $cachetime=1800;
7283:
7284: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 7285: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
7286: if (defined($cached)) {
1.734 albertel 7287: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 7288: } else {
7289: $grouplist = '';
1.816 raeburn 7290: my $courseurl = &courseid_to_courseurl($courseid);
1.1166 raeburn 7291: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 7292: my $access_end = $env{'course.'.$courseid.
7293: '.default_enrollment_end_date'};
7294: my $now = time;
7295: foreach my $key (keys(%roleshash)) {
7296: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
7297: my $group = $1;
7298: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
7299: my $start = $2;
7300: my $end = $1;
7301: if ($start == -1) { next; } # deleted from group
7302: if (($start!=0) && ($start>$now)) { next; }
7303: if (($end!=0) && ($end<$now)) {
7304: if ($access_end && $access_end < $now) {
7305: if ($access_end - $end < 86400) {
7306: push(@usersgroups,$group);
1.733 raeburn 7307: }
7308: }
1.817 raeburn 7309: next;
1.733 raeburn 7310: }
1.817 raeburn 7311: push(@usersgroups,$group);
1.683 raeburn 7312: }
7313: }
7314: }
1.817 raeburn 7315: @usersgroups = &sort_course_groups($courseid,@usersgroups);
7316: $grouplist = join(':',@usersgroups);
7317: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 7318: }
1.733 raeburn 7319: return @usersgroups;
1.683 raeburn 7320: }
7321:
7322: sub devalidate_getgroups_cache {
7323: my ($udom,$uname,$cdom,$cnum)=@_;
7324: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 7325:
1.683 raeburn 7326: my $hashid="$udom:$uname:$courseid";
7327: &devalidate_cache_new('getgroups',$hashid);
7328: }
7329:
1.12 www 7330: # ------------------------------------------------------------------ Plain Text
7331:
7332: sub plaintext {
1.988 raeburn 7333: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 7334: if ($short =~ m{^cr/}) {
1.758 albertel 7335: return (split('/',$short))[-1];
7336: }
1.742 raeburn 7337: if (!defined($cid)) {
7338: $cid = $env{'request.course.id'};
7339: }
7340: my %rolenames = (
1.1008 raeburn 7341: Course => 'std',
7342: Community => 'alt1',
1.742 raeburn 7343: );
1.1037 raeburn 7344: if ($cid ne '') {
7345: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
7346: unless ($forcedefault) {
7347: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
7348: &Apache::lonlocal::mt_escape(\$roletext);
7349: return &Apache::lonlocal::mt($roletext);
7350: }
7351: }
7352: }
7353: if ((defined($type)) && (defined($rolenames{$type})) &&
7354: (defined($rolenames{$type})) &&
7355: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 7356: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 7357: } elsif ($cid ne '') {
7358: my $crstype = $env{'course.'.$cid.'.type'};
7359: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
7360: (defined($prp{$short}{$rolenames{$crstype}}))) {
7361: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
7362: }
1.742 raeburn 7363: }
1.1037 raeburn 7364: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 7365: }
7366:
7367: # ----------------------------------------------------------------- Assign Role
7368:
7369: sub assignrole {
1.957 raeburn 7370: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
7371: $context)=@_;
1.21 www 7372: my $mrole;
7373: if ($role =~ /^cr\//) {
1.393 www 7374: my $cwosec=$url;
1.811 albertel 7375: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 7376: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 7377: my $refused = 1;
7378: if ($context eq 'requestcourses') {
7379: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
7380: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
7381: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
7382: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
7383: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
7384: if ($crsenv{'internal.courseowner'} eq
7385: $env{'user.name'}.':'.$env{'user.domain'}) {
7386: $refused = '';
7387: }
7388: }
7389: }
7390: }
7391: }
7392: if ($refused) {
7393: &logthis('Refused custom assignrole: '.
7394: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
7395: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
7396: return 'refused';
7397: }
1.104 www 7398: }
1.21 www 7399: $mrole='cr';
1.678 raeburn 7400: } elsif ($role =~ /^gr\//) {
7401: my $cwogrp=$url;
1.811 albertel 7402: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 7403: unless (&allowed('mdg',$cwogrp)) {
7404: &logthis('Refused group assignrole: '.
7405: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
7406: $env{'user.name'}.' at '.$env{'user.domain'});
7407: return 'refused';
7408: }
7409: $mrole='gr';
1.21 www 7410: } else {
1.82 www 7411: my $cwosec=$url;
1.811 albertel 7412: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 7413: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
7414: my $refused;
7415: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
7416: if (!(&allowed('c'.$role,$url))) {
7417: $refused = 1;
7418: }
7419: } else {
7420: $refused = 1;
7421: }
1.947 raeburn 7422: if ($refused) {
1.1045 raeburn 7423: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
7424: if (!$selfenroll && $context eq 'course') {
7425: my %crsenv;
7426: if ($role eq 'cc' || $role eq 'co') {
7427: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
7428: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
7429: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
7430: if ($crsenv{'internal.courseowner'} eq
7431: $env{'user.name'}.':'.$env{'user.domain'}) {
7432: $refused = '';
7433: }
7434: }
7435: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
7436: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
7437: if ($crsenv{'internal.courseowner'} eq
7438: $env{'user.name'}.':'.$env{'user.domain'}) {
7439: $refused = '';
7440: }
7441: }
7442: }
7443: }
7444: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 7445: $refused = '';
1.1017 raeburn 7446: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 7447: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 7448: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 7449: my $wrongcc;
7450: if ($cnum =~ /^$match_community$/) {
7451: $wrongcc = 1 if ($role eq 'cc');
7452: } else {
7453: $wrongcc = 1 if ($role eq 'co');
7454: }
7455: unless ($wrongcc) {
7456: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
7457: if ($crsenv{'internal.courseowner'} eq
7458: $env{'user.name'}.':'.$env{'user.domain'}) {
7459: $refused = '';
7460: }
1.1017 raeburn 7461: }
7462: }
7463: }
7464: if ($refused) {
1.947 raeburn 7465: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
7466: ' '.$role.' '.$end.' '.$start.' by '.
7467: $env{'user.name'}.' at '.$env{'user.domain'});
7468: return 'refused';
7469: }
1.932 raeburn 7470: }
1.1131 raeburn 7471: } elsif ($role eq 'au') {
7472: if ($url ne '/'.$udom.'/') {
7473: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
7474: ' to assign author role for '.$uname.':'.$udom.
7475: ' in domain: '.$url.' refused (wrong domain).');
7476: return 'refused';
7477: }
1.104 www 7478: }
1.21 www 7479: $mrole=$role;
7480: }
1.620 albertel 7481: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 7482: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 7483: if ($end) { $command.='_'.$end; }
1.21 www 7484: if ($start) {
7485: if ($end) {
1.81 www 7486: $command.='_'.$start;
1.21 www 7487: } else {
1.81 www 7488: $command.='_0_'.$start;
1.21 www 7489: }
7490: }
1.739 raeburn 7491: my $origstart = $start;
7492: my $origend = $end;
1.957 raeburn 7493: my $delflag;
1.357 www 7494: # actually delete
7495: if ($deleteflag) {
1.373 www 7496: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 7497: # modify command to delete the role
1.620 albertel 7498: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 7499: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 7500: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 7501: # set start and finish to negative values for userrolelog
7502: $start=-1;
7503: $end=-1;
1.957 raeburn 7504: $delflag = 1;
1.357 www 7505: }
7506: }
7507: # send command
1.349 www 7508: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 7509: # log new user role if status is ok
1.349 www 7510: if ($answer eq 'ok') {
1.663 raeburn 7511: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.739 raeburn 7512: # for course roles, perform group memberships changes triggered by role change.
1.957 raeburn 7513: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739 raeburn 7514: unless ($role =~ /^gr/) {
7515: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957 raeburn 7516: $origstart,$selfenroll,$context);
1.739 raeburn 7517: }
1.1053 raeburn 7518: if ($role eq 'cc') {
7519: &autoupdate_coowners($url,$end,$start,$uname,$udom);
7520: }
1.349 www 7521: }
7522: return $answer;
1.169 harris41 7523: }
7524:
1.1053 raeburn 7525: sub autoupdate_coowners {
7526: my ($url,$end,$start,$uname,$udom) = @_;
7527: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
7528: if (($cdom ne '') && ($cnum ne '')) {
7529: my $now = time;
7530: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
7531: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
7532: my %coursehash = &coursedescription($cdom.'_'.$cnum);
7533: my $instcode = $coursehash{'internal.coursecode'};
7534: if ($instcode ne '') {
1.1056 raeburn 7535: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
7536: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 7537: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 7538: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
7539: if ($result eq 'valid') {
7540: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 7541: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
7542: push(@newcoowners,$coowner);
7543: }
7544: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
7545: push(@newcoowners,$uname.':'.$udom);
7546: }
7547: @newcoowners = sort(@newcoowners);
7548: } else {
7549: push(@newcoowners,$uname.':'.$udom);
7550: }
7551: } else {
7552: if ($coursehash{'internal.co-owners'}) {
7553: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
7554: unless ($coowner eq $uname.':'.$udom) {
7555: push(@newcoowners,$coowner);
7556: }
7557: }
7558: unless (@newcoowners > 0) {
7559: $delcoowners = 1;
7560: $coowners = '';
7561: }
7562: }
7563: }
7564: if (@newcoowners || $delcoowners) {
7565: &store_coowners($cdom,$cnum,$coursehash{'home'},
7566: $delcoowners,@newcoowners);
7567: }
7568: }
7569: }
7570: }
7571: }
7572: }
7573: }
7574:
7575: sub store_coowners {
7576: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
7577: my $cid = $cdom.'_'.$cnum;
7578: my ($coowners,$delresult,$putresult);
7579: if (@newcoowners) {
7580: $coowners = join(',',@newcoowners);
7581: my %coownershash = (
7582: 'internal.co-owners' => $coowners,
7583: );
7584: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
7585: if ($putresult eq 'ok') {
7586: if ($env{'course.'.$cid.'.num'} eq $cnum) {
7587: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
7588: }
7589: }
7590: }
7591: if ($delcoowners) {
7592: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
7593: if ($delresult eq 'ok') {
7594: if ($env{'course.'.$cid.'.internal.co-owners'}) {
7595: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
7596: }
7597: }
7598: }
7599: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
7600: my %crsinfo =
7601: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
7602: if (ref($crsinfo{$cid}) eq 'HASH') {
7603: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
7604: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
7605: }
7606: }
7607: }
7608:
1.169 harris41 7609: # -------------------------------------------------- Modify user authentication
1.197 www 7610: # Overrides without validation
7611:
1.169 harris41 7612: sub modifyuserauth {
7613: my ($udom,$uname,$umode,$upass)=@_;
7614: my $uhome=&homeserver($uname,$udom);
1.197 www 7615: unless (&allowed('mau',$udom)) { return 'refused'; }
7616: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 7617: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
7618: ' in domain '.$env{'request.role.domain'});
1.169 harris41 7619: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
7620: &escape($upass),$uhome);
1.620 albertel 7621: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 7622: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
7623: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
7624: &log($udom,,$uname,$uhome,
1.620 albertel 7625: 'Authentication changed by '.$env{'user.domain'}.', '.
7626: $env{'user.name'}.', '.$umode.
1.197 www 7627: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 7628: unless ($reply eq 'ok') {
1.197 www 7629: &logthis('Authentication mode error: '.$reply);
1.169 harris41 7630: return 'error: '.$reply;
7631: }
1.170 harris41 7632: return 'ok';
1.80 www 7633: }
7634:
1.81 www 7635: # --------------------------------------------------------------- Modify a user
1.80 www 7636:
1.81 www 7637: sub modifyuser {
1.206 matthew 7638: my ($udom, $uname, $uid,
7639: $umode, $upass, $first,
7640: $middle, $last, $gene,
1.1058 raeburn 7641: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 7642: $udom= &LONCAPA::clean_domain($udom);
7643: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 7644: my $showcandelete = 'none';
7645: if (ref($candelete) eq 'ARRAY') {
7646: if (@{$candelete} > 0) {
7647: $showcandelete = join(', ',@{$candelete});
7648: }
7649: }
1.81 www 7650: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 7651: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 7652: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 7653: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
7654: ' desiredhome not specified').
1.620 albertel 7655: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
7656: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 7657: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 7658: my $newuser;
7659: if ($uhome eq 'no_host') {
7660: $newuser = 1;
7661: }
1.80 www 7662: # ----------------------------------------------------------------- Create User
1.406 albertel 7663: if (($uhome eq 'no_host') &&
7664: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 7665: my $unhome='';
1.844 albertel 7666: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 7667: $unhome = $desiredhome;
1.620 albertel 7668: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
7669: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 7670: } else { # load balancing routine for determining $unhome
1.81 www 7671: my $loadm=10000000;
1.841 albertel 7672: my %servers = &get_servers($udom,'library');
7673: foreach my $tryserver (keys(%servers)) {
7674: my $answer=reply('load',$tryserver);
7675: if (($answer=~/\d+/) && ($answer<$loadm)) {
7676: $loadm=$answer;
7677: $unhome=$tryserver;
7678: }
1.80 www 7679: }
7680: }
7681: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 7682: return 'error: unable to find a home server for '.$uname.
7683: ' in domain '.$udom;
1.80 www 7684: }
7685: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
7686: &escape($upass),$unhome);
7687: unless ($reply eq 'ok') {
7688: return 'error: '.$reply;
7689: }
1.230 stredwic 7690: $uhome=&homeserver($uname,$udom,'true');
1.80 www 7691: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 7692: return 'error: unable verify users home machine.';
1.80 www 7693: }
1.209 matthew 7694: } # End of creation of new user
1.80 www 7695: # ---------------------------------------------------------------------- Add ID
7696: if ($uid) {
7697: $uid=~tr/A-Z/a-z/;
7698: my %uidhash=&idrget($udom,$uname);
1.196 www 7699: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
7700: && (!$forceid)) {
1.80 www 7701: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 7702: return 'error: user id "'.$uid.'" does not match '.
7703: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 7704: }
7705: } else {
7706: &idput($udom,($uname => $uid));
7707: }
7708: }
7709: # -------------------------------------------------------------- Add names, etc
1.313 matthew 7710: my @tmp=&get('environment',
1.899 raeburn 7711: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 7712: 'permanentemail','inststatus'],
1.134 albertel 7713: $udom,$uname);
1.1075 raeburn 7714: my (%names,%oldnames);
1.313 matthew 7715: if ($tmp[0] =~ m/^error:.*/) {
7716: %names=();
7717: } else {
7718: %names = @tmp;
1.1075 raeburn 7719: %oldnames = %names;
1.313 matthew 7720: }
1.388 www 7721: #
1.1058 raeburn 7722: # If name, email and/or uid are blank (e.g., because an uploaded file
7723: # of users did not contain them), do not overwrite existing values
7724: # unless field is in $candelete array ref.
7725: #
7726:
7727: my @fields = ('firstname','middlename','lastname','generation',
7728: 'permanentemail','id');
7729: my %newvalues;
7730: if (ref($candelete) eq 'ARRAY') {
7731: foreach my $field (@fields) {
7732: if (grep(/^\Q$field\E$/,@{$candelete})) {
7733: if ($field eq 'firstname') {
7734: $names{$field} = $first;
7735: } elsif ($field eq 'middlename') {
7736: $names{$field} = $middle;
7737: } elsif ($field eq 'lastname') {
7738: $names{$field} = $last;
7739: } elsif ($field eq 'generation') {
7740: $names{$field} = $gene;
7741: } elsif ($field eq 'permanentemail') {
7742: $names{$field} = $email;
7743: } elsif ($field eq 'id') {
7744: $names{$field} = $uid;
7745: }
7746: }
7747: }
7748: }
1.388 www 7749: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 7750: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 7751: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 7752: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 7753: if ($email) {
7754: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 7755: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 7756: }
1.899 raeburn 7757: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 7758: if (defined($inststatus)) {
7759: $names{'inststatus'} = '';
7760: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
7761: if (ref($usertypes) eq 'HASH') {
7762: my @okstatuses;
7763: foreach my $item (split(/:/,$inststatus)) {
7764: if (defined($usertypes->{$item})) {
7765: push(@okstatuses,$item);
7766: }
7767: }
7768: if (@okstatuses) {
7769: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
7770: }
7771: }
7772: }
1.1075 raeburn 7773: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 7774: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 7775: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 7776: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
7777: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
7778: } else {
7779: $logmsg .= ' during self creation';
7780: }
1.1075 raeburn 7781: my $changed;
7782: if ($newuser) {
7783: $changed = 1;
7784: } else {
7785: foreach my $field (@fields) {
7786: if ($names{$field} ne $oldnames{$field}) {
7787: $changed = 1;
7788: last;
7789: }
7790: }
7791: }
7792: unless ($changed) {
7793: $logmsg = 'No changes in user information needed for: '.$logmsg;
7794: &logthis($logmsg);
7795: return 'ok';
7796: }
7797: my $reply = &put('environment', \%names, $udom,$uname);
7798: if ($reply ne 'ok') {
7799: return 'error: '.$reply;
7800: }
1.1087 raeburn 7801: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
7802: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
7803: }
1.1075 raeburn 7804: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
7805: &devalidate_cache_new('namescache',$uname.':'.$udom);
7806: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 7807: &logthis($logmsg);
1.134 albertel 7808: return 'ok';
1.80 www 7809: }
7810:
1.81 www 7811: # -------------------------------------------------------------- Modify student
1.80 www 7812:
1.81 www 7813: sub modifystudent {
7814: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 7815: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.990 raeburn 7816: $selfenroll,$context,$inststatus)=@_;
1.455 albertel 7817: if (!$cid) {
1.620 albertel 7818: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 7819: return 'not_in_class';
7820: }
1.80 www 7821: }
7822: # --------------------------------------------------------------- Make the user
1.81 www 7823: my $reply=&modifyuser
1.209 matthew 7824: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 7825: $desiredhome,$email,$inststatus);
1.80 www 7826: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 7827: # This will cause &modify_student_enrollment to get the uid from the
7828: # students environment
7829: $uid = undef if (!$forceid);
1.455 albertel 7830: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957 raeburn 7831: $gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297 matthew 7832: return $reply;
7833: }
7834:
7835: sub modify_student_enrollment {
1.957 raeburn 7836: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455 albertel 7837: my ($cdom,$cnum,$chome);
7838: if (!$cid) {
1.620 albertel 7839: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 7840: return 'not_in_class';
7841: }
1.620 albertel 7842: $cdom=$env{'course.'.$cid.'.domain'};
7843: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 7844: } else {
7845: ($cdom,$cnum)=split(/_/,$cid);
7846: }
1.620 albertel 7847: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 7848: if (!$chome) {
1.457 raeburn 7849: $chome=&homeserver($cnum,$cdom);
1.297 matthew 7850: }
1.455 albertel 7851: if (!$chome) { return 'unknown_course'; }
1.297 matthew 7852: # Make sure the user exists
1.81 www 7853: my $uhome=&homeserver($uname,$udom);
7854: if (($uhome eq '') || ($uhome eq 'no_host')) {
7855: return 'error: no such user';
7856: }
1.297 matthew 7857: # Get student data if we were not given enough information
7858: if (!defined($first) || $first eq '' ||
7859: !defined($last) || $last eq '' ||
7860: !defined($uid) || $uid eq '' ||
7861: !defined($middle) || $middle eq '' ||
7862: !defined($gene) || $gene eq '') {
1.294 matthew 7863: # They did not supply us with enough data to enroll the student, so
7864: # we need to pick up more information.
1.297 matthew 7865: my %tmp = &get('environment',
1.294 matthew 7866: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 7867: ,$udom,$uname);
7868:
1.800 albertel 7869: #foreach my $key (keys(%tmp)) {
7870: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 7871: #}
1.294 matthew 7872: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
7873: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
7874: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 7875: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 7876: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
7877: }
1.556 albertel 7878: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148 raeburn 7879: my $user = "$uname:$udom";
7880: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487 albertel 7881: my $reply=cput('classlist',
1.1148 raeburn 7882: {$user =>
1.515 raeburn 7883: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487 albertel 7884: $cdom,$cnum);
1.1148 raeburn 7885: if (($reply eq 'ok') || ($reply eq 'delayed')) {
7886: &devalidate_getsection_cache($udom,$uname,$cid);
7887: } else {
1.81 www 7888: return 'error: '.$reply;
7889: }
1.297 matthew 7890: # Add student role to user
1.83 www 7891: my $uurl='/'.$cid;
1.81 www 7892: $uurl=~s/\_/\//g;
7893: if ($usec) {
7894: $uurl.='/'.$usec;
7895: }
1.1148 raeburn 7896: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
7897: $selfenroll,$context);
7898: if ($result ne 'ok') {
7899: if ($old_entry{$user} ne '') {
7900: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
7901: } else {
7902: $reply = &del('classlist',[$user],$cdom,$cnum);
7903: }
7904: }
7905: return $result;
1.21 www 7906: }
7907:
1.556 albertel 7908: sub format_name {
7909: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
7910: my $name;
7911: if ($first ne 'lastname') {
7912: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
7913: } else {
7914: if ($lastname=~/\S/) {
7915: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
7916: $name=~s/\s+,/,/;
7917: } else {
7918: $name.= $firstname.' '.$middlename.' '.$generation;
7919: }
7920: }
7921: $name=~s/^\s+//;
7922: $name=~s/\s+$//;
7923: $name=~s/\s+/ /g;
7924: return $name;
7925: }
7926:
1.84 www 7927: # ------------------------------------------------- Write to course preferences
7928:
7929: sub writecoursepref {
7930: my ($courseid,%prefs)=@_;
7931: $courseid=~s/^\///;
7932: $courseid=~s/\_/\//g;
7933: my ($cdomain,$cnum)=split(/\//,$courseid);
7934: my $chome=homeserver($cnum,$cdomain);
7935: if (($chome eq '') || ($chome eq 'no_host')) {
7936: return 'error: no such course';
7937: }
7938: my $cstring='';
1.800 albertel 7939: foreach my $pref (keys(%prefs)) {
7940: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 7941: }
1.84 www 7942: $cstring=~s/\&$//;
7943: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
7944: }
7945:
7946: # ---------------------------------------------------------- Make/modify course
7947:
7948: sub createcourse {
1.741 raeburn 7949: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 7950: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 7951: $url=&declutter($url);
7952: my $cid='';
1.1028 raeburn 7953: if ($context eq 'requestcourses') {
7954: my $can_create = 0;
7955: my ($ownername,$ownerdom) = split(':',$course_owner);
7956: if ($udom eq $ownerdom) {
7957: if (&usertools_access($ownername,$ownerdom,$category,undef,
7958: $context)) {
7959: $can_create = 1;
7960: }
7961: } else {
7962: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
7963: $category);
7964: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
7965: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
7966: if (@curr > 0) {
7967: my @options = qw(approval validate autolimit);
7968: my $optregex = join('|',@options);
7969: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
7970: $can_create = 1;
7971: }
7972: }
7973: }
7974: }
7975: if ($can_create) {
7976: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
7977: unless (&allowed('ccc',$udom)) {
7978: return 'refused';
7979: }
1.1017 raeburn 7980: }
7981: } else {
7982: return 'refused';
7983: }
1.1028 raeburn 7984: } elsif (!&allowed('ccc',$udom)) {
7985: return 'refused';
1.84 www 7986: }
1.1011 raeburn 7987: # --------------------------------------------------------------- Get Unique ID
7988: my $uname;
7989: if ($cnum =~ /^$match_courseid$/) {
7990: my $chome=&homeserver($cnum,$udom,'true');
7991: if (($chome eq '') || ($chome eq 'no_host')) {
7992: $uname = $cnum;
7993: } else {
1.1038 raeburn 7994: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 7995: }
7996: } else {
1.1038 raeburn 7997: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 7998: }
7999: return $uname if ($uname =~ /^error/);
8000: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 8001: if (!defined($course_server)) {
8002: if (defined(&domain($udom,'primary'))) {
8003: $course_server = &domain($udom,'primary');
8004: } else {
8005: $course_server = $env{'user.home'};
8006: }
8007: }
8008: my %host_servers =
8009: &Apache::lonnet::get_servers($udom,'library');
8010: unless ($host_servers{$course_server}) {
8011: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 8012: }
1.84 www 8013: # ------------------------------------------------------------- Make the course
8014: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 8015: $course_server);
1.84 www 8016: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 8017: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 8018: if (($uhome eq '') || ($uhome eq 'no_host')) {
8019: return 'error: no such course';
8020: }
1.271 www 8021: # ----------------------------------------------------------------- Course made
1.516 raeburn 8022: # log existence
1.1029 raeburn 8023: my $now = time;
1.918 raeburn 8024: my $newcourse = {
8025: $udom.'_'.$uname => {
1.921 raeburn 8026: description => $description,
8027: inst_code => $inst_code,
8028: owner => $course_owner,
8029: type => $crstype,
1.1029 raeburn 8030: creator => $env{'user.name'}.':'.
8031: $env{'user.domain'},
8032: created => $now,
8033: context => $context,
1.918 raeburn 8034: },
8035: };
1.921 raeburn 8036: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 8037: # set toplevel url
1.271 www 8038: my $topurl=$url;
8039: unless ($nonstandard) {
8040: # ------------------------------------------ For standard courses, make top url
8041: my $mapurl=&clutter($url);
1.278 www 8042: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 8043: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 8044: <map>
8045: <resource id="1" type="start"></resource>
8046: <resource id="2" src="$mapurl"></resource>
8047: <resource id="3" type="finish"></resource>
8048: <link index="1" from="1" to="2"></link>
8049: <link index="2" from="2" to="3"></link>
8050: </map>
8051: ENDINITMAP
8052: $topurl=&declutter(
1.638 albertel 8053: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 8054: );
8055: }
8056: # ----------------------------------------------------------- Write preferences
1.84 www 8057: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 8058: ('description' => $description,
8059: 'url' => $topurl,
8060: 'internal.creator' => $env{'user.name'}.':'.
8061: $env{'user.domain'},
8062: 'internal.created' => $now,
8063: 'internal.creationcontext' => $context)
8064: );
1.84 www 8065: return '/'.$udom.'/'.$uname;
8066: }
8067:
1.1011 raeburn 8068: # ------------------------------------------------------------------- Create ID
8069: sub generate_coursenum {
1.1038 raeburn 8070: my ($udom,$crstype) = @_;
1.1011 raeburn 8071: my $domdesc = &domain($udom);
8072: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 8073: my $first;
8074: if ($crstype eq 'Community') {
8075: $first = '0';
8076: } else {
8077: $first = int(1+rand(9));
8078: }
8079: my $uname=$first.
1.1011 raeburn 8080: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
8081: substr($$.time,0,5).unpack("H8",pack("I32",time)).
8082: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
8083: # ----------------------------------------------- Make sure that does not exist
8084: my $uhome=&homeserver($uname,$udom,'true');
8085: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 8086: if ($crstype eq 'Community') {
8087: $first = '0';
8088: } else {
8089: $first = int(1+rand(9));
8090: }
8091: $uname=$first.
1.1011 raeburn 8092: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
8093: substr($$.time,0,5).unpack("H8",pack("I32",time)).
8094: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
8095: $uhome=&homeserver($uname,$udom,'true');
8096: unless (($uhome eq '') || ($uhome eq 'no_host')) {
8097: return 'error: unable to generate unique course-ID';
8098: }
8099: }
8100: return $uname;
8101: }
8102:
1.813 albertel 8103: sub is_course {
1.1167 ! droeschl 8104: my ($cdom, $cnum) = scalar(@_) == 1 ?
! 8105: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
! 8106:
! 8107: return unless $cdom and $cnum;
! 8108:
! 8109: my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
! 8110: '.');
! 8111:
! 8112: return unless exists($courses{$cdom.'_'.$cnum});
! 8113: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813 albertel 8114: }
8115:
1.1015 raeburn 8116: sub store_userdata {
8117: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 8118: my $result;
1.1016 raeburn 8119: if ($datakey ne '') {
1.1013 raeburn 8120: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 8121: if ($udom eq '' || $uname eq '') {
8122: $udom = $env{'user.domain'};
8123: $uname = $env{'user.name'};
8124: }
8125: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 8126: if (($uhome eq '') || ($uhome eq 'no_host')) {
8127: $result = 'error: no_host';
8128: } else {
8129: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
8130: $storehash->{'host'} = $perlvar{'lonHostID'};
8131:
8132: my $namevalue='';
8133: foreach my $key (keys(%{$storehash})) {
8134: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
8135: }
8136: $namevalue=~s/\&$//;
1.1105 raeburn 8137: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
8138: $namevalue,$uhome);
1.1013 raeburn 8139: }
8140: } else {
8141: $result = 'error: data to store was not a hash reference';
8142: }
8143: } else {
8144: $result= 'error: invalid requestkey';
8145: }
8146: return $result;
8147: }
8148:
1.21 www 8149: # ---------------------------------------------------------- Assign Custom Role
8150:
8151: sub assigncustomrole {
1.957 raeburn 8152: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 8153: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 8154: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 8155: }
8156:
8157: # ----------------------------------------------------------------- Revoke Role
8158:
8159: sub revokerole {
1.957 raeburn 8160: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 8161: my $now=time;
1.965 raeburn 8162: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 8163: }
8164:
8165: # ---------------------------------------------------------- Revoke Custom Role
8166:
8167: sub revokecustomrole {
1.957 raeburn 8168: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 8169: my $now=time;
1.357 www 8170: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 8171: $deleteflag,$selfenroll,$context);
1.17 www 8172: }
8173:
1.533 banghart 8174: # ------------------------------------------------------------ Disk usage
1.535 albertel 8175: sub diskusage {
1.955 raeburn 8176: my ($udom,$uname,$directorypath,$getpropath)=@_;
8177: $directorypath =~ s/\/$//;
8178: my $listing=&reply('du2:'.&escape($directorypath).':'
8179: .&escape($getpropath).':'.&escape($uname).':'
8180: .&escape($udom),homeserver($uname,$udom));
8181: if ($listing eq 'unknown_cmd') {
8182: if ($getpropath) {
8183: $directorypath = &propath($udom,$uname).'/'.$directorypath;
8184: }
8185: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
8186: }
1.514 albertel 8187: return $listing;
1.512 banghart 8188: }
8189:
1.566 banghart 8190: sub is_locked {
1.1096 raeburn 8191: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 8192: my @check;
8193: my $is_locked;
1.1093 raeburn 8194: push (@check,$file_name);
1.613 albertel 8195: my %locked = &get('file_permissions',\@check,
1.620 albertel 8196: $env{'user.domain'},$env{'user.name'});
1.615 albertel 8197: my ($tmp)=keys(%locked);
8198: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 8199:
1.566 banghart 8200: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 8201: $is_locked = 'false';
8202: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 8203: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 8204: $is_locked = 'true';
1.1096 raeburn 8205: if (ref($which) eq 'ARRAY') {
8206: push(@{$which},$entry);
8207: } else {
8208: last;
8209: }
1.745 raeburn 8210: }
8211: }
1.566 banghart 8212: } else {
8213: $is_locked = 'false';
8214: }
1.1093 raeburn 8215: return $is_locked;
1.566 banghart 8216: }
8217:
1.759 albertel 8218: sub declutter_portfile {
8219: my ($file) = @_;
1.833 albertel 8220: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 8221: return $file;
8222: }
8223:
1.559 banghart 8224: # ------------------------------------------------------------- Mark as Read Only
8225:
8226: sub mark_as_readonly {
8227: my ($domain,$user,$files,$what) = @_;
1.613 albertel 8228: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 8229: my ($tmp)=keys(%current_permissions);
8230: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 8231: foreach my $file (@{$files}) {
1.759 albertel 8232: $file = &declutter_portfile($file);
1.561 banghart 8233: push(@{$current_permissions{$file}},$what);
1.559 banghart 8234: }
1.613 albertel 8235: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 8236: return;
8237: }
8238:
1.572 banghart 8239: # ------------------------------------------------------------Save Selected Files
8240:
8241: sub save_selected_files {
8242: my ($user, $path, @files) = @_;
8243: my $filename = $user."savedfiles";
1.573 banghart 8244: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 8245: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 8246: foreach my $file (@files) {
1.620 albertel 8247: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 8248: }
8249: foreach my $file (@other_files) {
1.574 banghart 8250: print (OUT $file."\n");
1.572 banghart 8251: }
1.574 banghart 8252: close (OUT);
1.572 banghart 8253: return 'ok';
8254: }
8255:
1.574 banghart 8256: sub clear_selected_files {
8257: my ($user) = @_;
8258: my $filename = $user."savedfiles";
1.1117 foxr 8259: open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574 banghart 8260: print (OUT undef);
8261: close (OUT);
8262: return ("ok");
8263: }
8264:
1.572 banghart 8265: sub files_in_path {
8266: my ($user, $path) = @_;
8267: my $filename = $user."savedfiles";
8268: my %return_files;
1.1117 foxr 8269: open (IN, '<'.LONCAPA::tempdir().$filename);
1.573 banghart 8270: while (my $line_in = <IN>) {
1.574 banghart 8271: chomp ($line_in);
8272: my @paths_and_file = split (m!/!, $line_in);
8273: my $file_part = pop (@paths_and_file);
8274: my $path_part = join ('/', @paths_and_file);
1.573 banghart 8275: $path_part.='/';
8276: my $path_and_file = $path_part.$file_part;
8277: if ($path_part eq $path) {
8278: $return_files{$file_part}= 'selected';
8279: }
8280: }
1.574 banghart 8281: close (IN);
8282: return (\%return_files);
1.572 banghart 8283: }
8284:
8285: # called in portfolio select mode, to show files selected NOT in current directory
8286: sub files_not_in_path {
8287: my ($user, $path) = @_;
8288: my $filename = $user."savedfiles";
8289: my @return_files;
8290: my $path_part;
1.1117 foxr 8291: open(IN, '<'.LONCAPA::.$filename);
1.800 albertel 8292: while (my $line = <IN>) {
1.572 banghart 8293: #ok, I know it's clunky, but I want it to work
1.800 albertel 8294: my @paths_and_file = split(m|/|, $line);
8295: my $file_part = pop(@paths_and_file);
8296: chomp($file_part);
8297: my $path_part = join('/', @paths_and_file);
1.572 banghart 8298: $path_part .= '/';
8299: my $path_and_file = $path_part.$file_part;
8300: if ($path_part ne $path) {
1.800 albertel 8301: push(@return_files, ($path_and_file));
1.572 banghart 8302: }
8303: }
1.800 albertel 8304: close(OUT);
1.574 banghart 8305: return (@return_files);
1.572 banghart 8306: }
8307:
1.745 raeburn 8308: #----------------------------------------------Get portfolio file permissions
1.629 banghart 8309:
1.745 raeburn 8310: sub get_portfile_permissions {
8311: my ($domain,$user) = @_;
1.613 albertel 8312: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 8313: my ($tmp)=keys(%current_permissions);
8314: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 8315: return \%current_permissions;
8316: }
8317:
8318: #---------------------------------------------Get portfolio file access controls
8319:
1.749 raeburn 8320: sub get_access_controls {
1.745 raeburn 8321: my ($current_permissions,$group,$file) = @_;
1.769 albertel 8322: my %access;
8323: my $real_file = $file;
8324: $file =~ s/\.meta$//;
1.745 raeburn 8325: if (defined($file)) {
1.749 raeburn 8326: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
8327: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 8328: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 8329: }
8330: }
1.745 raeburn 8331: } else {
1.749 raeburn 8332: foreach my $key (keys(%{$current_permissions})) {
8333: if ($key =~ /\0accesscontrol$/) {
8334: if (defined($group)) {
8335: if ($key !~ m-^\Q$group\E/-) {
8336: next;
8337: }
8338: }
8339: my ($fullpath) = split(/\0/,$key);
8340: if (ref($$current_permissions{$key}) eq 'HASH') {
8341: foreach my $control (keys(%{$$current_permissions{$key}})) {
8342: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
8343: }
8344: }
8345: }
8346: }
8347: }
8348: return %access;
8349: }
8350:
8351: sub modify_access_controls {
8352: my ($file_name,$changes,$domain,$user)=@_;
8353: my ($outcome,$deloutcome);
8354: my %store_permissions;
8355: my %new_values;
8356: my %new_control;
8357: my %translation;
8358: my @deletions = ();
8359: my $now = time;
8360: if (exists($$changes{'activate'})) {
8361: if (ref($$changes{'activate'}) eq 'HASH') {
8362: my @newitems = sort(keys(%{$$changes{'activate'}}));
8363: my $numnew = scalar(@newitems);
8364: for (my $i=0; $i<$numnew; $i++) {
8365: my $newkey = $newitems[$i];
8366: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 8367: if ($newkey =~ /^\d+:/) {
8368: $newkey =~ s/^(\d+)/$newid/;
8369: $translation{$1} = $newid;
8370: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
8371: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
8372: $translation{$1} = $newid;
8373: }
1.749 raeburn 8374: $new_values{$file_name."\0".$newkey} =
8375: $$changes{'activate'}{$newitems[$i]};
8376: $new_control{$newkey} = $now;
8377: }
8378: }
8379: }
8380: my %todelete;
8381: my %changed_items;
8382: foreach my $action ('delete','update') {
8383: if (exists($$changes{$action})) {
8384: if (ref($$changes{$action}) eq 'HASH') {
8385: foreach my $key (keys(%{$$changes{$action}})) {
8386: my ($itemnum) = ($key =~ /^([^:]+):/);
8387: if ($action eq 'delete') {
8388: $todelete{$itemnum} = 1;
8389: } else {
8390: $changed_items{$itemnum} = $key;
8391: }
8392: }
1.745 raeburn 8393: }
8394: }
1.749 raeburn 8395: }
8396: # get lock on access controls for file.
8397: my $lockhash = {
8398: $file_name."\0".'locked_access_records' => $env{'user.name'}.
8399: ':'.$env{'user.domain'},
8400: };
8401: my $tries = 0;
8402: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
8403:
8404: while (($gotlock ne 'ok') && $tries <3) {
8405: $tries ++;
8406: sleep 1;
8407: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
8408: }
8409: if ($gotlock eq 'ok') {
8410: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
8411: my ($tmp)=keys(%curr_permissions);
8412: if ($tmp=~/^error:/) { undef(%curr_permissions); }
8413: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
8414: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
8415: if (ref($curr_controls) eq 'HASH') {
8416: foreach my $control_item (keys(%{$curr_controls})) {
8417: my ($itemnum) = ($control_item =~ /^([^:]+):/);
8418: if (defined($todelete{$itemnum})) {
8419: push(@deletions,$file_name."\0".$control_item);
8420: } else {
8421: if (defined($changed_items{$itemnum})) {
8422: $new_control{$changed_items{$itemnum}} = $now;
8423: push(@deletions,$file_name."\0".$control_item);
8424: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
8425: } else {
8426: $new_control{$control_item} = $$curr_controls{$control_item};
8427: }
8428: }
1.745 raeburn 8429: }
8430: }
8431: }
1.970 raeburn 8432: my ($group);
8433: if (&is_course($domain,$user)) {
8434: ($group,my $file) = split(/\//,$file_name,2);
8435: }
1.749 raeburn 8436: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
8437: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
8438: $outcome = &put('file_permissions',\%new_values,$domain,$user);
8439: # remove lock
8440: my @del_lock = ($file_name."\0".'locked_access_records');
8441: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 8442: my $sqlresult =
1.970 raeburn 8443: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 8444: $group);
1.749 raeburn 8445: } else {
8446: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 8447: }
1.749 raeburn 8448: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 8449: }
8450:
1.827 raeburn 8451: sub make_public_indefinitely {
8452: my ($requrl) = @_;
8453: my $now = time;
8454: my $action = 'activate';
8455: my $aclnum = 0;
8456: if (&is_portfolio_url($requrl)) {
8457: my (undef,$udom,$unum,$file_name,$group) =
8458: &parse_portfolio_url($requrl);
8459: my $current_perms = &get_portfile_permissions($udom,$unum);
8460: my %access_controls = &get_access_controls($current_perms,
8461: $group,$file_name);
8462: foreach my $key (keys(%{$access_controls{$file_name}})) {
8463: my ($num,$scope,$end,$start) =
8464: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
8465: if ($scope eq 'public') {
8466: if ($start <= $now && $end == 0) {
8467: $action = 'none';
8468: } else {
8469: $action = 'update';
8470: $aclnum = $num;
8471: }
8472: last;
8473: }
8474: }
8475: if ($action eq 'none') {
8476: return 'ok';
8477: } else {
8478: my %changes;
8479: my $newend = 0;
8480: my $newstart = $now;
8481: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
8482: $changes{$action}{$newkey} = {
8483: type => 'public',
8484: time => {
8485: start => $newstart,
8486: end => $newend,
8487: },
8488: };
8489: my ($outcome,$deloutcome,$new_values,$translation) =
8490: &modify_access_controls($file_name,\%changes,$udom,$unum);
8491: return $outcome;
8492: }
8493: } else {
8494: return 'invalid';
8495: }
8496: }
8497:
1.745 raeburn 8498: #------------------------------------------------------Get Marked as Read Only
8499:
8500: sub get_marked_as_readonly {
8501: my ($domain,$user,$what,$group) = @_;
8502: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 8503: my @readonly_files;
1.629 banghart 8504: my $cmp1=$what;
8505: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 8506: while (my ($file_name,$value) = each(%{$current_permissions})) {
8507: if (defined($group)) {
8508: if ($file_name !~ m-^\Q$group\E/-) {
8509: next;
8510: }
8511: }
1.561 banghart 8512: if (ref($value) eq "ARRAY"){
8513: foreach my $stored_what (@{$value}) {
1.629 banghart 8514: my $cmp2=$stored_what;
1.759 albertel 8515: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 8516: $cmp2=join('',@{$stored_what});
1.745 raeburn 8517: }
1.629 banghart 8518: if ($cmp1 eq $cmp2) {
1.561 banghart 8519: push(@readonly_files, $file_name);
1.745 raeburn 8520: last;
1.563 banghart 8521: } elsif (!defined($what)) {
8522: push(@readonly_files, $file_name);
1.745 raeburn 8523: last;
1.561 banghart 8524: }
8525: }
1.745 raeburn 8526: }
1.561 banghart 8527: }
8528: return @readonly_files;
8529: }
1.577 banghart 8530: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 8531:
1.577 banghart 8532: sub get_marked_as_readonly_hash {
1.745 raeburn 8533: my ($current_permissions,$group,$what) = @_;
1.577 banghart 8534: my %readonly_files;
1.745 raeburn 8535: while (my ($file_name,$value) = each(%{$current_permissions})) {
8536: if (defined($group)) {
8537: if ($file_name !~ m-^\Q$group\E/-) {
8538: next;
8539: }
8540: }
1.577 banghart 8541: if (ref($value) eq "ARRAY"){
8542: foreach my $stored_what (@{$value}) {
1.745 raeburn 8543: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 8544: foreach my $lock_descriptor(@{$stored_what}) {
8545: if ($lock_descriptor eq 'graded') {
8546: $readonly_files{$file_name} = 'graded';
8547: } elsif ($lock_descriptor eq 'handback') {
8548: $readonly_files{$file_name} = 'handback';
8549: } else {
8550: if (!exists($readonly_files{$file_name})) {
8551: $readonly_files{$file_name} = 'locked';
8552: }
8553: }
1.745 raeburn 8554: }
1.750 banghart 8555: }
1.577 banghart 8556: }
8557: }
8558: }
8559: return %readonly_files;
8560: }
1.559 banghart 8561: # ------------------------------------------------------------ Unmark as Read Only
8562:
8563: sub unmark_as_readonly {
1.629 banghart 8564: # unmarks $file_name (if $file_name is defined), or all files locked by $what
8565: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 8566: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 8567: $file_name = &declutter_portfile($file_name);
1.634 albertel 8568: my $symb_crs = $what;
8569: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 8570: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 8571: my ($tmp)=keys(%current_permissions);
8572: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 8573: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 8574: foreach my $file (@readonly_files) {
1.759 albertel 8575: my $clean_file = &declutter_portfile($file);
8576: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 8577: my $current_locks = $current_permissions{$file};
1.563 banghart 8578: my @new_locks;
8579: my @del_keys;
8580: if (ref($current_locks) eq "ARRAY"){
8581: foreach my $locker (@{$current_locks}) {
1.632 albertel 8582: my $compare=$locker;
1.749 raeburn 8583: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 8584: $compare=join('',@{$locker});
1.746 raeburn 8585: if ($compare ne $symb_crs) {
8586: push(@new_locks, $locker);
8587: }
1.563 banghart 8588: }
8589: }
1.650 albertel 8590: if (scalar(@new_locks) > 0) {
1.563 banghart 8591: $current_permissions{$file} = \@new_locks;
8592: } else {
8593: push(@del_keys, $file);
1.613 albertel 8594: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 8595: delete($current_permissions{$file});
1.563 banghart 8596: }
8597: }
1.561 banghart 8598: }
1.613 albertel 8599: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 8600: return;
8601: }
1.512 banghart 8602:
1.17 www 8603: # ------------------------------------------------------------ Directory lister
8604:
8605: sub dirlist {
1.955 raeburn 8606: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 8607: $uri=~s/^\///;
8608: $uri=~s/\/$//;
1.253 stredwic 8609: my ($udom, $uname);
1.955 raeburn 8610: if ($getuserdir) {
1.253 stredwic 8611: $udom = $userdomain;
8612: $uname = $username;
1.955 raeburn 8613: } else {
8614: (undef,$udom,$uname)=split(/\//,$uri);
8615: if(defined($userdomain)) {
8616: $udom = $userdomain;
8617: }
8618: if(defined($username)) {
8619: $uname = $username;
8620: }
1.253 stredwic 8621: }
1.955 raeburn 8622: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 8623:
1.955 raeburn 8624: $dirRoot = $perlvar{'lonDocRoot'};
8625: if (defined($getpropath)) {
8626: $dirRoot = &propath($udom,$uname);
1.253 stredwic 8627: $dirRoot =~ s/\/$//;
1.955 raeburn 8628: } elsif (defined($getuserdir)) {
8629: my $subdir=$uname.'__';
8630: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
8631: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
8632: ."/$udom/$subdir/$uname";
8633: } elsif (defined($alternateRoot)) {
8634: $dirRoot = $alternateRoot;
1.751 banghart 8635: }
1.253 stredwic 8636:
8637: if($udom) {
8638: if($uname) {
1.1135 raeburn 8639: my $uhome = &homeserver($uname,$udom);
1.1136 raeburn 8640: if ($uhome eq 'no_host') {
8641: return ([],'no_host');
8642: }
1.955 raeburn 8643: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 8644: .$getuserdir.':'.&escape($dirRoot)
1.1135 raeburn 8645: .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955 raeburn 8646: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 8647: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955 raeburn 8648: } else {
8649: @listing_results = map { &unescape($_); } split(/:/,$listing);
8650: }
1.605 matthew 8651: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 8652: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605 matthew 8653: @listing_results = split(/:/,$listing);
8654: } else {
8655: @listing_results = map { &unescape($_); } split(/:/,$listing);
8656: }
1.1135 raeburn 8657: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
1.1136 raeburn 8658: ($listing eq 'rejected') || ($listing eq 'refused') ||
8659: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
8660: return ([],$listing);
8661: } else {
8662: return (\@listing_results);
1.1135 raeburn 8663: }
1.955 raeburn 8664: } elsif(!$alternateRoot) {
1.1136 raeburn 8665: my (%allusers,%listerror);
1.841 albertel 8666: my %servers = &get_servers($udom,'library');
1.955 raeburn 8667: foreach my $tryserver (keys(%servers)) {
8668: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
8669: &escape($udom),$tryserver);
8670: if ($listing eq 'unknown_cmd') {
8671: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
8672: $udom, $tryserver);
8673: } else {
8674: @listing_results = map { &unescape($_); } split(/:/,$listing);
8675: }
1.841 albertel 8676: if ($listing eq 'unknown_cmd') {
8677: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
8678: $udom, $tryserver);
8679: @listing_results = split(/:/,$listing);
8680: } else {
8681: @listing_results =
8682: map { &unescape($_); } split(/:/,$listing);
8683: }
1.1136 raeburn 8684: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
8685: ($listing eq 'rejected') || ($listing eq 'refused') ||
8686: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
8687: $listerror{$tryserver} = $listing;
8688: } else {
1.841 albertel 8689: foreach my $line (@listing_results) {
8690: my ($entry) = split(/&/,$line,2);
8691: $allusers{$entry} = 1;
8692: }
8693: }
1.253 stredwic 8694: }
1.1136 raeburn 8695: my @alluserslist=();
1.800 albertel 8696: foreach my $user (sort(keys(%allusers))) {
1.1136 raeburn 8697: push(@alluserslist,$user.'&user');
1.253 stredwic 8698: }
1.1136 raeburn 8699: return (\@alluserslist);
1.253 stredwic 8700: } else {
1.1136 raeburn 8701: return ([],'missing username');
1.253 stredwic 8702: }
1.955 raeburn 8703: } elsif(!defined($getpropath)) {
1.1136 raeburn 8704: my $path = $perlvar{'lonDocRoot'}.'/res/';
8705: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
8706: return (\@all_domains);
1.955 raeburn 8707: } else {
1.1136 raeburn 8708: return ([],'missing domain');
1.275 stredwic 8709: }
8710: }
8711:
8712: # --------------------------------------------- GetFileTimestamp
8713: # This function utilizes dirlist and returns the date stamp for
8714: # when it was last modified. It will also return an error of -1
8715: # if an error occurs
8716:
8717: sub GetFileTimestamp {
1.955 raeburn 8718: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 8719: $studentDomain = &LONCAPA::clean_domain($studentDomain);
8720: $studentName = &LONCAPA::clean_username($studentName);
1.1136 raeburn 8721: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
8722: undef,$getuserdir);
8723: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
8724: return -1;
8725: }
8726: if (ref($fileref) eq 'ARRAY') {
8727: my @stats = split('&',$fileref->[0]);
1.375 matthew 8728: # @stats contains first the filename, then the stat output
8729: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 8730: } else {
8731: return -1;
1.253 stredwic 8732: }
1.26 www 8733: }
8734:
1.712 albertel 8735: sub stat_file {
8736: my ($uri) = @_;
1.787 albertel 8737: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 8738:
1.955 raeburn 8739: my ($udom,$uname,$file);
1.712 albertel 8740: if ($uri =~ m-^/(uploaded|editupload)/-) {
8741: ($udom,$uname,$file) =
1.811 albertel 8742: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 8743: $file = 'userfiles/'.$file;
8744: }
8745: if ($uri =~ m-^/res/-) {
8746: ($udom,$uname) =
1.807 albertel 8747: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 8748: $file = $uri;
8749: }
8750:
8751: if (!$udom || !$uname || !$file) {
8752: # unable to handle the uri
8753: return ();
8754: }
1.956 raeburn 8755: my $getpropath;
8756: if ($file =~ /^userfiles\//) {
8757: $getpropath = 1;
8758: }
1.1136 raeburn 8759: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
8760: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
8761: return ();
8762: } else {
8763: if (ref($listref) eq 'ARRAY') {
8764: my @stats = split('&',$listref->[0]);
8765: shift(@stats); #filename is first
8766: return @stats;
8767: }
1.712 albertel 8768: }
8769: return ();
8770: }
8771:
1.26 www 8772: # -------------------------------------------------------- Value of a Condition
8773:
1.713 albertel 8774: # gets the value of a specific preevaluated condition
8775: # stored in the string $env{user.state.<cid>}
8776: # or looks up a condition reference in the bighash and if if hasn't
8777: # already been evaluated recurses into docondval to get the value of
8778: # the condition, then memoizing it to
8779: # $env{user.state.<cid>.<condition>}
1.40 www 8780: sub directcondval {
8781: my $number=shift;
1.620 albertel 8782: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 8783: &Apache::lonuserstate::evalstate();
8784: }
1.713 albertel 8785: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
8786: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
8787: } elsif ($number =~ /^_/) {
8788: my $sub_condition;
8789: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
8790: &GDBM_READER(),0640)) {
8791: $sub_condition=$bighash{'conditions'.$number};
8792: untie(%bighash);
8793: }
8794: my $value = &docondval($sub_condition);
1.949 raeburn 8795: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 8796: return $value;
8797: }
1.620 albertel 8798: if ($env{'user.state.'.$env{'request.course.id'}}) {
8799: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 8800: } else {
8801: return 2;
8802: }
8803: }
8804:
1.713 albertel 8805: # get the collection of conditions for this resource
1.26 www 8806: sub condval {
8807: my $condidx=shift;
1.54 www 8808: my $allpathcond='';
1.713 albertel 8809: foreach my $cond (split(/\|/,$condidx)) {
8810: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
8811: $allpathcond.=
8812: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
8813: }
1.191 harris41 8814: }
1.54 www 8815: $allpathcond=~s/\|$//;
1.713 albertel 8816: return &docondval($allpathcond);
8817: }
8818:
8819: #evaluates an expression of conditions
8820: sub docondval {
8821: my ($allpathcond) = @_;
8822: my $result=0;
8823: if ($env{'request.course.id'}
8824: && defined($allpathcond)) {
8825: my $operand='|';
8826: my @stack;
8827: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
8828: if ($chunk eq '(') {
8829: push @stack,($operand,$result);
8830: } elsif ($chunk eq ')') {
8831: my $before=pop @stack;
8832: if (pop @stack eq '&') {
8833: $result=$result>$before?$before:$result;
8834: } else {
8835: $result=$result>$before?$result:$before;
8836: }
8837: } elsif (($chunk eq '&') || ($chunk eq '|')) {
8838: $operand=$chunk;
8839: } else {
8840: my $new=directcondval($chunk);
8841: if ($operand eq '&') {
8842: $result=$result>$new?$new:$result;
8843: } else {
8844: $result=$result>$new?$result:$new;
8845: }
8846: }
8847: }
1.26 www 8848: }
8849: return $result;
1.421 albertel 8850: }
8851:
8852: # ---------------------------------------------------- Devalidate courseresdata
8853:
8854: sub devalidatecourseresdata {
8855: my ($coursenum,$coursedomain)=@_;
8856: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 8857: &devalidate_cache_new('courseres',$hashid);
1.28 www 8858: }
8859:
1.763 www 8860:
1.200 www 8861: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 8862: #
8863: # Parameters:
8864: # $coursenum - Number of the course.
8865: # $coursedomain - Domain at which the course was created.
8866: # Returns:
8867: # A hash of the course parameters along (I think) with timestamps
8868: # and version info.
1.877 foxr 8869:
1.624 albertel 8870: sub get_courseresdata {
8871: my ($coursenum,$coursedomain)=@_;
1.200 www 8872: my $coursehom=&homeserver($coursenum,$coursedomain);
8873: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 8874: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 8875: my %dumpreply;
1.417 albertel 8876: unless (defined($cached)) {
1.624 albertel 8877: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 8878: $result=\%dumpreply;
1.251 albertel 8879: my ($tmp) = keys(%dumpreply);
8880: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 8881: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 8882: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
8883: return $tmp;
1.416 albertel 8884: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 8885: $result=undef;
1.599 albertel 8886: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 8887: }
8888: }
1.624 albertel 8889: return $result;
8890: }
8891:
1.633 albertel 8892: sub devalidateuserresdata {
8893: my ($uname,$udom)=@_;
8894: my $hashid="$udom:$uname";
8895: &devalidate_cache_new('userres',$hashid);
8896: }
8897:
1.624 albertel 8898: sub get_userresdata {
8899: my ($uname,$udom)=@_;
8900: #most student don\'t have any data set, check if there is some data
8901: if (&EXT_cache_status($udom,$uname)) { return undef; }
8902:
8903: my $hashid="$udom:$uname";
8904: my ($result,$cached)=&is_cached_new('userres',$hashid);
8905: if (!defined($cached)) {
8906: my %resourcedata=&dump('resourcedata',$udom,$uname);
8907: $result=\%resourcedata;
8908: &do_cache_new('userres',$hashid,$result,600);
8909: }
8910: my ($tmp)=keys(%$result);
8911: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
8912: return $result;
8913: }
8914: #error 2 occurs when the .db doesn't exist
8915: if ($tmp!~/error: 2 /) {
1.672 albertel 8916: &logthis("<font color=\"blue\">WARNING:".
1.624 albertel 8917: " Trying to get resource data for ".
8918: $uname." at ".$udom.": ".
8919: $tmp."</font>");
8920: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 8921: #&EXT_cache_set($udom,$uname);
8922: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 8923: undef($tmp); # not really an error so don't send it back
1.624 albertel 8924: }
8925: return $tmp;
8926: }
1.879 foxr 8927: #----------------------------------------------- resdata - return resource data
8928: # Purpose:
8929: # Return resource data for either users or for a course.
8930: # Parameters:
8931: # $name - Course/user name.
8932: # $domain - Name of the domain the user/course is registered on.
8933: # $type - Type of thing $name is (must be 'course' or 'user'
8934: # @which - Array of names of resources desired.
8935: # Returns:
8936: # The value of the first reasource in @which that is found in the
8937: # resource hash.
8938: # Exceptional Conditions:
8939: # If the $type passed in is not valid (not the string 'course' or
8940: # 'user', an undefined reference is returned.
8941: # If none of the resources are found, an undef is returned
1.624 albertel 8942: sub resdata {
8943: my ($name,$domain,$type,@which)=@_;
8944: my $result;
8945: if ($type eq 'course') {
8946: $result=&get_courseresdata($name,$domain);
8947: } elsif ($type eq 'user') {
8948: $result=&get_userresdata($name,$domain);
8949: }
8950: if (!ref($result)) { return $result; }
1.251 albertel 8951: foreach my $item (@which) {
1.927 albertel 8952: if (defined($result->{$item->[0]})) {
8953: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 8954: }
1.250 albertel 8955: }
1.291 albertel 8956: return undef;
1.200 www 8957: }
8958:
1.379 matthew 8959: #
8960: # EXT resource caching routines
8961: #
8962:
8963: sub clear_EXT_cache_status {
1.383 albertel 8964: &delenv('cache.EXT.');
1.379 matthew 8965: }
8966:
8967: sub EXT_cache_status {
8968: my ($target_domain,$target_user) = @_;
1.383 albertel 8969: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 8970: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 8971: # We know already the user has no data
8972: return 1;
8973: } else {
8974: return 0;
8975: }
8976: }
8977:
8978: sub EXT_cache_set {
8979: my ($target_domain,$target_user) = @_;
1.383 albertel 8980: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 8981: #&appenv({$cachename => time});
1.379 matthew 8982: }
8983:
1.28 www 8984: # --------------------------------------------------------- Value of a Variable
1.58 www 8985: sub EXT {
1.715 albertel 8986:
1.395 albertel 8987: my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68 www 8988: unless ($varname) { return ''; }
1.218 albertel 8989: #get real user name/domain, courseid and symb
8990: my $courseid;
1.359 albertel 8991: my $publicuser;
1.427 www 8992: if ($symbparm) {
8993: $symbparm=&get_symb_from_alias($symbparm);
8994: }
1.218 albertel 8995: if (!($uname && $udom)) {
1.790 albertel 8996: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 8997: if (!$symbparm) { $symbparm=$cursymb; }
8998: } else {
1.620 albertel 8999: $courseid=$env{'request.course.id'};
1.218 albertel 9000: }
1.48 www 9001: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
9002: my $rest;
1.320 albertel 9003: if (defined($therest[0])) {
1.48 www 9004: $rest=join('.',@therest);
9005: } else {
9006: $rest='';
9007: }
1.320 albertel 9008:
1.57 www 9009: my $qualifierrest=$qualifier;
9010: if ($rest) { $qualifierrest.='.'.$rest; }
9011: my $spacequalifierrest=$space;
9012: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 9013: if ($realm eq 'user') {
1.48 www 9014: # --------------------------------------------------------------- user.resource
9015: if ($space eq 'resource') {
1.651 albertel 9016: if ( (defined($Apache::lonhomework::parsing_a_problem)
9017: || defined($Apache::lonhomework::parsing_a_task))
9018: &&
1.744 albertel 9019: ($symbparm eq &symbread()) ) {
9020: # if we are in the middle of processing the resource the
9021: # get the value we are planning on committing
9022: if (defined($Apache::lonhomework::results{$qualifierrest})) {
9023: return $Apache::lonhomework::results{$qualifierrest};
9024: } else {
9025: return $Apache::lonhomework::history{$qualifierrest};
9026: }
1.335 albertel 9027: } else {
1.359 albertel 9028: my %restored;
1.620 albertel 9029: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 9030: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
9031: } else {
9032: %restored=&restore($symbparm,$courseid,$udom,$uname);
9033: }
1.335 albertel 9034: return $restored{$qualifierrest};
9035: }
1.48 www 9036: # ----------------------------------------------------------------- user.access
9037: } elsif ($space eq 'access') {
1.218 albertel 9038: # FIXME - not supporting calls for a specific user
1.48 www 9039: return &allowed($qualifier,$rest);
9040: # ------------------------------------------ user.preferences, user.environment
9041: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 9042: if (($uname eq $env{'user.name'}) &&
9043: ($udom eq $env{'user.domain'})) {
9044: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 9045: } else {
1.359 albertel 9046: my %returnhash;
9047: if (!$publicuser) {
9048: %returnhash=&userenvironment($udom,$uname,
9049: $qualifierrest);
9050: }
1.218 albertel 9051: return $returnhash{$qualifierrest};
9052: }
1.48 www 9053: # ----------------------------------------------------------------- user.course
9054: } elsif ($space eq 'course') {
1.218 albertel 9055: # FIXME - not supporting calls for a specific user
1.620 albertel 9056: return $env{join('.',('request.course',$qualifier))};
1.48 www 9057: # ------------------------------------------------------------------- user.role
9058: } elsif ($space eq 'role') {
1.218 albertel 9059: # FIXME - not supporting calls for a specific user
1.620 albertel 9060: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 9061: if ($qualifier eq 'value') {
9062: return $role;
9063: } elsif ($qualifier eq 'extent') {
9064: return $where;
9065: }
9066: # ----------------------------------------------------------------- user.domain
9067: } elsif ($space eq 'domain') {
1.218 albertel 9068: return $udom;
1.48 www 9069: # ------------------------------------------------------------------- user.name
9070: } elsif ($space eq 'name') {
1.218 albertel 9071: return $uname;
1.48 www 9072: # ---------------------------------------------------- Any other user namespace
1.29 www 9073: } else {
1.359 albertel 9074: my %reply;
9075: if (!$publicuser) {
9076: %reply=&get($space,[$qualifierrest],$udom,$uname);
9077: }
9078: return $reply{$qualifierrest};
1.48 www 9079: }
1.236 www 9080: } elsif ($realm eq 'query') {
9081: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 9082: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
9083: [$spacequalifierrest]);
1.620 albertel 9084: return $env{'form.'.$spacequalifierrest};
1.236 www 9085: } elsif ($realm eq 'request') {
1.48 www 9086: # ------------------------------------------------------------- request.browser
9087: if ($space eq 'browser') {
1.1145 bisitz 9088: return $env{'browser.'.$qualifier};
1.57 www 9089: # ------------------------------------------------------------ request.filename
9090: } else {
1.620 albertel 9091: return $env{'request.'.$spacequalifierrest};
1.29 www 9092: }
1.28 www 9093: } elsif ($realm eq 'course') {
1.48 www 9094: # ---------------------------------------------------------- course.description
1.620 albertel 9095: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 9096: } elsif ($realm eq 'resource') {
1.165 www 9097:
1.620 albertel 9098: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 9099: if (!$symbparm) { $symbparm=&symbread(); }
9100: }
1.693 albertel 9101:
9102: if ($space eq 'title') {
9103: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
9104: return &gettitle($symbparm);
9105: }
9106:
9107: if ($space eq 'map') {
9108: my ($map) = &decode_symb($symbparm);
9109: return &symbread($map);
9110: }
1.905 albertel 9111: if ($space eq 'filename') {
9112: if ($symbparm) {
9113: return &clutter((&decode_symb($symbparm))[2]);
9114: }
9115: return &hreflocation('',$env{'request.filename'});
9116: }
1.693 albertel 9117:
9118: my ($section, $group, @groups);
1.593 albertel 9119: my ($courselevelm,$courselevel);
1.539 albertel 9120: if ($symbparm && defined($courseid) &&
1.620 albertel 9121: $courseid eq $env{'request.course.id'}) {
1.165 www 9122:
1.218 albertel 9123: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 9124:
1.60 www 9125: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 9126: my $symbp=$symbparm;
1.735 albertel 9127: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 9128:
9129: my $symbparm=$symbp.'.'.$spacequalifierrest;
9130: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
9131:
1.620 albertel 9132: if (($env{'user.name'} eq $uname) &&
9133: ($env{'user.domain'} eq $udom)) {
9134: $section=$env{'request.course.sec'};
1.733 raeburn 9135: @groups = split(/:/,$env{'request.course.groups'});
9136: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 9137: } else {
1.539 albertel 9138: if (! defined($usection)) {
1.551 albertel 9139: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 9140: } else {
9141: $section = $usection;
9142: }
1.733 raeburn 9143: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 9144: }
9145:
9146: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
9147: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
9148: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
9149:
1.593 albertel 9150: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 9151: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 9152: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 9153:
1.60 www 9154: # ----------------------------------------------------------- first, check user
1.624 albertel 9155:
9156: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 9157: ([$courselevelr,'resource'],
9158: [$courselevelm,'map' ],
9159: [$courselevel, 'course' ]));
1.931 albertel 9160: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 9161:
1.594 albertel 9162: # ------------------------------------------------ second, check some of course
1.684 raeburn 9163: my $coursereply;
1.691 raeburn 9164: if (@groups > 0) {
9165: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
9166: $mapparm,$spacequalifierrest);
1.927 albertel 9167: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 9168: }
1.96 www 9169:
1.684 raeburn 9170: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 9171: $env{'course.'.$courseid.'.domain'},
9172: 'course',
9173: ([$seclevelr, 'resource'],
9174: [$seclevelm, 'map' ],
9175: [$seclevel, 'course' ],
9176: [$courselevelr,'resource']));
9177: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 9178:
1.60 www 9179: # ------------------------------------------------------ third, check map parms
1.218 albertel 9180: my %parmhash=();
9181: my $thisparm='';
9182: if (tie(%parmhash,'GDBM_File',
1.620 albertel 9183: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 9184: &GDBM_READER(),0640)) {
1.218 albertel 9185: $thisparm=$parmhash{$symbparm};
9186: untie(%parmhash);
9187: }
1.927 albertel 9188: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 9189: }
1.594 albertel 9190: # ------------------------------------------ fourth, look in resource metadata
1.71 www 9191:
1.218 albertel 9192: $spacequalifierrest=~s/\./\_/;
1.282 albertel 9193: my $filename;
9194: if (!$symbparm) { $symbparm=&symbread(); }
9195: if ($symbparm) {
1.409 www 9196: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 9197: } else {
1.620 albertel 9198: $filename=$env{'request.filename'};
1.282 albertel 9199: }
9200: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 9201: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 9202: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 9203: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 9204:
1.927 albertel 9205: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 9206: if ($symbparm && defined($courseid) &&
1.620 albertel 9207: $courseid eq $env{'request.course.id'}) {
1.624 albertel 9208: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
9209: $env{'course.'.$courseid.'.domain'},
9210: 'course',
1.927 albertel 9211: ([$courselevelm,'map' ],
9212: [$courselevel, 'course']));
9213: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 9214: }
1.145 www 9215: # ------------------------------------------------------------------ Cascade up
1.218 albertel 9216: unless ($space eq '0') {
1.336 albertel 9217: my @parts=split(/_/,$space);
9218: my $id=pop(@parts);
9219: my $part=join('_',@parts);
9220: if ($part eq '') { $part='0'; }
1.927 albertel 9221: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 9222: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 9223: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 9224: }
1.395 albertel 9225: if ($recurse) { return undef; }
9226: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 9227: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 9228: # ---------------------------------------------------- Any other user namespace
9229: } elsif ($realm eq 'environment') {
9230: # ----------------------------------------------------------------- environment
1.620 albertel 9231: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
9232: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 9233: } else {
1.770 albertel 9234: if ($uname eq 'anonymous' && $udom eq '') {
9235: return '';
9236: }
1.219 albertel 9237: my %returnhash=&userenvironment($udom,$uname,
9238: $spacequalifierrest);
9239: return $returnhash{$spacequalifierrest};
9240: }
1.28 www 9241: } elsif ($realm eq 'system') {
1.48 www 9242: # ----------------------------------------------------------------- system.time
9243: if ($space eq 'time') {
9244: return time;
9245: }
1.696 albertel 9246: } elsif ($realm eq 'server') {
9247: # ----------------------------------------------------------------- system.time
9248: if ($space eq 'name') {
9249: return $ENV{'SERVER_NAME'};
9250: }
1.28 www 9251: }
1.48 www 9252: return '';
1.61 www 9253: }
9254:
1.927 albertel 9255: sub get_reply {
9256: my ($reply_value) = @_;
1.940 raeburn 9257: if (ref($reply_value) eq 'ARRAY') {
9258: if (wantarray) {
9259: return @$reply_value;
9260: }
9261: return $reply_value->[0];
9262: } else {
9263: return $reply_value;
1.927 albertel 9264: }
9265: }
9266:
1.691 raeburn 9267: sub check_group_parms {
9268: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
9269: my @groupitems = ();
9270: my $resultitem;
1.927 albertel 9271: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 9272: foreach my $group (@{$groups}) {
9273: foreach my $level (@levels) {
1.927 albertel 9274: my $item = $courseid.'.['.$group.'].'.$level->[0];
9275: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 9276: }
9277: }
9278: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
9279: $env{'course.'.$courseid.'.domain'},
9280: 'course',@groupitems);
9281: return $coursereply;
9282: }
9283:
9284: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 9285: my ($courseid,@groups) = @_;
9286: @groups = sort(@groups);
1.691 raeburn 9287: return @groups;
9288: }
9289:
1.395 albertel 9290: sub packages_tab_default {
9291: my ($uri,$varname)=@_;
9292: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 9293:
9294: my (@extension,@specifics,$do_default);
9295: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 9296: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 9297: if ($pack_type eq 'default') {
9298: $do_default=1;
9299: } elsif ($pack_type eq 'extension') {
9300: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 9301: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 9302: # only look at packages defaults for packages that this id is
1.738 albertel 9303: push(@specifics,[$package,$pack_type,$pack_part]);
9304: }
9305: }
9306: # first look for a package that matches the requested part id
9307: foreach my $package (@specifics) {
9308: my (undef,$pack_type,$pack_part)=@{$package};
9309: next if ($pack_part ne $part);
9310: if (defined($packagetab{"$pack_type&$name&default"})) {
9311: return $packagetab{"$pack_type&$name&default"};
9312: }
9313: }
9314: # look for any possible matching non extension_ package
9315: foreach my $package (@specifics) {
9316: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 9317: if (defined($packagetab{"$pack_type&$name&default"})) {
9318: return $packagetab{"$pack_type&$name&default"};
9319: }
1.585 albertel 9320: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 9321: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
9322: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 9323: }
9324: }
1.738 albertel 9325: # look for any posible extension_ match
9326: foreach my $package (@extension) {
9327: my ($package,$pack_type)=@{$package};
9328: if (defined($packagetab{"$pack_type&$name&default"})) {
9329: return $packagetab{"$pack_type&$name&default"};
9330: }
9331: if (defined($packagetab{$package."&$name&default"})) {
9332: return $packagetab{$package."&$name&default"};
9333: }
9334: }
9335: # look for a global default setting
9336: if ($do_default && defined($packagetab{"default&$name&default"})) {
9337: return $packagetab{"default&$name&default"};
9338: }
1.395 albertel 9339: return undef;
9340: }
9341:
1.334 albertel 9342: sub add_prefix_and_part {
9343: my ($prefix,$part)=@_;
9344: my $keyroot;
9345: if (defined($prefix) && $prefix !~ /^__/) {
9346: # prefix that has a part already
9347: $keyroot=$prefix;
9348: } elsif (defined($prefix)) {
9349: # prefix that is missing a part
9350: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
9351: } else {
9352: # no prefix at all
9353: if (defined($part)) { $keyroot='_'.$part; }
9354: }
9355: return $keyroot;
9356: }
9357:
1.71 www 9358: # ---------------------------------------------------------------- Get metadata
9359:
1.599 albertel 9360: my %metaentry;
1.1070 www 9361: my %importedpartids;
1.71 www 9362: sub metadata {
1.176 www 9363: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 9364: $uri=&declutter($uri);
1.288 albertel 9365: # if it is a non metadata possible uri return quickly
1.529 albertel 9366: if (($uri eq '') ||
9367: (($uri =~ m|^/*adm/|) &&
1.698 albertel 9368: ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.1108 raeburn 9369: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 9370: return undef;
9371: }
1.1140 www 9372: if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/)
1.924 albertel 9373: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 9374: return undef;
1.288 albertel 9375: }
1.73 www 9376: my $filename=$uri;
9377: $uri=~s/\.meta$//;
1.172 www 9378: #
9379: # Is the metadata already cached?
1.177 www 9380: # Look at timestamp of caching
1.172 www 9381: # Everything is cached by the main uri, libraries are never directly cached
9382: #
1.428 albertel 9383: if (!defined($liburi)) {
1.599 albertel 9384: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 9385: if (defined($cached)) { return $result->{':'.$what}; }
9386: }
9387: {
1.1069 www 9388: # Imported parts would go here
1.1070 www 9389: my %importedids=();
9390: my @origfileimportpartids=();
1.1069 www 9391: my $importedparts=0;
1.172 www 9392: #
9393: # Is this a recursive call for a library?
9394: #
1.599 albertel 9395: # if (! exists($metacache{$uri})) {
9396: # $metacache{$uri}={};
9397: # }
1.924 albertel 9398: my $cachetime = 60*60;
1.171 www 9399: if ($liburi) {
9400: $liburi=&declutter($liburi);
9401: $filename=$liburi;
1.401 bowersj2 9402: } else {
1.599 albertel 9403: &devalidate_cache_new('meta',$uri);
9404: undef(%metaentry);
1.401 bowersj2 9405: }
1.140 www 9406: my %metathesekeys=();
1.73 www 9407: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 9408: my $metastring;
1.1140 www 9409: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929 albertel 9410: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 9411: $metastring =
1.929 albertel 9412: &Apache::lonnet::ssi_body($which,
1.924 albertel 9413: ('grade_target' => 'meta'));
9414: $cachetime = 1; # only want this cached in the child not long term
1.1108 raeburn 9415: } elsif (($uri !~ m -^(editupload)/-) &&
9416: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 9417: my $file=&filelocation('',&clutter($filename));
1.599 albertel 9418: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 9419: $metastring=&getfile($file);
1.489 albertel 9420: }
1.208 albertel 9421: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 9422: my $token;
1.140 www 9423: undef %metathesekeys;
1.71 www 9424: while ($token=$parser->get_token) {
1.339 albertel 9425: if ($token->[0] eq 'S') {
9426: if (defined($token->[2]->{'package'})) {
1.172 www 9427: #
9428: # This is a package - get package info
9429: #
1.339 albertel 9430: my $package=$token->[2]->{'package'};
9431: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
9432: if (defined($token->[2]->{'id'})) {
9433: $keyroot.='_'.$token->[2]->{'id'};
9434: }
1.599 albertel 9435: if ($metaentry{':packages'}) {
9436: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 9437: } else {
1.599 albertel 9438: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 9439: }
1.736 albertel 9440: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 9441: my $part=$keyroot;
9442: $part=~s/^\_//;
1.736 albertel 9443: if ($pack_entry=~/^\Q$package\E\&/ ||
9444: $pack_entry=~/^\Q$package\E_0\&/) {
9445: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 9446: # ignore package.tab specified default values
9447: # here &package_tab_default() will fetch those
9448: if ($subp eq 'default') { next; }
1.736 albertel 9449: my $value=$packagetab{$pack_entry};
1.432 albertel 9450: my $unikey;
9451: if ($pack =~ /_0$/) {
9452: $unikey='parameter_0_'.$name;
9453: $part=0;
9454: } else {
9455: $unikey='parameter'.$keyroot.'_'.$name;
9456: }
1.339 albertel 9457: if ($subp eq 'display') {
9458: $value.=' [Part: '.$part.']';
9459: }
1.599 albertel 9460: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 9461: $metathesekeys{$unikey}=1;
1.599 albertel 9462: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
9463: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 9464: }
1.599 albertel 9465: if (defined($metaentry{':'.$unikey.'.default'})) {
9466: $metaentry{':'.$unikey}=
9467: $metaentry{':'.$unikey.'.default'};
1.356 albertel 9468: }
1.339 albertel 9469: }
9470: }
9471: } else {
1.172 www 9472: #
9473: # This is not a package - some other kind of start tag
1.339 albertel 9474: #
9475: my $entry=$token->[1];
1.1068 www 9476: my $unikey='';
1.175 www 9477:
1.339 albertel 9478: if ($entry eq 'import') {
1.175 www 9479: #
9480: # Importing a library here
1.339 albertel 9481: #
1.1067 www 9482: my $location=$parser->get_text('/import');
9483: my $dir=$filename;
9484: $dir=~s|[^/]*$||;
9485: $location=&filelocation($dir,$location);
1.1069 www 9486:
1.1068 www 9487: my $importmode=$token->[2]->{'importmode'};
9488: if ($importmode eq 'problem') {
1.1069 www 9489: # Import as problem/response
1.1068 www 9490: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
9491: } elsif ($importmode eq 'part') {
9492: # Import as part(s)
1.1069 www 9493: $importedparts=1;
9494: # We need to get the original file and the imported file to get the part order correct
9495: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
9496: # Load and inspect original file
1.1070 www 9497: if ($#origfileimportpartids<0) {
9498: undef(%importedpartids);
9499: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
9500: my $origfile=&getfile($origfilelocation);
9501: @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
9502: }
9503:
1.1069 www 9504: # Load and inspect imported file
9505: my $impfile=&getfile($location);
9506: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
9507: if ($#impfilepartids>=0) {
9508: # This problem had parts
1.1070 www 9509: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 9510: } else {
9511: # Importing by turning a single problem into a problem part
9512: # It gets the import-tags ID as part-ID
9513: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 9514: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 9515: }
1.1068 www 9516: } else {
9517: # Normal import
9518: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
9519: if (defined($token->[2]->{'id'})) {
9520: $unikey.='_'.$token->[2]->{'id'};
9521: }
1.1067 www 9522: }
9523:
1.339 albertel 9524: if ($depthcount<20) {
1.736 albertel 9525: my $metadata =
9526: &metadata($uri,'keys', $location,$unikey,
9527: $depthcount+1);
9528: foreach my $meta (split(',',$metadata)) {
9529: $metaentry{':'.$meta}=$metaentry{':'.$meta};
9530: $metathesekeys{$meta}=1;
1.339 albertel 9531: }
1.1068 www 9532:
9533: }
1.1067 www 9534: } else {
9535: #
9536: # Not importing, some other kind of non-package, non-library start tag
9537: #
9538: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
9539: if (defined($token->[2]->{'id'})) {
9540: $unikey.='_'.$token->[2]->{'id'};
9541: }
1.339 albertel 9542: if (defined($token->[2]->{'name'})) {
9543: $unikey.='_'.$token->[2]->{'name'};
9544: }
9545: $metathesekeys{$unikey}=1;
1.736 albertel 9546: foreach my $param (@{$token->[3]}) {
9547: $metaentry{':'.$unikey.'.'.$param} =
9548: $token->[2]->{$param};
1.339 albertel 9549: }
9550: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 9551: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 9552: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
9553: # only ws inside the tag, and not in default, so use default
9554: # as value
1.599 albertel 9555: $metaentry{':'.$unikey}=$default;
1.908 albertel 9556: } elsif ( $internaltext =~ /\S/ ) {
9557: # something interesting inside the tag
9558: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 9559: } else {
1.908 albertel 9560: # no interesting values, don't set a default
1.339 albertel 9561: }
1.172 www 9562: # end of not-a-package not-a-library import
1.339 albertel 9563: }
1.172 www 9564: # end of not-a-package start tag
1.339 albertel 9565: }
1.172 www 9566: # the next is the end of "start tag"
1.339 albertel 9567: }
9568: }
1.483 albertel 9569: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 9570: $extension = lc($extension);
9571: if ($extension eq 'htm') { $extension='html'; }
9572:
1.737 albertel 9573: foreach my $key (keys(%packagetab)) {
1.483 albertel 9574: #no specific packages #how's our extension
9575: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 9576: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 9577: \%metathesekeys);
9578: }
1.883 albertel 9579:
9580: if (!exists($metaentry{':packages'})
9581: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 9582: foreach my $key (keys(%packagetab)) {
1.483 albertel 9583: #no specific packages well let's get default then
9584: if ($key!~/^default&/) { next; }
1.488 albertel 9585: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 9586: \%metathesekeys);
9587: }
9588: }
1.338 www 9589: # are there custom rights to evaluate
1.599 albertel 9590: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 9591:
1.338 www 9592: #
9593: # Importing a rights file here
1.339 albertel 9594: #
9595: unless ($depthcount) {
1.599 albertel 9596: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 9597: my $dir=$filename;
9598: $dir=~s|[^/]*$||;
9599: $location=&filelocation($dir,$location);
1.736 albertel 9600: my $rights_metadata =
9601: &metadata($uri,'keys',$location,'_rights',
9602: $depthcount+1);
9603: foreach my $rights (split(',',$rights_metadata)) {
9604: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
9605: $metathesekeys{$rights}=1;
1.339 albertel 9606: }
9607: }
9608: }
1.737 albertel 9609: # uniqifiy package listing
9610: my %seen;
9611: my @uniq_packages =
9612: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
9613: $metaentry{':packages'} = join(',',@uniq_packages);
9614:
1.1070 www 9615: if ($importedparts) {
9616: # We had imported parts and need to rebuild partorder
9617: $metaentry{':partorder'}='';
9618: $metathesekeys{'partorder'}=1;
9619: for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
9620: if ($origfileimportpartids[$index] eq 'part') {
9621: # original part, part of the problem
9622: $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
9623: } else {
9624: # we have imported parts at this position
9625: $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
9626: }
9627: }
9628: $metaentry{':partorder'}=~s/^\,//;
9629: }
9630:
1.737 albertel 9631: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 9632: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
9633: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924 albertel 9634: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 9635: # this is the end of "was not already recently cached
1.71 www 9636: }
1.599 albertel 9637: return $metaentry{':'.$what};
1.261 albertel 9638: }
9639:
1.488 albertel 9640: sub metadata_create_package_def {
1.483 albertel 9641: my ($uri,$key,$package,$metathesekeys)=@_;
9642: my ($pack,$name,$subp)=split(/\&/,$key);
9643: if ($subp eq 'default') { next; }
9644:
1.599 albertel 9645: if (defined($metaentry{':packages'})) {
9646: $metaentry{':packages'}.=','.$package;
1.483 albertel 9647: } else {
1.599 albertel 9648: $metaentry{':packages'}=$package;
1.483 albertel 9649: }
9650: my $value=$packagetab{$key};
9651: my $unikey;
9652: $unikey='parameter_0_'.$name;
1.599 albertel 9653: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 9654: $$metathesekeys{$unikey}=1;
1.599 albertel 9655: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
9656: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 9657: }
1.599 albertel 9658: if (defined($metaentry{':'.$unikey.'.default'})) {
9659: $metaentry{':'.$unikey}=
9660: $metaentry{':'.$unikey.'.default'};
1.483 albertel 9661: }
9662: }
9663:
1.261 albertel 9664: sub metadata_generate_part0 {
9665: my ($metadata,$metacache,$uri) = @_;
9666: my %allnames;
1.737 albertel 9667: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 9668: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 9669: my $part=$$metacache{':'.$metakey.'.part'};
9670: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 9671: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 9672: $allnames{$name}=$part;
9673: }
9674: }
9675: }
9676: foreach my $name (keys(%allnames)) {
9677: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 9678: my $key=":parameter_0_$name";
1.261 albertel 9679: $$metacache{"$key.part"}='0';
9680: $$metacache{"$key.name"}=$name;
1.428 albertel 9681: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 9682: $allnames{$name}.'_'.$name.
9683: '.type'};
1.428 albertel 9684: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 9685: '.display'};
1.644 www 9686: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 9687: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 9688: $$metacache{"$key.display"}=$olddis;
9689: }
1.71 www 9690: }
9691:
1.764 albertel 9692: # ------------------------------------------------------ Devalidate title cache
9693:
9694: sub devalidate_title_cache {
9695: my ($url)=@_;
9696: if (!$env{'request.course.id'}) { return; }
9697: my $symb=&symbread($url);
9698: if (!$symb) { return; }
9699: my $key=$env{'request.course.id'}."\0".$symb;
9700: &devalidate_cache_new('title',$key);
9701: }
9702:
1.1014 droeschl 9703: # ------------------------------------------------- Get the title of a course
9704:
9705: sub current_course_title {
9706: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
9707: }
1.301 www 9708: # ------------------------------------------------- Get the title of a resource
9709:
9710: sub gettitle {
9711: my $urlsymb=shift;
9712: my $symb=&symbread($urlsymb);
1.534 albertel 9713: if ($symb) {
1.620 albertel 9714: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 9715: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 9716: if (defined($cached)) {
9717: return $result;
9718: }
1.534 albertel 9719: my ($map,$resid,$url)=&decode_symb($symb);
9720: my $title='';
1.907 albertel 9721: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
9722: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
9723: } else {
9724: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
9725: &GDBM_READER(),0640)) {
9726: my $mapid=$bighash{'map_pc_'.&clutter($map)};
9727: $title=$bighash{'title_'.$mapid.'.'.$resid};
9728: untie(%bighash);
9729: }
1.534 albertel 9730: }
9731: $title=~s/\&colon\;/\:/gs;
9732: if ($title) {
1.1159 www 9733: # Remember both $symb and $title for dynamic metadata
9734: $accesshash{$symb.'___crstitle'}=$title;
1.1161 www 9735: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159 www 9736: # Cache this title and then return it
1.599 albertel 9737: return &do_cache_new('title',$key,$title,600);
1.534 albertel 9738: }
9739: $urlsymb=$url;
9740: }
9741: my $title=&metadata($urlsymb,'title');
9742: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
9743: return $title;
1.301 www 9744: }
1.613 albertel 9745:
1.614 albertel 9746: sub get_slot {
9747: my ($which,$cnum,$cdom)=@_;
9748: if (!$cnum || !$cdom) {
1.790 albertel 9749: (undef,my $courseid)=&whichuser();
1.620 albertel 9750: $cdom=$env{'course.'.$courseid.'.domain'};
9751: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 9752: }
1.703 albertel 9753: my $key=join("\0",'slots',$cdom,$cnum,$which);
9754: my %slotinfo;
9755: if (exists($remembered{$key})) {
9756: $slotinfo{$which} = $remembered{$key};
9757: } else {
9758: %slotinfo=&get('slots',[$which],$cdom,$cnum);
9759: &Apache::lonhomework::showhash(%slotinfo);
9760: my ($tmp)=keys(%slotinfo);
9761: if ($tmp=~/^error:/) { return (); }
9762: $remembered{$key} = $slotinfo{$which};
9763: }
1.616 albertel 9764: if (ref($slotinfo{$which}) eq 'HASH') {
9765: return %{$slotinfo{$which}};
9766: }
9767: return $slotinfo{$which};
1.614 albertel 9768: }
1.1150 raeburn 9769:
9770: sub get_reservable_slots {
9771: my ($cnum,$cdom,$uname,$udom) = @_;
9772: my $now = time;
9773: my $reservable_info;
9774: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
9775: if (exists($remembered{$key})) {
9776: $reservable_info = $remembered{$key};
9777: } else {
9778: my %resv;
9779: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
9780: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
9781: $reservable_info = \%resv;
9782: $remembered{$key} = $reservable_info;
9783: }
9784: return $reservable_info;
9785: }
9786:
9787: sub get_course_slots {
9788: my ($cnum,$cdom) = @_;
9789: my $hashid=$cnum.':'.$cdom;
9790: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
9791: if (defined($cached)) {
9792: if (ref($result) eq 'HASH') {
9793: return %{$result};
9794: }
9795: } else {
9796: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
9797: my ($tmp) = keys(%slots);
9798: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
9799: &Apache::lonnet::do_cache_new('allslots',$hashid,\%slots,600);
9800: return %slots;
9801: }
9802: }
9803: return;
9804: }
9805:
9806: sub devalidate_slots_cache {
9807: my ($cnum,$cdom)=@_;
9808: my $hashid=$cnum.':'.$cdom;
9809: &devalidate_cache_new('allslots',$hashid);
9810: }
9811:
1.31 www 9812: # ------------------------------------------------- Update symbolic store links
9813:
9814: sub symblist {
9815: my ($mapname,%newhash)=@_;
1.438 www 9816: $mapname=&deversion(&declutter($mapname));
1.31 www 9817: my %hash;
1.620 albertel 9818: if (($env{'request.course.fn'}) && (%newhash)) {
9819: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 9820: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 9821: foreach my $url (keys(%newhash)) {
1.711 albertel 9822: next if ($url eq 'last_known'
9823: && $env{'form.no_update_last_known'});
9824: $hash{declutter($url)}=&encode_symb($mapname,
9825: $newhash{$url}->[1],
9826: $newhash{$url}->[0]);
1.191 harris41 9827: }
1.31 www 9828: if (untie(%hash)) {
9829: return 'ok';
9830: }
9831: }
9832: }
9833: return 'error';
1.212 www 9834: }
9835:
9836: # --------------------------------------------------------------- Verify a symb
9837:
9838: sub symbverify {
1.510 www 9839: my ($symb,$thisurl)=@_;
9840: my $thisfn=$thisurl;
1.439 www 9841: $thisfn=&declutter($thisfn);
1.215 www 9842: # direct jump to resource in page or to a sequence - will construct own symbs
9843: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
9844: # check URL part
1.409 www 9845: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 9846:
1.431 www 9847: unless ($url eq $thisfn) { return 0; }
1.213 www 9848:
1.216 www 9849: $symb=&symbclean($symb);
1.510 www 9850: $thisurl=&deversion($thisurl);
1.439 www 9851: $thisfn=&deversion($thisfn);
1.213 www 9852:
9853: my %bighash;
9854: my $okay=0;
1.431 www 9855:
1.620 albertel 9856: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 9857: &GDBM_READER(),0640)) {
1.1032 raeburn 9858: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
9859: $thisurl =~ s/\?.+$//;
9860: }
1.510 www 9861: my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1102 raeburn 9862: unless ($ids) {
9863: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
9864: $ids=$bighash{$idkey};
1.216 www 9865: }
9866: if ($ids) {
9867: # ------------------------------------------------------------------- Has ID(s)
1.800 albertel 9868: foreach my $id (split(/\,/,$ids)) {
9869: my ($mapid,$resid)=split(/\./,$id);
1.1032 raeburn 9870: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
9871: $symb =~ s/\?.+$//;
9872: }
1.216 www 9873: if (
9874: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
9875: eq $symb) {
1.620 albertel 9876: if (($env{'request.role.adv'}) ||
1.1101 raeburn 9877: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
9878: ($thisurl eq '/adm/navmaps')) {
1.582 albertel 9879: $okay=1;
9880: }
9881: }
1.216 www 9882: }
9883: }
1.213 www 9884: untie(%bighash);
9885: }
9886: return $okay;
1.31 www 9887: }
9888:
1.210 www 9889: # --------------------------------------------------------------- Clean-up symb
9890:
9891: sub symbclean {
9892: my $symb=shift;
1.568 albertel 9893: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 9894: # remove version from map
9895: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 9896:
1.210 www 9897: # remove version from URL
9898: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 9899:
1.507 www 9900: # remove wrapper
9901:
1.510 www 9902: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 9903: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 9904: return $symb;
1.409 www 9905: }
9906:
9907: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 9908:
9909: sub encode_symb {
9910: my ($map,$resid,$url)=@_;
9911: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
9912: }
1.409 www 9913:
9914: sub decode_symb {
1.568 albertel 9915: my $symb=shift;
9916: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
9917: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 9918: return (&fixversion($map),$resid,&fixversion($url));
9919: }
9920:
9921: sub fixversion {
9922: my $fn=shift;
1.609 banghart 9923: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 9924: my %bighash;
9925: my $uri=&clutter($fn);
1.620 albertel 9926: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 9927: # is this cached?
1.599 albertel 9928: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 9929: if (defined($cached)) { return $result; }
9930: # unfortunately not cached, or expired
1.620 albertel 9931: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 9932: &GDBM_READER(),0640)) {
9933: if ($bighash{'version_'.$uri}) {
9934: my $version=$bighash{'version_'.$uri};
1.444 www 9935: unless (($version eq 'mostrecent') ||
9936: ($version==&getversion($uri))) {
1.440 www 9937: $uri=~s/\.(\w+)$/\.$version\.$1/;
9938: }
9939: }
9940: untie %bighash;
1.413 www 9941: }
1.599 albertel 9942: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 9943: }
9944:
9945: sub deversion {
9946: my $url=shift;
9947: $url=~s/\.\d+\.(\w+)$/\.$1/;
9948: return $url;
1.210 www 9949: }
9950:
1.31 www 9951: # ------------------------------------------------------ Return symb list entry
9952:
9953: sub symbread {
1.249 www 9954: my ($thisfn,$donotrecurse)=@_;
1.542 albertel 9955: my $cache_str='request.symbread.cached.'.$thisfn;
1.620 albertel 9956: if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242 www 9957: # no filename provided? try from environment
1.44 www 9958: unless ($thisfn) {
1.620 albertel 9959: if ($env{'request.symb'}) {
9960: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 9961: }
1.620 albertel 9962: $thisfn=$env{'request.filename'};
1.44 www 9963: }
1.569 albertel 9964: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 9965: # is that filename actually a symb? Verify, clean, and return
9966: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 9967: if (&symbverify($thisfn,$1)) {
1.620 albertel 9968: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 9969: }
1.242 www 9970: }
1.44 www 9971: $thisfn=declutter($thisfn);
1.31 www 9972: my %hash;
1.37 www 9973: my %bighash;
9974: my $syval='';
1.620 albertel 9975: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 9976: my $targetfn = $thisfn;
1.609 banghart 9977: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 9978: $targetfn = 'adm/wrapper/'.$thisfn;
9979: }
1.687 albertel 9980: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
9981: $targetfn=$1;
9982: }
1.620 albertel 9983: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 9984: &GDBM_READER(),0640)) {
1.481 raeburn 9985: $syval=$hash{$targetfn};
1.37 www 9986: untie(%hash);
9987: }
9988: # ---------------------------------------------------------- There was an entry
9989: if ($syval) {
1.601 albertel 9990: #unless ($syval=~/\_\d+$/) {
1.620 albertel 9991: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 9992: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 9993: #return $env{$cache_str}='';
1.601 albertel 9994: #}
9995: #$syval.=$1;
9996: #}
1.37 www 9997: } else {
9998: # ------------------------------------------------------- Was not in symb table
1.620 albertel 9999: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 10000: &GDBM_READER(),0640)) {
1.37 www 10001: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 10002: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 10003: unless ($ids) {
10004: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 10005: }
10006: unless ($ids) {
10007: # alias?
10008: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 10009: }
1.37 www 10010: if ($ids) {
10011: # ------------------------------------------------------------------- Has ID(s)
10012: my @possibilities=split(/\,/,$ids);
1.39 www 10013: if ($#possibilities==0) {
10014: # ----------------------------------------------- There is only one possibility
1.37 www 10015: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 10016: $syval=&encode_symb($bighash{'map_id_'.$mapid},
10017: $resid,$thisfn);
1.249 www 10018: } elsif (!$donotrecurse) {
1.39 www 10019: # ------------------------------------------ There is more than one possibility
10020: my $realpossible=0;
1.800 albertel 10021: foreach my $id (@possibilities) {
10022: my $file=$bighash{'src_'.$id};
1.39 www 10023: if (&allowed('bre',$file)) {
1.800 albertel 10024: my ($mapid,$resid)=split(/\./,$id);
1.39 www 10025: if ($bighash{'map_type_'.$mapid} ne 'page') {
10026: $realpossible++;
1.626 albertel 10027: $syval=&encode_symb($bighash{'map_id_'.$mapid},
10028: $resid,$thisfn);
1.39 www 10029: }
10030: }
1.191 harris41 10031: }
1.39 www 10032: if ($realpossible!=1) { $syval=''; }
1.249 www 10033: } else {
10034: $syval='';
1.37 www 10035: }
10036: }
10037: untie(%bighash)
1.481 raeburn 10038: }
1.31 www 10039: }
1.62 www 10040: if ($syval) {
1.620 albertel 10041: return $env{$cache_str}=$syval;
1.62 www 10042: }
1.31 www 10043: }
1.949 raeburn 10044: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 10045: return $env{$cache_str}='';
1.31 www 10046: }
10047:
10048: # ---------------------------------------------------------- Return random seed
10049:
1.32 www 10050: sub numval {
10051: my $txt=shift;
10052: $txt=~tr/A-J/0-9/;
10053: $txt=~tr/a-j/0-9/;
10054: $txt=~tr/K-T/0-9/;
10055: $txt=~tr/k-t/0-9/;
10056: $txt=~tr/U-Z/0-5/;
10057: $txt=~tr/u-z/0-5/;
10058: $txt=~s/\D//g;
1.564 albertel 10059: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 10060: return int($txt);
1.368 albertel 10061: }
10062:
1.484 albertel 10063: sub numval2 {
10064: my $txt=shift;
10065: $txt=~tr/A-J/0-9/;
10066: $txt=~tr/a-j/0-9/;
10067: $txt=~tr/K-T/0-9/;
10068: $txt=~tr/k-t/0-9/;
10069: $txt=~tr/U-Z/0-5/;
10070: $txt=~tr/u-z/0-5/;
10071: $txt=~s/\D//g;
10072: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10073: my $total;
10074: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 10075: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 10076: return int($total);
10077: }
10078:
1.575 albertel 10079: sub numval3 {
10080: use integer;
10081: my $txt=shift;
10082: $txt=~tr/A-J/0-9/;
10083: $txt=~tr/a-j/0-9/;
10084: $txt=~tr/K-T/0-9/;
10085: $txt=~tr/k-t/0-9/;
10086: $txt=~tr/U-Z/0-5/;
10087: $txt=~tr/u-z/0-5/;
10088: $txt=~s/\D//g;
10089: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10090: my $total;
10091: foreach my $val (@txts) { $total+=$val; }
10092: if ($_64bit) { $total=(($total<<32)>>32); }
10093: return $total;
10094: }
10095:
1.675 albertel 10096: sub digest {
10097: my ($data)=@_;
10098: my $digest=&Digest::MD5::md5($data);
10099: my ($a,$b,$c,$d)=unpack("iiii",$digest);
10100: my ($e,$f);
10101: {
10102: use integer;
10103: $e=($a+$b);
10104: $f=($c+$d);
10105: if ($_64bit) {
10106: $e=(($e<<32)>>32);
10107: $f=(($f<<32)>>32);
10108: }
10109: }
10110: if (wantarray) {
10111: return ($e,$f);
10112: } else {
10113: my $g;
10114: {
10115: use integer;
10116: $g=($e+$f);
10117: if ($_64bit) {
10118: $g=(($g<<32)>>32);
10119: }
10120: }
10121: return $g;
10122: }
10123: }
10124:
1.368 albertel 10125: sub latest_rnd_algorithm_id {
1.675 albertel 10126: return '64bit5';
1.366 albertel 10127: }
1.32 www 10128:
1.503 albertel 10129: sub get_rand_alg {
10130: my ($courseid)=@_;
1.790 albertel 10131: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 10132: if ($courseid) {
1.620 albertel 10133: return $env{"course.$courseid.rndseed"};
1.503 albertel 10134: }
10135: return &latest_rnd_algorithm_id();
10136: }
10137:
1.562 albertel 10138: sub validCODE {
10139: my ($CODE)=@_;
10140: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
10141: return 0;
10142: }
10143:
1.491 albertel 10144: sub getCODE {
1.620 albertel 10145: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 10146: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
10147: defined($Apache::lonhomework::parsing_a_task) ) &&
10148: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 10149: return $Apache::lonhomework::history{'resource.CODE'};
10150: }
10151: return undef;
10152: }
1.1133 foxr 10153: #
10154: # Determines the random seed for a specific context:
10155: #
10156: # parameters:
10157: # symb - in course context the symb for the seed.
10158: # course_id - The course id of the form domain_coursenum.
10159: # domain - Domain for the user.
10160: # course - Course for the user.
10161: # cenv - environment of the course.
10162: #
10163: # NOTE:
10164: # All parameters are picked out of the environment if missing
10165: # or not defined.
10166: # If a symb cannot be determined the current time is used instead.
10167: #
10168: # For a given well defined symb, courside, domain, username,
10169: # and course environment, the seed is reproducible.
10170: #
1.31 www 10171: sub rndseed {
1.1133 foxr 10172: my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790 albertel 10173: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 10174: if (!defined($symb)) {
1.366 albertel 10175: unless ($symb=$wsymb) { return time; }
10176: }
1.1146 foxr 10177: if (!defined $courseid) {
10178: $courseid=$wcourseid;
10179: }
10180: if (!defined $domain) { $domain=$wdomain; }
10181: if (!defined $username) { $username=$wusername }
1.1133 foxr 10182:
10183: my $which;
10184: if (defined($cenv->{'rndseed'})) {
10185: $which = $cenv->{'rndseed'};
10186: } else {
10187: $which =&get_rand_alg($courseid);
10188: }
1.491 albertel 10189: if (defined(&getCODE())) {
1.1133 foxr 10190:
1.675 albertel 10191: if ($which eq '64bit5') {
10192: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
10193: } elsif ($which eq '64bit4') {
1.575 albertel 10194: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
10195: } else {
10196: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
10197: }
1.675 albertel 10198: } elsif ($which eq '64bit5') {
10199: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 10200: } elsif ($which eq '64bit4') {
10201: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 10202: } elsif ($which eq '64bit3') {
10203: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 10204: } elsif ($which eq '64bit2') {
10205: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 10206: } elsif ($which eq '64bit') {
10207: return &rndseed_64bit($symb,$courseid,$domain,$username);
10208: }
10209: return &rndseed_32bit($symb,$courseid,$domain,$username);
10210: }
10211:
10212: sub rndseed_32bit {
10213: my ($symb,$courseid,$domain,$username)=@_;
10214: {
10215: use integer;
10216: my $symbchck=unpack("%32C*",$symb) << 27;
10217: my $symbseed=numval($symb) << 22;
10218: my $namechck=unpack("%32C*",$username) << 17;
10219: my $nameseed=numval($username) << 12;
10220: my $domainseed=unpack("%32C*",$domain) << 7;
10221: my $courseseed=unpack("%32C*",$courseid);
10222: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 10223: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10224: #&logthis("rndseed :$num:$symb");
1.564 albertel 10225: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 10226: return $num;
10227: }
10228: }
10229:
10230: sub rndseed_64bit {
10231: my ($symb,$courseid,$domain,$username)=@_;
10232: {
10233: use integer;
10234: my $symbchck=unpack("%32S*",$symb) << 21;
10235: my $symbseed=numval($symb) << 10;
10236: my $namechck=unpack("%32S*",$username);
10237:
10238: my $nameseed=numval($username) << 21;
10239: my $domainseed=unpack("%32S*",$domain) << 10;
10240: my $courseseed=unpack("%32S*",$courseid);
10241:
10242: my $num1=$symbchck+$symbseed+$namechck;
10243: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 10244: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10245: #&logthis("rndseed :$num:$symb");
1.564 albertel 10246: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 10247: return "$num1,$num2";
1.155 albertel 10248: }
1.366 albertel 10249: }
10250:
1.443 albertel 10251: sub rndseed_64bit2 {
10252: my ($symb,$courseid,$domain,$username)=@_;
10253: {
10254: use integer;
10255: # strings need to be an even # of cahracters long, it it is odd the
10256: # last characters gets thrown away
10257: my $symbchck=unpack("%32S*",$symb.' ') << 21;
10258: my $symbseed=numval($symb) << 10;
10259: my $namechck=unpack("%32S*",$username.' ');
10260:
10261: my $nameseed=numval($username) << 21;
1.501 albertel 10262: my $domainseed=unpack("%32S*",$domain.' ') << 10;
10263: my $courseseed=unpack("%32S*",$courseid.' ');
10264:
10265: my $num1=$symbchck+$symbseed+$namechck;
10266: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 10267: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10268: #&logthis("rndseed :$num:$symb");
1.803 albertel 10269: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 10270: return "$num1,$num2";
10271: }
10272: }
10273:
10274: sub rndseed_64bit3 {
10275: my ($symb,$courseid,$domain,$username)=@_;
10276: {
10277: use integer;
10278: # strings need to be an even # of cahracters long, it it is odd the
10279: # last characters gets thrown away
10280: my $symbchck=unpack("%32S*",$symb.' ') << 21;
10281: my $symbseed=numval2($symb) << 10;
10282: my $namechck=unpack("%32S*",$username.' ');
10283:
10284: my $nameseed=numval2($username) << 21;
1.443 albertel 10285: my $domainseed=unpack("%32S*",$domain.' ') << 10;
10286: my $courseseed=unpack("%32S*",$courseid.' ');
10287:
10288: my $num1=$symbchck+$symbseed+$namechck;
10289: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 10290: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10291: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 10292: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 10293:
1.503 albertel 10294: return "$num1:$num2";
1.443 albertel 10295: }
10296: }
10297:
1.575 albertel 10298: sub rndseed_64bit4 {
10299: my ($symb,$courseid,$domain,$username)=@_;
10300: {
10301: use integer;
10302: # strings need to be an even # of cahracters long, it it is odd the
10303: # last characters gets thrown away
10304: my $symbchck=unpack("%32S*",$symb.' ') << 21;
10305: my $symbseed=numval3($symb) << 10;
10306: my $namechck=unpack("%32S*",$username.' ');
10307:
10308: my $nameseed=numval3($username) << 21;
10309: my $domainseed=unpack("%32S*",$domain.' ') << 10;
10310: my $courseseed=unpack("%32S*",$courseid.' ');
10311:
10312: my $num1=$symbchck+$symbseed+$namechck;
10313: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 10314: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10315: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 10316: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 10317:
1.575 albertel 10318: return "$num1:$num2";
10319: }
10320: }
10321:
1.675 albertel 10322: sub rndseed_64bit5 {
10323: my ($symb,$courseid,$domain,$username)=@_;
10324: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
10325: return "$num1:$num2";
10326: }
10327:
1.366 albertel 10328: sub rndseed_CODE_64bit {
10329: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 10330: {
1.366 albertel 10331: use integer;
1.443 albertel 10332: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 10333: my $symbseed=numval2($symb);
1.491 albertel 10334: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
10335: my $CODEseed=numval(&getCODE());
1.443 albertel 10336: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 10337: my $num1=$symbseed+$CODEchck;
10338: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 10339: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
10340: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 10341: if ($_64bit) { $num1=(($num1<<32)>>32); }
10342: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 10343: return "$num1:$num2";
1.366 albertel 10344: }
10345: }
10346:
1.575 albertel 10347: sub rndseed_CODE_64bit4 {
10348: my ($symb,$courseid,$domain,$username)=@_;
10349: {
10350: use integer;
10351: my $symbchck=unpack("%32S*",$symb.' ') << 16;
10352: my $symbseed=numval3($symb);
10353: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
10354: my $CODEseed=numval3(&getCODE());
10355: my $courseseed=unpack("%32S*",$courseid.' ');
10356: my $num1=$symbseed+$CODEchck;
10357: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 10358: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
10359: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 10360: if ($_64bit) { $num1=(($num1<<32)>>32); }
10361: if ($_64bit) { $num2=(($num2<<32)>>32); }
10362: return "$num1:$num2";
10363: }
10364: }
10365:
1.675 albertel 10366: sub rndseed_CODE_64bit5 {
10367: my ($symb,$courseid,$domain,$username)=@_;
10368: my $code = &getCODE();
10369: my ($num1,$num2)=&digest("$symb,$courseid,$code");
10370: return "$num1:$num2";
10371: }
10372:
1.366 albertel 10373: sub setup_random_from_rndseed {
10374: my ($rndseed)=@_;
1.503 albertel 10375: if ($rndseed =~/([,:])/) {
10376: my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366 albertel 10377: &Math::Random::random_set_seed(abs($num1),abs($num2));
10378: } else {
10379: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 10380: }
1.36 albertel 10381: }
10382:
1.474 albertel 10383: sub latest_receipt_algorithm_id {
1.835 albertel 10384: return 'receipt3';
1.474 albertel 10385: }
10386:
1.480 www 10387: sub recunique {
10388: my $fucourseid=shift;
10389: my $unique;
1.835 albertel 10390: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
10391: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 10392: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 10393: } else {
10394: $unique=$perlvar{'lonReceipt'};
10395: }
10396: return unpack("%32C*",$unique);
10397: }
10398:
10399: sub recprefix {
10400: my $fucourseid=shift;
10401: my $prefix;
1.835 albertel 10402: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
10403: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 10404: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 10405: } else {
10406: $prefix=$perlvar{'lonHostID'};
10407: }
10408: return unpack("%32C*",$prefix);
10409: }
10410:
1.76 www 10411: sub ireceipt {
1.474 albertel 10412: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 10413:
10414: my $return =&recprefix($fucourseid).'-';
10415:
10416: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
10417: $env{'request.state'} eq 'construct') {
10418: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
10419: return $return;
10420: }
10421:
1.76 www 10422: my $cuname=unpack("%32C*",$funame);
10423: my $cudom=unpack("%32C*",$fudom);
10424: my $cucourseid=unpack("%32C*",$fucourseid);
10425: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 10426: my $cunique=&recunique($fucourseid);
1.474 albertel 10427: my $cpart=unpack("%32S*",$part);
1.835 albertel 10428: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
10429:
1.790 albertel 10430: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 10431:
10432: $return.= ($cunique%$cuname+
10433: $cunique%$cudom+
10434: $cusymb%$cuname+
10435: $cusymb%$cudom+
10436: $cucourseid%$cuname+
10437: $cucourseid%$cudom+
10438: $cpart%$cuname+
10439: $cpart%$cudom);
10440: } else {
10441: $return.= ($cunique%$cuname+
10442: $cunique%$cudom+
10443: $cusymb%$cuname+
10444: $cusymb%$cudom+
10445: $cucourseid%$cuname+
10446: $cucourseid%$cudom);
10447: }
10448: return $return;
1.76 www 10449: }
10450:
10451: sub receipt {
1.474 albertel 10452: my ($part)=@_;
1.790 albertel 10453: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 10454: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 10455: }
1.260 ng 10456:
1.790 albertel 10457: sub whichuser {
10458: my ($passedsymb)=@_;
10459: my ($symb,$courseid,$domain,$name,$publicuser);
10460: if (defined($env{'form.grade_symb'})) {
10461: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
10462: my $allowed=&allowed('vgr',$tmp_courseid);
10463: if (!$allowed &&
10464: exists($env{'request.course.sec'}) &&
10465: $env{'request.course.sec'} !~ /^\s*$/) {
10466: $allowed=&allowed('vgr',$tmp_courseid.
10467: '/'.$env{'request.course.sec'});
10468: }
10469: if ($allowed) {
10470: ($symb)=&get_env_multiple('form.grade_symb');
10471: $courseid=$tmp_courseid;
10472: ($domain)=&get_env_multiple('form.grade_domain');
10473: ($name)=&get_env_multiple('form.grade_username');
10474: return ($symb,$courseid,$domain,$name,$publicuser);
10475: }
10476: }
10477: if (!$passedsymb) {
10478: $symb=&symbread();
10479: } else {
10480: $symb=$passedsymb;
10481: }
10482: $courseid=$env{'request.course.id'};
10483: $domain=$env{'user.domain'};
10484: $name=$env{'user.name'};
10485: if ($name eq 'public' && $domain eq 'public') {
10486: if (!defined($env{'form.username'})) {
10487: $env{'form.username'}.=time.rand(10000000);
10488: }
10489: $name.=$env{'form.username'};
10490: }
10491: return ($symb,$courseid,$domain,$name,$publicuser);
10492:
10493: }
10494:
1.36 albertel 10495: # ------------------------------------------------------------ Serves up a file
1.472 albertel 10496: # returns either the contents of the file or
10497: # -1 if the file doesn't exist
1.481 raeburn 10498: #
10499: # if the target is a file that was uploaded via DOCS,
10500: # a check will be made to see if a current copy exists on the local server,
10501: # if it does this will be served, otherwise a copy will be retrieved from
10502: # the home server for the course and stored in /home/httpd/html/userfiles on
10503: # the local server.
1.472 albertel 10504:
1.36 albertel 10505: sub getfile {
1.538 albertel 10506: my ($file) = @_;
1.609 banghart 10507: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 10508: &repcopy($file);
10509: return &readfile($file);
10510: }
10511:
10512: sub repcopy_userfile {
10513: my ($file)=@_;
1.1142 raeburn 10514: my $londocroot = $perlvar{'lonDocRoot'};
10515: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164 raeburn 10516: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538 albertel 10517: my ($cdom,$cnum,$filename) =
1.811 albertel 10518: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 10519: my $uri="/uploaded/$cdom/$cnum/$filename";
10520: if (-e "$file") {
1.828 www 10521: # we already have a local copy, check it out
1.538 albertel 10522: my @fileinfo = stat($file);
1.828 www 10523: my $rtncode;
10524: my $info;
1.538 albertel 10525: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 10526: if ($lwpresp ne 'ok') {
1.828 www 10527: # there is no such file anymore, even though we had a local copy
1.482 albertel 10528: if ($rtncode eq '404') {
1.538 albertel 10529: unlink($file);
1.482 albertel 10530: }
10531: return -1;
10532: }
10533: if ($info < $fileinfo[9]) {
1.828 www 10534: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 10535: return 'ok';
1.828 www 10536: } else {
10537: # the file is outdated, get rid of it
10538: unlink($file);
1.482 albertel 10539: }
1.828 www 10540: }
10541: # one way or the other, at this point, we don't have the file
10542: # construct the correct path for the file
10543: my @parts = ($cdom,$cnum);
10544: if ($filename =~ m|^(.+)/[^/]+$|) {
10545: push @parts, split(/\//,$1);
10546: }
10547: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
10548: foreach my $part (@parts) {
10549: $path .= '/'.$part;
10550: if (!-e $path) {
10551: mkdir($path,0770);
1.482 albertel 10552: }
10553: }
1.828 www 10554: # now the path exists for sure
10555: # get a user agent
10556: my $ua=new LWP::UserAgent;
10557: my $transferfile=$file.'.in.transfer';
10558: # FIXME: this should flock
10559: if (-e $transferfile) { return 'ok'; }
10560: my $request;
10561: $uri=~s/^\///;
1.980 raeburn 10562: my $homeserver = &homeserver($cnum,$cdom);
10563: my $protocol = $protocol{$homeserver};
10564: $protocol = 'http' if ($protocol ne 'https');
10565: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 10566: my $response=$ua->request($request,$transferfile);
10567: # did it work?
10568: if ($response->is_error()) {
10569: unlink($transferfile);
10570: &logthis("Userfile repcopy failed for $uri");
10571: return -1;
10572: }
10573: # worked, rename the transfer file
10574: rename($transferfile,$file);
1.607 raeburn 10575: return 'ok';
1.481 raeburn 10576: }
10577:
1.517 albertel 10578: sub tokenwrapper {
10579: my $uri=shift;
1.980 raeburn 10580: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 10581: $uri=~s|^/||;
1.620 albertel 10582: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 10583: my $token=$1;
1.552 albertel 10584: my (undef,$udom,$uname,$file)=split('/',$uri,4);
10585: if ($udom && $uname && $file) {
10586: $file=~s|(\?\.*)*$||;
1.949 raeburn 10587: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 10588: my $homeserver = &homeserver($uname,$udom);
10589: my $protocol = $protocol{$homeserver};
10590: $protocol = 'http' if ($protocol ne 'https');
10591: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 10592: (($uri=~/\?/)?'&':'?').'token='.$token.
10593: '&tokenissued='.$perlvar{'lonHostID'};
10594: } else {
10595: return '/adm/notfound.html';
10596: }
10597: }
10598:
1.828 www 10599: # call with reqtype HEAD: get last modification time
10600: # call with reqtype GET: get the file contents
10601: # Do not call this with reqtype GET for large files! It loads everything into memory
10602: #
1.481 raeburn 10603: sub getuploaded {
10604: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
10605: $uri=~s/^\///;
1.980 raeburn 10606: my $homeserver = &homeserver($cnum,$cdom);
10607: my $protocol = $protocol{$homeserver};
10608: $protocol = 'http' if ($protocol ne 'https');
10609: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 10610: my $ua=new LWP::UserAgent;
10611: my $request=new HTTP::Request($reqtype,$uri);
10612: my $response=$ua->request($request);
10613: $$rtncode = $response->code;
1.482 albertel 10614: if (! $response->is_success()) {
10615: return 'failed';
10616: }
10617: if ($reqtype eq 'HEAD') {
1.486 www 10618: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 10619: } elsif ($reqtype eq 'GET') {
10620: $$info = $response->content;
1.472 albertel 10621: }
1.482 albertel 10622: return 'ok';
1.36 albertel 10623: }
10624:
1.481 raeburn 10625: sub readfile {
10626: my $file = shift;
10627: if ( (! -e $file ) || ($file eq '') ) { return -1; };
10628: my $fh;
10629: open($fh,"<$file");
10630: my $a='';
1.800 albertel 10631: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 10632: return $a;
10633: }
10634:
1.36 albertel 10635: sub filelocation {
1.590 banghart 10636: my ($dir,$file) = @_;
10637: my $location;
10638: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 10639:
10640: if ($file =~ m-^/adm/-) {
10641: $file=~s-^/adm/wrapper/-/-;
10642: $file=~s-^/adm/coursedocs/showdoc/-/-;
10643: }
1.882 albertel 10644:
1.1139 www 10645: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956 raeburn 10646: $location = $file;
1.609 banghart 10647: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 10648: my ($udom,$uname,$filename)=
1.811 albertel 10649: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 10650: my $home=&homeserver($uname,$udom);
10651: my $is_me=0;
10652: my @ids=¤t_machine_ids();
10653: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
10654: if ($is_me) {
1.1117 foxr 10655: $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 10656: } else {
10657: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
10658: $udom.'/'.$uname.'/'.$filename;
10659: }
1.882 albertel 10660: } elsif ($file =~ m-^/adm/-) {
10661: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 10662: } else {
10663: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139 www 10664: $file=~s:^/(res|priv)/:/:;
10665: my $space=$1;
1.590 banghart 10666: if ( !( $file =~ m:^/:) ) {
10667: $location = $dir. '/'.$file;
10668: } else {
1.1142 raeburn 10669: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590 banghart 10670: }
1.59 albertel 10671: }
1.590 banghart 10672: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 10673: while ($location=~m{/\.\./}) {
10674: if ($location =~ m{/[^/]+/\.\./}) {
10675: $location=~ s{/[^/]+/\.\./}{/}g;
10676: } else {
10677: $location=~ s{/\.\./}{/}g;
10678: }
10679: } #remove dir/..
1.590 banghart 10680: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
10681: return $location;
1.46 www 10682: }
1.36 albertel 10683:
1.46 www 10684: sub hreflocation {
10685: my ($dir,$file)=@_;
1.980 raeburn 10686: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 10687: $file=filelocation($dir,$file);
1.700 albertel 10688: } elsif ($file=~m-^/adm/-) {
10689: $file=~s-^/adm/wrapper/-/-;
10690: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 10691: }
10692: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
10693: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
10694: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143 raeburn 10695: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
10696: {/uploaded/$1/$2/}x;
1.46 www 10697: }
1.913 albertel 10698: if ($file=~ m{^/userfiles/}) {
10699: $file =~ s{^/userfiles/}{/uploaded/};
10700: }
1.462 albertel 10701: return $file;
1.465 albertel 10702: }
10703:
1.1139 www 10704:
10705:
10706:
10707:
1.465 albertel 10708: sub current_machine_domains {
1.853 albertel 10709: return &machine_domains(&hostname($perlvar{'lonHostID'}));
10710: }
10711:
10712: sub machine_domains {
10713: my ($hostname) = @_;
1.465 albertel 10714: my @domains;
1.838 albertel 10715: my %hostname = &all_hostnames();
1.465 albertel 10716: while( my($id, $name) = each(%hostname)) {
1.467 matthew 10717: # &logthis("-$id-$name-$hostname-");
1.465 albertel 10718: if ($hostname eq $name) {
1.844 albertel 10719: push(@domains,&host_domain($id));
1.465 albertel 10720: }
10721: }
10722: return @domains;
10723: }
10724:
10725: sub current_machine_ids {
1.853 albertel 10726: return &machine_ids(&hostname($perlvar{'lonHostID'}));
10727: }
10728:
10729: sub machine_ids {
10730: my ($hostname) = @_;
10731: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 10732: my @ids;
1.888 albertel 10733: my %name_to_host = &all_names();
1.889 albertel 10734: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
10735: return @{ $name_to_host{$hostname} };
10736: }
10737: return;
1.31 www 10738: }
10739:
1.824 raeburn 10740: sub additional_machine_domains {
10741: my @domains;
10742: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
10743: while( my $line = <$fh>) {
10744: $line =~ s/\s//g;
10745: push(@domains,$line);
10746: }
10747: return @domains;
10748: }
10749:
10750: sub default_login_domain {
10751: my $domain = $perlvar{'lonDefDomain'};
10752: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
10753: foreach my $posdom (¤t_machine_domains(),
10754: &additional_machine_domains()) {
10755: if (lc($posdom) eq lc($testdomain)) {
10756: $domain=$posdom;
10757: last;
10758: }
10759: }
10760: return $domain;
10761: }
10762:
1.31 www 10763: # ------------------------------------------------------------- Declutters URLs
10764:
10765: sub declutter {
10766: my $thisfn=shift;
1.569 albertel 10767: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479 albertel 10768: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31 www 10769: $thisfn=~s/^\///;
1.697 albertel 10770: $thisfn=~s|^adm/wrapper/||;
10771: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 10772: $thisfn=~s/^res\///;
1.1032 raeburn 10773: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
10774: $thisfn=~s/\?.+$//;
10775: }
1.268 www 10776: return $thisfn;
10777: }
10778:
10779: # ------------------------------------------------------------- Clutter up URLs
10780:
10781: sub clutter {
10782: my $thisfn='/'.&declutter(shift);
1.887 albertel 10783: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 10784: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 10785: $thisfn='/res'.$thisfn;
10786: }
1.1031 raeburn 10787: if ($thisfn !~m|^/adm|) {
10788: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 10789: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 10790: } else {
10791: my ($ext) = ($thisfn =~ /\.(\w+)$/);
10792: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 10793: if ($embstyle eq 'ssi'
10794: || ($embstyle eq 'hdn')
10795: || ($embstyle eq 'rat')
10796: || ($embstyle eq 'prv')
10797: || ($embstyle eq 'ign')) {
10798: #do nothing with these
10799: } elsif (($embstyle eq 'img')
1.695 albertel 10800: || ($embstyle eq 'emb')
10801: || ($embstyle eq 'wrp')) {
10802: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 10803: } elsif ($embstyle eq 'unk'
10804: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 10805: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 10806: } else {
1.718 www 10807: # &logthis("Got a blank emb style");
1.695 albertel 10808: }
1.694 albertel 10809: }
10810: }
1.31 www 10811: return $thisfn;
1.12 www 10812: }
10813:
1.787 albertel 10814: sub clutter_with_no_wrapper {
10815: my $uri = &clutter(shift);
10816: if ($uri =~ m-^/adm/-) {
10817: $uri =~ s-^/adm/wrapper/-/-;
10818: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
10819: }
10820: return $uri;
10821: }
10822:
1.557 albertel 10823: sub freeze_escape {
10824: my ($value)=@_;
10825: if (ref($value)) {
10826: $value=&nfreeze($value);
10827: return '__FROZEN__'.&escape($value);
10828: }
10829: return &escape($value);
10830: }
10831:
1.11 www 10832:
1.557 albertel 10833: sub thaw_unescape {
10834: my ($value)=@_;
10835: if ($value =~ /^__FROZEN__/) {
10836: substr($value,0,10,undef);
10837: $value=&unescape($value);
10838: return &thaw($value);
10839: }
10840: return &unescape($value);
10841: }
10842:
1.436 albertel 10843: sub correct_line_ends {
10844: my ($result)=@_;
10845: $$result =~s/\r\n/\n/mg;
10846: $$result =~s/\r/\n/mg;
1.415 albertel 10847: }
1.1 albertel 10848: # ================================================================ Main Program
10849:
1.184 www 10850: sub goodbye {
1.204 albertel 10851: &logthis("Starting Shut down");
1.443 albertel 10852: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 10853: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 10854: #converted
1.599 albertel 10855: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 10856: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
10857: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
10858: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 10859: #1.1 only
1.870 albertel 10860: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
10861: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
10862: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
10863: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
10864: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 10865: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
10866: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 10867: &flushcourselogs();
10868: &logthis("Shutting down");
10869: }
10870:
1.852 albertel 10871: sub get_dns {
1.869 albertel 10872: my ($url,$func,$ignore_cache) = @_;
10873: if (!$ignore_cache) {
10874: my ($content,$cached)=
10875: &Apache::lonnet::is_cached_new('dns',$url);
10876: if ($cached) {
10877: &$func($content);
10878: return;
10879: }
10880: }
10881:
10882: my %alldns;
1.852 albertel 10883: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
10884: foreach my $dns (<$config>) {
10885: next if ($dns !~ /^\^(\S*)/x);
1.979 raeburn 10886: my $line = $1;
10887: my ($host,$protocol) = split(/:/,$line);
10888: if ($protocol ne 'https') {
10889: $protocol = 'http';
10890: }
10891: $alldns{$host} = $protocol;
1.869 albertel 10892: }
10893: while (%alldns) {
10894: my ($dns) = keys(%alldns);
1.852 albertel 10895: my $ua=new LWP::UserAgent;
1.1134 raeburn 10896: $ua->timeout(30);
1.979 raeburn 10897: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 10898: my $response=$ua->request($request);
1.979 raeburn 10899: delete($alldns{$dns});
1.852 albertel 10900: next if ($response->is_error());
10901: my @content = split("\n",$response->content);
1.869 albertel 10902: &Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852 albertel 10903: &$func(\@content);
1.869 albertel 10904: return;
1.852 albertel 10905: }
10906: close($config);
1.871 albertel 10907: my $which = (split('/',$url))[3];
10908: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
10909: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 10910: my @content = <$config>;
10911: &$func(\@content);
10912: return;
1.852 albertel 10913: }
1.327 albertel 10914: # ------------------------------------------------------------ Read domain file
10915: {
1.852 albertel 10916: my $loaded;
1.846 albertel 10917: my %domain;
10918:
1.852 albertel 10919: sub parse_domain_tab {
10920: my ($lines) = @_;
10921: foreach my $line (@$lines) {
10922: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 10923:
1.846 albertel 10924: chomp($line);
1.852 albertel 10925: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 10926: my %this_domain;
10927: foreach my $field ('description', 'auth_def', 'auth_arg_def',
10928: 'lang_def', 'city', 'longi', 'lati',
10929: 'primary') {
10930: $this_domain{$field} = shift(@elements);
10931: }
10932: $domain{$name} = \%this_domain;
1.852 albertel 10933: }
10934: }
1.864 albertel 10935:
10936: sub reset_domain_info {
10937: undef($loaded);
10938: undef(%domain);
10939: }
10940:
1.852 albertel 10941: sub load_domain_tab {
1.869 albertel 10942: my ($ignore_cache) = @_;
10943: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852 albertel 10944: my $fh;
10945: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
10946: my @lines = <$fh>;
10947: &parse_domain_tab(\@lines);
1.448 albertel 10948: }
1.852 albertel 10949: close($fh);
10950: $loaded = 1;
1.327 albertel 10951: }
1.846 albertel 10952:
10953: sub domain {
1.852 albertel 10954: &load_domain_tab() if (!$loaded);
10955:
1.846 albertel 10956: my ($name,$what) = @_;
10957: return if ( !exists($domain{$name}) );
10958:
10959: if (!$what) {
10960: return $domain{$name}{'description'};
10961: }
10962: return $domain{$name}{$what};
10963: }
1.974 raeburn 10964:
10965: sub domain_info {
10966: &load_domain_tab() if (!$loaded);
10967: return %domain;
10968: }
10969:
1.327 albertel 10970: }
10971:
10972:
1.1 albertel 10973: # ------------------------------------------------------------- Read hosts file
10974: {
1.838 albertel 10975: my %hostname;
1.844 albertel 10976: my %hostdom;
1.845 albertel 10977: my %libserv;
1.852 albertel 10978: my $loaded;
1.888 albertel 10979: my %name_to_host;
1.1074 raeburn 10980: my %internetdom;
1.1107 raeburn 10981: my %LC_dns_serv;
1.852 albertel 10982:
10983: sub parse_hosts_tab {
10984: my ($file) = @_;
10985: foreach my $configline (@$file) {
10986: next if ($configline =~ /^(\#|\s*$ )/x);
1.1107 raeburn 10987: chomp($configline);
10988: if ($configline =~ /^\^/) {
10989: if ($configline =~ /^\^([\w.\-]+)/) {
10990: $LC_dns_serv{$1} = 1;
10991: }
10992: next;
10993: }
1.1074 raeburn 10994: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 10995: $name=~s/\s//g;
10996: if ($id && $domain && $role && $name) {
10997: $hostname{$id}=$name;
1.888 albertel 10998: push(@{$name_to_host{$name}}, $id);
1.852 albertel 10999: $hostdom{$id}=$domain;
11000: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 11001: if (defined($protocol)) {
11002: if ($protocol eq 'https') {
11003: $protocol{$id} = $protocol;
11004: } else {
11005: $protocol{$id} = 'http';
11006: }
1.968 raeburn 11007: } else {
1.969 raeburn 11008: $protocol{$id} = 'http';
1.968 raeburn 11009: }
1.1074 raeburn 11010: if (defined($intdom)) {
11011: $internetdom{$id} = $intdom;
11012: }
1.852 albertel 11013: }
11014: }
11015: }
1.864 albertel 11016:
11017: sub reset_hosts_info {
1.897 albertel 11018: &purge_remembered();
1.864 albertel 11019: &reset_domain_info();
11020: &reset_hosts_ip_info();
1.892 albertel 11021: undef(%name_to_host);
1.864 albertel 11022: undef(%hostname);
11023: undef(%hostdom);
11024: undef(%libserv);
11025: undef($loaded);
11026: }
1.1 albertel 11027:
1.852 albertel 11028: sub load_hosts_tab {
1.869 albertel 11029: my ($ignore_cache) = @_;
11030: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852 albertel 11031: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11032: my @config = <$config>;
11033: &parse_hosts_tab(\@config);
11034: close($config);
11035: $loaded=1;
1.1 albertel 11036: }
1.852 albertel 11037:
1.838 albertel 11038: sub hostname {
1.852 albertel 11039: &load_hosts_tab() if (!$loaded);
11040:
1.838 albertel 11041: my ($lonid) = @_;
11042: return $hostname{$lonid};
11043: }
1.845 albertel 11044:
1.838 albertel 11045: sub all_hostnames {
1.852 albertel 11046: &load_hosts_tab() if (!$loaded);
11047:
1.838 albertel 11048: return %hostname;
11049: }
1.845 albertel 11050:
1.888 albertel 11051: sub all_names {
11052: &load_hosts_tab() if (!$loaded);
11053:
11054: return %name_to_host;
11055: }
11056:
1.974 raeburn 11057: sub all_host_domain {
11058: &load_hosts_tab() if (!$loaded);
11059: return %hostdom;
11060: }
11061:
1.845 albertel 11062: sub is_library {
1.852 albertel 11063: &load_hosts_tab() if (!$loaded);
11064:
1.845 albertel 11065: return exists($libserv{$_[0]});
11066: }
11067:
11068: sub all_library {
1.852 albertel 11069: &load_hosts_tab() if (!$loaded);
11070:
1.845 albertel 11071: return %libserv;
11072: }
11073:
1.1062 droeschl 11074: sub unique_library {
11075: #2x reverse removes all hostnames that appear more than once
11076: my %unique = reverse &all_library();
11077: return reverse %unique;
11078: }
11079:
1.841 albertel 11080: sub get_servers {
1.852 albertel 11081: &load_hosts_tab() if (!$loaded);
11082:
1.841 albertel 11083: my ($domain,$type) = @_;
11084: my %possible_hosts = ($type eq 'library') ? %libserv
11085: : %hostname;
11086: my %result;
1.842 albertel 11087: if (ref($domain) eq 'ARRAY') {
11088: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 11089: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 11090: $result{$host} = $hostname;
11091: }
11092: }
11093: } else {
11094: while ( my ($host,$hostname) = each(%possible_hosts)) {
11095: if ($hostdom{$host} eq $domain) {
11096: $result{$host} = $hostname;
11097: }
1.841 albertel 11098: }
11099: }
11100: return %result;
11101: }
1.845 albertel 11102:
1.1062 droeschl 11103: sub get_unique_servers {
11104: my %unique = reverse &get_servers(@_);
11105: return reverse %unique;
11106: }
11107:
1.844 albertel 11108: sub host_domain {
1.852 albertel 11109: &load_hosts_tab() if (!$loaded);
11110:
1.844 albertel 11111: my ($lonid) = @_;
11112: return $hostdom{$lonid};
11113: }
11114:
1.841 albertel 11115: sub all_domains {
1.852 albertel 11116: &load_hosts_tab() if (!$loaded);
11117:
1.841 albertel 11118: my %seen;
11119: my @uniq = grep(!$seen{$_}++, values(%hostdom));
11120: return @uniq;
11121: }
1.1074 raeburn 11122:
11123: sub internet_dom {
11124: &load_hosts_tab() if (!$loaded);
11125:
11126: my ($lonid) = @_;
11127: return $internetdom{$lonid};
11128: }
1.1107 raeburn 11129:
11130: sub is_LC_dns {
11131: &load_hosts_tab() if (!$loaded);
11132:
11133: my ($hostname) = @_;
11134: return exists($LC_dns_serv{$hostname});
11135: }
11136:
1.1 albertel 11137: }
11138:
1.847 albertel 11139: {
11140: my %iphost;
1.856 albertel 11141: my %name_to_ip;
11142: my %lonid_to_ip;
1.869 albertel 11143:
1.847 albertel 11144: sub get_hosts_from_ip {
11145: my ($ip) = @_;
11146: my %iphosts = &get_iphost();
11147: if (ref($iphosts{$ip})) {
11148: return @{$iphosts{$ip}};
11149: }
11150: return;
1.839 albertel 11151: }
1.864 albertel 11152:
11153: sub reset_hosts_ip_info {
11154: undef(%iphost);
11155: undef(%name_to_ip);
11156: undef(%lonid_to_ip);
11157: }
1.856 albertel 11158:
11159: sub get_host_ip {
11160: my ($lonid) = @_;
11161: if (exists($lonid_to_ip{$lonid})) {
11162: return $lonid_to_ip{$lonid};
11163: }
11164: my $name=&hostname($lonid);
11165: my $ip = gethostbyname($name);
11166: return if (!$ip || length($ip) ne 4);
11167: $ip=inet_ntoa($ip);
11168: $name_to_ip{$name} = $ip;
11169: $lonid_to_ip{$lonid} = $ip;
11170: return $ip;
11171: }
1.847 albertel 11172:
11173: sub get_iphost {
1.869 albertel 11174: my ($ignore_cache) = @_;
1.894 albertel 11175:
1.869 albertel 11176: if (!$ignore_cache) {
11177: if (%iphost) {
11178: return %iphost;
11179: }
11180: my ($ip_info,$cached)=
11181: &Apache::lonnet::is_cached_new('iphost','iphost');
11182: if ($cached) {
11183: %iphost = %{$ip_info->[0]};
11184: %name_to_ip = %{$ip_info->[1]};
11185: %lonid_to_ip = %{$ip_info->[2]};
11186: return %iphost;
11187: }
11188: }
1.894 albertel 11189:
11190: # get yesterday's info for fallback
11191: my %old_name_to_ip;
11192: my ($ip_info,$cached)=
11193: &Apache::lonnet::is_cached_new('iphost','iphost');
11194: if ($cached) {
11195: %old_name_to_ip = %{$ip_info->[1]};
11196: }
11197:
1.888 albertel 11198: my %name_to_host = &all_names();
11199: foreach my $name (keys(%name_to_host)) {
1.847 albertel 11200: my $ip;
11201: if (!exists($name_to_ip{$name})) {
11202: $ip = gethostbyname($name);
11203: if (!$ip || length($ip) ne 4) {
1.894 albertel 11204: if (defined($old_name_to_ip{$name})) {
11205: $ip = $old_name_to_ip{$name};
11206: &logthis("Can't find $name defaulting to old $ip");
11207: } else {
11208: &logthis("Name $name no IP found");
11209: next;
11210: }
11211: } else {
11212: $ip=inet_ntoa($ip);
1.847 albertel 11213: }
11214: $name_to_ip{$name} = $ip;
11215: } else {
11216: $ip = $name_to_ip{$name};
1.653 albertel 11217: }
1.888 albertel 11218: foreach my $id (@{ $name_to_host{$name} }) {
11219: $lonid_to_ip{$id} = $ip;
11220: }
11221: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 11222: }
1.869 albertel 11223: &Apache::lonnet::do_cache_new('iphost','iphost',
11224: [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894 albertel 11225: 48*60*60);
1.869 albertel 11226:
1.847 albertel 11227: return %iphost;
1.598 albertel 11228: }
11229:
1.992 raeburn 11230: #
11231: # Given a DNS returns the loncapa host name for that DNS
11232: #
11233: sub host_from_dns {
11234: my ($dns) = @_;
11235: my @hosts;
11236: my $ip;
11237:
1.993 raeburn 11238: if (exists($name_to_ip{$dns})) {
1.992 raeburn 11239: $ip = $name_to_ip{$dns};
11240: }
11241: if (!$ip) {
11242: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
11243: if (length($ip) == 4) {
11244: $ip = &IO::Socket::inet_ntoa($ip);
11245: }
11246: }
11247: if ($ip) {
11248: @hosts = get_hosts_from_ip($ip);
11249: return $hosts[0];
11250: }
11251: return undef;
1.986 foxr 11252: }
1.992 raeburn 11253:
1.1074 raeburn 11254: sub get_internet_names {
11255: my ($lonid) = @_;
11256: return if ($lonid eq '');
11257: my ($idnref,$cached)=
11258: &Apache::lonnet::is_cached_new('internetnames',$lonid);
11259: if ($cached) {
11260: return $idnref;
11261: }
11262: my $ip = &get_host_ip($lonid);
11263: my @hosts = &get_hosts_from_ip($ip);
11264: my %iphost = &get_iphost();
11265: my (@idns,%seen);
11266: foreach my $id (@hosts) {
11267: my $dom = &host_domain($id);
11268: my $prim_id = &domain($dom,'primary');
11269: my $prim_ip = &get_host_ip($prim_id);
11270: next if ($seen{$prim_ip});
11271: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
11272: foreach my $id (@{$iphost{$prim_ip}}) {
11273: my $intdom = &internet_dom($id);
11274: unless (grep(/^\Q$intdom\E$/,@idns)) {
11275: push(@idns,$intdom);
11276: }
11277: }
11278: }
11279: $seen{$prim_ip} = 1;
11280: }
11281: return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
11282: }
11283:
1.986 foxr 11284: }
11285:
1.1079 raeburn 11286: sub all_loncaparevs {
11287: 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);
11288: }
11289:
1.862 albertel 11290: BEGIN {
11291:
11292: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
11293: unless ($readit) {
11294: {
11295: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
11296: %perlvar = (%perlvar,%{$configvars});
11297: }
11298:
11299:
1.1 albertel 11300: # ------------------------------------------------------ Read spare server file
11301: {
1.448 albertel 11302: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 11303:
11304: while (my $configline=<$config>) {
11305: chomp($configline);
1.284 matthew 11306: if ($configline) {
1.784 albertel 11307: my ($host,$type) = split(':',$configline,2);
1.785 albertel 11308: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 11309: push(@{ $spareid{$type} }, $host);
1.1 albertel 11310: }
11311: }
1.448 albertel 11312: close($config);
1.1 albertel 11313: }
1.11 www 11314: # ------------------------------------------------------------ Read permissions
11315: {
1.448 albertel 11316: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 11317:
11318: while (my $configline=<$config>) {
1.448 albertel 11319: chomp($configline);
11320: if ($configline) {
11321: my ($role,$perm)=split(/ /,$configline);
11322: if ($perm ne '') { $pr{$role}=$perm; }
11323: }
1.11 www 11324: }
1.448 albertel 11325: close($config);
1.11 www 11326: }
11327:
11328: # -------------------------------------------- Read plain texts for permissions
11329: {
1.448 albertel 11330: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 11331:
11332: while (my $configline=<$config>) {
1.448 albertel 11333: chomp($configline);
11334: if ($configline) {
1.742 raeburn 11335: my ($short,@plain)=split(/:/,$configline);
11336: %{$prp{$short}} = ();
11337: if (@plain > 0) {
11338: $prp{$short}{'std'} = $plain[0];
11339: for (my $i=1; $i<@plain; $i++) {
11340: $prp{$short}{'alt'.$i} = $plain[$i];
11341: }
11342: }
1.448 albertel 11343: }
1.135 www 11344: }
1.448 albertel 11345: close($config);
1.135 www 11346: }
11347:
11348: # ---------------------------------------------------------- Read package table
11349: {
1.448 albertel 11350: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 11351:
11352: while (my $configline=<$config>) {
1.483 albertel 11353: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 11354: chomp($configline);
11355: my ($short,$plain)=split(/:/,$configline);
11356: my ($pack,$name)=split(/\&/,$short);
11357: if ($plain ne '') {
11358: $packagetab{$pack.'&'.$name.'&name'}=$name;
11359: $packagetab{$short}=$plain;
11360: }
1.11 www 11361: }
1.448 albertel 11362: close($config);
1.329 matthew 11363: }
11364:
1.1073 raeburn 11365: # ---------------------------------------------------------- Read loncaparev table
11366: {
11367: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
11368: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
11369: while (my $configline=<$config>) {
11370: chomp($configline);
11371: my ($hostid,$loncaparev)=split(/:/,$configline);
11372: $loncaparevs{$hostid}=$loncaparev;
11373: }
11374: close($config);
11375: }
11376: }
11377: }
11378:
1.1074 raeburn 11379: # ---------------------------------------------------------- Read serverhostID table
11380: {
11381: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
11382: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
11383: while (my $configline=<$config>) {
11384: chomp($configline);
11385: my ($name,$id)=split(/:/,$configline);
11386: $serverhomeIDs{$name}=$id;
11387: }
11388: close($config);
11389: }
11390: }
11391: }
11392:
1.1079 raeburn 11393: {
11394: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
11395: if (-e $file) {
11396: my $parser = HTML::LCParser->new($file);
11397: while (my $token = $parser->get_token()) {
11398: if ($token->[0] eq 'S') {
11399: my $item = $token->[1];
11400: my $name = $token->[2]{'name'};
11401: my $value = $token->[2]{'value'};
11402: if ($item ne '' && $name ne '' && $value ne '') {
11403: my $release = $parser->get_text();
11404: $release =~ s/(^\s*|\s*$ )//gx;
11405: $needsrelease{$item.':'.$name.':'.$value} = $release;
11406: }
11407: }
11408: }
11409: }
1.1073 raeburn 11410: }
11411:
1.1138 raeburn 11412: # ---------------------------------------------------------- Read managers table
11413: {
11414: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
11415: if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
11416: while (my $configline=<$config>) {
11417: chomp($configline);
11418: next if ($configline =~ /^\#/);
11419: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
11420: $managerstab{$configline} = 1;
11421: }
11422: }
11423: close($config);
11424: }
11425: }
11426: }
11427:
1.329 matthew 11428: # ------------- set up temporary directory
11429: {
1.1117 foxr 11430: $tmpdir = LONCAPA::tempdir();
1.329 matthew 11431:
1.11 www 11432: }
11433:
1.794 albertel 11434: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
11435: 'compress_threshold'=> 20_000,
11436: });
1.185 www 11437:
1.281 www 11438: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 11439: $dumpcount=0;
1.958 www 11440: $locknum=0;
1.22 www 11441:
1.163 harris41 11442: &logtouch();
1.672 albertel 11443: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 11444: $readit=1;
1.564 albertel 11445: {
11446: use integer;
11447: my $test=(2**32)+1;
1.568 albertel 11448: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 11449: &logthis(" Detected 64bit platform ($_64bit)");
11450: }
1.195 www 11451: }
1.1 albertel 11452: }
1.179 www 11453:
1.1 albertel 11454: 1;
1.191 harris41 11455: __END__
11456:
1.243 albertel 11457: =pod
11458:
1.191 harris41 11459: =head1 NAME
11460:
1.243 albertel 11461: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 11462:
11463: =head1 SYNOPSIS
11464:
1.243 albertel 11465: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 11466:
11467: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
11468:
1.243 albertel 11469: Common parameters:
11470:
11471: =over 4
11472:
11473: =item *
11474:
11475: $uname : an internal username (if $cname expecting a course Id specifically)
11476:
11477: =item *
11478:
11479: $udom : a domain (if $cdom expecting a course's domain specifically)
11480:
11481: =item *
11482:
11483: $symb : a resource instance identifier
11484:
11485: =item *
11486:
11487: $namespace : the name of a .db file that contains the data needed or
11488: being set.
11489:
11490: =back
11491:
1.394 bowersj2 11492: =head1 OVERVIEW
1.191 harris41 11493:
1.394 bowersj2 11494: lonnet provides subroutines which interact with the
11495: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
11496: about classes, users, and resources.
1.243 albertel 11497:
11498: For many of these objects you can also use this to store data about
11499: them or modify them in various ways.
1.191 harris41 11500:
1.394 bowersj2 11501: =head2 Symbs
1.191 harris41 11502:
1.394 bowersj2 11503: To identify a specific instance of a resource, LON-CAPA uses symbols
11504: or "symbs"X<symb>. These identifiers are built from the URL of the
11505: map, the resource number of the resource in the map, and the URL of
11506: the resource itself. The latter is somewhat redundant, but might help
11507: if maps change.
11508:
11509: An example is
11510:
11511: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
11512:
11513: The respective map entry is
11514:
11515: <resource id="19" src="/res/msu/korte/tests/part12.problem"
11516: title="Problem 2">
11517: </resource>
11518:
11519: Symbs are used by the random number generator, as well as to store and
11520: restore data specific to a certain instance of for example a problem.
11521:
11522: =head2 Storing And Retrieving Data
11523:
11524: X<store()>X<cstore()>X<restore()>Three of the most important functions
11525: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
11526: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
11527: is is the non-critical message twin of cstore. These functions are for
11528: handlers to store a perl hash to a user's permanent data space in an
11529: easy manner, and to retrieve it again on another call. It is expected
11530: that a handler would use this once at the beginning to retrieve data,
11531: and then again once at the end to send only the new data back.
11532:
11533: The data is stored in the user's data directory on the user's
11534: homeserver under the ID of the course.
11535:
11536: The hash that is returned by restore will have all of the previous
11537: value for all of the elements of the hash.
11538:
11539: Example:
11540:
11541: #creating a hash
11542: my %hash;
11543: $hash{'foo'}='bar';
11544:
11545: #storing it
11546: &Apache::lonnet::cstore(\%hash);
11547:
11548: #changing a value
11549: $hash{'foo'}='notbar';
11550:
11551: #adding a new value
11552: $hash{'bar'}='foo';
11553: &Apache::lonnet::cstore(\%hash);
11554:
11555: #retrieving the hash
11556: my %history=&Apache::lonnet::restore();
11557:
11558: #print the hash
11559: foreach my $key (sort(keys(%history))) {
11560: print("\%history{$key} = $history{$key}");
11561: }
11562:
11563: Will print out:
1.191 harris41 11564:
1.394 bowersj2 11565: %history{1:foo} = bar
11566: %history{1:keys} = foo:timestamp
11567: %history{1:timestamp} = 990455579
11568: %history{2:bar} = foo
11569: %history{2:foo} = notbar
11570: %history{2:keys} = foo:bar:timestamp
11571: %history{2:timestamp} = 990455580
11572: %history{bar} = foo
11573: %history{foo} = notbar
11574: %history{timestamp} = 990455580
11575: %history{version} = 2
11576:
11577: Note that the special hash entries C<keys>, C<version> and
11578: C<timestamp> were added to the hash. C<version> will be equal to the
11579: total number of versions of the data that have been stored. The
11580: C<timestamp> attribute will be the UNIX time the hash was
11581: stored. C<keys> is available in every historical section to list which
11582: keys were added or changed at a specific historical revision of a
11583: hash.
11584:
11585: B<Warning>: do not store the hash that restore returns directly. This
11586: will cause a mess since it will restore the historical keys as if the
11587: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 11588:
1.394 bowersj2 11589: Calling convention:
1.191 harris41 11590:
1.394 bowersj2 11591: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
11592: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191 harris41 11593:
1.394 bowersj2 11594: For more detailed information, see lonnet specific documentation.
1.191 harris41 11595:
1.394 bowersj2 11596: =head1 RETURN MESSAGES
1.191 harris41 11597:
1.394 bowersj2 11598: =over 4
1.191 harris41 11599:
1.394 bowersj2 11600: =item * B<con_lost>: unable to contact remote host
1.191 harris41 11601:
1.394 bowersj2 11602: =item * B<con_delayed>: unable to contact remote host, message will be delivered
11603: when the connection is brought back up
1.191 harris41 11604:
1.394 bowersj2 11605: =item * B<con_failed>: unable to contact remote host and unable to save message
11606: for later delivery
1.191 harris41 11607:
1.967 bisitz 11608: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 11609:
1.394 bowersj2 11610: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 11611: that was requested
1.191 harris41 11612:
1.243 albertel 11613: =back
1.191 harris41 11614:
1.243 albertel 11615: =head1 PUBLIC SUBROUTINES
1.191 harris41 11616:
1.243 albertel 11617: =head2 Session Environment Functions
1.191 harris41 11618:
1.243 albertel 11619: =over 4
1.191 harris41 11620:
1.394 bowersj2 11621: =item *
11622: X<appenv()>
1.949 raeburn 11623: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 11624: the user envirnoment file, and will be restored for each access this
1.620 albertel 11625: user makes during this session, also modifies the %env for the current
1.949 raeburn 11626: process. Optional rolesarrayref - if defined contains a reference to an array
11627: of roles which are exempt from the restriction on modifying user.role entries
11628: in the user's environment.db and in %env.
1.191 harris41 11629:
11630: =item *
1.394 bowersj2 11631: X<delenv()>
1.987 raeburn 11632: B<delenv($delthis,$regexp)>: removes all items from the session
11633: environment file that begin with $delthis. If the
11634: optional second arg - $regexp - is true, $delthis is treated as a
11635: regular expression, otherwise \Q$delthis\E is used.
11636: The values are also deleted from the current processes %env.
1.191 harris41 11637:
1.795 albertel 11638: =item * get_env_multiple($name)
11639:
11640: gets $name from the %env hash, it seemlessly handles the cases where multiple
11641: values may be defined and end up as an array ref.
11642:
11643: returns an array of values
11644:
1.243 albertel 11645: =back
11646:
11647: =head2 User Information
1.191 harris41 11648:
1.243 albertel 11649: =over 4
1.191 harris41 11650:
11651: =item *
1.394 bowersj2 11652: X<queryauthenticate()>
11653: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 11654: authentication scheme
11655:
11656: =item *
1.394 bowersj2 11657: X<authenticate()>
1.1073 raeburn 11658: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 11659: authenticate user from domain's lib servers (first use the current
11660: one). C<$upass> should be the users password.
1.1073 raeburn 11661: $checkdefauth is optional (value is 1 if a check should be made to
11662: authenticate user using default authentication method, and allow
11663: account creation if username does not have account in the domain).
11664: $clientcancheckhost is optional (value is 1 if checking whether the
11665: server can host will occur on the client side in lonauth.pm).
1.191 harris41 11666:
11667: =item *
1.394 bowersj2 11668: X<homeserver()>
11669: B<homeserver($uname,$udom)>: find the server which has
11670: the user's directory and files (there must be only one), this caches
11671: the answer, and also caches if there is a borken connection.
1.191 harris41 11672:
11673: =item *
1.394 bowersj2 11674: X<idget()>
11675: B<idget($udom,@ids)>: find the usernames behind a list of IDs
11676: (IDs are a unique resource in a domain, there must be only 1 ID per
11677: username, and only 1 username per ID in a specific domain) (returns
11678: hash: id=>name,id=>name)
1.191 harris41 11679:
11680: =item *
1.394 bowersj2 11681: X<idrget()>
11682: B<idrget($udom,@unames)>: find the IDs behind a list of
11683: usernames (returns hash: name=>id,name=>id)
1.191 harris41 11684:
11685: =item *
1.394 bowersj2 11686: X<idput()>
11687: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 11688:
11689: =item *
1.394 bowersj2 11690: X<rolesinit()>
11691: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243 albertel 11692:
11693: =item *
1.551 albertel 11694: X<getsection()>
11695: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 11696: course $cname, return section name/number or '' for "not in course"
11697: and '-1' for "no section"
11698:
11699: =item *
1.394 bowersj2 11700: X<userenvironment()>
11701: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 11702: passed in @what from the requested user's environment, returns a hash
11703:
1.858 raeburn 11704: =item *
11705: X<userlog_query()>
1.859 albertel 11706: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
11707: activity.log file. %filters defines filters applied when parsing the
11708: log file. These can be start or end timestamps, or the type of action
11709: - log to look for Login or Logout events, check for Checkin or
11710: Checkout, role for role selection. The response is in the form
11711: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
11712: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 11713:
1.243 albertel 11714: =back
11715:
11716: =head2 User Roles
11717:
11718: =over 4
11719:
11720: =item *
11721:
1.810 raeburn 11722: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243 albertel 11723: F: full access
11724: U,I,K: authentication modes (cxx only)
11725: '': forbidden
11726: 1: user needs to choose course
11727: 2: browse allowed
1.766 albertel 11728: A: passphrase authentication needed
1.243 albertel 11729:
11730: =item *
11731:
11732: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
11733: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
11734: and course level
11735:
11736: =item *
11737:
1.988 raeburn 11738: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
11739: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 11740: $type is Course (default) or Community.
1.988 raeburn 11741: If $forcedefault evaluates to true, text returned will be default
11742: text for $type. Otherwise, if this is a course, the text returned
11743: will be a custom name for the role (if defined in the course's
11744: environment). If no custom name is defined the default is returned.
11745:
1.832 raeburn 11746: =item *
11747:
1.935 raeburn 11748: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858 raeburn 11749: All arguments are optional. Returns a hash of a roles, either for
11750: co-author/assistant author roles for a user's Construction Space
1.906 albertel 11751: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 11752: In the hash, keys are set to colon-separated $uname,$udom,$role, and
11753: (optionally) if $withsec is true, a fourth colon-separated item - $section.
11754: For each key, value is set to colon-separated start and end times for
11755: the role. If no username and domain are specified, will default to
1.934 raeburn 11756: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 11757: of role statuses (active, future or previous), roles
11758: (e.g., cc,in, st etc.) and domains of the roles which can be used
11759: to restrict the list of roles reported. If no array ref is
11760: provided for types, will default to return only active roles.
1.834 albertel 11761:
1.243 albertel 11762: =back
11763:
11764: =head2 User Modification
11765:
11766: =over 4
11767:
11768: =item *
11769:
1.957 raeburn 11770: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 11771: user for the level given by URL. Optional start and end dates (leave empty
11772: string or zero for "no date")
1.191 harris41 11773:
11774: =item *
11775:
1.243 albertel 11776: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
11777: change a users, password, possible return values are: ok,
11778: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
11779: refused
1.191 harris41 11780:
11781: =item *
11782:
1.243 albertel 11783: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 11784:
11785: =item *
11786:
1.1058 raeburn 11787: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
11788: $forceid,$desiredhome,$email,$inststatus,$candelete) :
11789:
11790: will update user information (firstname,middlename,lastname,generation,
11791: permanentemail), and if forceid is true, student/employee ID also.
11792: A user's institutional affiliation(s) can also be updated.
11793: User information fields will not be overwritten with empty entries
11794: unless the field is included in the $candelete array reference.
11795: This array is included when a single user is modified via "Manage Users",
11796: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 11797:
11798: =item *
11799:
1.286 matthew 11800: modifystudent
11801:
1.957 raeburn 11802: modify a student's enrollment and identification information.
1.286 matthew 11803: The course id is resolved based on the current users environment.
11804: This means the envoking user must be a course coordinator or otherwise
11805: associated with a course.
11806:
1.297 matthew 11807: This call is essentially a wrapper for lonnet::modifyuser and
11808: lonnet::modify_student_enrollment
1.286 matthew 11809:
11810: Inputs:
11811:
11812: =over 4
11813:
1.957 raeburn 11814: =item B<$udom> Student's loncapa domain
1.286 matthew 11815:
1.957 raeburn 11816: =item B<$uname> Student's loncapa login name
1.286 matthew 11817:
1.964 bisitz 11818: =item B<$uid> Student/Employee ID
1.286 matthew 11819:
1.957 raeburn 11820: =item B<$umode> Student's authentication mode
1.286 matthew 11821:
1.957 raeburn 11822: =item B<$upass> Student's password
1.286 matthew 11823:
1.957 raeburn 11824: =item B<$first> Student's first name
1.286 matthew 11825:
1.957 raeburn 11826: =item B<$middle> Student's middle name
1.286 matthew 11827:
1.957 raeburn 11828: =item B<$last> Student's last name
1.286 matthew 11829:
1.957 raeburn 11830: =item B<$gene> Student's generation
1.286 matthew 11831:
1.957 raeburn 11832: =item B<$usec> Student's section in course
1.286 matthew 11833:
11834: =item B<$end> Unix time of the roles expiration
11835:
11836: =item B<$start> Unix time of the roles start date
11837:
11838: =item B<$forceid> If defined, allow $uid to be changed
11839:
11840: =item B<$desiredhome> server to use as home server for student
11841:
1.957 raeburn 11842: =item B<$email> Student's permanent e-mail address
11843:
11844: =item B<$type> Type of enrollment (auto or manual)
11845:
1.963 raeburn 11846: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
11847:
11848: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 11849:
1.963 raeburn 11850: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 11851:
1.963 raeburn 11852: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 11853:
1.963 raeburn 11854: =item B<$inststatus> institutional status of user - : separated string of escaped status types
1.957 raeburn 11855:
1.286 matthew 11856: =back
1.297 matthew 11857:
11858: =item *
11859:
11860: modify_student_enrollment
11861:
11862: Change a students enrollment status in a class. The environment variable
11863: 'role.request.course' must be defined for this function to proceed.
11864:
11865: Inputs:
11866:
11867: =over 4
11868:
11869: =item $udom, students domain
11870:
11871: =item $uname, students name
11872:
11873: =item $uid, students user id
11874:
11875: =item $first, students first name
11876:
11877: =item $middle
11878:
11879: =item $last
11880:
11881: =item $gene
11882:
11883: =item $usec
11884:
11885: =item $end
11886:
11887: =item $start
11888:
1.957 raeburn 11889: =item $type
11890:
11891: =item $locktype
11892:
11893: =item $cid
11894:
11895: =item $selfenroll
11896:
11897: =item $context
11898:
1.297 matthew 11899: =back
11900:
1.191 harris41 11901:
11902: =item *
11903:
1.243 albertel 11904: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
11905: custom role; give a custom role to a user for the level given by URL. Specify
11906: name and domain of role author, and role name
1.191 harris41 11907:
11908: =item *
11909:
1.243 albertel 11910: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 11911:
11912: =item *
11913:
1.243 albertel 11914: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
11915:
11916: =back
11917:
11918: =head2 Course Infomation
11919:
11920: =over 4
1.191 harris41 11921:
11922: =item *
11923:
1.1118 foxr 11924: coursedescription($courseid,$options) : returns a hash of information about the
1.631 albertel 11925: specified course id, including all environment settings for the
11926: course, the description of the course will be in the hash under the
11927: key 'description'
1.191 harris41 11928:
1.1118 foxr 11929: $options is an optional parameter that if supplied is a hash reference that controls
11930: what how this function works. It has the following key/values:
11931:
11932: =over 4
11933:
11934: =item freshen_cache
11935:
11936: If defined, and the environment cache for the course is valid, it is
11937: returned in the returned hash.
11938:
11939: =item one_time
11940:
11941: If defined, the last cache time is set to _now_
11942:
11943: =item user
11944:
11945: If defined, the supplied username is used instead of the current user.
11946:
11947:
11948: =back
11949:
1.191 harris41 11950: =item *
11951:
1.624 albertel 11952: resdata($name,$domain,$type,@which) : request for current parameter
11953: setting for a specific $type, where $type is either 'course' or 'user',
11954: @what should be a list of parameters to ask about. This routine caches
11955: answers for 5 minutes.
1.243 albertel 11956:
1.877 foxr 11957: =item *
11958:
11959: get_courseresdata($courseid, $domain) : dump the entire course resource
11960: data base, returning a hash that is keyed by the resource name and has
11961: values that are the resource value. I believe that the timestamps and
11962: versions are also returned.
11963:
11964:
1.243 albertel 11965: =back
11966:
11967: =head2 Course Modification
11968:
11969: =over 4
1.191 harris41 11970:
11971: =item *
11972:
1.243 albertel 11973: writecoursepref($courseid,%prefs) : write preferences (environment
11974: database) for a course
1.191 harris41 11975:
11976: =item *
11977:
1.1011 raeburn 11978: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
11979:
11980: =item *
11981:
1.1038 raeburn 11982: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 11983:
1.1167 ! droeschl 11984: =item *
! 11985:
! 11986: is_course($courseid), is_course($cdom, $cnum)
! 11987:
! 11988: Accepts either a combined $courseid (in the form of domain_courseid) or the
! 11989: two component version $cdom, $cnum. It checks if the specified course exists.
! 11990:
! 11991: Returns:
! 11992: undef if the course doesn't exist, otherwise
! 11993: in scalar context the combined courseid.
! 11994: in list context the two components of the course identifier, domain and
! 11995: courseid.
! 11996:
1.243 albertel 11997: =back
11998:
11999: =head2 Resource Subroutines
12000:
12001: =over 4
1.191 harris41 12002:
12003: =item *
12004:
1.243 albertel 12005: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 12006:
12007: =item *
12008:
1.243 albertel 12009: repcopy($filename) : subscribes to the requested file, and attempts to
12010: replicate from the owning library server, Might return
1.607 raeburn 12011: 'unavailable', 'not_found', 'forbidden', 'ok', or
12012: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 12013: resource. Expects the local filesystem pathname
12014: (/home/httpd/html/res/....)
12015:
12016: =back
12017:
12018: =head2 Resource Information
12019:
12020: =over 4
1.191 harris41 12021:
12022: =item *
12023:
1.243 albertel 12024: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
12025: a vairety of different possible values, $varname should be a request
12026: string, and the other parameters can be used to specify who and what
12027: one is asking about.
12028:
12029: Possible values for $varname are environment.lastname (or other item
12030: from the envirnment hash), user.name (or someother aspect about the
12031: user), resource.0.maxtries (or some other part and parameter of a
12032: resource)
1.204 albertel 12033:
12034: =item *
12035:
1.243 albertel 12036: directcondval($number) : get current value of a condition; reads from a state
12037: string
1.204 albertel 12038:
12039: =item *
12040:
1.243 albertel 12041: condval($condidx) : value of condition index based on state
1.204 albertel 12042:
12043: =item *
12044:
1.243 albertel 12045: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
12046: resource's metadata, $what should be either a specific key, or either
12047: 'keys' (to get a list of possible keys) or 'packages' to get a list of
12048: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
12049:
12050: this function automatically caches all requests
1.191 harris41 12051:
12052: =item *
12053:
1.243 albertel 12054: metadata_query($query,$custom,$customshow) : make a metadata query against the
12055: network of library servers; returns file handle of where SQL and regex results
12056: will be stored for query
1.191 harris41 12057:
12058: =item *
12059:
1.243 albertel 12060: symbread($filename) : return symbolic list entry (filename argument optional);
12061: returns the data handle
1.191 harris41 12062:
12063: =item *
12064:
1.243 albertel 12065: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582 albertel 12066: a possible symb for the URL in $thisfn, and if is an encryypted
12067: resource that the user accessed using /enc/ returns a 1 on success, 0
12068: on failure, user must be in a course, as it assumes the existance of
1.620 albertel 12069: the course initial hash, and uses $env('request.course.id'}
1.243 albertel 12070:
1.191 harris41 12071:
12072: =item *
12073:
1.243 albertel 12074: symbclean($symb) : removes versions numbers from a symb, returns the
12075: cleaned symb
1.191 harris41 12076:
12077: =item *
12078:
1.243 albertel 12079: is_on_map($uri) : checks if the $uri is somewhere on the current
12080: course map, user must be in a course for it to work.
1.191 harris41 12081:
12082: =item *
12083:
1.243 albertel 12084: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 12085:
12086: =item *
12087:
1.243 albertel 12088: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
12089: a random seed, all arguments are optional, if they aren't sent it uses the
12090: environment to derive them. Note: if symb isn't sent and it can't get one
12091: from &symbread it will use the current time as its return value
1.191 harris41 12092:
12093: =item *
12094:
1.243 albertel 12095: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
12096: unfakeable, receipt
1.191 harris41 12097:
12098: =item *
12099:
1.620 albertel 12100: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 12101:
12102: =item *
12103:
1.243 albertel 12104: countacc($url) : count the number of accesses to a given URL
1.191 harris41 12105:
12106: =item *
12107:
1.243 albertel 12108: 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 12109:
12110: =item *
12111:
1.243 albertel 12112: 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 12113:
12114: =item *
12115:
1.243 albertel 12116: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 12117:
12118: =item *
12119:
1.243 albertel 12120: devalidate($symb) : devalidate temporary spreadsheet calculations,
12121: forcing spreadsheet to reevaluate the resource scores next time.
12122:
12123: =back
12124:
12125: =head2 Storing/Retreiving Data
12126:
12127: =over 4
1.191 harris41 12128:
12129: =item *
12130:
1.243 albertel 12131: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
12132: for this url; hashref needs to be given and should be a \%hashname; the
12133: remaining args aren't required and if they aren't passed or are '' they will
1.620 albertel 12134: be derived from the env
1.191 harris41 12135:
12136: =item *
12137:
1.243 albertel 12138: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
12139: uses critical subroutine
1.191 harris41 12140:
12141: =item *
12142:
1.243 albertel 12143: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
12144: all args are optional
1.191 harris41 12145:
12146: =item *
12147:
1.717 albertel 12148: dumpstore($namespace,$udom,$uname,$regexp,$range) :
12149: dumps the complete (or key matching regexp) namespace into a hash
12150: ($udom, $uname, $regexp, $range are optional) for a namespace that is
12151: normally &store()ed into
12152:
12153: $range should be either an integer '100' (give me the first 100
12154: matching records)
12155: or be two integers sperated by a - with no spaces
12156: '30-50' (give me the 30th through the 50th matching
12157: records)
12158:
12159:
12160: =item *
12161:
12162: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
12163: replaces a &store() version of data with a replacement set of data
12164: for a particular resource in a namespace passed in the $storehash hash
12165: reference
12166:
12167: =item *
12168:
1.243 albertel 12169: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
12170: works very similar to store/cstore, but all data is stored in a
12171: temporary location and can be reset using tmpreset, $storehash should
12172: be a hash reference, returns nothing on success
1.191 harris41 12173:
12174: =item *
12175:
1.243 albertel 12176: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
12177: similar to restore, but all data is stored in a temporary location and
12178: can be reset using tmpreset. Returns a hash of values on success,
12179: error string otherwise.
1.191 harris41 12180:
12181: =item *
12182:
1.243 albertel 12183: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
12184: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 12185:
12186: =item *
12187:
1.243 albertel 12188: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
12189: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 12190:
12191: =item *
12192:
1.243 albertel 12193: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
12194: namesp ($udom and $uname are optional)
1.191 harris41 12195:
12196: =item *
12197:
1.702 albertel 12198: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 12199: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 12200: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 12201:
1.702 albertel 12202: $range should be either an integer '100' (give me the first 100
12203: matching records)
12204: or be two integers sperated by a - with no spaces
12205: '30-50' (give me the 30th through the 50th matching
12206: records)
1.449 matthew 12207: =item *
12208:
12209: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
12210: $store can be a scalar, an array reference, or if the amount to be
12211: incremented is > 1, a hash reference.
12212:
12213: ($udom and $uname are optional)
1.191 harris41 12214:
12215: =item *
12216:
1.243 albertel 12217: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
12218: ($udom and $uname are optional)
1.191 harris41 12219:
12220: =item *
12221:
1.243 albertel 12222: cput($namespace,$storehash,$udom,$uname) : critical put
12223: ($udom and $uname are optional)
1.191 harris41 12224:
12225: =item *
12226:
1.748 albertel 12227: newput($namespace,$storehash,$udom,$uname) :
12228:
12229: Attempts to store the items in the $storehash, but only if they don't
12230: currently exist, if this succeeds you can be certain that you have
12231: successfully created a new key value pair in the $namespace db.
12232:
12233:
12234: Args:
12235: $namespace: name of database to store values to
12236: $storehash: hashref to store to the db
12237: $udom: (optional) domain of user containing the db
12238: $uname: (optional) name of user caontaining the db
12239:
12240: Returns:
12241: 'ok' -> succeeded in storing all keys of $storehash
12242: 'key_exists: <key>' -> failed to anything out of $storehash, as at
12243: least <key> already existed in the db (other
12244: requested keys may also already exist)
1.967 bisitz 12245: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 12246: 'con_lost' -> unable to contact request server
12247: 'refused' -> action was not allowed by remote machine
12248:
12249:
12250: =item *
12251:
1.243 albertel 12252: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
12253: reference filled in from namesp (encrypts the return communication)
12254: ($udom and $uname are optional)
1.191 harris41 12255:
12256: =item *
12257:
1.243 albertel 12258: log($udom,$name,$home,$message) : write to permanent log for user; use
12259: critical subroutine
12260:
1.806 raeburn 12261: =item *
12262:
1.860 raeburn 12263: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
12264: array reference filled in from namespace found in domain level on either
12265: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 12266:
12267: =item *
12268:
1.860 raeburn 12269: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
12270: domain level either on specified domain server ($uhome) or primary domain
12271: server ($udom and $uhome are optional)
1.806 raeburn 12272:
1.943 raeburn 12273: =item *
12274:
12275: get_domain_defaults($target_domain) : returns hash with defaults for
12276: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
12277: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
12278: or localauth), initial password or a kerberos realm, language (e.g., en-us).
12279: Values are retrieved from cache (if current), or from domain's configuration.db
12280: (if available), or lastly from values in lonTabs/dns_domain,tab,
12281: or lonTabs/domain.tab.
12282:
12283: %domdefaults = &get_auth_defaults($target_domain);
12284:
1.243 albertel 12285: =back
12286:
12287: =head2 Network Status Functions
12288:
12289: =over 4
1.191 harris41 12290:
12291: =item *
12292:
1.1137 raeburn 12293: dirlist() : return directory list based on URI (first arg).
12294:
12295: Inputs: 1 required, 5 optional.
12296:
12297: =over
12298:
12299: =item
12300: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
12301:
12302: =item
12303: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
12304:
12305: =item
12306: $username - username of user/course to be listed. Extracted from $uri if absent.
12307:
12308: =item
12309: $getpropath - boolean: 1 if prepend path using &propath().
12310:
12311: =item
12312: $getuserdir - boolean: 1 if prepend path for "userfiles".
12313:
12314: =item
12315: $alternateRoot - path to prepend in place of path from $uri.
12316:
12317: =back
12318:
12319: Returns: Array of up to two items.
12320:
12321: =over
12322:
12323: a reference to an array of files/subdirectories
12324:
12325: =over
12326:
12327: Each element in the array of files/subdirectories is a & separated list of
12328: item name and the result of running stat on the item. If dirlist was requested
12329: for a file instead of a directory, the item name will be ''. For a directory
12330: listing, if the item is a metadata file, the element will end &N&M
12331: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
12332: default copyright set (1).
12333:
12334: =back
12335:
12336: a scalar containing error condition (if encountered).
12337:
12338: =over
12339:
12340: =item
12341: no_host (no homeserver identified for $username:$domain).
12342:
12343: =item
12344: no_such_host (server contacted for listing not identified as valid host).
12345:
12346: =item
12347: con_lost (connection to remote server failed).
12348:
12349: =item
12350: refused (invalid $username:$domain received on lond side).
12351:
12352: =item
12353: no_such_dir (directory at specified path on lond side does not exist).
12354:
12355: =item
12356: empty (directory at specified path on lond side is empty).
12357:
12358: =over
12359:
12360: This is currently not encountered because the &ls3, &ls2,
12361: &ls (_handler) routines on the lond side do not filter out
12362: . and .. from a directory listing.
12363:
12364: =back
12365:
12366: =back
12367:
12368: =back
1.191 harris41 12369:
12370: =item *
12371:
1.243 albertel 12372: spareserver() : find server with least workload from spare.tab
12373:
1.986 foxr 12374:
12375: =item *
12376:
12377: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
12378: if there is no corresponding loncapa host.
12379:
1.243 albertel 12380: =back
12381:
1.986 foxr 12382:
1.243 albertel 12383: =head2 Apache Request
12384:
12385: =over 4
1.191 harris41 12386:
12387: =item *
12388:
1.243 albertel 12389: ssi($url,%hash) : server side include, does a complete request cycle on url to
12390: localhost, posts hash
12391:
12392: =back
12393:
12394: =head2 Data to String to Data
12395:
12396: =over 4
1.191 harris41 12397:
12398: =item *
12399:
1.243 albertel 12400: hash2str(%hash) : convert a hash into a string complete with escaping and '='
12401: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 12402:
12403: =item *
12404:
1.243 albertel 12405: hashref2str($hashref) : convert a hashref into a string complete with
12406: escaping and '=' and '&' separators, supports elements that are
12407: arrayrefs and hashrefs
1.191 harris41 12408:
12409: =item *
12410:
1.243 albertel 12411: arrayref2str($arrayref) : convert an arrayref into a string complete
12412: with escaping and '&' separators, supports elements that are arrayrefs
12413: and hashrefs
1.191 harris41 12414:
12415: =item *
12416:
1.243 albertel 12417: str2hash($string) : convert string to hash using unescaping and
12418: splitting on '=' and '&', supports elements that are arrayrefs and
12419: hashrefs
1.191 harris41 12420:
12421: =item *
12422:
1.243 albertel 12423: str2array($string) : convert string to hash using unescaping and
12424: splitting on '&', supports elements that are arrayrefs and hashrefs
12425:
12426: =back
12427:
12428: =head2 Logging Routines
12429:
12430:
12431: These routines allow one to make log messages in the lonnet.log and
12432: lonnet.perm logfiles.
1.191 harris41 12433:
1.1119 foxr 12434: =over 4
12435:
1.191 harris41 12436: =item *
12437:
1.243 albertel 12438: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 12439:
12440: =item *
12441:
1.243 albertel 12442: logthis() : append message to the normal lonnet.log file, it gets
12443: preiodically rolled over and deleted.
1.191 harris41 12444:
12445: =item *
12446:
1.243 albertel 12447: logperm() : append a permanent message to lonnet.perm.log, this log
12448: file never gets deleted by any automated portion of the system, only
12449: messages of critical importance should go in here.
12450:
1.1119 foxr 12451:
1.243 albertel 12452: =back
12453:
12454: =head2 General File Helper Routines
12455:
12456: =over 4
1.191 harris41 12457:
12458: =item *
12459:
1.481 raeburn 12460: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
12461: (a) files in /uploaded
12462: (i) If a local copy of the file exists -
12463: compares modification date of local copy with last-modified date for
12464: definitive version stored on home server for course. If local copy is
12465: stale, requests a new version from the home server and stores it.
12466: If the original has been removed from the home server, then local copy
12467: is unlinked.
12468: (ii) If local copy does not exist -
12469: requests the file from the home server and stores it.
12470:
12471: If $caller is 'uploadrep':
12472: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
12473: for request for files originally uploaded via DOCS.
12474: - returns 'ok' if fresh local copy now available, -1 otherwise.
12475:
12476: Otherwise:
12477: This indicates a call from the content generation phase of the request.
12478: - returns the entire contents of the file or -1.
12479:
12480: (b) files in /res
12481: - returns the entire contents of a file or -1;
12482: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 12483:
1.712 albertel 12484:
12485: =item *
12486:
12487: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
12488: reference
12489:
12490: returns either a stat() list of data about the file or an empty list
12491: if the file doesn't exist or couldn't find out about it (connection
12492: problems or user unknown)
12493:
1.191 harris41 12494: =item *
12495:
1.243 albertel 12496: filelocation($dir,$file) : returns file system location of a file
12497: based on URI; meant to be "fairly clean" absolute reference, $dir is a
12498: directory that relative $file lookups are to looked in ($dir of /a/dir
12499: and a file of ../bob will become /a/bob)
1.191 harris41 12500:
12501: =item *
12502:
12503: hreflocation($dir,$file) : returns file system location or a URL; same as
12504: filelocation except for hrefs
12505:
12506: =item *
12507:
12508: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
12509:
1.243 albertel 12510: =back
12511:
1.608 albertel 12512: =head2 Usererfile file routines (/uploaded*)
12513:
12514: =over 4
12515:
12516: =item *
12517:
12518: userfileupload(): main rotine for putting a file in a user or course's
12519: filespace, arguments are,
12520:
1.620 albertel 12521: formname - required - this is the name of the element in $env where the
1.608 albertel 12522: filename, and the contents of the file to create/modifed exist
1.620 albertel 12523: the filename is in $env{'form.'.$formname.'.filename'} and the
12524: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 12525: context - if coursedoc, store the file in the course of the active role
12526: of the current user;
12527: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
12528: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 12529: subdir - required - subdirectory to put the file in under ../userfiles/
12530: if undefined, it will be placed in "unknown"
12531:
12532: (This routine calls clean_filename() to remove any dangerous
12533: characters from the filename, and then calls finuserfileupload() to
12534: complete the transaction)
12535:
12536: returns either the url of the uploaded file (/uploaded/....) if successful
12537: and /adm/notfound.html if unsuccessful
12538:
12539: =item *
12540:
12541: clean_filename(): routine for cleaing a filename up for storage in
12542: userfile space, argument is:
12543:
12544: filename - proposed filename
12545:
12546: returns: the new clean filename
12547:
12548: =item *
12549:
1.1090 raeburn 12550: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 12551: userspace, probably shouldn't be called directly
12552:
12553: docuname: username or courseid of destination for the file
12554: docudom: domain of user/course of destination for the file
12555: formname: same as for userfileupload()
1.1090 raeburn 12556: fname: filename (including subdirectories) for the file
12557: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
12558: allfiles: reference to hash used to store objects found by parser
12559: codebase: reference to hash used for codebases of java objects found by parser
12560: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
12561: thumbheight: height (pixels) of thumbnail to be created for uploaded image
12562: resizewidth: width to be used to resize image using resizeImage from ImageMagick
12563: resizeheight: height to be used to resize image using resizeImage from ImageMagick
12564: context: if 'overwrite', will move the uploaded file from its temporary location to
12565: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 12566: mimetype: reference to scalar to accommodate mime type determined
12567: from File::MMagic if $parser = parse.
1.608 albertel 12568:
12569: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 12570: and /adm/notfound.html if unsuccessful (or an error message if context
12571: was 'overwrite').
12572:
1.608 albertel 12573:
12574: =item *
12575:
12576: renameuserfile(): renames an existing userfile to a new name
12577:
12578: Args:
12579: docuname: username or courseid of destination for the file
12580: docudom: domain of user/course of destination for the file
12581: old: current file name (including any subdirs under userfiles)
12582: new: desired file name (including any subdirs under userfiles)
12583:
12584: =item *
12585:
12586: mkdiruserfile(): creates a directory is a userfiles dir
12587:
12588: Args:
12589: docuname: username or courseid of destination for the file
12590: docudom: domain of user/course of destination for the file
12591: dir: dir to create (including any subdirs under userfiles)
12592:
12593: =item *
12594:
12595: removeuserfile(): removes a file that exists in userfiles
12596:
12597: Args:
12598: docuname: username or courseid of destination for the file
12599: docudom: domain of user/course of destination for the file
12600: fname: filname to delete (including any subdirs under userfiles)
12601:
12602: =item *
12603:
12604: removeuploadedurl(): convience function for removeuserfile()
12605:
12606: Args:
12607: url: a full /uploaded/... url to delete
12608:
1.747 albertel 12609: =item *
12610:
12611: get_portfile_permissions():
12612: Args:
12613: domain: domain of user or course contain the portfolio files
12614: user: name of user or num of course contain the portfolio files
12615: Returns:
12616: hashref of a dump of the proper file_permissions.db
12617:
12618:
12619: =item *
12620:
12621: get_access_controls():
12622:
12623: Args:
12624: current_permissions: the hash ref returned from get_portfile_permissions()
12625: group: (optional) the group you want the files associated with
12626: file: (optional) the file you want access info on
12627:
12628: Returns:
1.749 raeburn 12629: a hash (keys are file names) of hashes containing
12630: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
12631: values are XML containing access control settings (see below)
1.747 albertel 12632:
12633: Internal notes:
12634:
1.749 raeburn 12635: access controls are stored in file_permissions.db as key=value pairs.
12636: key -> path to file/file_name\0uniqueID:scope_end_start
12637: where scope -> public,guest,course,group,domains or users.
12638: end -> UNIX time for end of access (0 -> no end date)
12639: start -> UNIX time for start of access
12640:
12641: value -> XML description of access control
12642: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
12643: <start></start>
12644: <end></end>
12645:
12646: <password></password> for scope type = guest
12647:
12648: <domain></domain> for scope type = course or group
12649: <number></number>
12650: <roles id="">
12651: <role></role>
12652: <access></access>
12653: <section></section>
12654: <group></group>
12655: </roles>
12656:
12657: <dom></dom> for scope type = domains
12658:
12659: <users> for scope type = users
12660: <user>
12661: <uname></uname>
12662: <udom></udom>
12663: </user>
12664: </users>
12665: </scope>
12666:
12667: Access data is also aggregated for each file in an additional key=value pair:
12668: key -> path to file/file_name\0accesscontrol
12669: value -> reference to hash
12670: hash contains key = value pairs
12671: where key = uniqueID:scope_end_start
12672: value = UNIX time record was last updated
12673:
12674: Used to improve speed of look-ups of access controls for each file.
12675:
12676: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
12677:
12678: modify_access_controls():
12679:
12680: Modifies access controls for a portfolio file
12681: Args
12682: 1. file name
12683: 2. reference to hash of required changes,
12684: 3. domain
12685: 4. username
12686: where domain,username are the domain of the portfolio owner
12687: (either a user or a course)
12688:
12689: Returns:
12690: 1. result of additions or updates ('ok' or 'error', with error message).
12691: 2. result of deletions ('ok' or 'error', with error message).
12692: 3. reference to hash of any new or updated access controls.
12693: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
12694: key = integer (inbound ID)
12695: value = uniqueID
1.747 albertel 12696:
1.608 albertel 12697: =back
12698:
1.243 albertel 12699: =head2 HTTP Helper Routines
12700:
12701: =over 4
12702:
1.191 harris41 12703: =item *
12704:
12705: escape() : unpack non-word characters into CGI-compatible hex codes
12706:
12707: =item *
12708:
12709: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
12710:
1.243 albertel 12711: =back
12712:
12713: =head1 PRIVATE SUBROUTINES
12714:
12715: =head2 Underlying communication routines (Shouldn't call)
12716:
12717: =over 4
12718:
12719: =item *
12720:
12721: subreply() : tries to pass a message to lonc, returns con_lost if incapable
12722:
12723: =item *
12724:
12725: reply() : uses subreply to send a message to remote machine, logs all failures
12726:
12727: =item *
12728:
12729: critical() : passes a critical message to another server; if cannot
12730: get through then place message in connection buffer directory and
12731: returns con_delayed, if incapable of saving message, returns
12732: con_failed
12733:
12734: =item *
12735:
12736: reconlonc() : tries to reconnect lonc client processes.
12737:
12738: =back
12739:
12740: =head2 Resource Access Logging
12741:
12742: =over 4
12743:
12744: =item *
12745:
12746: flushcourselogs() : flush (save) buffer logs and access logs
12747:
12748: =item *
12749:
12750: courselog($what) : save message for course in hash
12751:
12752: =item *
12753:
12754: courseacclog($what) : save message for course using &courselog(). Perform
12755: special processing for specific resource types (problems, exams, quizzes, etc).
12756:
1.191 harris41 12757: =item *
12758:
12759: goodbye() : flush course logs and log shutting down; it is called in srm.conf
12760: as a PerlChildExitHandler
1.243 albertel 12761:
12762: =back
12763:
12764: =head2 Other
12765:
12766: =over 4
12767:
12768: =item *
12769:
12770: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 12771:
12772: =back
12773:
12774: =cut
1.877 foxr 12775:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>