Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1258
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1258 ! raeburn 4: # $Id: lonnet.pm,v 1.1257 2014/04/30 17:17:46 raeburn Exp $
1.178 www 5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27: #
1.169 harris41 28: ###
29:
1.971 jms 30: =pod
31:
1.972 jms 32: =head1 NAME
33:
34: Apache::lonnet.pm
35:
36: =head1 SYNOPSIS
37:
38: This file is an interface to the lonc processes of
39: the LON-CAPA network as well as set of elaborated functions for handling information
40: necessary for navigating through a given cluster of LON-CAPA machines within a
41: domain. There are over 40 specialized functions in this module which handle the
42: reading and transmission of metadata, user information (ids, names, environments, roles,
43: logs), file information (storage, reading, directories, extensions, replication, embedded
44: styles and descriptors), educational resources (course descriptions, section names and
45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
46: and from more descriptive phrases or explanations.
47:
48: This is part of the LearningOnline Network with CAPA project
49: described at http://www.lon-capa.org.
50:
1.971 jms 51: =head1 Package Variables
52:
53: These are largely undocumented, so if you decipher one please note it here.
54:
55: =over 4
56:
57: =item $processmarker
58:
59: Contains the time this process was started and this servers host id.
60:
61: =item $dumpcount
62:
63: Counts the number of times a message log flush has been attempted (regardless
64: of success) by this process. Used as part of the filename when messages are
65: delayed.
66:
67: =back
68:
69: =cut
70:
1.1 albertel 71: package Apache::lonnet;
72:
73: use strict;
1.8 www 74: use LWP::UserAgent();
1.486 www 75: use HTTP::Date;
1.977 amueller 76: use Image::Magick;
77:
1.1182 foxr 78:
1.1173 foxr 79: use Encode;
80:
1.1245 raeburn 81: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.1138 raeburn 82: $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
83: %managerstab);
1.871 albertel 84:
85: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
86: %userrolehash, $processmarker, $dumpcount, %coursedombuf,
87: %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958 www 88: %courseownerbuf, %coursetypebuf,$locknum);
1.403 www 89:
1.1 albertel 90: use IO::Socket;
1.31 www 91: use GDBM_File;
1.208 albertel 92: use HTML::LCParser;
1.88 www 93: use Fcntl qw(:flock);
1.870 albertel 94: use Storable qw(thaw nfreeze);
1.539 albertel 95: use Time::HiRes qw( gettimeofday tv_interval );
1.599 albertel 96: use Cache::Memcached;
1.676 albertel 97: use Digest::MD5;
1.790 albertel 98: use Math::Random;
1.1024 raeburn 99: use File::MMagic;
1.807 albertel 100: use LONCAPA qw(:DEFAULT :match);
1.740 www 101: use LONCAPA::Configuration;
1.1160 www 102: use LONCAPA::lonmetadata;
1.1167 droeschl 103: use LONCAPA::Lond;
1.1117 foxr 104:
1.1090 raeburn 105: use File::Copy;
1.676 albertel 106:
1.195 www 107: my $readit;
1.550 foxr 108: my $max_connection_retries = 10; # Or some such value.
1.1 albertel 109:
1.619 albertel 110: require Exporter;
111:
112: our @ISA = qw (Exporter);
113: our @EXPORT = qw(%env);
114:
1.449 matthew 115:
1.1187 raeburn 116: # ------------------------------------ Logging (parameters, docs, slots, roles)
1.729 www 117: {
118: my $logid;
1.1187 raeburn 119: sub write_log {
1.1188 raeburn 120: my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
1.1184 raeburn 121: if ($context eq 'course') {
122: if (($cnum eq '') || ($cdom eq '')) {
123: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
124: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
125: }
1.957 raeburn 126: }
1.1184 raeburn 127: $logid ++;
1.957 raeburn 128: my $now = time();
129: my $id=$now.'00000'.$$.'00000'.$logid;
1.1184 raeburn 130: my $logentry = {
131: $id => {
132: 'exe_uname' => $env{'user.name'},
133: 'exe_udom' => $env{'user.domain'},
134: 'exe_time' => $now,
135: 'exe_ip' => $ENV{'REMOTE_ADDR'},
136: 'delflag' => $delflag,
137: 'logentry' => $storehash,
138: 'uname' => $uname,
139: 'udom' => $udom,
140: }
141: };
142: return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
1.729 www 143: }
144: }
1.1 albertel 145:
1.163 harris41 146: sub logtouch {
147: my $execdir=$perlvar{'lonDaemons'};
1.448 albertel 148: unless (-e "$execdir/logs/lonnet.log") {
149: open(my $fh,">>$execdir/logs/lonnet.log");
1.163 harris41 150: close $fh;
151: }
152: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
153: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
154: }
155:
1.1 albertel 156: sub logthis {
157: my $message=shift;
158: my $execdir=$perlvar{'lonDaemons'};
159: my $now=time;
160: my $local=localtime($now);
1.448 albertel 161: if (open(my $fh,">>$execdir/logs/lonnet.log")) {
1.986 foxr 162: my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
163: print $fh $logstring;
1.448 albertel 164: close($fh);
165: }
1.1 albertel 166: return 1;
167: }
168:
169: sub logperm {
170: my $message=shift;
171: my $execdir=$perlvar{'lonDaemons'};
172: my $now=time;
173: my $local=localtime($now);
1.448 albertel 174: if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
175: print $fh "$now:$message:$local\n";
176: close($fh);
177: }
1.1 albertel 178: return 1;
179: }
180:
1.850 albertel 181: sub create_connection {
1.853 albertel 182: my ($hostname,$lonid) = @_;
1.851 albertel 183: my $client=IO::Socket::UNIX->new(Peer => $perlvar{'lonSockCreate'},
1.850 albertel 184: Type => SOCK_STREAM,
185: Timeout => 10);
186: return 0 if (!$client);
1.890 albertel 187: print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850 albertel 188: my $result = <$client>;
189: chomp($result);
190: return 1 if ($result eq 'done');
191: return 0;
192: }
193:
1.983 raeburn 194: sub get_server_timezone {
195: my ($cnum,$cdom) = @_;
196: my $home=&homeserver($cnum,$cdom);
197: if ($home ne 'no_host') {
198: my $cachetime = 24*3600;
199: my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
200: if (defined($cached)) {
201: return $timezone;
202: } else {
203: my $timezone = &reply('servertimezone',$home);
204: return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
205: }
206: }
207: }
1.850 albertel 208:
1.1106 raeburn 209: sub get_server_distarch {
210: my ($lonhost,$ignore_cache) = @_;
211: if (defined($lonhost)) {
212: if (!defined(&hostname($lonhost))) {
213: return;
214: }
215: my $cachetime = 12*3600;
216: if (!$ignore_cache) {
217: my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
218: if (defined($cached)) {
219: return $distarch;
220: }
221: }
222: my $rep = &reply('serverdistarch',$lonhost);
223: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
224: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
225: $rep eq '') {
226: return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
227: }
228: }
229: return;
230: }
231:
1.993 raeburn 232: sub get_server_loncaparev {
1.1073 raeburn 233: my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993 raeburn 234: if (defined($lonhost)) {
235: if (!defined(&hostname($lonhost))) {
236: undef($lonhost);
237: }
238: }
239: if (!defined($lonhost)) {
240: if (defined(&domain($dom,'primary'))) {
241: $lonhost=&domain($dom,'primary');
242: if ($lonhost eq 'no_host') {
243: undef($lonhost);
244: }
245: }
246: }
247: if (defined($lonhost)) {
1.1073 raeburn 248: my $cachetime = 12*3600;
249: if (!$ignore_cache) {
250: my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
251: if (defined($cached)) {
252: return $loncaparev;
253: }
254: }
255: my ($answer,$loncaparev);
256: my @ids=¤t_machine_ids();
257: if (grep(/^\Q$lonhost\E$/,@ids)) {
258: $answer = $perlvar{'lonVersion'};
1.1081 raeburn 259: if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 260: $loncaparev = $1;
261: }
262: } else {
263: $answer = &reply('serverloncaparev',$lonhost);
264: if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
265: if ($caller eq 'loncron') {
266: my $ua=new LWP::UserAgent;
1.1082 raeburn 267: $ua->timeout(4);
1.1073 raeburn 268: my $protocol = $protocol{$lonhost};
269: $protocol = 'http' if ($protocol ne 'https');
270: my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
271: my $request=new HTTP::Request('GET',$url);
272: my $response=$ua->request($request);
273: unless ($response->is_error()) {
274: my $content = $response->content;
1.1081 raeburn 275: if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073 raeburn 276: $loncaparev = $1;
277: }
278: }
279: } else {
280: $loncaparev = $loncaparevs{$lonhost};
281: }
1.1081 raeburn 282: } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 283: $loncaparev = $1;
284: }
1.993 raeburn 285: }
1.1073 raeburn 286: return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993 raeburn 287: }
288: }
289:
1.1074 raeburn 290: sub get_server_homeID {
291: my ($hostname,$ignore_cache,$caller) = @_;
292: unless ($ignore_cache) {
293: my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
294: if (defined($cached)) {
295: return $serverhomeID;
296: }
297: }
298: my $cachetime = 12*3600;
299: my $serverhomeID;
300: if ($caller eq 'loncron') {
301: my @machine_ids = &machine_ids($hostname);
302: foreach my $id (@machine_ids) {
303: my $response = &reply('serverhomeID',$id);
304: unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
305: $serverhomeID = $response;
306: last;
307: }
308: }
309: if ($serverhomeID eq '') {
310: $serverhomeID = $machine_ids[-1];
311: }
312: } else {
313: $serverhomeID = $serverhomeIDs{$hostname};
314: }
315: return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
316: }
317:
1.1121 raeburn 318: sub get_remote_globals {
319: my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125 raeburn 320: my ($result,%returnhash,%whatneeded);
321: if (ref($whathash) eq 'HASH') {
1.1121 raeburn 322: foreach my $what (sort(keys(%{$whathash}))) {
323: my $hashid = $lonhost.'-'.$what;
1.1125 raeburn 324: my ($response,$cached);
1.1121 raeburn 325: unless ($ignore_cache) {
1.1125 raeburn 326: ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121 raeburn 327: }
328: if (defined($cached)) {
1.1125 raeburn 329: $returnhash{$what} = $response;
1.1121 raeburn 330: } else {
1.1125 raeburn 331: $whatneeded{$what} = 1;
1.1121 raeburn 332: }
333: }
1.1125 raeburn 334: if (keys(%whatneeded) == 0) {
335: $result = 'ok';
336: } else {
1.1121 raeburn 337: my $requested = &freeze_escape(\%whatneeded);
338: my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125 raeburn 339: if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
340: ($rep eq 'unknown_cmd')) {
341: $result = $rep;
342: } else {
343: $result = 'ok';
1.1121 raeburn 344: my @pairs=split(/\&/,$rep);
1.1125 raeburn 345: foreach my $item (@pairs) {
346: my ($key,$value)=split(/=/,$item,2);
347: my $what = &unescape($key);
348: my $hashid = $lonhost.'-'.$what;
349: $returnhash{$what}=&thaw_unescape($value);
350: &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121 raeburn 351: }
352: }
353: }
354: }
1.1125 raeburn 355: return ($result,\%returnhash);
1.1121 raeburn 356: }
357:
1.1124 raeburn 358: sub remote_devalidate_cache {
1.1241 raeburn 359: my ($lonhost,$cachekeys) = @_;
360: my $items;
361: return unless (ref($cachekeys) eq 'ARRAY');
362: my $cachestr = join('&',@{$cachekeys});
363: my $response = &reply('devalidatecache:'.&escape($cachestr),$lonhost);
1.1124 raeburn 364: return $response;
365: }
366:
1.1 albertel 367: # -------------------------------------------------- Non-critical communication
368: sub subreply {
369: my ($cmd,$server)=@_;
1.838 albertel 370: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549 foxr 371: #
372: # With loncnew process trimming, there's a timing hole between lonc server
373: # process exit and the master server picking up the listen on the AF_UNIX
374: # socket. In that time interval, a lock file will exist:
375:
376: my $lockfile=$peerfile.".lock";
377: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
378: sleep(1);
379: }
380: # At this point, either a loncnew parent is listening or an old lonc
1.550 foxr 381: # or loncnew child is listening so we can connect or everything's dead.
1.549 foxr 382: #
1.550 foxr 383: # We'll give the connection a few tries before abandoning it. If
384: # connection is not possible, we'll con_lost back to the client.
385: #
386: my $client;
387: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
388: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
389: Type => SOCK_STREAM,
390: Timeout => 10);
1.869 albertel 391: if ($client) {
1.550 foxr 392: last; # Connected!
1.850 albertel 393: } else {
1.853 albertel 394: &create_connection(&hostname($server),$server);
1.550 foxr 395: }
1.850 albertel 396: sleep(1); # Try again later if failed connection.
1.550 foxr 397: }
398: my $answer;
399: if ($client) {
1.704 albertel 400: print $client "sethost:$server:$cmd\n";
1.550 foxr 401: $answer=<$client>;
402: if (!$answer) { $answer="con_lost"; }
403: chomp($answer);
404: } else {
405: $answer = 'con_lost'; # Failed connection.
406: }
1.1 albertel 407: return $answer;
408: }
409:
410: sub reply {
411: my ($cmd,$server)=@_;
1.838 albertel 412: unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1 albertel 413: my $answer=subreply($cmd,$server);
1.65 www 414: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672 albertel 415: &logthis("<font color=\"blue\">WARNING:".
1.12 www 416: " $cmd to $server returned $answer</font>");
417: }
1.1 albertel 418: return $answer;
419: }
420:
421: # ----------------------------------------------------------- Send USR1 to lonc
422:
423: sub reconlonc {
1.891 albertel 424: my ($lonid) = @_;
425: my $hostname = &hostname($lonid);
426: if ($lonid) {
427: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
428: if ($hostname && -e $peerfile) {
429: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
430: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
431: Type => SOCK_STREAM,
432: Timeout => 10);
433: if ($client) {
434: print $client ("reset_retries\n");
435: my $answer=<$client>;
436: #reset just this one.
437: }
438: }
439: return;
440: }
441:
1.836 www 442: &logthis("Trying to reconnect lonc");
1.1 albertel 443: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448 albertel 444: if (open(my $fh,"<$loncfile")) {
1.1 albertel 445: my $loncpid=<$fh>;
446: chomp($loncpid);
447: if (kill 0 => $loncpid) {
448: &logthis("lonc at pid $loncpid responding, sending USR1");
449: kill USR1 => $loncpid;
450: sleep 1;
1.836 www 451: } else {
1.12 www 452: &logthis(
1.672 albertel 453: "<font color=\"blue\">WARNING:".
1.12 www 454: " lonc at pid $loncpid not responding, giving up</font>");
1.1 albertel 455: }
456: } else {
1.836 www 457: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1 albertel 458: }
459: }
460:
461: # ------------------------------------------------------ Critical communication
1.12 www 462:
1.1 albertel 463: sub critical {
464: my ($cmd,$server)=@_;
1.838 albertel 465: unless (&hostname($server)) {
1.672 albertel 466: &logthis("<font color=\"blue\">WARNING:".
1.89 www 467: " Critical message to unknown server ($server)</font>");
468: return 'no_such_host';
469: }
1.1 albertel 470: my $answer=reply($cmd,$server);
471: if ($answer eq 'con_lost') {
472: &reconlonc("$perlvar{'lonSockDir'}/$server");
1.589 albertel 473: my $answer=reply($cmd,$server);
1.1 albertel 474: if ($answer eq 'con_lost') {
475: my $now=time;
476: my $middlename=$cmd;
1.5 www 477: $middlename=substr($middlename,0,16);
1.1 albertel 478: $middlename=~s/\W//g;
479: my $dfilename=
1.305 www 480: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
481: $dumpcount++;
1.1 albertel 482: {
1.448 albertel 483: my $dfh;
484: if (open($dfh,">$dfilename")) {
485: print $dfh "$cmd\n";
486: close($dfh);
487: }
1.1 albertel 488: }
489: sleep 2;
490: my $wcmd='';
491: {
1.448 albertel 492: my $dfh;
493: if (open($dfh,"<$dfilename")) {
494: $wcmd=<$dfh>;
495: close($dfh);
496: }
1.1 albertel 497: }
498: chomp($wcmd);
1.7 www 499: if ($wcmd eq $cmd) {
1.672 albertel 500: &logthis("<font color=\"blue\">WARNING: ".
1.12 www 501: "Connection buffer $dfilename: $cmd</font>");
1.1 albertel 502: &logperm("D:$server:$cmd");
503: return 'con_delayed';
504: } else {
1.672 albertel 505: &logthis("<font color=\"red\">CRITICAL:"
1.12 www 506: ." Critical connection failed: $server $cmd</font>");
1.1 albertel 507: &logperm("F:$server:$cmd");
508: return 'con_failed';
509: }
510: }
511: }
512: return $answer;
1.405 albertel 513: }
514:
1.755 albertel 515: # ------------------------------------------- check if return value is an error
516:
517: sub error {
518: my ($result) = @_;
1.756 albertel 519: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755 albertel 520: if ($2 == 2) { return undef; }
521: return $1;
522: }
523: return undef;
524: }
525:
1.783 albertel 526: sub convert_and_load_session_env {
527: my ($lonidsdir,$handle)=@_;
528: my @profile;
529: {
1.917 albertel 530: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
531: if (!$opened) {
1.915 albertel 532: return 0;
533: }
1.783 albertel 534: flock($idf,LOCK_SH);
535: @profile=<$idf>;
536: close($idf);
537: }
538: my %temp_env;
539: foreach my $line (@profile) {
1.786 albertel 540: if ($line !~ m/=/) {
541: return 0;
542: }
1.783 albertel 543: chomp($line);
544: my ($envname,$envvalue)=split(/=/,$line,2);
545: $temp_env{&unescape($envname)} = &unescape($envvalue);
546: }
547: unlink("$lonidsdir/$handle.id");
548: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
549: 0640)) {
550: %disk_env = %temp_env;
551: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
552: untie(%disk_env);
553: }
1.786 albertel 554: return 1;
1.783 albertel 555: }
556:
1.374 www 557: # ------------------------------------------- Transfer profile into environment
1.780 albertel 558: my $env_loaded;
559: sub transfer_profile_to_env {
1.788 albertel 560: my ($lonidsdir,$handle,$force_transfer) = @_;
561: if (!$force_transfer && $env_loaded) { return; }
1.374 www 562:
1.720 albertel 563: if (!defined($lonidsdir)) {
564: $lonidsdir = $perlvar{'lonIDsDir'};
565: }
566: if (!defined($handle)) {
567: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
568: }
569:
1.786 albertel 570: my $convert;
571: {
1.917 albertel 572: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
573: if (!$opened) {
1.915 albertel 574: return;
575: }
1.786 albertel 576: flock($idf,LOCK_SH);
577: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
578: &GDBM_READER(),0640)) {
579: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
580: untie(%disk_env);
581: } else {
582: $convert = 1;
583: }
584: }
585: if ($convert) {
586: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
587: &logthis("Failed to load session, or convert session.");
588: }
1.374 www 589: }
1.783 albertel 590:
1.786 albertel 591: my %remove;
1.783 albertel 592: while ( my $envname = each(%env) ) {
1.433 matthew 593: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
594: if ($time < time-300) {
1.783 albertel 595: $remove{$key}++;
1.433 matthew 596: }
597: }
598: }
1.783 albertel 599:
1.619 albertel 600: $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780 albertel 601: $env_loaded=1;
1.783 albertel 602: foreach my $expired_key (keys(%remove)) {
1.433 matthew 603: &delenv($expired_key);
1.374 www 604: }
1.1 albertel 605: }
606:
1.916 albertel 607: # ---------------------------------------------------- Check for valid session
608: sub check_for_valid_session {
1.1245 raeburn 609: my ($r,$name,$userhashref) = @_;
1.916 albertel 610: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1155 raeburn 611: if ($name eq '') {
612: $name = 'lonID';
613: }
614: my $lonid=$cookies{$name};
1.916 albertel 615: return undef if (!$lonid);
616:
617: my $handle=&LONCAPA::clean_handle($lonid->value);
1.1155 raeburn 618: my $lonidsdir;
619: if ($name eq 'lonDAV') {
620: $lonidsdir=$r->dir_config('lonDAVsessDir');
621: } else {
622: $lonidsdir=$r->dir_config('lonIDsDir');
623: }
1.916 albertel 624: return undef if (!-e "$lonidsdir/$handle.id");
625:
1.917 albertel 626: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
627: return undef if (!$opened);
1.916 albertel 628:
629: flock($idf,LOCK_SH);
630: my %disk_env;
631: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
632: &GDBM_READER(),0640)) {
633: return undef;
634: }
635:
636: if (!defined($disk_env{'user.name'})
637: || !defined($disk_env{'user.domain'})) {
638: return undef;
639: }
1.1245 raeburn 640:
641: if (ref($userhashref) eq 'HASH') {
642: $userhashref->{'name'} = $disk_env{'user.name'};
643: $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1212 raeburn 644: }
1.1245 raeburn 645:
1.916 albertel 646: return $handle;
647: }
648:
1.830 albertel 649: sub timed_flock {
650: my ($file,$lock_type) = @_;
651: my $failed=0;
652: eval {
653: local $SIG{__DIE__}='DEFAULT';
654: local $SIG{ALRM}=sub {
655: $failed=1;
656: die("failed lock");
657: };
658: alarm(13);
659: flock($file,$lock_type);
660: alarm(0);
661: };
662: if ($failed) {
663: return undef;
664: } else {
665: return 1;
666: }
667: }
668:
1.5 www 669: # ---------------------------------------------------------- Append Environment
670:
671: sub appenv {
1.949 raeburn 672: my ($newenv,$roles) = @_;
673: if (ref($newenv) eq 'HASH') {
674: foreach my $key (keys(%{$newenv})) {
675: my $refused = 0;
676: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
677: $refused = 1;
678: if (ref($roles) eq 'ARRAY') {
1.1250 raeburn 679: my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949 raeburn 680: if (grep(/^\Q$role\E$/,@{$roles})) {
681: $refused = 0;
682: }
683: }
684: }
685: if ($refused) {
686: &logthis("<font color=\"blue\">WARNING: ".
687: "Attempt to modify environment ".$key." to ".$newenv->{$key}
688: .'</font>');
689: delete($newenv->{$key});
690: } else {
691: $env{$key}=$newenv->{$key};
692: }
693: }
694: my $opened = open(my $env_file,'+<',$env{'user.environment'});
695: if ($opened
696: && &timed_flock($env_file,LOCK_EX)
697: &&
698: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
699: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
700: while (my ($key,$value) = each(%{$newenv})) {
701: $disk_env{$key} = $value;
702: }
703: untie(%disk_env);
1.35 www 704: }
1.191 harris41 705: }
1.56 www 706: return 'ok';
707: }
708: # ----------------------------------------------------- Delete from Environment
709:
710: sub delenv {
1.1104 raeburn 711: my ($delthis,$regexp,$roles) = @_;
712: if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
713: my $refused = 1;
714: if (ref($roles) eq 'ARRAY') {
715: my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
716: if (grep(/^\Q$role\E$/,@{$roles})) {
717: $refused = 0;
718: }
719: }
720: if ($refused) {
721: &logthis("<font color=\"blue\">WARNING: ".
722: "Attempt to delete from environment ".$delthis);
723: return 'error';
724: }
1.56 www 725: }
1.917 albertel 726: my $opened = open(my $env_file,'+<',$env{'user.environment'});
727: if ($opened
1.915 albertel 728: && &timed_flock($env_file,LOCK_EX)
1.830 albertel 729: &&
730: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
731: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 732: foreach my $key (keys(%disk_env)) {
1.987 raeburn 733: if ($regexp) {
734: if ($key=~/^$delthis/) {
735: delete($env{$key});
736: delete($disk_env{$key});
737: }
738: } else {
739: if ($key=~/^\Q$delthis\E/) {
740: delete($env{$key});
741: delete($disk_env{$key});
742: }
743: }
1.448 albertel 744: }
1.783 albertel 745: untie(%disk_env);
1.5 www 746: }
747: return 'ok';
1.369 albertel 748: }
749:
1.790 albertel 750: sub get_env_multiple {
751: my ($name) = @_;
752: my @values;
753: if (defined($env{$name})) {
754: # exists is it an array
755: if (ref($env{$name})) {
756: @values=@{ $env{$name} };
757: } else {
758: $values[0]=$env{$name};
759: }
760: }
761: return(@values);
762: }
763:
1.958 www 764: # ------------------------------------------------------------------- Locking
765:
766: sub set_lock {
767: my ($text)=@_;
768: $locknum++;
769: my $id=$$.'-'.$locknum;
770: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
771: 'session.lock.'.$id => $text});
772: return $id;
773: }
774:
775: sub get_locks {
776: my $num=0;
777: my %texts=();
778: foreach my $lock (split(/\,/,$env{'session.locks'})) {
779: if ($lock=~/\w/) {
780: $num++;
781: $texts{$lock}=$env{'session.lock.'.$lock};
782: }
783: }
784: return ($num,%texts);
785: }
786:
787: sub remove_lock {
788: my ($id)=@_;
789: my $newlocks='';
790: foreach my $lock (split(/\,/,$env{'session.locks'})) {
791: if (($lock=~/\w/) && ($lock ne $id)) {
792: $newlocks.=','.$lock;
793: }
794: }
795: &appenv({'session.locks' => $newlocks});
796: &delenv('session.lock.'.$id);
797: }
798:
799: sub remove_all_locks {
800: my $activelocks=$env{'session.locks'};
801: foreach my $lock (split(/\,/,$env{'session.locks'})) {
802: if ($lock=~/\w/) {
803: &remove_lock($lock);
804: }
805: }
806: }
807:
808:
1.369 albertel 809: # ------------------------------------------ Find out current server userload
810: sub userload {
811: my $numusers=0;
812: {
813: opendir(LONIDS,$perlvar{'lonIDsDir'});
814: my $filename;
815: my $curtime=time;
816: while ($filename=readdir(LONIDS)) {
1.925 albertel 817: next if ($filename eq '.' || $filename eq '..');
818: next if ($filename =~ /publicuser_\d+\.id/);
1.404 albertel 819: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437 albertel 820: if ($curtime-$mtime < 1800) { $numusers++; }
1.369 albertel 821: }
822: closedir(LONIDS);
823: }
824: my $userloadpercent=0;
825: my $maxuserload=$perlvar{'lonUserLoadLim'};
826: if ($maxuserload) {
1.371 albertel 827: $userloadpercent=100*$numusers/$maxuserload;
1.369 albertel 828: }
1.372 albertel 829: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369 albertel 830: return $userloadpercent;
1.283 www 831: }
832:
1.1 albertel 833: # ------------------------------ Find server with least workload from spare.tab
1.11 www 834:
1.1 albertel 835: sub spareserver {
1.1083 raeburn 836: my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784 albertel 837: my $spare_server;
1.370 albertel 838: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784 albertel 839: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
840: : $userloadpercent;
1.1083 raeburn 841: my ($uint_dom,$remotesessions);
842: if (($udom ne '') && (&domain($udom) ne '')) {
843: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
844: $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
845: my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
846: $remotesessions = $udomdefaults{'remotesessions'};
847: }
1.1123 raeburn 848: my $spareshash = &this_host_spares($udom);
849: if (ref($spareshash) eq 'HASH') {
850: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
851: foreach my $try_server (@{ $spareshash->{'primary'} }) {
852: if ($uint_dom) {
853: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
854: $try_server));
855: }
856: ($spare_server, $lowest_load) =
857: &compare_server_load($try_server, $spare_server, $lowest_load);
858: }
1.1083 raeburn 859: }
1.784 albertel 860:
1.1123 raeburn 861: my $found_server = ($spare_server ne '' && $lowest_load < 100);
862:
863: if (!$found_server) {
864: if (ref($spareshash->{'default'}) eq 'ARRAY') {
865: foreach my $try_server (@{ $spareshash->{'default'} }) {
866: if ($uint_dom) {
867: next unless (&spare_can_host($udom,$uint_dom,
868: $remotesessions,$try_server));
869: }
870: ($spare_server, $lowest_load) =
871: &compare_server_load($try_server, $spare_server, $lowest_load);
872: }
873: }
874: }
1.784 albertel 875: }
876:
877: if (!$want_server_name) {
1.968 raeburn 878: my $protocol = 'http';
879: if ($protocol{$spare_server} eq 'https') {
880: $protocol = $protocol{$spare_server};
881: }
1.1001 raeburn 882: if (defined($spare_server)) {
883: my $hostname = &hostname($spare_server);
1.1083 raeburn 884: if (defined($hostname)) {
1.1001 raeburn 885: $spare_server = $protocol.'://'.$hostname;
886: }
887: }
1.784 albertel 888: }
889: return $spare_server;
890: }
891:
892: sub compare_server_load {
1.1253 raeburn 893: my ($try_server, $spare_server, $lowest_load, $required) = @_;
894:
895: if ($required) {
896: my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
897: my $remoterev = &get_server_loncaparev(undef,$try_server);
898: my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
899: if (($major eq '' && $minor eq '') ||
900: (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
901: return ($spare_server,$lowest_load);
902: }
903: }
1.784 albertel 904:
905: my $loadans = &reply('load', $try_server);
906: my $userloadans = &reply('userload',$try_server);
907:
908: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114 raeburn 909: return ($spare_server, $lowest_load); #didn't get a number from the server
1.784 albertel 910: }
911:
912: my $load;
913: if ($loadans =~ /\d/) {
914: if ($userloadans =~ /\d/) {
915: #both are numbers, pick the bigger one
916: $load = ($loadans > $userloadans) ? $loadans
917: : $userloadans;
1.411 albertel 918: } else {
1.784 albertel 919: $load = $loadans;
1.411 albertel 920: }
1.784 albertel 921: } else {
922: $load = $userloadans;
923: }
924:
925: if (($load =~ /\d/) && ($load < $lowest_load)) {
926: $spare_server = $try_server;
927: $lowest_load = $load;
1.370 albertel 928: }
1.784 albertel 929: return ($spare_server,$lowest_load);
1.202 matthew 930: }
1.914 albertel 931:
932: # --------------------------- ask offload servers if user already has a session
933: sub find_existing_session {
934: my ($udom,$uname) = @_;
1.1123 raeburn 935: my $spareshash = &this_host_spares($udom);
936: if (ref($spareshash) eq 'HASH') {
937: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
938: foreach my $try_server (@{ $spareshash->{'primary'} }) {
939: return $try_server if (&has_user_session($try_server, $udom, $uname));
940: }
941: }
942: if (ref($spareshash->{'default'}) eq 'ARRAY') {
943: foreach my $try_server (@{ $spareshash->{'default'} }) {
944: return $try_server if (&has_user_session($try_server, $udom, $uname));
945: }
946: }
1.914 albertel 947: }
948: return;
949: }
950:
951: # -------------------------------- ask if server already has a session for user
952: sub has_user_session {
953: my ($lonid,$udom,$uname) = @_;
954: my $result = &reply(join(':','userhassession',
955: map {&escape($_)} ($udom,$uname)),$lonid);
956: return 1 if ($result eq 'ok');
957:
958: return 0;
959: }
960:
1.1076 raeburn 961: # --------- determine least loaded server in a user's domain which allows login
962:
963: sub choose_server {
1.1253 raeburn 964: my ($udom,$checkloginvia,$required) = @_;
1.1076 raeburn 965: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077 raeburn 966: my %servers = &get_servers($udom);
1.1076 raeburn 967: my $lowest_load = 30000;
1.1151 raeburn 968: my ($login_host,$hostname,$portal_path,$isredirect);
1.1076 raeburn 969: foreach my $lonhost (keys(%servers)) {
1.1115 raeburn 970: my $loginvia;
971: if ($checkloginvia) {
972: $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116 raeburn 973: if ($loginvia) {
974: my ($server,$path) = split(/:/,$loginvia);
975: ($login_host, $lowest_load) =
1.1253 raeburn 976: &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116 raeburn 977: if ($login_host eq $server) {
978: $portal_path = $path;
1.1151 raeburn 979: $isredirect = 1;
1.1116 raeburn 980: }
981: } else {
982: ($login_host, $lowest_load) =
1.1253 raeburn 983: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116 raeburn 984: if ($login_host eq $lonhost) {
985: $portal_path = '';
1.1151 raeburn 986: $isredirect = '';
1.1116 raeburn 987: }
988: }
989: } else {
1.1076 raeburn 990: ($login_host, $lowest_load) =
1.1253 raeburn 991: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076 raeburn 992: }
993: }
994: if ($login_host ne '') {
1.1116 raeburn 995: $hostname = &hostname($login_host);
1.1076 raeburn 996: }
1.1151 raeburn 997: return ($login_host,$hostname,$portal_path,$isredirect);
1.1076 raeburn 998: }
999:
1.202 matthew 1000: # --------------------------------------------- Try to change a user's password
1001:
1002: sub changepass {
1.799 raeburn 1003: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 1004: $currentpass = &escape($currentpass);
1005: $newpass = &escape($newpass);
1.1030 raeburn 1006: my $lonhost = $perlvar{'lonHostID'};
1007: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202 matthew 1008: $server);
1009: if (! $answer) {
1010: &logthis("No reply on password change request to $server ".
1011: "by $uname in domain $udom.");
1012: } elsif ($answer =~ "^ok") {
1013: &logthis("$uname in $udom successfully changed their password ".
1014: "on $server.");
1015: } elsif ($answer =~ "^pwchange_failure") {
1016: &logthis("$uname in $udom was unable to change their password ".
1017: "on $server. The action was blocked by either lcpasswd ".
1018: "or pwchange");
1019: } elsif ($answer =~ "^non_authorized") {
1020: &logthis("$uname in $udom did not get their password correct when ".
1021: "attempting to change it on $server.");
1022: } elsif ($answer =~ "^auth_mode_error") {
1023: &logthis("$uname in $udom attempted to change their password despite ".
1024: "not being locally or internally authenticated on $server.");
1025: } elsif ($answer =~ "^unknown_user") {
1026: &logthis("$uname in $udom attempted to change their password ".
1027: "on $server but were unable to because $server is not ".
1028: "their home server.");
1029: } elsif ($answer =~ "^refused") {
1030: &logthis("$server refused to change $uname in $udom password because ".
1031: "it was sent an unencrypted request to change the password.");
1.1030 raeburn 1032: } elsif ($answer =~ "invalid_client") {
1033: &logthis("$server refused to change $uname in $udom password because ".
1034: "it was a reset by e-mail originating from an invalid server.");
1.202 matthew 1035: }
1036: return $answer;
1.1 albertel 1037: }
1038:
1.169 harris41 1039: # ----------------------- Try to determine user's current authentication scheme
1040:
1041: sub queryauthenticate {
1042: my ($uname,$udom)=@_;
1.456 albertel 1043: my $uhome=&homeserver($uname,$udom);
1044: if (!$uhome) {
1045: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
1046: return 'no_host';
1047: }
1048: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
1049: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
1050: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 1051: }
1.456 albertel 1052: return $answer;
1.169 harris41 1053: }
1054:
1.1 albertel 1055: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 1056:
1.1 albertel 1057: sub authenticate {
1.1073 raeburn 1058: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807 albertel 1059: $upass=&escape($upass);
1060: $uname= &LONCAPA::clean_username($uname);
1.836 www 1061: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 1062: my $newhome;
1.836 www 1063: if ((!$uhome) || ($uhome eq 'no_host')) {
1064: # Maybe the machine was offline and only re-appeared again recently?
1065: &reconlonc();
1066: # One more
1.952 raeburn 1067: $uhome=&homeserver($uname,$udom,1);
1068: if (($uhome eq 'no_host') && $checkdefauth) {
1069: if (defined(&domain($udom,'primary'))) {
1070: $newhome=&domain($udom,'primary');
1071: }
1072: if ($newhome ne '') {
1073: $uhome = $newhome;
1074: }
1075: }
1.836 www 1076: if ((!$uhome) || ($uhome eq 'no_host')) {
1077: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 1078: return 'no_host';
1079: }
1.1 albertel 1080: }
1.1073 raeburn 1081: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471 albertel 1082: if ($answer eq 'authorized') {
1.952 raeburn 1083: if ($newhome) {
1084: &logthis("User $uname at $udom authorized by $uhome, but needs account");
1085: return 'no_account_on_host';
1086: } else {
1087: &logthis("User $uname at $udom authorized by $uhome");
1088: return $uhome;
1089: }
1.471 albertel 1090: }
1091: if ($answer eq 'non_authorized') {
1092: &logthis("User $uname at $udom rejected by $uhome");
1093: return 'no_host';
1.9 www 1094: }
1.471 albertel 1095: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 1096: return 'no_host';
1097: }
1098:
1.1073 raeburn 1099: sub can_host_session {
1.1074 raeburn 1100: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073 raeburn 1101: my $canhost = 1;
1.1074 raeburn 1102: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073 raeburn 1103: if (ref($remotesessions) eq 'HASH') {
1104: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074 raeburn 1105: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073 raeburn 1106: $canhost = 0;
1107: } else {
1108: $canhost = 1;
1109: }
1110: }
1111: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074 raeburn 1112: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073 raeburn 1113: $canhost = 1;
1114: } else {
1115: $canhost = 0;
1116: }
1117: }
1118: if ($canhost) {
1119: if ($remotesessions->{'version'} ne '') {
1120: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1121: if ($reqmajor ne '' && $reqminor ne '') {
1122: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1123: my $major = $1;
1124: my $minor = $2;
1125: if (($major < $reqmajor ) ||
1126: (($major == $reqmajor) && ($minor < $reqminor))) {
1127: $canhost = 0;
1128: }
1129: } else {
1130: $canhost = 0;
1131: }
1132: }
1133: }
1134: }
1135: }
1136: if ($canhost) {
1137: if (ref($hostedsessions) eq 'HASH') {
1.1120 raeburn 1138: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1139: my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073 raeburn 1140: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120 raeburn 1141: if (($uint_dom ne '') &&
1142: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073 raeburn 1143: $canhost = 0;
1144: } else {
1145: $canhost = 1;
1146: }
1147: }
1148: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120 raeburn 1149: if (($uint_dom ne '') &&
1150: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073 raeburn 1151: $canhost = 1;
1152: } else {
1153: $canhost = 0;
1154: }
1155: }
1156: }
1157: }
1158: return $canhost;
1159: }
1160:
1.1083 raeburn 1161: sub spare_can_host {
1162: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1163: my $canhost=1;
1164: my @intdoms;
1165: my $internet_names = &Apache::lonnet::get_internet_names($try_server);
1166: if (ref($internet_names) eq 'ARRAY') {
1167: @intdoms = @{$internet_names};
1168: }
1169: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1170: my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
1171: my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
1172: my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
1173: my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
1174: $canhost = &can_host_session($udom,$try_server,$remoterev,
1175: $remotesessions,
1176: $defdomdefaults{'hostedsessions'});
1177: }
1178: return $canhost;
1179: }
1180:
1.1123 raeburn 1181: sub this_host_spares {
1182: my ($dom) = @_;
1.1126 raeburn 1183: my ($dom_in_use,$lonhost_in_use,$result);
1.1123 raeburn 1184: my @hosts = ¤t_machine_ids();
1185: foreach my $lonhost (@hosts) {
1186: if (&host_domain($lonhost) eq $dom) {
1.1126 raeburn 1187: $dom_in_use = $dom;
1188: $lonhost_in_use = $lonhost;
1.1123 raeburn 1189: last;
1190: }
1191: }
1.1126 raeburn 1192: if ($dom_in_use ne '') {
1193: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1194: }
1195: if (ref($result) ne 'HASH') {
1196: $lonhost_in_use = $perlvar{'lonHostID'};
1197: $dom_in_use = &host_domain($lonhost_in_use);
1198: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1199: if (ref($result) ne 'HASH') {
1200: $result = \%spareid;
1201: }
1202: }
1203: return $result;
1204: }
1205:
1206: sub spares_for_offload {
1207: my ($dom_in_use,$lonhost_in_use) = @_;
1208: my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123 raeburn 1209: if (defined($cached)) {
1210: return $result;
1211: } else {
1.1126 raeburn 1212: my $cachetime = 60*60*24;
1213: my %domconfig =
1214: &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
1215: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1216: if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
1217: if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
1218: return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123 raeburn 1219: }
1220: }
1221: }
1222: }
1.1126 raeburn 1223: return;
1.1123 raeburn 1224: }
1225:
1.1129 raeburn 1226: sub get_lonbalancer_config {
1227: my ($servers) = @_;
1228: my ($currbalancer,$currtargets);
1229: if (ref($servers) eq 'HASH') {
1230: foreach my $server (keys(%{$servers})) {
1231: my %what = (
1232: spareid => 1,
1233: perlvar => 1,
1234: );
1235: my ($result,$returnhash) = &get_remote_globals($server,\%what);
1236: if ($result eq 'ok') {
1237: if (ref($returnhash) eq 'HASH') {
1238: if (ref($returnhash->{'perlvar'}) eq 'HASH') {
1239: if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
1240: $currbalancer = $server;
1241: $currtargets = {};
1242: if (ref($returnhash->{'spareid'}) eq 'HASH') {
1243: if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
1244: $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
1245: }
1246: if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
1247: $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
1248: }
1249: }
1250: last;
1251: }
1252: }
1253: }
1254: }
1255: }
1256: }
1257: return ($currbalancer,$currtargets);
1258: }
1259:
1260: sub check_loadbalancing {
1261: my ($uname,$udom) = @_;
1.1191 raeburn 1262: my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1263: $rule_in_effect,$offloadto,$otherserver);
1.1129 raeburn 1264: my $lonhost = $perlvar{'lonHostID'};
1.1175 raeburn 1265: my @hosts = ¤t_machine_ids();
1.1129 raeburn 1266: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1267: my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
1268: my $intdom = &Apache::lonnet::internet_dom($lonhost);
1269: my $serverhomedom = &host_domain($lonhost);
1270:
1271: my $cachetime = 60*60*24;
1272:
1273: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1274: $dom_in_use = $udom;
1275: $homeintdom = 1;
1276: } else {
1277: $dom_in_use = $serverhomedom;
1278: }
1279: my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
1280: unless (defined($cached)) {
1281: my %domconfig =
1282: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
1283: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1284: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129 raeburn 1285: }
1286: }
1287: if (ref($result) eq 'HASH') {
1.1191 raeburn 1288: ($is_balancer,$currtargets,$currrules) =
1289: &check_balancer_result($result,@hosts);
1.1129 raeburn 1290: if ($is_balancer) {
1291: if (ref($currrules) eq 'HASH') {
1292: if ($homeintdom) {
1293: if ($uname ne '') {
1294: if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
1295: my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
1296: if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
1297: $rule_in_effect = $currrules->{'_LC_author'};
1298: } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
1299: $rule_in_effect = $currrules->{'_LC_adv'}
1300: }
1301: }
1302: if ($rule_in_effect eq '') {
1303: my %userenv = &userenvironment($udom,$uname,'inststatus');
1304: if ($userenv{'inststatus'} ne '') {
1305: my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
1306: my ($othertitle,$usertypes,$types) =
1307: &Apache::loncommon::sorted_inst_types($udom);
1308: if (ref($types) eq 'ARRAY') {
1309: foreach my $type (@{$types}) {
1310: if (grep(/^\Q$type\E$/,@statuses)) {
1311: if (exists($currrules->{$type})) {
1312: $rule_in_effect = $currrules->{$type};
1313: }
1314: }
1315: }
1316: }
1317: } else {
1318: if (exists($currrules->{'default'})) {
1319: $rule_in_effect = $currrules->{'default'};
1320: }
1321: }
1322: }
1323: } else {
1324: if (exists($currrules->{'default'})) {
1325: $rule_in_effect = $currrules->{'default'};
1326: }
1327: }
1328: } else {
1329: if ($currrules->{'_LC_external'} ne '') {
1330: $rule_in_effect = $currrules->{'_LC_external'};
1331: }
1332: }
1333: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1334: $uname,$udom);
1335: }
1336: }
1337: } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1239 raeburn 1338: ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129 raeburn 1339: unless (defined($cached)) {
1340: my %domconfig =
1341: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
1342: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1343: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129 raeburn 1344: }
1345: }
1346: if (ref($result) eq 'HASH') {
1.1191 raeburn 1347: ($is_balancer,$currtargets,$currrules) =
1348: &check_balancer_result($result,@hosts);
1349: if ($is_balancer) {
1.1129 raeburn 1350: if (ref($currrules) eq 'HASH') {
1351: if ($currrules->{'_LC_internetdom'} ne '') {
1352: $rule_in_effect = $currrules->{'_LC_internetdom'};
1353: }
1354: }
1355: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1356: $uname,$udom);
1357: }
1358: } else {
1359: if ($perlvar{'lonBalancer'} eq 'yes') {
1360: $is_balancer = 1;
1361: $offloadto = &this_host_spares($dom_in_use);
1362: }
1363: }
1364: } else {
1365: if ($perlvar{'lonBalancer'} eq 'yes') {
1366: $is_balancer = 1;
1367: $offloadto = &this_host_spares($dom_in_use);
1368: }
1369: }
1.1176 raeburn 1370: if ($is_balancer) {
1371: my $lowest_load = 30000;
1372: if (ref($offloadto) eq 'HASH') {
1373: if (ref($offloadto->{'primary'}) eq 'ARRAY') {
1374: foreach my $try_server (@{$offloadto->{'primary'}}) {
1375: ($otherserver,$lowest_load) =
1376: &compare_server_load($try_server,$otherserver,$lowest_load);
1377: }
1.1129 raeburn 1378: }
1.1176 raeburn 1379: my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129 raeburn 1380:
1.1176 raeburn 1381: if (!$found_server) {
1382: if (ref($offloadto->{'default'}) eq 'ARRAY') {
1383: foreach my $try_server (@{$offloadto->{'default'}}) {
1384: ($otherserver,$lowest_load) =
1385: &compare_server_load($try_server,$otherserver,$lowest_load);
1386: }
1387: }
1388: }
1389: } elsif (ref($offloadto) eq 'ARRAY') {
1390: if (@{$offloadto} == 1) {
1391: $otherserver = $offloadto->[0];
1392: } elsif (@{$offloadto} > 1) {
1393: foreach my $try_server (@{$offloadto}) {
1.1129 raeburn 1394: ($otherserver,$lowest_load) =
1395: &compare_server_load($try_server,$otherserver,$lowest_load);
1396: }
1397: }
1398: }
1.1176 raeburn 1399: if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
1400: $is_balancer = 0;
1401: if ($uname ne '' && $udom ne '') {
1402: if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1403:
1404: &appenv({'user.loadbalexempt' => $lonhost,
1405: 'user.loadbalcheck.time' => time});
1406: }
1.1129 raeburn 1407: }
1408: }
1409: }
1410: return ($is_balancer,$otherserver);
1411: }
1412:
1.1191 raeburn 1413: sub check_balancer_result {
1414: my ($result,@hosts) = @_;
1415: my ($is_balancer,$currtargets,$currrules);
1416: if (ref($result) eq 'HASH') {
1417: if ($result->{'lonhost'} ne '') {
1418: my $currbalancer = $result->{'lonhost'};
1419: if (grep(/^\Q$currbalancer\E$/,@hosts)) {
1420: $is_balancer = 1;
1421: $currtargets = $result->{'targets'};
1422: $currrules = $result->{'rules'};
1423: }
1424: } else {
1425: foreach my $key (keys(%{$result})) {
1426: if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
1427: (ref($result->{$key}) eq 'HASH')) {
1428: $is_balancer = 1;
1429: $currrules = $result->{$key}{'rules'};
1430: $currtargets = $result->{$key}{'targets'};
1431: last;
1432: }
1433: }
1434: }
1435: }
1436: return ($is_balancer,$currtargets,$currrules);
1437: }
1438:
1.1129 raeburn 1439: sub get_loadbalancer_targets {
1440: my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
1441: my $offloadto;
1.1175 raeburn 1442: if ($rule_in_effect eq 'none') {
1443: return [$perlvar{'lonHostID'}];
1444: } elsif ($rule_in_effect eq '') {
1.1129 raeburn 1445: $offloadto = $currtargets;
1446: } else {
1447: if ($rule_in_effect eq 'homeserver') {
1448: my $homeserver = &homeserver($uname,$udom);
1449: if ($homeserver ne 'no_host') {
1450: $offloadto = [$homeserver];
1451: }
1452: } elsif ($rule_in_effect eq 'externalbalancer') {
1453: my %domconfig =
1454: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1455: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1456: if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
1457: if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
1458: $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
1459: }
1460: }
1461: } else {
1.1178 raeburn 1462: my %servers = &internet_dom_servers($udom);
1.1129 raeburn 1463: my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
1464: if (&hostname($remotebalancer) ne '') {
1465: $offloadto = [$remotebalancer];
1466: }
1467: }
1468: } elsif (&hostname($rule_in_effect) ne '') {
1469: $offloadto = [$rule_in_effect];
1470: }
1471: }
1472: return $offloadto;
1473: }
1474:
1.1127 raeburn 1475: sub internet_dom_servers {
1476: my ($dom) = @_;
1477: my (%uniqservers,%servers);
1478: my $primaryserver = &hostname(&domain($dom,'primary'));
1479: my @machinedoms = &machine_domains($primaryserver);
1480: foreach my $mdom (@machinedoms) {
1481: my %currservers = %servers;
1482: my %server = &get_servers($mdom);
1483: %servers = (%currservers,%server);
1484: }
1485: my %by_hostname;
1486: foreach my $id (keys(%servers)) {
1487: push(@{$by_hostname{$servers{$id}}},$id);
1488: }
1489: foreach my $hostname (sort(keys(%by_hostname))) {
1490: if (@{$by_hostname{$hostname}} > 1) {
1491: my $match = 0;
1492: foreach my $id (@{$by_hostname{$hostname}}) {
1493: if (&host_domain($id) eq $dom) {
1494: $uniqservers{$id} = $hostname;
1495: $match = 1;
1496: }
1497: }
1498: unless ($match) {
1499: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1500: }
1501: } else {
1502: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1503: }
1504: }
1505: return %uniqservers;
1506: }
1507:
1.1 albertel 1508: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 1509:
1.599 albertel 1510: my %homecache;
1.1 albertel 1511: sub homeserver {
1.230 stredwic 1512: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 1513: my $index="$uname:$udom";
1.426 albertel 1514:
1.599 albertel 1515: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 1516:
1517: my %servers = &get_servers($udom,'library');
1518: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 1519: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 1520: exists($badServerCache{$tryserver}));
1.841 albertel 1521:
1522: my $answer=reply("home:$udom:$uname",$tryserver);
1523: if ($answer eq 'found') {
1524: delete($badServerCache{$tryserver});
1525: return $homecache{$index}=$tryserver;
1526: } elsif ($answer eq 'no_host') {
1527: $badServerCache{$tryserver}=1;
1528: }
1.1 albertel 1529: }
1530: return 'no_host';
1.70 www 1531: }
1532:
1533: # ------------------------------------- Find the usernames behind a list of IDs
1534:
1535: sub idget {
1536: my ($udom,@ids)=@_;
1537: my %returnhash=();
1538:
1.841 albertel 1539: my %servers = &get_servers($udom,'library');
1540: foreach my $tryserver (keys(%servers)) {
1541: my $idlist=join('&',@ids);
1542: $idlist=~tr/A-Z/a-z/;
1543: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
1544: my @answer=();
1545: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1546: @answer=split(/\&/,$reply);
1547: } ;
1548: my $i;
1549: for ($i=0;$i<=$#ids;$i++) {
1550: if ($answer[$i]) {
1551: $returnhash{$ids[$i]}=$answer[$i];
1552: }
1553: }
1554: }
1.70 www 1555: return %returnhash;
1556: }
1557:
1558: # ------------------------------------- Find the IDs behind a list of usernames
1559:
1560: sub idrget {
1561: my ($udom,@unames)=@_;
1562: my %returnhash=();
1.800 albertel 1563: foreach my $uname (@unames) {
1564: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 1565: }
1.70 www 1566: return %returnhash;
1567: }
1568:
1569: # ------------------------------- Store away a list of names and associated IDs
1570:
1571: sub idput {
1572: my ($udom,%ids)=@_;
1573: my %servers=();
1.800 albertel 1574: foreach my $uname (keys(%ids)) {
1575: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1576: my $uhom=&homeserver($uname,$udom);
1.70 www 1577: if ($uhom ne 'no_host') {
1.800 albertel 1578: my $id=&escape($ids{$uname});
1.70 www 1579: $id=~tr/A-Z/a-z/;
1.800 albertel 1580: my $esc_unam=&escape($uname);
1.70 www 1581: if ($servers{$uhom}) {
1.800 albertel 1582: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70 www 1583: } else {
1.800 albertel 1584: $servers{$uhom}=$id.'='.$esc_unam;
1.70 www 1585: }
1586: }
1.191 harris41 1587: }
1.800 albertel 1588: foreach my $server (keys(%servers)) {
1589: &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191 harris41 1590: }
1.344 www 1591: }
1592:
1.1231 raeburn 1593: # ---------------------------------------- Delete unwanted IDs from ids.db file
1594:
1595: sub iddel {
1596: my ($udom,$idshashref,$uhome)=@_;
1597: my %result=();
1598: unless (ref($idshashref) eq 'HASH') {
1599: return %result;
1600: }
1601: my %servers=();
1602: while (my ($id,$uname) = each(%{$idshashref})) {
1603: my $uhom;
1604: if ($uhome) {
1605: $uhom = $uhome;
1606: } else {
1607: $uhom=&homeserver($uname,$udom);
1608: }
1609: if ($uhom ne 'no_host') {
1610: if ($servers{$uhom}) {
1611: $servers{$uhom}.='&'.&escape($id);
1612: } else {
1613: $servers{$uhom}=&escape($id);
1614: }
1615: }
1616: }
1617: foreach my $server (keys(%servers)) {
1618: $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
1619: }
1620: return %result;
1621: }
1622:
1.1023 raeburn 1623: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 1624: sub dump_dom {
1.1165 droeschl 1625: my ($namespace, $udom, $regexp) = @_;
1626:
1627: $udom ||= $env{'user.domain'};
1628:
1629: return () unless $udom;
1630:
1631: return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012 raeburn 1632: }
1633:
1.1023 raeburn 1634: # ------------------------------------------ get items from domain db files
1.806 raeburn 1635:
1636: sub get_dom {
1.860 raeburn 1637: my ($namespace,$storearr,$udom,$uhome)=@_;
1.806 raeburn 1638: my $items='';
1639: foreach my $item (@$storearr) {
1640: $items.=&escape($item).'&';
1641: }
1642: $items=~s/\&$//;
1.860 raeburn 1643: if (!$udom) {
1644: $udom=$env{'user.domain'};
1645: if (defined(&domain($udom,'primary'))) {
1646: $uhome=&domain($udom,'primary');
1647: } else {
1.874 albertel 1648: undef($uhome);
1.860 raeburn 1649: }
1650: } else {
1651: if (!$uhome) {
1652: if (defined(&domain($udom,'primary'))) {
1653: $uhome=&domain($udom,'primary');
1654: }
1655: }
1656: }
1657: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1658: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866 raeburn 1659: my %returnhash;
1.875 albertel 1660: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 1661: return %returnhash;
1662: }
1.806 raeburn 1663: my @pairs=split(/\&/,$rep);
1664: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1665: return @pairs;
1666: }
1667: my $i=0;
1668: foreach my $item (@$storearr) {
1669: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1670: $i++;
1671: }
1672: return %returnhash;
1673: } else {
1.880 banghart 1674: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 1675: }
1676: }
1677:
1678: # -------------------------------------------- put items in domain db files
1679:
1680: sub put_dom {
1.860 raeburn 1681: my ($namespace,$storehash,$udom,$uhome)=@_;
1682: if (!$udom) {
1683: $udom=$env{'user.domain'};
1684: if (defined(&domain($udom,'primary'))) {
1685: $uhome=&domain($udom,'primary');
1686: } else {
1.874 albertel 1687: undef($uhome);
1.860 raeburn 1688: }
1689: } else {
1690: if (!$uhome) {
1691: if (defined(&domain($udom,'primary'))) {
1692: $uhome=&domain($udom,'primary');
1693: }
1694: }
1695: }
1696: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1697: my $items='';
1698: foreach my $item (keys(%$storehash)) {
1699: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1700: }
1701: $items=~s/\&$//;
1702: return &reply("putdom:$udom:$namespace:$items",$uhome);
1703: } else {
1.860 raeburn 1704: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 1705: }
1706: }
1707:
1.1023 raeburn 1708: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 1709: sub newput_dom {
1.1023 raeburn 1710: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 1711: my $result;
1712: if (!$udom) {
1713: $udom=$env{'user.domain'};
1714: }
1.1023 raeburn 1715: if ($udom) {
1716: my $uname = &get_domainconfiguser($udom);
1717: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 1718: }
1719: return $result;
1720: }
1721:
1.1023 raeburn 1722: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 1723: sub del_dom {
1.1023 raeburn 1724: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 1725: if (ref($storearr) eq 'ARRAY') {
1726: if (!$udom) {
1727: $udom=$env{'user.domain'};
1728: }
1.1023 raeburn 1729: if ($udom) {
1730: my $uname = &get_domainconfiguser($udom);
1731: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 1732: }
1733: }
1734: }
1735:
1.1023 raeburn 1736: # ----------------------------------construct domainconfig user for a domain
1737: sub get_domainconfiguser {
1738: my ($udom) = @_;
1739: return $udom.'-domainconfig';
1740: }
1741:
1.837 raeburn 1742: sub retrieve_inst_usertypes {
1743: my ($udom) = @_;
1744: my (%returnhash,@order);
1.989 raeburn 1745: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1746: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1747: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1256 raeburn 1748: return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989 raeburn 1749: } else {
1750: if (defined(&domain($udom,'primary'))) {
1751: my $uhome=&domain($udom,'primary');
1752: my $rep=&reply("inst_usertypes:$udom",$uhome);
1753: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1256 raeburn 1754: &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989 raeburn 1755: return (\%returnhash,\@order);
1756: }
1757: my ($hashitems,$orderitems) = split(/:/,$rep);
1758: my @pairs=split(/\&/,$hashitems);
1759: foreach my $item (@pairs) {
1760: my ($key,$value)=split(/=/,$item,2);
1761: $key = &unescape($key);
1762: next if ($key =~ /^error: 2 /);
1763: $returnhash{$key}=&thaw_unescape($value);
1764: }
1765: my @esc_order = split(/\&/,$orderitems);
1766: foreach my $item (@esc_order) {
1767: push(@order,&unescape($item));
1768: }
1769: } else {
1.1256 raeburn 1770: &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837 raeburn 1771: }
1.1256 raeburn 1772: return (\%returnhash,\@order);
1.837 raeburn 1773: }
1774: }
1775:
1.868 raeburn 1776: sub is_domainimage {
1777: my ($url) = @_;
1778: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
1779: if (&domain($1) ne '') {
1780: return '1';
1781: }
1782: }
1783: return;
1784: }
1785:
1.899 raeburn 1786: sub inst_directory_query {
1787: my ($srch) = @_;
1788: my $udom = $srch->{'srchdomain'};
1789: my %results;
1790: my $homeserver = &domain($udom,'primary');
1.909 raeburn 1791: my $outcome;
1.899 raeburn 1792: if ($homeserver ne '') {
1.904 albertel 1793: my $queryid=&reply("querysend:instdirsearch:".
1794: &escape($srch->{'srchby'}).':'.
1795: &escape($srch->{'srchterm'}).':'.
1796: &escape($srch->{'srchtype'}),$homeserver);
1797: my $host=&hostname($homeserver);
1798: if ($queryid !~/^\Q$host\E\_/) {
1799: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1800: return;
1801: }
1802: my $response = &get_query_reply($queryid);
1803: my $maxtries = 5;
1804: my $tries = 1;
1805: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1806: $response = &get_query_reply($queryid);
1807: $tries ++;
1808: }
1809:
1810: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 1811: if ($response eq 'unavailable') {
1812: $outcome = $response;
1813: } else {
1814: $outcome = 'ok';
1815: my @matches = split(/\n/,$response);
1816: foreach my $match (@matches) {
1817: my ($key,$value) = split(/=/,$match);
1818: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1819: }
1.899 raeburn 1820: }
1821: }
1822: }
1.909 raeburn 1823: return ($outcome,%results);
1.899 raeburn 1824: }
1825:
1826: sub usersearch {
1827: my ($srch) = @_;
1828: my $dom = $srch->{'srchdomain'};
1829: my %results;
1830: my %libserv = &all_library();
1831: my $query = 'usersearch';
1832: foreach my $tryserver (keys(%libserv)) {
1833: if (&host_domain($tryserver) eq $dom) {
1834: my $host=&hostname($tryserver);
1835: my $queryid=
1.911 raeburn 1836: &reply("querysend:".&escape($query).':'.
1837: &escape($srch->{'srchby'}).':'.
1.899 raeburn 1838: &escape($srch->{'srchtype'}).':'.
1839: &escape($srch->{'srchterm'}),$tryserver);
1840: if ($queryid !~/^\Q$host\E\_/) {
1841: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 1842: next;
1.899 raeburn 1843: }
1844: my $reply = &get_query_reply($queryid);
1845: my $maxtries = 1;
1846: my $tries = 1;
1847: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1848: $reply = &get_query_reply($queryid);
1849: $tries ++;
1850: }
1851: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1852: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1853: } else {
1.911 raeburn 1854: my @matches;
1855: if ($reply =~ /\n/) {
1856: @matches = split(/\n/,$reply);
1857: } else {
1858: @matches = split(/\&/,$reply);
1859: }
1.899 raeburn 1860: foreach my $match (@matches) {
1861: my ($uname,$udom,%userhash);
1.911 raeburn 1862: foreach my $entry (split(/:/,$match)) {
1863: my ($key,$value) =
1864: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 1865: $userhash{$key} = $value;
1866: if ($key eq 'username') {
1867: $uname = $value;
1868: } elsif ($key eq 'domain') {
1869: $udom = $value;
1.911 raeburn 1870: }
1.899 raeburn 1871: }
1872: $results{$uname.':'.$udom} = \%userhash;
1873: }
1874: }
1875: }
1876: }
1877: return %results;
1878: }
1879:
1.912 raeburn 1880: sub get_instuser {
1881: my ($udom,$uname,$id) = @_;
1882: my $homeserver = &domain($udom,'primary');
1883: my ($outcome,%results);
1884: if ($homeserver ne '') {
1885: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1886: &escape($id).':'.&escape($udom),$homeserver);
1887: my $host=&hostname($homeserver);
1888: if ($queryid !~/^\Q$host\E\_/) {
1889: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1890: return;
1891: }
1892: my $response = &get_query_reply($queryid);
1893: my $maxtries = 5;
1894: my $tries = 1;
1895: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1896: $response = &get_query_reply($queryid);
1897: $tries ++;
1898: }
1899: if (!&error($response) && $response ne 'refused') {
1900: if ($response eq 'unavailable') {
1901: $outcome = $response;
1902: } else {
1903: $outcome = 'ok';
1904: my @matches = split(/\n/,$response);
1905: foreach my $match (@matches) {
1906: my ($key,$value) = split(/=/,$match);
1907: $results{&unescape($key)} = &thaw_unescape($value);
1908: }
1909: }
1910: }
1911: }
1912: my %userinfo;
1913: if (ref($results{$uname}) eq 'HASH') {
1914: %userinfo = %{$results{$uname}};
1915: }
1916: return ($outcome,%userinfo);
1917: }
1918:
1919: sub inst_rulecheck {
1.923 raeburn 1920: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 1921: my %returnhash;
1922: if ($udom ne '') {
1923: if (ref($rules) eq 'ARRAY') {
1924: @{$rules} = map {&escape($_);} (@{$rules});
1925: my $rulestr = join(':',@{$rules});
1926: my $homeserver=&domain($udom,'primary');
1927: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1928: my $response;
1929: if ($item eq 'username') {
1930: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
1931: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 1932: $homeserver));
1.923 raeburn 1933: } elsif ($item eq 'id') {
1934: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
1935: ':'.&escape($id).':'.$rulestr,
1936: $homeserver));
1.945 raeburn 1937: } elsif ($item eq 'selfcreate') {
1938: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 1939: &escape($udom).':'.&escape($uname).
1940: ':'.$rulestr,$homeserver));
1.923 raeburn 1941: }
1.912 raeburn 1942: if ($response ne 'refused') {
1943: my @pairs=split(/\&/,$response);
1944: foreach my $item (@pairs) {
1945: my ($key,$value)=split(/=/,$item,2);
1946: $key = &unescape($key);
1947: next if ($key =~ /^error: 2 /);
1948: $returnhash{$key}=&thaw_unescape($value);
1949: }
1950: }
1951: }
1952: }
1953: }
1954: return %returnhash;
1955: }
1956:
1957: sub inst_userrules {
1.923 raeburn 1958: my ($udom,$check) = @_;
1.912 raeburn 1959: my (%ruleshash,@ruleorder);
1960: if ($udom ne '') {
1961: my $homeserver=&domain($udom,'primary');
1962: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1963: my $response;
1964: if ($check eq 'id') {
1965: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 1966: $homeserver);
1.943 raeburn 1967: } elsif ($check eq 'email') {
1968: $response=&reply('instemailrules:'.&escape($udom),
1969: $homeserver);
1.923 raeburn 1970: } else {
1971: $response=&reply('instuserrules:'.&escape($udom),
1972: $homeserver);
1973: }
1.912 raeburn 1974: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 1975: ($response ne 'unknown_cmd') &&
1.912 raeburn 1976: ($response ne 'no_such_host')) {
1977: my ($hashitems,$orderitems) = split(/:/,$response);
1978: my @pairs=split(/\&/,$hashitems);
1979: foreach my $item (@pairs) {
1980: my ($key,$value)=split(/=/,$item,2);
1981: $key = &unescape($key);
1982: next if ($key =~ /^error: 2 /);
1983: $ruleshash{$key}=&thaw_unescape($value);
1984: }
1985: my @esc_order = split(/\&/,$orderitems);
1986: foreach my $item (@esc_order) {
1987: push(@ruleorder,&unescape($item));
1988: }
1989: }
1990: }
1991: }
1992: return (\%ruleshash,\@ruleorder);
1993: }
1994:
1.976 raeburn 1995: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 1996:
1997: sub get_domain_defaults {
1.1240 raeburn 1998: my ($domain,$ignore_cache) = @_;
1.1242 raeburn 1999: return if (($domain eq '') || ($domain eq 'public'));
1.943 raeburn 2000: my $cachetime = 60*60*24;
1.1240 raeburn 2001: unless ($ignore_cache) {
2002: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
2003: if (defined($cached)) {
2004: if (ref($result) eq 'HASH') {
2005: return %{$result};
2006: }
1.943 raeburn 2007: }
2008: }
2009: my %domdefaults;
2010: my %domconfig =
1.989 raeburn 2011: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 2012: 'requestcourses','inststatus',
1.1183 raeburn 2013: 'coursedefaults','usersessions',
1.1258 ! raeburn 2014: 'requestauthor','selfenrollment',
! 2015: 'coursecategories'],$domain);
1.1254 raeburn 2016: my @coursetypes = ('official','unofficial','community','textbook');
1.943 raeburn 2017: if (ref($domconfig{'defaults'}) eq 'HASH') {
2018: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
2019: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
2020: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 2021: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 2022: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147 raeburn 2023: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943 raeburn 2024: } else {
2025: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
2026: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
2027: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
2028: }
1.976 raeburn 2029: if (ref($domconfig{'quotas'}) eq 'HASH') {
2030: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
2031: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
2032: } else {
2033: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1229 raeburn 2034: }
1.1177 raeburn 2035: my @usertools = ('aboutme','blog','webdav','portfolio');
1.976 raeburn 2036: foreach my $item (@usertools) {
2037: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
2038: $domdefaults{$item} = $domconfig{'quotas'}{$item};
2039: }
2040: }
1.1229 raeburn 2041: if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
2042: $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
2043: }
1.976 raeburn 2044: }
1.985 raeburn 2045: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1246 raeburn 2046: foreach my $item ('official','unofficial','community','textbook') {
1.985 raeburn 2047: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
2048: }
2049: }
1.1183 raeburn 2050: if (ref($domconfig{'requestauthor'}) eq 'HASH') {
2051: $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
2052: }
1.989 raeburn 2053: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1256 raeburn 2054: foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989 raeburn 2055: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
2056: }
2057: }
1.1047 raeburn 2058: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1230 raeburn 2059: $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
1.1254 raeburn 2060: foreach my $type (@coursetypes) {
2061: if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
2062: unless ($type eq 'community') {
2063: $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
2064: }
2065: }
2066: if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
2067: $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
2068: }
1.1230 raeburn 2069: }
1.1047 raeburn 2070: }
1.1073 raeburn 2071: if (ref($domconfig{'usersessions'}) eq 'HASH') {
2072: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
2073: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
2074: }
2075: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
2076: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
2077: }
2078: }
1.1254 raeburn 2079: if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
2080: if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
2081: my @settings = ('types','registered','enroll_dates','access_dates','section',
2082: 'approval','limit');
2083: foreach my $type (@coursetypes) {
2084: if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
2085: my @mgrdc = ();
2086: foreach my $item (@settings) {
2087: if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
2088: push(@mgrdc,$item);
2089: }
2090: }
2091: if (@mgrdc) {
2092: $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
2093: }
2094: }
2095: }
2096: }
2097: if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
2098: foreach my $type (@coursetypes) {
2099: if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
2100: foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
2101: $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
2102: }
2103: }
2104: }
2105: }
2106: }
1.1258 ! raeburn 2107: if (ref($domconfig{'coursecategories'}) eq 'HASH') {
! 2108: $domdefaults{'catauth'} = 'std';
! 2109: $domdefaults{'catunauth'} = 'std';
! 2110: if ($domconfig{'coursecategories'}{'auth'}) {
! 2111: $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
! 2112: }
! 2113: if ($domconfig{'coursecategories'}{'unauth'}) {
! 2114: $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
! 2115: }
! 2116: }
1.1219 raeburn 2117: &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943 raeburn 2118: return %domdefaults;
2119: }
2120:
1.344 www 2121: # --------------------------------------------------- Assign a key to a student
2122:
2123: sub assign_access_key {
1.364 www 2124: #
2125: # a valid key looks like uname:udom#comments
2126: # comments are being appended
2127: #
1.498 www 2128: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
2129: $kdom=
1.620 albertel 2130: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 2131: $knum=
1.620 albertel 2132: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 2133: $cdom=
1.620 albertel 2134: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2135: $cnum=
1.620 albertel 2136: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2137: $udom=$env{'user.name'} unless (defined($udom));
2138: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 2139: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 2140: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 2141: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 2142: # assigned to this person
2143: # - this should not happen,
1.345 www 2144: # unless something went wrong
2145: # the first time around
2146: # ready to assign
1.364 www 2147: $logentry=$1.'; '.$logentry;
1.496 www 2148: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 2149: $kdom,$knum) eq 'ok') {
1.345 www 2150: # key now belongs to user
1.346 www 2151: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 2152: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 2153: &appenv({'environment.'.$envkey => $ckey});
1.345 www 2154: return 'ok';
2155: } else {
2156: return
2157: 'error: Count not permanently assign key, will need to be re-entered later.';
2158: }
2159: } else {
2160: return 'error: Could not assign key, try again later.';
2161: }
1.364 www 2162: } elsif (!$existing{$ckey}) {
1.345 www 2163: # the key does not exist
2164: return 'error: The key does not exist';
2165: } else {
2166: # the key is somebody else's
2167: return 'error: The key is already in use';
2168: }
1.344 www 2169: }
2170:
1.364 www 2171: # ------------------------------------------ put an additional comment on a key
2172:
2173: sub comment_access_key {
2174: #
2175: # a valid key looks like uname:udom#comments
2176: # comments are being appended
2177: #
2178: my ($ckey,$cdom,$cnum,$logentry)=@_;
2179: $cdom=
1.620 albertel 2180: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 2181: $cnum=
1.620 albertel 2182: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 2183: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2184: if ($existing{$ckey}) {
2185: $existing{$ckey}.='; '.$logentry;
2186: # ready to assign
1.367 www 2187: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 2188: $cdom,$cnum) eq 'ok') {
2189: return 'ok';
2190: } else {
2191: return 'error: Count not store comment.';
2192: }
2193: } else {
2194: # the key does not exist
2195: return 'error: The key does not exist';
2196: }
2197: }
2198:
1.344 www 2199: # ------------------------------------------------------ Generate a set of keys
2200:
2201: sub generate_access_keys {
1.364 www 2202: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 2203: $cdom=
1.620 albertel 2204: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2205: $cnum=
1.620 albertel 2206: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 2207: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 2208: unless (($cdom) && ($cnum)) { return 0; }
2209: if ($number>10000) { return 0; }
2210: sleep(2); # make sure don't get same seed twice
2211: srand(time()^($$+($$<<15))); # from "Programming Perl"
2212: my $total=0;
2213: for (my $i=1;$i<=$number;$i++) {
2214: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
2215: sprintf("%lx",int(100000*rand)).'-'.
2216: sprintf("%lx",int(100000*rand));
2217: $newkey=~s/1/g/g; # folks mix up 1 and l
2218: $newkey=~s/0/h/g; # and also 0 and O
2219: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
2220: if ($existing{$newkey}) {
2221: $i--;
2222: } else {
1.364 www 2223: if (&put('accesskeys',
2224: { $newkey => '# generated '.localtime().
1.620 albertel 2225: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 2226: '; '.$logentry },
2227: $cdom,$cnum) eq 'ok') {
1.344 www 2228: $total++;
2229: }
2230: }
2231: }
1.620 albertel 2232: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 2233: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
2234: return $total;
2235: }
2236:
2237: # ------------------------------------------------------- Validate an accesskey
2238:
2239: sub validate_access_key {
2240: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
2241: $cdom=
1.620 albertel 2242: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2243: $cnum=
1.620 albertel 2244: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2245: $udom=$env{'user.domain'} unless (defined($udom));
2246: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 2247: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 2248: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 2249: }
2250:
2251: # ------------------------------------- Find the section of student in a course
1.652 albertel 2252: sub devalidate_getsection_cache {
2253: my ($udom,$unam,$courseid)=@_;
2254: my $hashid="$udom:$unam:$courseid";
2255: &devalidate_cache_new('getsection',$hashid);
2256: }
1.298 matthew 2257:
1.815 albertel 2258: sub courseid_to_courseurl {
2259: my ($courseid) = @_;
2260: #already url style courseid
2261: return $courseid if ($courseid =~ m{^/});
2262:
2263: if (exists($env{'course.'.$courseid.'.num'})) {
2264: my $cnum = $env{'course.'.$courseid.'.num'};
2265: my $cdom = $env{'course.'.$courseid.'.domain'};
2266: return "/$cdom/$cnum";
2267: }
2268:
2269: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
2270: if (exists($courseinfo{'num'})) {
2271: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
2272: }
2273:
2274: return undef;
2275: }
2276:
1.298 matthew 2277: sub getsection {
2278: my ($udom,$unam,$courseid)=@_;
1.599 albertel 2279: my $cachetime=1800;
1.551 albertel 2280:
2281: my $hashid="$udom:$unam:$courseid";
1.599 albertel 2282: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 2283: if (defined($cached)) { return $result; }
2284:
1.298 matthew 2285: my %Pending;
2286: my %Expired;
2287: #
2288: # Each role can either have not started yet (pending), be active,
2289: # or have expired.
2290: #
2291: # If there is an active role, we are done.
2292: #
2293: # If there is more than one role which has not started yet,
2294: # choose the one which will start sooner
2295: # If there is one role which has not started yet, return it.
2296: #
2297: # If there is more than one expired role, choose the one which ended last.
2298: # If there is a role which has expired, return it.
2299: #
1.815 albertel 2300: $courseid = &courseid_to_courseurl($courseid);
1.1166 raeburn 2301: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817 raeburn 2302: foreach my $key (keys(%roleshash)) {
1.479 albertel 2303: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 2304: my $section=$1;
2305: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 2306: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 2307: my $now=time;
1.548 albertel 2308: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 2309: $Expired{$end}=$section;
2310: next;
2311: }
1.548 albertel 2312: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 2313: $Pending{$start}=$section;
2314: next;
2315: }
1.599 albertel 2316: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 2317: }
2318: #
2319: # Presumedly there will be few matching roles from the above
2320: # loop and the sorting time will be negligible.
2321: if (scalar(keys(%Pending))) {
2322: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 2323: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 2324: }
2325: if (scalar(keys(%Expired))) {
2326: my @sorted = sort {$a <=> $b} keys(%Expired);
2327: my $time = pop(@sorted);
1.599 albertel 2328: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 2329: }
1.599 albertel 2330: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 2331: }
1.70 www 2332:
1.599 albertel 2333: sub save_cache {
2334: &purge_remembered();
1.722 albertel 2335: #&Apache::loncommon::validate_page();
1.620 albertel 2336: undef(%env);
1.780 albertel 2337: undef($env_loaded);
1.599 albertel 2338: }
1.452 albertel 2339:
1.599 albertel 2340: my $to_remember=-1;
2341: my %remembered;
2342: my %accessed;
2343: my $kicks=0;
2344: my $hits=0;
1.849 albertel 2345: sub make_key {
2346: my ($name,$id) = @_;
1.872 albertel 2347: if (length($id) > 65
2348: && length(&escape($id)) > 200) {
2349: $id=length($id).':'.&Digest::MD5::md5_hex($id);
2350: }
1.849 albertel 2351: return &escape($name.':'.$id);
2352: }
2353:
1.599 albertel 2354: sub devalidate_cache_new {
2355: my ($name,$id,$debug) = @_;
2356: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849 albertel 2357: $id=&make_key($name,$id);
1.599 albertel 2358: $memcache->delete($id);
2359: delete($remembered{$id});
2360: delete($accessed{$id});
2361: }
2362:
2363: sub is_cached_new {
2364: my ($name,$id,$debug) = @_;
1.849 albertel 2365: $id=&make_key($name,$id);
1.599 albertel 2366: if (exists($remembered{$id})) {
1.1133 foxr 2367: if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
1.599 albertel 2368: $accessed{$id}=[&gettimeofday()];
2369: $hits++;
2370: return ($remembered{$id},1);
2371: }
2372: my $value = $memcache->get($id);
2373: if (!(defined($value))) {
2374: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 2375: return (undef,undef);
1.416 albertel 2376: }
1.599 albertel 2377: if ($value eq '__undef__') {
2378: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
2379: $value=undef;
2380: }
2381: &make_room($id,$value,$debug);
2382: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
2383: return ($value,1);
2384: }
2385:
2386: sub do_cache_new {
2387: my ($name,$id,$value,$time,$debug) = @_;
1.849 albertel 2388: $id=&make_key($name,$id);
1.599 albertel 2389: my $setvalue=$value;
2390: if (!defined($setvalue)) {
2391: $setvalue='__undef__';
2392: }
1.623 albertel 2393: if (!defined($time) ) {
2394: $time=600;
2395: }
1.599 albertel 2396: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 2397: my $result = $memcache->set($id,$setvalue,$time);
2398: if (! $result) {
1.872 albertel 2399: &logthis("caching of id -> $id failed");
1.910 albertel 2400: $memcache->disconnect_all();
1.872 albertel 2401: }
1.600 albertel 2402: # need to make a copy of $value
1.919 albertel 2403: &make_room($id,$value,$debug);
1.599 albertel 2404: return $value;
2405: }
2406:
2407: sub make_room {
2408: my ($id,$value,$debug)=@_;
1.919 albertel 2409:
2410: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
2411: : $value;
1.599 albertel 2412: if ($to_remember<0) { return; }
2413: $accessed{$id}=[&gettimeofday()];
2414: if (scalar(keys(%remembered)) <= $to_remember) { return; }
2415: my $to_kick;
2416: my $max_time=0;
2417: foreach my $other (keys(%accessed)) {
2418: if (&tv_interval($accessed{$other}) > $max_time) {
2419: $to_kick=$other;
2420: $max_time=&tv_interval($accessed{$other});
2421: }
2422: }
2423: delete($remembered{$to_kick});
2424: delete($accessed{$to_kick});
2425: $kicks++;
2426: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 2427: return;
2428: }
2429:
1.599 albertel 2430: sub purge_remembered {
1.604 albertel 2431: #&logthis("Tossing ".scalar(keys(%remembered)));
2432: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 2433: undef(%remembered);
2434: undef(%accessed);
1.428 albertel 2435: }
1.70 www 2436: # ------------------------------------- Read an entry from a user's environment
2437:
2438: sub userenvironment {
2439: my ($udom,$unam,@what)=@_;
1.976 raeburn 2440: my $items;
2441: foreach my $item (@what) {
2442: $items.=&escape($item).'&';
2443: }
2444: $items=~s/\&$//;
1.70 www 2445: my %returnhash=();
1.1009 raeburn 2446: my $uhome = &homeserver($unam,$udom);
2447: unless ($uhome eq 'no_host') {
2448: my @answer=split(/\&/,
2449: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 2450: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
2451: return %returnhash;
2452: }
1.1009 raeburn 2453: my $i;
2454: for ($i=0;$i<=$#what;$i++) {
2455: $returnhash{$what[$i]}=&unescape($answer[$i]);
2456: }
1.70 www 2457: }
2458: return %returnhash;
1.1 albertel 2459: }
2460:
1.617 albertel 2461: # ---------------------------------------------------------- Get a studentphoto
2462: sub studentphoto {
2463: my ($udom,$unam,$ext) = @_;
2464: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 2465: if (defined($env{'request.course.id'})) {
1.708 raeburn 2466: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 2467: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
2468: return(&retrievestudentphoto($udom,$unam,$ext));
2469: } else {
2470: my ($result,$perm_reqd)=
1.707 albertel 2471: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2472: if ($result eq 'ok') {
2473: if (!($perm_reqd eq 'yes')) {
2474: return(&retrievestudentphoto($udom,$unam,$ext));
2475: }
2476: }
2477: }
2478: }
2479: } else {
2480: my ($result,$perm_reqd) =
1.707 albertel 2481: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2482: if ($result eq 'ok') {
2483: if (!($perm_reqd eq 'yes')) {
2484: return(&retrievestudentphoto($udom,$unam,$ext));
2485: }
2486: }
2487: }
2488: return '/adm/lonKaputt/lonlogo_broken.gif';
2489: }
2490:
2491: sub retrievestudentphoto {
2492: my ($udom,$unam,$ext,$type) = @_;
2493: my $home=&Apache::lonnet::homeserver($unam,$udom);
2494: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
2495: if ($ret eq 'ok') {
2496: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
2497: if ($type eq 'thumbnail') {
2498: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
2499: }
2500: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
2501: return $tokenurl;
2502: } else {
2503: if ($type eq 'thumbnail') {
2504: return '/adm/lonKaputt/genericstudent_tn.gif';
2505: } else {
2506: return '/adm/lonKaputt/lonlogo_broken.gif';
2507: }
1.617 albertel 2508: }
2509: }
2510:
1.263 www 2511: # -------------------------------------------------------------------- New chat
2512:
2513: sub chatsend {
1.724 raeburn 2514: my ($newentry,$anon,$group)=@_;
1.620 albertel 2515: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
2516: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2517: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 2518: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 2519: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 2520: &escape($newentry)).':'.$group,$chome);
1.292 www 2521: }
2522:
2523: # ------------------------------------------ Find current version of a resource
2524:
2525: sub getversion {
2526: my $fname=&clutter(shift);
1.1189 raeburn 2527: unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292 www 2528: return ¤tversion(&filelocation('',$fname));
2529: }
2530:
2531: sub currentversion {
2532: my $fname=shift;
2533: my $author=$fname;
2534: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2535: my ($udom,$uname)=split(/\//,$author);
1.1112 www 2536: my $home=&homeserver($uname,$udom);
1.292 www 2537: if ($home eq 'no_host') {
2538: return -1;
2539: }
1.1112 www 2540: my $answer=&reply("currentversion:$fname",$home);
1.292 www 2541: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2542: return -1;
2543: }
1.1112 www 2544: return $answer;
1.263 www 2545: }
2546:
1.1111 www 2547: #
2548: # Return special version number of resource if set by override, empty otherwise
2549: #
2550: sub usedversion {
2551: my $fname=shift;
2552: unless ($fname) { $fname=$env{'request.uri'}; }
2553: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
2554: if ($urlversion) { return $urlversion; }
2555: return '';
2556: }
2557:
1.1 albertel 2558: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 2559:
1.1 albertel 2560: sub subscribe {
2561: my $fname=shift;
1.761 raeburn 2562: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 2563: $fname=~s/[\n\r]//g;
1.1 albertel 2564: my $author=$fname;
2565: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2566: my ($udom,$uname)=split(/\//,$author);
2567: my $home=homeserver($uname,$udom);
1.335 albertel 2568: if ($home eq 'no_host') {
2569: return 'not_found';
1.1 albertel 2570: }
2571: my $answer=reply("sub:$fname",$home);
1.64 www 2572: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2573: $answer.=' by '.$home;
2574: }
1.1 albertel 2575: return $answer;
2576: }
2577:
1.8 www 2578: # -------------------------------------------------------------- Replicate file
2579:
2580: sub repcopy {
2581: my $filename=shift;
1.23 www 2582: $filename=~s/\/+/\//g;
1.1142 raeburn 2583: my $londocroot = $perlvar{'lonDocRoot'};
2584: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164 raeburn 2585: if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142 raeburn 2586: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
2587: $filename=~m{^/*(uploaded|editupload)/}) {
1.538 albertel 2588: return &repcopy_userfile($filename);
2589: }
1.532 albertel 2590: $filename=~s/[\n\r]//g;
1.8 www 2591: my $transname="$filename.in.transfer";
1.828 www 2592: # FIXME: this should flock
1.607 raeburn 2593: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 2594: my $remoteurl=subscribe($filename);
1.64 www 2595: if ($remoteurl =~ /^con_lost by/) {
2596: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2597: return 'unavailable';
1.8 www 2598: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 2599: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 2600: return 'not_found';
1.64 www 2601: } elsif ($remoteurl =~ /^rejected by/) {
2602: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2603: return 'forbidden';
1.20 www 2604: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 2605: return 'ok';
1.8 www 2606: } else {
1.290 www 2607: my $author=$filename;
2608: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2609: my ($udom,$uname)=split(/\//,$author);
2610: my $home=homeserver($uname,$udom);
2611: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 2612: my @parts=split(/\//,$filename);
2613: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142 raeburn 2614: if ($path ne "$londocroot/res") {
1.8 www 2615: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 2616: return 'bad_request';
1.8 www 2617: }
2618: my $count;
2619: for ($count=5;$count<$#parts;$count++) {
2620: $path.="/$parts[$count]";
2621: if ((-e $path)!=1) {
2622: mkdir($path,0777);
2623: }
2624: }
2625: my $ua=new LWP::UserAgent;
2626: my $request=new HTTP::Request('GET',"$remoteurl");
2627: my $response=$ua->request($request,$transname);
2628: if ($response->is_error()) {
2629: unlink($transname);
2630: my $message=$response->status_line;
1.672 albertel 2631: &logthis("<font color=\"blue\">WARNING:"
1.12 www 2632: ." LWP get: $message: $filename</font>");
1.607 raeburn 2633: return 'unavailable';
1.8 www 2634: } else {
1.16 www 2635: if ($remoteurl!~/\.meta$/) {
2636: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2637: my $mresponse=$ua->request($mrequest,$filename.'.meta');
2638: if ($mresponse->is_error()) {
2639: unlink($filename.'.meta');
2640: &logthis(
1.672 albertel 2641: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 2642: }
2643: }
1.8 www 2644: rename($transname,$filename);
1.607 raeburn 2645: return 'ok';
1.8 www 2646: }
1.290 www 2647: }
1.8 www 2648: }
1.330 www 2649: }
2650:
2651: # ------------------------------------------------ Get server side include body
2652: sub ssi_body {
1.381 albertel 2653: my ($filelink,%form)=@_;
1.606 matthew 2654: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
2655: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
2656: }
1.953 www 2657: my $output='';
2658: my $response;
1.980 raeburn 2659: if ($filelink=~/^https?\:/) {
1.954 raeburn 2660: ($output,$response)=&externalssi($filelink);
1.953 www 2661: } else {
1.1004 droeschl 2662: $filelink .= $filelink=~/\?/ ? '&' : '?';
2663: $filelink .= 'inhibitmenu=yes';
1.953 www 2664: ($output,$response)=&ssi($filelink,%form);
2665: }
1.778 albertel 2666: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 2667: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 2668: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 2669: if (wantarray) {
2670: return ($output, $response);
2671: } else {
2672: return $output;
2673: }
1.8 www 2674: }
2675:
1.15 www 2676: # --------------------------------------------------------- Server Side Include
2677:
1.782 albertel 2678: sub absolute_url {
2679: my ($host_name) = @_;
2680: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
2681: if ($host_name eq '') {
2682: $host_name = $ENV{'SERVER_NAME'};
2683: }
2684: return $protocol.$host_name;
2685: }
2686:
1.942 foxr 2687: #
2688: # Server side include.
2689: # Parameters:
2690: # fn Possibly encrypted resource name/id.
2691: # form Hash that describes how the rendering should be done
2692: # and other things.
1.944 foxr 2693: # Returns:
1.950 raeburn 2694: # Scalar context: The content of the response.
2695: # Array context: 2 element list of the content and the full response object.
1.942 foxr 2696: #
1.15 www 2697: sub ssi {
2698:
1.944 foxr 2699: my ($fn,%form)=@_;
1.15 www 2700: my $ua=new LWP::UserAgent;
1.23 www 2701: my $request;
1.711 albertel 2702:
2703: $form{'no_update_last_known'}=1;
1.895 albertel 2704: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 2705: if (%form) {
1.782 albertel 2706: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000 raeburn 2707: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23 www 2708: } else {
1.782 albertel 2709: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 2710: }
2711:
1.15 www 2712: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1173 foxr 2713: my $response= $ua->request($request);
1.1182 foxr 2714: my $content = $response->content;
2715:
2716:
1.944 foxr 2717: if (wantarray) {
1.1173 foxr 2718: return ($content, $response);
1.944 foxr 2719: } else {
1.1173 foxr 2720: return $content;
1.942 foxr 2721: }
1.324 www 2722: }
2723:
2724: sub externalssi {
2725: my ($url)=@_;
2726: my $ua=new LWP::UserAgent;
2727: my $request=new HTTP::Request('GET',$url);
2728: my $response=$ua->request($request);
1.954 raeburn 2729: if (wantarray) {
2730: return ($response->content, $response);
2731: } else {
2732: return $response->content;
2733: }
1.15 www 2734: }
1.254 www 2735:
1.492 albertel 2736: # -------------------------------- Allow a /uploaded/ URI to be vouched for
2737:
2738: sub allowuploaded {
2739: my ($srcurl,$url)=@_;
2740: $url=&clutter(&declutter($url));
2741: my $dir=$url;
2742: $dir=~s/\/[^\/]+$//;
2743: my %httpref=();
2744: my $httpurl=&hreflocation('',$url);
2745: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 2746: &Apache::lonnet::appenv(\%httpref);
1.254 www 2747: }
1.477 raeburn 2748:
1.1193 raeburn 2749: #
2750: # Determine if the current user should be able to edit a particular resource,
2751: # when viewing in course context.
2752: # (a) When viewing resource used to determine if "Edit" item is included in
2753: # Functions.
2754: # (b) When displaying folder contents in course editor, used to determine if
2755: # "Edit" link will be displayed alongside resource.
2756: #
1.1196 raeburn 2757: # input: six args -- filename (decluttered), course number, course domain,
2758: # url, symb (if registered) and group (if this is a group
2759: # item -- e.g., bulletin board, group page etc.).
2760: # output: array of five scalars --
1.1193 raeburn 2761: # $cfile -- url for file editing if editable on current server
2762: # $home -- homeserver of resource (i.e., for author if published,
2763: # or course if uploaded.).
2764: # $switchserver -- 1 if server switch will be needed.
1.1196 raeburn 2765: # $forceedit -- 1 if icon/link should be to go to edit mode
2766: # $forceview -- 1 if icon/link should be to go to view mode
1.1193 raeburn 2767: #
2768:
2769: sub can_edit_resource {
1.1194 raeburn 2770: my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
2771: my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
2772: #
2773: # For aboutme pages user can only edit his/her own.
2774: #
1.1199 raeburn 2775: if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
1.1194 raeburn 2776: my ($sdom,$sname) = ($1,$2);
2777: if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
2778: $home = $env{'user.home'};
2779: $cfile = $resurl;
2780: if ($env{'form.forceedit'}) {
2781: $forceview = 1;
2782: } else {
2783: $forceedit = 1;
2784: }
2785: return ($cfile,$home,$switchserver,$forceedit,$forceview);
2786: } else {
2787: return;
2788: }
2789: }
2790:
2791: if ($env{'request.course.id'}) {
2792: my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
2793: if ($group ne '') {
2794: # if this is a group homepage or group bulletin board, check group privs
2795: my $allowed = 0;
1.1197 raeburn 2796: if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
2797: if ((&allowed('mdg',$env{'request.course.id'}.
1.1198 raeburn 2798: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
1.1194 raeburn 2799: (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
2800: $allowed = 1;
2801: }
1.1197 raeburn 2802: } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
2803: if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
2804: (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
1.1194 raeburn 2805: $allowed = 1;
2806: }
2807: }
2808: if ($allowed) {
2809: $home=&homeserver($cnum,$cdom);
2810: if ($env{'form.forceedit'}) {
2811: $forceview = 1;
2812: } else {
2813: $forceedit = 1;
2814: }
2815: $cfile = $resurl;
2816: } else {
2817: return;
2818: }
2819: } else {
1.1208 raeburn 2820: if ($resurl =~ m{^/?adm/viewclasslist$}) {
2821: unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
2822: return;
2823: }
2824: } elsif (!$crsedit) {
1.1194 raeburn 2825: #
2826: # No edit allowed where CC has switched to student role.
2827: #
2828: return;
2829: }
2830: }
2831: }
2832:
1.1193 raeburn 2833: if ($file ne '') {
2834: if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
1.1194 raeburn 2835: if (&is_course_upload($file,$cnum,$cdom)) {
2836: $uploaded = 1;
2837: $incourse = 1;
1.1193 raeburn 2838: if ($file =~/\.(htm|html|css|js|txt)$/) {
2839: $cfile = &hreflocation('',$file);
1.1201 raeburn 2840: if ($env{'form.forceedit'}) {
2841: $forceview = 1;
2842: } else {
2843: $forceedit = 1;
2844: }
1.1194 raeburn 2845: }
2846: } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
2847: $incourse = 1;
2848: if ($env{'form.forceedit'}) {
2849: $forceview = 1;
2850: } else {
2851: $forceedit = 1;
2852: }
2853: $cfile = $resurl;
2854: } elsif (($resurl ne '') && (&is_on_map($resurl))) {
2855: if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
2856: $incourse = 1;
2857: if ($env{'form.forceedit'}) {
2858: $forceview = 1;
2859: } else {
2860: $forceedit = 1;
2861: }
2862: $cfile = $resurl;
1.1199 raeburn 2863: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
1.1194 raeburn 2864: $incourse = 1;
2865: $cfile = $resurl.'/smpedit';
1.1199 raeburn 2866: } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
1.1194 raeburn 2867: $incourse = 1;
1.1199 raeburn 2868: if ($env{'form.forceedit'}) {
2869: $forceview = 1;
2870: } else {
2871: $forceedit = 1;
2872: }
2873: $cfile = $resurl;
1.1208 raeburn 2874: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
2875: $incourse = 1;
2876: if ($env{'form.forceedit'}) {
2877: $forceview = 1;
2878: } else {
2879: $forceedit = 1;
2880: }
2881: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1194 raeburn 2882: }
2883: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
2884: my $template = '/res/lib/templates/simpleproblem.problem';
2885: if (&is_on_map($template)) {
2886: $incourse = 1;
2887: $forceview = 1;
2888: $cfile = $template;
1.1193 raeburn 2889: }
1.1199 raeburn 2890: } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
2891: $incourse = 1;
2892: if ($env{'form.forceedit'}) {
2893: $forceview = 1;
2894: } else {
2895: $forceedit = 1;
2896: }
2897: $cfile = $resurl;
2898: } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
2899: $incourse = 1;
2900: $forceview = 1;
2901: if ($symb) {
2902: my ($map,$id,$res)=&decode_symb($symb);
2903: $env{'request.symb'} = $symb;
2904: $cfile = &clutter($res);
2905: } else {
2906: $cfile = $env{'form.suppurl'};
2907: $cfile =~ s{^http://}{};
2908: $cfile = '/adm/wrapper/ext/'.$cfile;
2909: }
1.1234 raeburn 2910: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
2911: if ($env{'form.forceedit'}) {
2912: $forceview = 1;
2913: } else {
2914: $forceedit = 1;
2915: }
2916: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1193 raeburn 2917: }
2918: }
1.1194 raeburn 2919: if ($uploaded || $incourse) {
2920: $home=&homeserver($cnum,$cdom);
1.1207 raeburn 2921: } elsif ($file !~ m{/$}) {
1.1193 raeburn 2922: $file=~s{^(priv/$match_domain/$match_username)}{/$1};
2923: $file=~s{^($match_domain/$match_username)}{/priv/$1};
2924: # Check that the user has permission to edit this resource
2925: my $setpriv = 1;
2926: my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
2927: if (defined($cfudom)) {
2928: $home=&homeserver($cfuname,$cfudom);
2929: $cfile=$file;
2930: }
2931: }
1.1194 raeburn 2932: if (($cfile ne '') && (!$incourse || $uploaded) &&
2933: (($home ne '') && ($home ne 'no_host'))) {
1.1193 raeburn 2934: my @ids=¤t_machine_ids();
2935: unless (grep(/^\Q$home\E$/,@ids)) {
2936: $switchserver=1;
2937: }
2938: }
2939: }
1.1194 raeburn 2940: return ($cfile,$home,$switchserver,$forceedit,$forceview);
1.1193 raeburn 2941: }
2942:
2943: sub is_course_upload {
2944: my ($file,$cnum,$cdom) = @_;
2945: my $uploadpath = &LONCAPA::propath($cdom,$cnum);
2946: $uploadpath =~ s{^\/}{};
1.1201 raeburn 2947: if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
2948: ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
1.1193 raeburn 2949: return 1;
2950: }
2951: return;
2952: }
2953:
1.1194 raeburn 2954: sub in_course {
1.1195 raeburn 2955: my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
2956: if ($hideprivileged) {
2957: my $skipuser;
1.1219 raeburn 2958: my %coursehash = &coursedescription($cdom.'_'.$cnum);
2959: my @possdoms = ($cdom);
2960: if ($coursehash{'checkforpriv'}) {
2961: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
2962: }
2963: if (&privileged($uname,$udom,\@possdoms)) {
1.1195 raeburn 2964: $skipuser = 1;
2965: if ($coursehash{'nothideprivileged'}) {
2966: foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
2967: my $user;
2968: if ($item =~ /:/) {
2969: $user = $item;
2970: } else {
2971: $user = join(':',split(/[\@]/,$item));
2972: }
2973: if ($user eq $uname.':'.$udom) {
2974: undef($skipuser);
2975: last;
2976: }
2977: }
2978: }
2979: if ($skipuser) {
2980: return 0;
2981: }
2982: }
2983: }
1.1194 raeburn 2984: $type ||= 'any';
2985: if (!defined($cdom) || !defined($cnum)) {
2986: my $cid = $env{'request.course.id'};
2987: $cdom = $env{'course.'.$cid.'.domain'};
2988: $cnum = $env{'course.'.$cid.'.num'};
2989: }
2990: my $typesref;
1.1195 raeburn 2991: if (($type eq 'any') || ($type eq 'all')) {
1.1194 raeburn 2992: $typesref = ['active','previous','future'];
2993: } elsif ($type eq 'previous' || $type eq 'future') {
2994: $typesref = [$type];
2995: }
2996: my %roles = &get_my_roles($uname,$udom,'userroles',
2997: $typesref,undef,[$cdom]);
2998: my ($tmp) = keys(%roles);
2999: return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
3000: my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
3001: if (@course_roles > 0) {
3002: return 1;
3003: }
3004: return 0;
3005: }
3006:
1.478 albertel 3007: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 3008: # input: action, courseID, current domain, intended
1.637 raeburn 3009: # path to file, source of file, instruction to parse file for objects,
3010: # ref to hash for embedded objects,
3011: # ref to hash for codebase of java objects.
1.1095 raeburn 3012: # reference to scalar to accommodate mime type determined
3013: # from File::MMagic if $parser = parse.
1.637 raeburn 3014: #
1.485 raeburn 3015: # output: url to file (if action was uploaddoc),
3016: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 3017: #
1.478 albertel 3018: # Allows directory structure to be used within lonUsers/../userfiles/ for a
3019: # course.
1.477 raeburn 3020: #
1.478 albertel 3021: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3022: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
3023: # course's home server.
1.477 raeburn 3024: #
1.478 albertel 3025: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
3026: # be copied from $source (current location) to
3027: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3028: # and will then be copied to
3029: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
3030: # course's home server.
1.485 raeburn 3031: #
1.481 raeburn 3032: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 3033: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 3034: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3035: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
3036: # in course's home server.
1.637 raeburn 3037: #
1.477 raeburn 3038:
3039: sub process_coursefile {
1.1095 raeburn 3040: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
3041: $mimetype)=@_;
1.477 raeburn 3042: my $fetchresult;
1.638 albertel 3043: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 3044: if ($action eq 'propagate') {
1.638 albertel 3045: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
3046: $home);
1.481 raeburn 3047: } else {
1.477 raeburn 3048: my $fpath = '';
3049: my $fname = $file;
1.478 albertel 3050: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 3051: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 3052: my $filepath = &build_filepath($fpath);
1.481 raeburn 3053: if ($action eq 'copy') {
3054: if ($source eq '') {
3055: $fetchresult = 'no source file';
3056: return $fetchresult;
3057: } else {
3058: my $destination = $filepath.'/'.$fname;
3059: rename($source,$destination);
3060: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3061: $home);
1.481 raeburn 3062: }
3063: } elsif ($action eq 'uploaddoc') {
3064: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 3065: print $fh $env{'form.'.$source};
1.481 raeburn 3066: close($fh);
1.637 raeburn 3067: if ($parser eq 'parse') {
1.1024 raeburn 3068: my $mm = new File::MMagic;
1.1095 raeburn 3069: my $type = $mm->checktype_filename($filepath.'/'.$fname);
3070: if ($type eq 'text/html') {
1.1024 raeburn 3071: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
3072: unless ($parse_result eq 'ok') {
3073: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
3074: }
1.637 raeburn 3075: }
1.1095 raeburn 3076: if (ref($mimetype)) {
3077: $$mimetype = $type;
3078: }
1.637 raeburn 3079: }
1.477 raeburn 3080: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3081: $home);
1.481 raeburn 3082: if ($fetchresult eq 'ok') {
3083: return '/uploaded/'.$fpath.'/'.$fname;
3084: } else {
3085: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3086: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 3087: return '/adm/notfound.html';
3088: }
1.477 raeburn 3089: }
3090: }
1.485 raeburn 3091: unless ( $fetchresult eq 'ok') {
1.477 raeburn 3092: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3093: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 3094: }
3095: return $fetchresult;
3096: }
3097:
1.637 raeburn 3098: sub build_filepath {
3099: my ($fpath) = @_;
3100: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
3101: unless ($fpath eq '') {
3102: my @parts=split('/',$fpath);
3103: foreach my $part (@parts) {
3104: $filepath.= '/'.$part;
3105: if ((-e $filepath)!=1) {
3106: mkdir($filepath,0777);
3107: }
3108: }
3109: }
3110: return $filepath;
3111: }
3112:
3113: sub store_edited_file {
1.638 albertel 3114: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 3115: my $file = $primary_url;
3116: $file =~ s#^/uploaded/$docudom/$docuname/##;
3117: my $fpath = '';
3118: my $fname = $file;
3119: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
3120: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
3121: my $filepath = &build_filepath($fpath);
3122: open(my $fh,'>'.$filepath.'/'.$fname);
3123: print $fh $content;
3124: close($fh);
1.638 albertel 3125: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 3126: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3127: $home);
1.637 raeburn 3128: if ($$fetchresult eq 'ok') {
3129: return '/uploaded/'.$fpath.'/'.$fname;
3130: } else {
1.638 albertel 3131: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
3132: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 3133: return '/adm/notfound.html';
3134: }
3135: }
3136:
1.531 albertel 3137: sub clean_filename {
1.831 albertel 3138: my ($fname,$args)=@_;
1.315 www 3139: # Replace Windows backslashes by forward slashes
1.257 www 3140: $fname=~s/\\/\//g;
1.831 albertel 3141: if (!$args->{'keep_path'}) {
3142: # Get rid of everything but the actual filename
3143: $fname=~s/^.*\/([^\/]+)$/$1/;
3144: }
1.315 www 3145: # Replace spaces by underscores
3146: $fname=~s/\s+/\_/g;
3147: # Replace all other weird characters by nothing
1.831 albertel 3148: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 3149: # Replace all .\d. sequences with _\d. so they no longer look like version
3150: # numbers
3151: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 3152: return $fname;
3153: }
1.1051 raeburn 3154: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
3155: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
3156: # image with the same aspect ratio as the original, but with dimensions which do
3157: # not exceed $resizewidth and $resizeheight.
3158:
1.984 neumanie 3159: sub resizeImage {
1.1051 raeburn 3160: my ($img_path,$resizewidth,$resizeheight) = @_;
3161: my $ima = Image::Magick->new;
3162: my $resized;
3163: if (-e $img_path) {
3164: $ima->Read($img_path);
3165: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
3166: my $width = $ima->Get('width');
3167: my $height = $ima->Get('height');
3168: if ($width > $resizewidth) {
3169: my $factor = $width/$resizewidth;
3170: my $newheight = $height/$factor;
3171: $ima->Scale(width=>$resizewidth,height=>$newheight);
3172: $resized = 1;
3173: }
3174: }
3175: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
3176: my $width = $ima->Get('width');
3177: my $height = $ima->Get('height');
3178: if ($height > $resizeheight) {
3179: my $factor = $height/$resizeheight;
3180: my $newwidth = $width/$factor;
3181: $ima->Scale(width=>$newwidth,height=>$resizeheight);
3182: $resized = 1;
3183: }
3184: }
3185: if ($resized) {
3186: $ima->Write($img_path);
3187: }
3188: }
3189: return;
1.977 amueller 3190: }
3191:
1.608 albertel 3192: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 3193: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093 raeburn 3194: # the desired filename is in $env{"form.$formname.filename"}
1.1090 raeburn 3195: # $context - possible values: coursedoc, existingfile, overwrite,
3196: # canceloverwrite, or ''.
3197: # if 'coursedoc': upload to the current course
3198: # if 'existingfile': write file to tmp/overwrites directory
3199: # if 'canceloverwrite': delete file written to tmp/overwrites directory
3200: # $context is passed as argument to &finishuserfileupload
1.686 albertel 3201: # $subdir - directory in userfile to store the file into
1.858 raeburn 3202: # $parser - instruction to parse file for objects ($parser = parse)
3203: # $allfiles - reference to hash for embedded objects
3204: # $codebase - reference to hash for codebase of java objects
3205: # $desuname - username for permanent storage of uploaded file
3206: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 3207: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
3208: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 3209: # $resizewidth - width (pixels) to which to resize uploaded image
3210: # $resizeheight - height (pixels) to which to resize uploaded image
1.1095 raeburn 3211: # $mimetype - reference to scalar to accommodate mime type determined
1.1152 raeburn 3212: # from File::MMagic.
1.858 raeburn 3213: #
1.686 albertel 3214: # output: url of file in userspace, or error: <message>
3215: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 3216:
1.531 albertel 3217: sub userfileupload {
1.1090 raeburn 3218: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095 raeburn 3219: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531 albertel 3220: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 3221: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 3222: $fname=&clean_filename($fname);
1.1090 raeburn 3223: # See if there is anything left
1.257 www 3224: unless ($fname) { return 'error: no uploaded file'; }
1.1090 raeburn 3225: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
3226: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
3227: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
3228: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523 raeburn 3229: my $now = time;
1.1090 raeburn 3230: my $filepath;
1.1095 raeburn 3231: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090 raeburn 3232: $filepath = 'tmp/helprequests/'.$now;
3233: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
3234: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
3235: '_'.$env{'user.domain'}.'/pending';
3236: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
3237: my ($docuname,$docudom);
3238: if ($destudom) {
3239: $docudom = $destudom;
3240: } else {
3241: $docudom = $env{'user.domain'};
3242: }
3243: if ($destuname) {
3244: $docuname = $destuname;
3245: } else {
3246: $docuname = $env{'user.name'};
3247: }
3248: if (exists($env{'form.group'})) {
3249: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3250: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3251: }
3252: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
3253: if ($context eq 'canceloverwrite') {
3254: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
3255: if (-e $tempfile) {
3256: my @info = stat($tempfile);
3257: if ($info[9] eq $env{'form.timestamp'}) {
3258: unlink($tempfile);
3259: }
3260: }
3261: return;
1.523 raeburn 3262: }
3263: }
1.1090 raeburn 3264: # Create the directory if not present
1.741 raeburn 3265: my @parts=split(/\//,$filepath);
3266: my $fullpath = $perlvar{'lonDaemons'};
3267: for (my $i=0;$i<@parts;$i++) {
3268: $fullpath .= '/'.$parts[$i];
3269: if ((-e $fullpath)!=1) {
3270: mkdir($fullpath,0777);
3271: }
3272: }
3273: open(my $fh,'>'.$fullpath.'/'.$fname);
3274: print $fh $env{'form.'.$formname};
3275: close($fh);
1.1090 raeburn 3276: if ($context eq 'existingfile') {
3277: my @info = stat($fullpath.'/'.$fname);
3278: return ($fullpath.'/'.$fname,$info[9]);
3279: } else {
3280: return $fullpath.'/'.$fname;
3281: }
1.523 raeburn 3282: }
1.995 raeburn 3283: if ($subdir eq 'scantron') {
3284: $fname = 'scantron_orig_'.$fname;
1.1093 raeburn 3285: } else {
1.995 raeburn 3286: $fname="$subdir/$fname";
3287: }
1.1090 raeburn 3288: if ($context eq 'coursedoc') {
1.638 albertel 3289: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3290: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 3291: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 3292: return &finishuserfileupload($docuname,$docudom,
3293: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 3294: $codebase,$thumbwidth,$thumbheight,
1.1095 raeburn 3295: $resizewidth,$resizeheight,$context,$mimetype);
1.481 raeburn 3296: } else {
1.1218 raeburn 3297: if ($env{'form.folder'}) {
3298: $fname=$env{'form.folder'}.'/'.$fname;
3299: }
1.638 albertel 3300: return &process_coursefile('uploaddoc',$docuname,$docudom,
3301: $fname,$formname,$parser,
1.1095 raeburn 3302: $allfiles,$codebase,$mimetype);
1.481 raeburn 3303: }
1.719 banghart 3304: } elsif (defined($destuname)) {
3305: my $docuname=$destuname;
3306: my $docudom=$destudom;
1.860 raeburn 3307: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3308: $parser,$allfiles,$codebase,
1.1051 raeburn 3309: $thumbwidth,$thumbheight,
1.1095 raeburn 3310: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3311: } else {
1.638 albertel 3312: my $docuname=$env{'user.name'};
3313: my $docudom=$env{'user.domain'};
1.1220 raeburn 3314: if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714 raeburn 3315: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3316: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3317: }
1.860 raeburn 3318: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3319: $parser,$allfiles,$codebase,
1.1051 raeburn 3320: $thumbwidth,$thumbheight,
1.1095 raeburn 3321: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3322: }
1.271 www 3323: }
3324:
3325: sub finishuserfileupload {
1.860 raeburn 3326: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095 raeburn 3327: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477 raeburn 3328: my $path=$docudom.'/'.$docuname.'/';
1.258 www 3329: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 3330:
1.860 raeburn 3331: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 3332: $file=$fname;
3333: if ($fname=~m|/|) {
3334: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
3335: $path.=$fnamepath.'/';
3336: }
1.259 www 3337: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 3338: my $count;
3339: for ($count=4;$count<=$#parts;$count++) {
3340: $filepath.="/$parts[$count]";
3341: if ((-e $filepath)!=1) {
3342: mkdir($filepath,0777);
3343: }
3344: }
1.984 neumanie 3345:
1.258 www 3346: # Save the file
3347: {
1.701 albertel 3348: if (!open(FH,'>'.$filepath.'/'.$file)) {
3349: &logthis('Failed to create '.$filepath.'/'.$file);
3350: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
3351: return '/adm/notfound.html';
3352: }
1.1090 raeburn 3353: if ($context eq 'overwrite') {
1.1117 foxr 3354: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090 raeburn 3355: my $target = $filepath.'/'.$file;
3356: if (-e $source) {
3357: my @info = stat($source);
3358: if ($info[9] eq $env{'form.timestamp'}) {
3359: unless (&File::Copy::move($source,$target)) {
3360: &logthis('Failed to overwrite '.$filepath.'/'.$file);
3361: return "Moving from $source failed";
3362: }
3363: } else {
3364: return "Temporary file: $source had unexpected date/time for last modification";
3365: }
3366: } else {
3367: return "Temporary file: $source missing";
3368: }
3369: } elsif (!print FH ($env{'form.'.$formname})) {
1.701 albertel 3370: &logthis('Failed to write to '.$filepath.'/'.$file);
3371: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
3372: return '/adm/notfound.html';
3373: }
1.570 albertel 3374: close(FH);
1.1051 raeburn 3375: if ($resizewidth && $resizeheight) {
3376: my $mm = new File::MMagic;
3377: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
3378: if ($mime_type =~ m{^image/}) {
3379: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
3380: }
1.977 amueller 3381: }
1.258 www 3382: }
1.1152 raeburn 3383: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
3384: if (ref($mimetype)) {
3385: if ($$mimetype eq '') {
3386: my $mm = new File::MMagic;
3387: my $type = $mm->checktype_filename($filepath.'/'.$file);
3388: $$mimetype = $type;
3389: }
3390: }
3391: }
1.637 raeburn 3392: if ($parser eq 'parse') {
1.1152 raeburn 3393: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024 raeburn 3394: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
3395: $allfiles,$codebase);
3396: unless ($parse_result eq 'ok') {
3397: &logthis('Failed to parse '.$filepath.$file.
3398: ' for embedded media: '.$parse_result);
3399: }
1.637 raeburn 3400: }
3401: }
1.860 raeburn 3402: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
3403: my $input = $filepath.'/'.$file;
3404: my $output = $filepath.'/'.'tn-'.$file;
3405: my $thumbsize = $thumbwidth.'x'.$thumbheight;
3406: system("convert -sample $thumbsize $input $output");
3407: if (-e $filepath.'/'.'tn-'.$file) {
3408: $fetchthumb = 1;
3409: }
3410: }
1.858 raeburn 3411:
1.259 www 3412: # Notify homeserver to grep it
3413: #
1.984 neumanie 3414: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 3415: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 3416: if ($fetchresult eq 'ok') {
1.860 raeburn 3417: if ($fetchthumb) {
3418: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
3419: if ($thumbresult ne 'ok') {
3420: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
3421: $docuhome.': '.$thumbresult);
3422: }
3423: }
1.259 www 3424: #
1.258 www 3425: # Return the URL to it
1.494 albertel 3426: return '/uploaded/'.$path.$file;
1.263 www 3427: } else {
1.494 albertel 3428: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
3429: ': '.$fetchresult);
1.263 www 3430: return '/adm/notfound.html';
1.858 raeburn 3431: }
1.493 albertel 3432: }
3433:
1.637 raeburn 3434: sub extract_embedded_items {
1.961 raeburn 3435: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 3436: my @state = ();
1.1164 raeburn 3437: my (%lastids,%related,%shockwave,%flashvars);
1.637 raeburn 3438: my %javafiles = (
3439: codebase => '',
3440: code => '',
3441: archive => ''
3442: );
3443: my %mediafiles = (
3444: src => '',
3445: movie => '',
3446: );
1.648 raeburn 3447: my $p;
3448: if ($content) {
3449: $p = HTML::LCParser->new($content);
3450: } else {
1.961 raeburn 3451: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 3452: }
1.641 albertel 3453: while (my $t=$p->get_token()) {
1.640 albertel 3454: if ($t->[0] eq 'S') {
3455: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 3456: push(@state, $tagname);
1.648 raeburn 3457: if (lc($tagname) eq 'allow') {
3458: &add_filetype($allfiles,$attr->{'src'},'src');
3459: }
1.640 albertel 3460: if (lc($tagname) eq 'img') {
3461: &add_filetype($allfiles,$attr->{'src'},'src');
3462: }
1.886 albertel 3463: if (lc($tagname) eq 'a') {
1.1222 raeburn 3464: unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
1.1221 raeburn 3465: &add_filetype($allfiles,$attr->{'href'},'href');
3466: }
1.886 albertel 3467: }
1.645 raeburn 3468: if (lc($tagname) eq 'script') {
1.1164 raeburn 3469: my $src;
1.645 raeburn 3470: if ($attr->{'archive'} =~ /\.jar$/i) {
3471: &add_filetype($allfiles,$attr->{'archive'},'archive');
3472: } else {
1.1164 raeburn 3473: if ($attr->{'src'} ne '') {
3474: $src = $attr->{'src'};
3475: &add_filetype($allfiles,$src,'src');
3476: }
3477: }
3478: my $text = $p->get_trimmed_text();
3479: if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
3480: my @swfargs = split(/,/,$1);
3481: foreach my $item (@swfargs) {
3482: $item =~ s/["']//g;
3483: $item =~ s/^\s+//;
3484: $item =~ s/\s+$//;
3485: }
3486: if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
3487: if (ref($related{$swfargs[0]}) eq 'ARRAY') {
3488: push(@{$related{$swfargs[0]}},$swfargs[2]);
3489: } else {
3490: $related{$swfargs[0]} = [$swfargs[2]];
3491: }
3492: }
1.645 raeburn 3493: }
3494: }
3495: if (lc($tagname) eq 'link') {
3496: if (lc($attr->{'rel'}) eq 'stylesheet') {
3497: &add_filetype($allfiles,$attr->{'href'},'href');
3498: }
3499: }
1.640 albertel 3500: if (lc($tagname) eq 'object' ||
3501: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
3502: foreach my $item (keys(%javafiles)) {
3503: $javafiles{$item} = '';
3504: }
1.1164 raeburn 3505: if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
3506: $lastids{lc($tagname)} = $attr->{'id'};
3507: }
1.640 albertel 3508: }
3509: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
3510: my $name = lc($attr->{'name'});
3511: foreach my $item (keys(%javafiles)) {
3512: if ($name eq $item) {
3513: $javafiles{$item} = $attr->{'value'};
3514: last;
3515: }
3516: }
1.1164 raeburn 3517: my $pathfrom;
1.640 albertel 3518: foreach my $item (keys(%mediafiles)) {
3519: if ($name eq $item) {
1.1164 raeburn 3520: $pathfrom = $attr->{'value'};
3521: $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
3522: &add_filetype($allfiles,$pathfrom,$name);
1.640 albertel 3523: last;
3524: }
3525: }
1.1164 raeburn 3526: if ($name eq 'flashvars') {
3527: $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
3528: }
3529: if ($pathfrom ne '') {
3530: &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
3531: $pathfrom);
3532: }
1.640 albertel 3533: }
3534: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
3535: foreach my $item (keys(%javafiles)) {
3536: if ($attr->{$item}) {
3537: $javafiles{$item} = $attr->{$item};
3538: last;
3539: }
3540: }
3541: foreach my $item (keys(%mediafiles)) {
3542: if ($attr->{$item}) {
3543: &add_filetype($allfiles,$attr->{$item},$item);
3544: last;
3545: }
3546: }
1.1164 raeburn 3547: if (lc($tagname) eq 'embed') {
3548: if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
3549: &embedded_dependency($allfiles,\%related,$attr->{'name'},
3550: $attr->{'src'});
3551: }
3552: }
1.640 albertel 3553: }
1.1243 raeburn 3554: if (lc($tagname) eq 'iframe') {
3555: my $src = $attr->{'src'} ;
3556: if (($src ne '') && ($src !~ m{^(/|https?://)})) {
3557: &add_filetype($allfiles,$src,'src');
3558: } elsif ($src =~ m{^/}) {
3559: if ($env{'request.course.id'}) {
3560: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
3561: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
3562: my $url = &hreflocation('',$fullpath);
3563: if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
3564: my $relpath = $1;
3565: if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
3566: &add_filetype($allfiles,$1,'src');
3567: }
3568: }
3569: }
3570: }
3571: }
1.1164 raeburn 3572: if ($t->[4] =~ m{/>$}) {
1.1243 raeburn 3573: pop(@state);
1.1164 raeburn 3574: }
1.640 albertel 3575: } elsif ($t->[0] eq 'E') {
3576: my ($tagname) = ($t->[1]);
3577: if ($javafiles{'codebase'} ne '') {
3578: $javafiles{'codebase'} .= '/';
3579: }
3580: if (lc($tagname) eq 'applet' ||
3581: lc($tagname) eq 'object' ||
3582: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
3583: ) {
3584: foreach my $item (keys(%javafiles)) {
3585: if ($item ne 'codebase' && $javafiles{$item} ne '') {
3586: my $file=$javafiles{'codebase'}.$javafiles{$item};
3587: &add_filetype($allfiles,$file,$item);
3588: }
3589: }
3590: }
3591: pop @state;
3592: }
3593: }
1.1164 raeburn 3594: foreach my $id (sort(keys(%flashvars))) {
3595: if ($shockwave{$id} ne '') {
3596: my @pairs = split(/\&/,$flashvars{$id});
3597: foreach my $pair (@pairs) {
3598: my ($key,$value) = split(/\=/,$pair);
3599: if ($key eq 'thumb') {
3600: &add_filetype($allfiles,$value,$key);
3601: } elsif ($key eq 'content') {
3602: my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
3603: my ($ext) = ($value =~ /\.([^.]+)$/);
3604: if ($ext ne '') {
3605: &add_filetype($allfiles,$path.$value,$ext);
3606: }
3607: }
3608: }
3609: }
3610: }
1.637 raeburn 3611: return 'ok';
3612: }
3613:
1.639 albertel 3614: sub add_filetype {
3615: my ($allfiles,$file,$type)=@_;
3616: if (exists($allfiles->{$file})) {
3617: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
3618: push(@{$allfiles->{$file}}, &escape($type));
3619: }
3620: } else {
3621: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 3622: }
3623: }
3624:
1.1164 raeburn 3625: sub embedded_dependency {
3626: my ($allfiles,$related,$identifier,$pathfrom) = @_;
3627: if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
3628: if (($identifier ne '') &&
3629: (ref($related->{$identifier}) eq 'ARRAY') &&
3630: ($pathfrom ne '')) {
3631: my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
3632: foreach my $dep (@{$related->{$identifier}}) {
3633: &add_filetype($allfiles,$path.$dep,'object');
3634: }
3635: }
3636: }
3637: return;
3638: }
3639:
1.493 albertel 3640: sub removeuploadedurl {
1.984 neumanie 3641: my ($url)=@_;
3642: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 3643: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 3644: }
3645:
3646: sub removeuserfile {
3647: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 3648: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3649: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 3650: if ($result eq 'ok') {
1.798 raeburn 3651: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
3652: my $metafile = $fname.'.meta';
3653: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 3654: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 3655: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3656: my $sqlresult =
1.823 albertel 3657: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3658: 'portfolio_metadata',$group,
3659: 'delete');
1.798 raeburn 3660: }
3661: }
3662: return $result;
1.257 www 3663: }
1.15 www 3664:
1.530 albertel 3665: sub mkdiruserfile {
3666: my ($docuname,$docudom,$dir)=@_;
3667: my $home=&homeserver($docuname,$docudom);
3668: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
3669: }
3670:
1.531 albertel 3671: sub renameuserfile {
3672: my ($docuname,$docudom,$old,$new)=@_;
3673: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3674: my $result = &reply("renameuserfile:$docudom:$docuname:".
3675: &escape("$old").':'.&escape("$new"),$home);
3676: if ($result eq 'ok') {
3677: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
3678: my $oldmeta = $old.'.meta';
3679: my $newmeta = $new.'.meta';
3680: my $metaresult =
3681: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 3682: my $url = "/uploaded/$docudom/$docuname/$old";
3683: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3684: my $sqlresult =
1.823 albertel 3685: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3686: 'portfolio_metadata',$group,
3687: 'delete');
1.798 raeburn 3688: }
3689: }
3690: return $result;
1.531 albertel 3691: }
3692:
1.14 www 3693: # ------------------------------------------------------------------------- Log
3694:
3695: sub log {
3696: my ($dom,$nam,$hom,$what)=@_;
1.47 www 3697: return critical("log:$dom:$nam:$what",$hom);
1.157 www 3698: }
3699:
3700: # ------------------------------------------------------------------ Course Log
1.352 www 3701: #
3702: # This routine flushes several buffers of non-mission-critical nature
3703: #
1.157 www 3704:
3705: sub flushcourselogs {
1.352 www 3706: &logthis('Flushing log buffers');
3707: #
3708: # course logs
3709: # This is a log of all transactions in a course, which can be used
3710: # for data mining purposes
3711: #
3712: # It also collects the courseid database, which lists last transaction
3713: # times and course titles for all courseids
3714: #
3715: my %courseidbuffer=();
1.921 raeburn 3716: foreach my $crsid (keys(%courselogs)) {
1.352 www 3717: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 3718: &escape($courselogs{$crsid}),
3719: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 3720: delete $courselogs{$crsid};
3721: } else {
3722: &logthis('Failed to flush log buffer for '.$crsid);
3723: if (length($courselogs{$crsid})>40000) {
1.672 albertel 3724: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 3725: " exceeded maximum size, deleting.</font>");
3726: delete $courselogs{$crsid};
3727: }
1.352 www 3728: }
1.920 raeburn 3729: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 3730: 'description' => $coursedescrbuf{$crsid},
3731: 'inst_code' => $courseinstcodebuf{$crsid},
3732: 'type' => $coursetypebuf{$crsid},
3733: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 3734: };
1.191 harris41 3735: }
1.352 www 3736: #
3737: # Write course id database (reverse lookup) to homeserver of courses
3738: # Is used in pickcourse
3739: #
1.840 albertel 3740: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 3741: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 3742: $courseidbuffer{$crs_home},
3743: $crs_home,'timeonly');
1.352 www 3744: }
3745: #
3746: # File accesses
3747: # Writes to the dynamic metadata of resources to get hit counts, etc.
3748: #
1.449 matthew 3749: foreach my $entry (keys(%accesshash)) {
1.458 matthew 3750: if ($entry =~ /___count$/) {
3751: my ($dom,$name);
1.807 albertel 3752: ($dom,$name,undef)=
1.811 albertel 3753: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 3754: if (! defined($dom) || $dom eq '' ||
3755: ! defined($name) || $name eq '') {
1.620 albertel 3756: my $cid = $env{'request.course.id'};
3757: $dom = $env{'request.'.$cid.'.domain'};
3758: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 3759: }
1.450 matthew 3760: my $value = $accesshash{$entry};
3761: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
3762: my %temphash=($url => $value);
1.449 matthew 3763: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
3764: if ($result eq 'ok') {
3765: delete $accesshash{$entry};
3766: }
3767: } else {
1.811 albertel 3768: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159 www 3769: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450 matthew 3770: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 3771: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
3772: delete $accesshash{$entry};
3773: }
1.185 www 3774: }
1.191 harris41 3775: }
1.352 www 3776: #
3777: # Roles
3778: # Reverse lookup of user roles for course faculty/staff and co-authorship
3779: #
1.800 albertel 3780: foreach my $entry (keys(%userrolehash)) {
1.351 www 3781: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 3782: split(/\:/,$entry);
3783: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 3784: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 3785: $rudom,$runame) eq 'ok') {
3786: delete $userrolehash{$entry};
3787: }
3788: }
1.662 raeburn 3789: #
3790: # Reverse lookup of domain roles (dc, ad, li, sc, au)
3791: #
3792: my %domrolebuffer = ();
1.1000 raeburn 3793: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 3794: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 3795: if ($domrolebuffer{$rudom}) {
3796: $domrolebuffer{$rudom}.='&'.&escape($entry).
3797: '='.&escape($domainrolehash{$entry});
3798: } else {
3799: $domrolebuffer{$rudom}.=&escape($entry).
3800: '='.&escape($domainrolehash{$entry});
3801: }
3802: delete $domainrolehash{$entry};
3803: }
3804: foreach my $dom (keys(%domrolebuffer)) {
1.841 albertel 3805: my %servers = &get_servers($dom,'library');
3806: foreach my $tryserver (keys(%servers)) {
3807: unless (&reply('domroleput:'.$dom.':'.
3808: $domrolebuffer{$dom},$tryserver) eq 'ok') {
3809: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
3810: }
1.662 raeburn 3811: }
3812: }
1.186 www 3813: $dumpcount++;
1.157 www 3814: }
3815:
3816: sub courselog {
3817: my $what=shift;
1.158 www 3818: $what=time.':'.$what;
1.620 albertel 3819: unless ($env{'request.course.id'}) { return ''; }
3820: $coursedombuf{$env{'request.course.id'}}=
3821: $env{'course.'.$env{'request.course.id'}.'.domain'};
3822: $coursenumbuf{$env{'request.course.id'}}=
3823: $env{'course.'.$env{'request.course.id'}.'.num'};
3824: $coursehombuf{$env{'request.course.id'}}=
3825: $env{'course.'.$env{'request.course.id'}.'.home'};
3826: $coursedescrbuf{$env{'request.course.id'}}=
3827: $env{'course.'.$env{'request.course.id'}.'.description'};
3828: $courseinstcodebuf{$env{'request.course.id'}}=
3829: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
3830: $courseownerbuf{$env{'request.course.id'}}=
3831: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 3832: $coursetypebuf{$env{'request.course.id'}}=
3833: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 3834: if (defined $courselogs{$env{'request.course.id'}}) {
3835: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 3836: } else {
1.620 albertel 3837: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 3838: }
1.620 albertel 3839: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 3840: &flushcourselogs();
3841: }
1.158 www 3842: }
3843:
3844: sub courseacclog {
3845: my $fnsymb=shift;
1.620 albertel 3846: unless ($env{'request.course.id'}) { return ''; }
3847: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144 www 3848: if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187 www 3849: $what.=':POST';
1.583 matthew 3850: # FIXME: Probably ought to escape things....
1.800 albertel 3851: foreach my $key (keys(%env)) {
3852: if ($key=~/^form\.(.*)/) {
1.975 raeburn 3853: my $formitem = $1;
3854: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
3855: $what.=':'.$formitem.'='.$env{$key};
3856: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
3857: $what.=':'.$formitem.'='.$env{$key};
3858: }
1.158 www 3859: }
1.191 harris41 3860: }
1.583 matthew 3861: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
3862: # FIXME: We should not be depending on a form parameter that someone
3863: # editing lonsearchcat.pm might change in the future.
1.620 albertel 3864: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 3865: $what.= ':POST';
3866: # FIXME: Probably ought to escape things....
3867: foreach my $element ('courseexp','crsfulltext','crsrelated',
3868: 'crsdiscuss') {
1.620 albertel 3869: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 3870: }
3871: }
1.158 www 3872: }
3873: &courselog($what);
1.149 www 3874: }
3875:
1.185 www 3876: sub countacc {
3877: my $url=&declutter(shift);
1.458 matthew 3878: return if (! defined($url) || $url eq '');
1.620 albertel 3879: unless ($env{'request.course.id'}) { return ''; }
1.1158 www 3880: #
3881: # Mark that this url was used in this course
3882: #
1.620 albertel 3883: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158 www 3884: #
3885: # Increase the access count for this resource in this child process
3886: #
1.281 www 3887: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 3888: $accesshash{$key}++;
1.185 www 3889: }
1.349 www 3890:
1.361 www 3891: sub linklog {
3892: my ($from,$to)=@_;
3893: $from=&declutter($from);
3894: $to=&declutter($to);
3895: $accesshash{$from.'___'.$to.'___comefrom'}=1;
3896: $accesshash{$to.'___'.$from.'___goto'}=1;
3897: }
1.1160 www 3898:
3899: sub statslog {
3900: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
3901: if ($users<2) { return; }
3902: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
3903: 'course' => $env{'request.course.id'},
3904: 'sections' => '"all"',
3905: 'num_students' => $users,
3906: 'part' => $part,
3907: 'symb' => $symb,
3908: 'mean_tries' => $av_attempts,
3909: 'deg_of_diff' => $degdiff});
3910: foreach my $key (keys(%dynstore)) {
3911: $accesshash{$key}=$dynstore{$key};
3912: }
3913: }
1.361 www 3914:
1.349 www 3915: sub userrolelog {
3916: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169 droeschl 3917: if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350 www 3918: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3919: $userrolehash
3920: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 3921: =$tend.':'.$tstart;
1.662 raeburn 3922: }
1.1169 droeschl 3923: if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898 albertel 3924: $userrolehash
3925: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
3926: =$tend.':'.$tstart;
3927: }
1.1169 droeschl 3928: if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
1.662 raeburn 3929: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3930: $domainrolehash
3931: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
3932: = $tend.':'.$tstart;
3933: }
1.351 www 3934: }
3935:
1.957 raeburn 3936: sub courserolelog {
3937: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1184 raeburn 3938: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
3939: my $cdom = $1;
3940: my $cnum = $2;
3941: my $sec = $3;
3942: my $namespace = 'rolelog';
3943: my %storehash = (
3944: role => $trole,
3945: start => $tstart,
3946: end => $tend,
3947: selfenroll => $selfenroll,
3948: context => $context,
3949: );
3950: if ($trole eq 'gr') {
3951: $namespace = 'groupslog';
3952: $storehash{'group'} = $sec;
3953: } else {
3954: $storehash{'section'} = $sec;
3955: }
1.1188 raeburn 3956: &write_log('course',$namespace,\%storehash,$delflag,$username,
3957: $domain,$cnum,$cdom);
1.1184 raeburn 3958: if (($trole ne 'st') || ($sec ne '')) {
3959: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957 raeburn 3960: }
3961: }
3962: return;
3963: }
3964:
1.1184 raeburn 3965: sub domainrolelog {
3966: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
3967: if ($area =~ m{^/($match_domain)/$}) {
3968: my $cdom = $1;
3969: my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
3970: my $namespace = 'rolelog';
3971: my %storehash = (
3972: role => $trole,
3973: start => $tstart,
3974: end => $tend,
3975: context => $context,
3976: );
1.1188 raeburn 3977: &write_log('domain',$namespace,\%storehash,$delflag,$username,
3978: $domain,$domconfiguser,$cdom);
1.1184 raeburn 3979: }
3980: return;
3981:
3982: }
3983:
3984: sub coauthorrolelog {
3985: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
3986: if ($area =~ m{^/($match_domain)/($match_username)$}) {
3987: my $audom = $1;
3988: my $auname = $2;
3989: my $namespace = 'rolelog';
3990: my %storehash = (
3991: role => $trole,
3992: start => $tstart,
3993: end => $tend,
3994: context => $context,
3995: );
1.1188 raeburn 3996: &write_log('author',$namespace,\%storehash,$delflag,$username,
3997: $domain,$auname,$audom);
1.1184 raeburn 3998: }
3999: return;
4000: }
4001:
1.351 www 4002: sub get_course_adv_roles {
1.948 raeburn 4003: my ($cid,$codes) = @_;
1.620 albertel 4004: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 4005: my %coursehash=&coursedescription($cid);
1.988 raeburn 4006: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 4007: my %nothide=();
1.800 albertel 4008: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 4009: if ($user !~ /:/) {
4010: $nothide{join(':',split(/[\@]/,$user))}=1;
4011: } else {
4012: $nothide{$user}=1;
4013: }
1.470 www 4014: }
1.1219 raeburn 4015: my @possdoms = ($coursehash{'domain'});
4016: if ($coursehash{'checkforpriv'}) {
4017: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
4018: }
1.351 www 4019: my %returnhash=();
4020: my %dumphash=
4021: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
4022: my $now=time;
1.997 raeburn 4023: my %privileged;
1.1000 raeburn 4024: foreach my $entry (keys(%dumphash)) {
1.800 albertel 4025: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 4026: if (($tstart) && ($tstart<0)) { next; }
4027: if (($tend) && ($tend<$now)) { next; }
4028: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 4029: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 4030: if ($username eq '' || $domain eq '') { next; }
1.1219 raeburn 4031: if ((&privileged($username,$domain,\@possdoms)) &&
1.997 raeburn 4032: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 4033: if ($role eq 'cr') { next; }
1.948 raeburn 4034: if ($codes) {
4035: if ($section) { $role .= ':'.$section; }
4036: if ($returnhash{$role}) {
4037: $returnhash{$role}.=','.$username.':'.$domain;
4038: } else {
4039: $returnhash{$role}=$username.':'.$domain;
4040: }
1.351 www 4041: } else {
1.988 raeburn 4042: my $key=&plaintext($role,$crstype);
1.973 bisitz 4043: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 4044: if ($returnhash{$key}) {
4045: $returnhash{$key}.=','.$username.':'.$domain;
4046: } else {
4047: $returnhash{$key}=$username.':'.$domain;
4048: }
1.351 www 4049: }
1.948 raeburn 4050: }
1.400 www 4051: return %returnhash;
4052: }
4053:
4054: sub get_my_roles {
1.937 raeburn 4055: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 4056: unless (defined($uname)) { $uname=$env{'user.name'}; }
4057: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 4058: my (%dumphash,%nothide);
1.1086 raeburn 4059: if ($context eq 'userroles') {
1.1166 raeburn 4060: %dumphash = &dump('roles',$udom,$uname);
1.858 raeburn 4061: } else {
1.1219 raeburn 4062: %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 4063: if ($hidepriv) {
4064: my %coursehash=&coursedescription($udom.'_'.$uname);
4065: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
4066: if ($user !~ /:/) {
4067: $nothide{join(':',split(/[\@]/,$user))} = 1;
4068: } else {
4069: $nothide{$user} = 1;
4070: }
4071: }
4072: }
1.858 raeburn 4073: }
1.400 www 4074: my %returnhash=();
4075: my $now=time;
1.999 raeburn 4076: my %privileged;
1.800 albertel 4077: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 4078: my ($role,$tend,$tstart);
4079: if ($context eq 'userroles') {
1.1149 raeburn 4080: next if ($entry =~ /^rolesdef/);
1.867 raeburn 4081: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
4082: } else {
4083: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
4084: }
1.400 www 4085: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 4086: my $status = 'active';
1.939 raeburn 4087: if (($tend) && ($tend<=$now)) {
1.832 raeburn 4088: $status = 'previous';
4089: }
4090: if (($tstart) && ($now<$tstart)) {
4091: $status = 'future';
4092: }
4093: if (ref($types) eq 'ARRAY') {
4094: if (!grep(/^\Q$status\E$/,@{$types})) {
4095: next;
4096: }
4097: } else {
4098: if ($status ne 'active') {
4099: next;
4100: }
4101: }
1.867 raeburn 4102: my ($rolecode,$username,$domain,$section,$area);
4103: if ($context eq 'userroles') {
1.1186 raeburn 4104: ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867 raeburn 4105: (undef,$domain,$username,$section) = split(/\//,$area);
4106: } else {
4107: ($role,$username,$domain,$section) = split(/\:/,$entry);
4108: }
1.832 raeburn 4109: if (ref($roledoms) eq 'ARRAY') {
4110: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
4111: next;
4112: }
4113: }
4114: if (ref($roles) eq 'ARRAY') {
4115: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 4116: if ($role =~ /^cr\//) {
4117: if (!grep(/^cr$/,@{$roles})) {
4118: next;
4119: }
1.1104 raeburn 4120: } elsif ($role =~ /^gr\//) {
4121: if (!grep(/^gr$/,@{$roles})) {
4122: next;
4123: }
1.922 raeburn 4124: } else {
4125: next;
4126: }
1.832 raeburn 4127: }
1.867 raeburn 4128: }
1.937 raeburn 4129: if ($hidepriv) {
1.1219 raeburn 4130: my @privroles = ('dc','su');
1.999 raeburn 4131: if ($context eq 'userroles') {
1.1219 raeburn 4132: next if (grep(/^\Q$role\E$/,@privroles));
1.999 raeburn 4133: } else {
1.1219 raeburn 4134: my $possdoms = [$domain];
4135: if (ref($roledoms) eq 'ARRAY') {
4136: push(@{$possdoms},@{$roledoms});
1.999 raeburn 4137: }
1.1219 raeburn 4138: if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999 raeburn 4139: if (!$nothide{$username.':'.$domain}) {
4140: next;
4141: }
4142: }
1.937 raeburn 4143: }
4144: }
1.933 raeburn 4145: if ($withsec) {
4146: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
4147: $tstart.':'.$tend;
4148: } else {
4149: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
4150: }
1.832 raeburn 4151: }
1.373 www 4152: return %returnhash;
1.399 www 4153: }
4154:
4155: # ----------------------------------------------------- Frontpage Announcements
4156: #
4157: #
4158:
4159: sub postannounce {
4160: my ($server,$text)=@_;
1.844 albertel 4161: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 4162: unless ($text=~/\w/) { $text=''; }
4163: return &reply('setannounce:'.&escape($text),$server);
4164: }
4165:
4166: sub getannounce {
1.448 albertel 4167:
4168: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 4169: my $announcement='';
1.800 albertel 4170: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 4171: close($fh);
1.399 www 4172: if ($announcement=~/\w/) {
4173: return
4174: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 4175: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 4176: } else {
4177: return '';
4178: }
4179: } else {
4180: return '';
4181: }
1.351 www 4182: }
1.353 www 4183:
4184: # ---------------------------------------------------------- Course ID routines
4185: # Deal with domain's nohist_courseid.db files
4186: #
4187:
4188: sub courseidput {
1.921 raeburn 4189: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 4190: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 4191: my $outcome;
4192: if ($caller eq 'timeonly') {
4193: my $cids = '';
4194: foreach my $item (keys(%$storehash)) {
4195: $cids.=&escape($item).'&';
4196: }
4197: $cids=~s/\&$//;
4198: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
4199: $coursehome);
4200: } else {
4201: my $items = '';
4202: foreach my $item (keys(%$storehash)) {
4203: $items.= &escape($item).'='.
4204: &freeze_escape($$storehash{$item}).'&';
4205: }
4206: $items=~s/\&$//;
4207: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
4208: $coursehome);
1.918 raeburn 4209: }
4210: if ($outcome eq 'unknown_cmd') {
4211: my $what;
4212: foreach my $cid (keys(%$storehash)) {
4213: $what .= &escape($cid).'=';
1.921 raeburn 4214: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 4215: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 4216: }
4217: $what =~ s/\:$/&/;
4218: }
4219: $what =~ s/\&$//;
4220: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
4221: } else {
4222: return $outcome;
4223: }
1.353 www 4224: }
4225:
4226: sub courseiddump {
1.921 raeburn 4227: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 4228: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 4229: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1247 raeburn 4230: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
4231: $hasuniquecode)=@_;
1.918 raeburn 4232: my $as_hash = 1;
4233: my %returnhash;
4234: if (!$domfilter) { $domfilter=''; }
1.845 albertel 4235: my %libserv = &all_library();
4236: foreach my $tryserver (keys(%libserv)) {
4237: if ( ( $hostidflag == 1
4238: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
4239: || (!defined($hostidflag)) ) {
4240:
1.918 raeburn 4241: if (($domfilter eq '') ||
4242: (&host_domain($tryserver) eq $domfilter)) {
1.1180 droeschl 4243: my $rep;
4244: if (grep { $_ eq $tryserver } current_machine_ids()) {
4245: $rep = LONCAPA::Lond::dump_course_id_handler(
4246: join(":", (&host_domain($tryserver), $sincefilter,
4247: &escape($descfilter), &escape($instcodefilter),
4248: &escape($ownerfilter), &escape($coursefilter),
4249: &escape($typefilter), &escape($regexp_ok),
4250: $as_hash, &escape($selfenrollonly),
4251: &escape($catfilter), $showhidden, $caller,
4252: &escape($cloner), &escape($cc_clone), $cloneonly,
4253: &escape($createdbefore), &escape($createdafter),
1.1247 raeburn 4254: &escape($creationcontext), $domcloner, $hasuniquecode)));
1.1180 droeschl 4255: } else {
4256: $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
4257: $sincefilter.':'.&escape($descfilter).':'.
4258: &escape($instcodefilter).':'.&escape($ownerfilter).
4259: ':'.&escape($coursefilter).':'.&escape($typefilter).
4260: ':'.&escape($regexp_ok).':'.$as_hash.':'.
4261: &escape($selfenrollonly).':'.&escape($catfilter).':'.
4262: $showhidden.':'.$caller.':'.&escape($cloner).':'.
4263: &escape($cc_clone).':'.$cloneonly.':'.
4264: &escape($createdbefore).':'.&escape($createdafter).':'.
1.1247 raeburn 4265: &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode,
1.1180 droeschl 4266: $tryserver);
4267: }
4268:
1.918 raeburn 4269: my @pairs=split(/\&/,$rep);
4270: foreach my $item (@pairs) {
4271: my ($key,$value)=split(/\=/,$item,2);
4272: $key = &unescape($key);
4273: next if ($key =~ /^error: 2 /);
4274: my $result = &thaw_unescape($value);
4275: if (ref($result) eq 'HASH') {
4276: $returnhash{$key}=$result;
4277: } else {
1.921 raeburn 4278: my @responses = split(/:/,$value);
4279: my @items = ('description','inst_code','owner','type');
1.918 raeburn 4280: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 4281: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 4282: }
1.1008 raeburn 4283: }
1.353 www 4284: }
4285: }
4286: }
4287: }
4288: return %returnhash;
4289: }
4290:
1.1055 raeburn 4291: sub courselastaccess {
4292: my ($cdom,$cnum,$hostidref) = @_;
4293: my %returnhash;
4294: if ($cdom && $cnum) {
4295: my $chome = &homeserver($cnum,$cdom);
4296: if ($chome ne 'no_host') {
4297: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
4298: &extract_lastaccess(\%returnhash,$rep);
4299: }
4300: } else {
4301: if (!$cdom) { $cdom=''; }
4302: my %libserv = &all_library();
4303: foreach my $tryserver (keys(%libserv)) {
4304: if (ref($hostidref) eq 'ARRAY') {
4305: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
4306: }
4307: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
4308: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
4309: &extract_lastaccess(\%returnhash,$rep);
4310: }
4311: }
4312: }
4313: return %returnhash;
4314: }
4315:
4316: sub extract_lastaccess {
4317: my ($returnhash,$rep) = @_;
4318: if (ref($returnhash) eq 'HASH') {
4319: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
4320: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
4321: $rep eq '') {
4322: my @pairs=split(/\&/,$rep);
4323: foreach my $item (@pairs) {
4324: my ($key,$value)=split(/\=/,$item,2);
4325: $key = &unescape($key);
4326: next if ($key =~ /^error: 2 /);
4327: $returnhash->{$key} = &thaw_unescape($value);
4328: }
4329: }
4330: }
4331: return;
4332: }
4333:
1.658 raeburn 4334: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 4335:
4336: sub dcmailput {
1.685 raeburn 4337: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 4338: my $status = &Apache::lonnet::critical(
1.740 www 4339: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
4340: &escape($message),$server);
1.662 raeburn 4341: return $status;
4342: }
4343:
1.658 raeburn 4344: sub dcmaildump {
4345: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 4346: my %returnhash=();
1.846 albertel 4347:
4348: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 4349: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
4350: &escape($enddate).':';
4351: my @esc_senders=map { &escape($_)} @$senders;
4352: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 4353: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 4354: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 4355: if (($key) && ($value)) {
4356: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 4357: }
4358: }
4359: }
4360: return %returnhash;
4361: }
1.662 raeburn 4362: # ---------------------------------------------------------- Domain roles
4363:
4364: sub get_domain_roles {
4365: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 4366: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 4367: $startdate = '.';
4368: }
1.1018 raeburn 4369: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 4370: $enddate = '.';
4371: }
1.922 raeburn 4372: my $rolelist;
4373: if (ref($roles) eq 'ARRAY') {
1.1219 raeburn 4374: $rolelist = join('&',@{$roles});
1.922 raeburn 4375: }
1.662 raeburn 4376: my %personnel = ();
1.841 albertel 4377:
4378: my %servers = &get_servers($dom,'library');
4379: foreach my $tryserver (keys(%servers)) {
4380: %{$personnel{$tryserver}}=();
4381: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
4382: &escape($startdate).':'.
4383: &escape($enddate).':'.
4384: &escape($rolelist), $tryserver))) {
4385: my ($key,$value) = split(/\=/,$line,2);
4386: if (($key) && ($value)) {
4387: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
4388: }
4389: }
1.662 raeburn 4390: }
4391: return %personnel;
4392: }
1.658 raeburn 4393:
1.1057 www 4394: # ----------------------------------------------------------- Interval timing
1.149 www 4395:
1.1153 www 4396: {
4397: # Caches needed for speedup of navmaps
4398: # We don't want to cache this for very long at all (5 seconds at most)
4399: #
4400: # The user for whom we cache
4401: my $cachedkey='';
4402: # The cached times for this user
4403: my %cachedtimes=();
4404: # When this was last done
4405: my $cachedtime=();
4406:
4407: sub load_all_first_access {
1.1154 raeburn 4408: my ($uname,$udom)=@_;
1.1156 www 4409: if (($cachedkey eq $uname.':'.$udom) &&
1.1174 raeburn 4410: (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154 raeburn 4411: return;
4412: }
4413: $cachedtime=time;
4414: $cachedkey=$uname.':'.$udom;
4415: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153 www 4416: }
4417:
1.504 albertel 4418: sub get_first_access {
1.1162 raeburn 4419: my ($type,$argsymb,$argmap)=@_;
1.790 albertel 4420: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4421: if ($argsymb) { $symb=$argsymb; }
4422: my ($map,$id,$res)=&decode_symb($symb);
1.1162 raeburn 4423: if ($argmap) { $map = $argmap; }
1.926 albertel 4424: if ($type eq 'course') {
4425: $res='course';
4426: } elsif ($type eq 'map') {
1.588 albertel 4427: $res=&symbread($map);
4428: } else {
4429: $res=$symb;
4430: }
1.1153 www 4431: &load_all_first_access($uname,$udom);
4432: return $cachedtimes{"$courseid\0$res"};
1.504 albertel 4433: }
4434:
4435: sub set_first_access {
1.1162 raeburn 4436: my ($type,$interval)=@_;
1.790 albertel 4437: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4438: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 4439: if ($type eq 'course') {
4440: $res='course';
4441: } elsif ($type eq 'map') {
1.588 albertel 4442: $res=&symbread($map);
4443: } else {
4444: $res=$symb;
4445: }
1.1153 www 4446: $cachedkey='';
1.1162 raeburn 4447: my $firstaccess=&get_first_access($type,$symb,$map);
1.505 albertel 4448: if (!$firstaccess) {
1.1162 raeburn 4449: my $start = time;
4450: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
4451: $udom,$uname);
4452: if ($putres eq 'ok') {
4453: &put('timerinterval',{"$courseid\0$res"=>$interval},
4454: $udom,$uname);
4455: &appenv(
4456: {
4457: 'course.'.$courseid.'.firstaccess.'.$res => $start,
4458: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
4459: }
4460: );
4461: }
4462: return $putres;
1.505 albertel 4463: }
4464: return 'already_set';
1.504 albertel 4465: }
1.1153 www 4466: }
1.110 www 4467: # --------------------------------------------- Set Expire Date for Spreadsheet
4468:
4469: sub expirespread {
4470: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 4471: my $cid=$env{'request.course.id'};
1.110 www 4472: if ($cid) {
4473: my $now=time;
4474: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 4475: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
4476: $env{'course.'.$cid.'.num'}.
1.110 www 4477: ':nohist_expirationdates:'.
4478: &escape($key).'='.$now,
1.620 albertel 4479: $env{'course.'.$cid.'.home'})
1.110 www 4480: }
4481: return 'ok';
1.14 www 4482: }
4483:
1.109 www 4484: # ----------------------------------------------------- Devalidate Spreadsheets
4485:
4486: sub devalidate {
1.325 www 4487: my ($symb,$uname,$udom)=@_;
1.620 albertel 4488: my $cid=$env{'request.course.id'};
1.109 www 4489: if ($cid) {
1.391 matthew 4490: # delete the stored spreadsheets for
4491: # - the student level sheet of this user in course's homespace
4492: # - the assessment level sheet for this resource
4493: # for this user in user's homespace
1.553 albertel 4494: # - current conditional state info
1.325 www 4495: my $key=$uname.':'.$udom.':';
1.109 www 4496: my $status=
1.299 matthew 4497: &del('nohist_calculatedsheets',
1.391 matthew 4498: [$key.'studentcalc:'],
1.620 albertel 4499: $env{'course.'.$cid.'.domain'},
4500: $env{'course.'.$cid.'.num'})
1.133 albertel 4501: .' '.
4502: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 4503: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 4504: unless ($status eq 'ok ok') {
4505: &logthis('Could not devalidate spreadsheet '.
1.325 www 4506: $uname.' at '.$udom.' for '.
1.109 www 4507: $symb.': '.$status);
1.133 albertel 4508: }
1.553 albertel 4509: &delenv('user.state.'.$cid);
1.109 www 4510: }
4511: }
4512:
1.265 albertel 4513: sub get_scalar {
4514: my ($string,$end) = @_;
4515: my $value;
4516: if ($$string =~ s/^([^&]*?)($end)/$2/) {
4517: $value = $1;
4518: } elsif ($$string =~ s/^([^&]*?)&//) {
4519: $value = $1;
4520: }
4521: return &unescape($value);
4522: }
4523:
4524: sub array2str {
4525: my (@array) = @_;
4526: my $result=&arrayref2str(\@array);
4527: $result=~s/^__ARRAY_REF__//;
4528: $result=~s/__END_ARRAY_REF__$//;
4529: return $result;
4530: }
4531:
1.204 albertel 4532: sub arrayref2str {
4533: my ($arrayref) = @_;
1.265 albertel 4534: my $result='__ARRAY_REF__';
1.204 albertel 4535: foreach my $elem (@$arrayref) {
1.265 albertel 4536: if(ref($elem) eq 'ARRAY') {
4537: $result.=&arrayref2str($elem).'&';
4538: } elsif(ref($elem) eq 'HASH') {
4539: $result.=&hashref2str($elem).'&';
4540: } elsif(ref($elem)) {
4541: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 4542: } else {
4543: $result.=&escape($elem).'&';
4544: }
4545: }
4546: $result=~s/\&$//;
1.265 albertel 4547: $result .= '__END_ARRAY_REF__';
1.204 albertel 4548: return $result;
4549: }
4550:
1.168 albertel 4551: sub hash2str {
1.204 albertel 4552: my (%hash) = @_;
4553: my $result=&hashref2str(\%hash);
1.265 albertel 4554: $result=~s/^__HASH_REF__//;
4555: $result=~s/__END_HASH_REF__$//;
1.204 albertel 4556: return $result;
4557: }
4558:
4559: sub hashref2str {
4560: my ($hashref)=@_;
1.265 albertel 4561: my $result='__HASH_REF__';
1.800 albertel 4562: foreach my $key (sort(keys(%$hashref))) {
4563: if (ref($key) eq 'ARRAY') {
4564: $result.=&arrayref2str($key).'=';
4565: } elsif (ref($key) eq 'HASH') {
4566: $result.=&hashref2str($key).'=';
4567: } elsif (ref($key)) {
1.265 albertel 4568: $result.='=';
1.800 albertel 4569: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 4570: } else {
1.1132 raeburn 4571: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 4572: }
4573:
1.800 albertel 4574: if(ref($hashref->{$key}) eq 'ARRAY') {
4575: $result.=&arrayref2str($hashref->{$key}).'&';
4576: } elsif(ref($hashref->{$key}) eq 'HASH') {
4577: $result.=&hashref2str($hashref->{$key}).'&';
4578: } elsif(ref($hashref->{$key})) {
1.265 albertel 4579: $result.='&';
1.800 albertel 4580: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 4581: } else {
1.800 albertel 4582: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 4583: }
4584: }
1.168 albertel 4585: $result=~s/\&$//;
1.265 albertel 4586: $result .= '__END_HASH_REF__';
1.168 albertel 4587: return $result;
4588: }
4589:
4590: sub str2hash {
1.265 albertel 4591: my ($string)=@_;
4592: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
4593: return %$hash;
4594: }
4595:
4596: sub str2hashref {
1.168 albertel 4597: my ($string) = @_;
1.265 albertel 4598:
4599: my %hash;
4600:
4601: if($string !~ /^__HASH_REF__/) {
4602: if (! ($string eq '' || !defined($string))) {
4603: $hash{'error'}='Not hash reference';
4604: }
4605: return (\%hash, $string);
4606: }
4607:
4608: $string =~ s/^__HASH_REF__//;
4609:
4610: while($string !~ /^__END_HASH_REF__/) {
4611: #key
4612: my $key='';
4613: if($string =~ /^__HASH_REF__/) {
4614: ($key, $string)=&str2hashref($string);
4615: if(defined($key->{'error'})) {
4616: $hash{'error'}='Bad data';
4617: return (\%hash, $string);
4618: }
4619: } elsif($string =~ /^__ARRAY_REF__/) {
4620: ($key, $string)=&str2arrayref($string);
4621: if($key->[0] eq 'Array reference error') {
4622: $hash{'error'}='Bad data';
4623: return (\%hash, $string);
4624: }
4625: } else {
4626: $string =~ s/^(.*?)=//;
1.267 albertel 4627: $key=&unescape($1);
1.265 albertel 4628: }
4629: $string =~ s/^=//;
4630:
4631: #value
4632: my $value='';
4633: if($string =~ /^__HASH_REF__/) {
4634: ($value, $string)=&str2hashref($string);
4635: if(defined($value->{'error'})) {
4636: $hash{'error'}='Bad data';
4637: return (\%hash, $string);
4638: }
4639: } elsif($string =~ /^__ARRAY_REF__/) {
4640: ($value, $string)=&str2arrayref($string);
4641: if($value->[0] eq 'Array reference error') {
4642: $hash{'error'}='Bad data';
4643: return (\%hash, $string);
4644: }
4645: } else {
4646: $value=&get_scalar(\$string,'__END_HASH_REF__');
4647: }
4648: $string =~ s/^&//;
4649:
4650: $hash{$key}=$value;
1.204 albertel 4651: }
1.265 albertel 4652:
4653: $string =~ s/^__END_HASH_REF__//;
4654:
4655: return (\%hash, $string);
1.204 albertel 4656: }
4657:
4658: sub str2array {
1.265 albertel 4659: my ($string)=@_;
4660: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
4661: return @$array;
4662: }
4663:
4664: sub str2arrayref {
1.204 albertel 4665: my ($string) = @_;
1.265 albertel 4666: my @array;
4667:
4668: if($string !~ /^__ARRAY_REF__/) {
4669: if (! ($string eq '' || !defined($string))) {
4670: $array[0]='Array reference error';
4671: }
4672: return (\@array, $string);
4673: }
4674:
4675: $string =~ s/^__ARRAY_REF__//;
4676:
4677: while($string !~ /^__END_ARRAY_REF__/) {
4678: my $value='';
4679: if($string =~ /^__HASH_REF__/) {
4680: ($value, $string)=&str2hashref($string);
4681: if(defined($value->{'error'})) {
4682: $array[0] ='Array reference error';
4683: return (\@array, $string);
4684: }
4685: } elsif($string =~ /^__ARRAY_REF__/) {
4686: ($value, $string)=&str2arrayref($string);
4687: if($value->[0] eq 'Array reference error') {
4688: $array[0] ='Array reference error';
4689: return (\@array, $string);
4690: }
4691: } else {
4692: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
4693: }
4694: $string =~ s/^&//;
4695:
4696: push(@array, $value);
1.191 harris41 4697: }
1.265 albertel 4698:
4699: $string =~ s/^__END_ARRAY_REF__//;
4700:
4701: return (\@array, $string);
1.168 albertel 4702: }
4703:
1.167 albertel 4704: # -------------------------------------------------------------------Temp Store
4705:
1.168 albertel 4706: sub tmpreset {
4707: my ($symb,$namespace,$domain,$stuname) = @_;
4708: if (!$symb) {
4709: $symb=&symbread();
1.620 albertel 4710: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4711: }
4712: $symb=escape($symb);
4713:
1.620 albertel 4714: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 4715: $namespace=~s/\//\_/g;
4716: $namespace=~s/\W//g;
4717:
1.620 albertel 4718: if (!$domain) { $domain=$env{'user.domain'}; }
4719: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4720: if ($domain eq 'public' && $stuname eq 'public') {
4721: $stuname=$ENV{'REMOTE_ADDR'};
4722: }
1.1117 foxr 4723: my $path=LONCAPA::tempdir();
1.168 albertel 4724: my %hash;
4725: if (tie(%hash,'GDBM_File',
4726: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4727: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 4728: foreach my $key (keys(%hash)) {
1.180 albertel 4729: if ($key=~ /:$symb/) {
1.168 albertel 4730: delete($hash{$key});
4731: }
4732: }
4733: }
4734: }
4735:
1.167 albertel 4736: sub tmpstore {
1.168 albertel 4737: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4738:
4739: if (!$symb) {
4740: $symb=&symbread();
1.620 albertel 4741: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4742: }
4743: $symb=escape($symb);
4744:
4745: if (!$namespace) {
4746: # I don't think we would ever want to store this for a course.
4747: # it seems this will only be used if we don't have a course.
1.620 albertel 4748: #$namespace=$env{'request.course.id'};
1.168 albertel 4749: #if (!$namespace) {
1.620 albertel 4750: $namespace=$env{'request.state'};
1.168 albertel 4751: #}
4752: }
4753: $namespace=~s/\//\_/g;
4754: $namespace=~s/\W//g;
1.620 albertel 4755: if (!$domain) { $domain=$env{'user.domain'}; }
4756: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4757: if ($domain eq 'public' && $stuname eq 'public') {
4758: $stuname=$ENV{'REMOTE_ADDR'};
4759: }
1.168 albertel 4760: my $now=time;
4761: my %hash;
1.1117 foxr 4762: my $path=LONCAPA::tempdir();
1.168 albertel 4763: if (tie(%hash,'GDBM_File',
4764: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4765: &GDBM_WRCREAT(),0640)) {
1.168 albertel 4766: $hash{"version:$symb"}++;
4767: my $version=$hash{"version:$symb"};
4768: my $allkeys='';
4769: foreach my $key (keys(%$storehash)) {
4770: $allkeys.=$key.':';
1.591 albertel 4771: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 4772: }
4773: $hash{"$version:$symb:timestamp"}=$now;
4774: $allkeys.='timestamp';
4775: $hash{"$version:keys:$symb"}=$allkeys;
4776: if (untie(%hash)) {
4777: return 'ok';
4778: } else {
4779: return "error:$!";
4780: }
4781: } else {
4782: return "error:$!";
4783: }
4784: }
1.167 albertel 4785:
1.168 albertel 4786: # -----------------------------------------------------------------Temp Restore
1.167 albertel 4787:
1.168 albertel 4788: sub tmprestore {
4789: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 4790:
1.168 albertel 4791: if (!$symb) {
4792: $symb=&symbread();
1.620 albertel 4793: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4794: }
4795: $symb=escape($symb);
4796:
1.620 albertel 4797: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 4798:
1.620 albertel 4799: if (!$domain) { $domain=$env{'user.domain'}; }
4800: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4801: if ($domain eq 'public' && $stuname eq 'public') {
4802: $stuname=$ENV{'REMOTE_ADDR'};
4803: }
1.168 albertel 4804: my %returnhash;
4805: $namespace=~s/\//\_/g;
4806: $namespace=~s/\W//g;
4807: my %hash;
1.1117 foxr 4808: my $path=LONCAPA::tempdir();
1.168 albertel 4809: if (tie(%hash,'GDBM_File',
4810: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4811: &GDBM_READER(),0640)) {
1.168 albertel 4812: my $version=$hash{"version:$symb"};
4813: $returnhash{'version'}=$version;
4814: my $scope;
4815: for ($scope=1;$scope<=$version;$scope++) {
4816: my $vkeys=$hash{"$scope:keys:$symb"};
4817: my @keys=split(/:/,$vkeys);
4818: my $key;
4819: $returnhash{"$scope:keys"}=$vkeys;
4820: foreach $key (@keys) {
1.591 albertel 4821: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
4822: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 4823: }
4824: }
1.168 albertel 4825: if (!(untie(%hash))) {
4826: return "error:$!";
4827: }
4828: } else {
4829: return "error:$!";
4830: }
4831: return %returnhash;
1.167 albertel 4832: }
4833:
1.9 www 4834: # ----------------------------------------------------------------------- Store
4835:
4836: sub store {
1.124 www 4837: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4838: my $home='';
4839:
1.168 albertel 4840: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4841:
1.213 www 4842: $symb=&symbclean($symb);
1.122 albertel 4843: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 4844:
1.620 albertel 4845: if (!$domain) { $domain=$env{'user.domain'}; }
4846: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 4847:
4848: &devalidate($symb,$stuname,$domain);
1.109 www 4849:
4850: $symb=escape($symb);
1.187 www 4851: if (!$namespace) {
1.620 albertel 4852: unless ($namespace=$env{'request.course.id'}) {
1.187 www 4853: return '';
4854: }
4855: }
1.620 albertel 4856: if (!$home) { $home=$env{'user.home'}; }
1.447 www 4857:
4858: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4859: $$storehash{'host'}=$perlvar{'lonHostID'};
4860:
1.12 www 4861: my $namevalue='';
1.800 albertel 4862: foreach my $key (keys(%$storehash)) {
4863: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 4864: }
1.12 www 4865: $namevalue=~s/\&$//;
1.187 www 4866: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124 www 4867: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9 www 4868: }
4869:
1.47 www 4870: # -------------------------------------------------------------- Critical Store
4871:
4872: sub cstore {
1.124 www 4873: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4874: my $home='';
4875:
1.168 albertel 4876: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4877:
1.213 www 4878: $symb=&symbclean($symb);
1.122 albertel 4879: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 4880:
1.620 albertel 4881: if (!$domain) { $domain=$env{'user.domain'}; }
4882: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 4883:
4884: &devalidate($symb,$stuname,$domain);
1.109 www 4885:
4886: $symb=escape($symb);
1.187 www 4887: if (!$namespace) {
1.620 albertel 4888: unless ($namespace=$env{'request.course.id'}) {
1.187 www 4889: return '';
4890: }
4891: }
1.620 albertel 4892: if (!$home) { $home=$env{'user.home'}; }
1.447 www 4893:
4894: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4895: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 4896:
1.47 www 4897: my $namevalue='';
1.800 albertel 4898: foreach my $key (keys(%$storehash)) {
4899: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 4900: }
1.47 www 4901: $namevalue=~s/\&$//;
1.187 www 4902: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 4903: return critical
4904: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47 www 4905: }
4906:
1.9 www 4907: # --------------------------------------------------------------------- Restore
4908:
4909: sub restore {
1.124 www 4910: my ($symb,$namespace,$domain,$stuname) = @_;
4911: my $home='';
4912:
1.168 albertel 4913: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4914:
1.122 albertel 4915: if (!$symb) {
1.1224 raeburn 4916: return if ($namespace eq 'courserequests');
4917: unless ($symb=escape(&symbread())) { return ''; }
1.122 albertel 4918: } else {
1.1224 raeburn 4919: unless ($namespace eq 'courserequests') {
4920: $symb=&escape(&symbclean($symb));
4921: }
1.122 albertel 4922: }
1.188 www 4923: if (!$namespace) {
1.620 albertel 4924: unless ($namespace=$env{'request.course.id'}) {
1.188 www 4925: return '';
4926: }
4927: }
1.620 albertel 4928: if (!$domain) { $domain=$env{'user.domain'}; }
4929: if (!$stuname) { $stuname=$env{'user.name'}; }
4930: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 4931: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
4932:
1.12 www 4933: my %returnhash=();
1.800 albertel 4934: foreach my $line (split(/\&/,$answer)) {
4935: my ($name,$value)=split(/\=/,$line);
1.591 albertel 4936: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 4937: }
1.75 www 4938: my $version;
4939: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 4940: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
4941: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 4942: }
1.75 www 4943: }
1.13 www 4944: return %returnhash;
1.34 www 4945: }
4946:
4947: # ---------------------------------------------------------- Course Description
1.1118 foxr 4948: #
4949: #
1.34 www 4950:
4951: sub coursedescription {
1.731 albertel 4952: my ($courseid,$args)=@_;
1.34 www 4953: $courseid=~s/^\///;
1.49 www 4954: $courseid=~s/\_/\//g;
1.34 www 4955: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 4956: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 4957: my $normalid=$cdomain.'_'.$cnum;
4958: # need to always cache even if we get errors otherwise we keep
4959: # trying and trying and trying to get the course description.
4960: my %envhash=();
4961: my %returnhash=();
1.731 albertel 4962:
4963: my $expiretime=600;
4964: if ($env{'request.course.id'} eq $normalid) {
4965: $expiretime=120;
4966: }
4967:
4968: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
4969: if (!$args->{'freshen_cache'}
4970: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
4971: foreach my $key (keys(%env)) {
4972: next if ($key !~ /^\Q$prefix\E(.*)/);
4973: my ($setting) = $1;
4974: $returnhash{$setting} = $env{$key};
4975: }
4976: return %returnhash;
4977: }
4978:
1.1118 foxr 4979: # get the data again
4980:
1.731 albertel 4981: if (!$args->{'one_time'}) {
4982: $envhash{'course.'.$normalid.'.last_cache'}=time;
4983: }
1.811 albertel 4984:
1.34 www 4985: if ($chome ne 'no_host') {
1.302 albertel 4986: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 4987: if (!exists($returnhash{'con_lost'})) {
1.1118 foxr 4988: my $username = $env{'user.name'}; # Defult username
4989: if(defined $args->{'user'}) {
4990: $username = $args->{'user'};
4991: }
1.129 albertel 4992: $returnhash{'home'}= $chome;
4993: $returnhash{'domain'} = $cdomain;
4994: $returnhash{'num'} = $cnum;
1.741 raeburn 4995: if (!defined($returnhash{'type'})) {
4996: $returnhash{'type'} = 'Course';
4997: }
1.130 albertel 4998: while (my ($name,$value) = each %returnhash) {
1.53 www 4999: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 5000: }
1.270 www 5001: $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117 foxr 5002: $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118 foxr 5003: $username.'_'.$cdomain.'_'.$cnum;
1.60 www 5004: $envhash{'course.'.$normalid.'.home'}=$chome;
5005: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
5006: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 5007: }
5008: }
1.731 albertel 5009: if (!$args->{'one_time'}) {
1.949 raeburn 5010: &appenv(\%envhash);
1.731 albertel 5011: }
1.302 albertel 5012: return %returnhash;
1.461 www 5013: }
5014:
1.1080 raeburn 5015: sub update_released_required {
5016: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
5017: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
5018: $cid = $env{'request.course.id'};
5019: $cdom = $env{'course.'.$cid.'.domain'};
5020: $cnum = $env{'course.'.$cid.'.num'};
5021: $chome = $env{'course.'.$cid.'.home'};
5022: }
5023: if ($needsrelease) {
5024: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
5025: my $needsupdate;
5026: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
5027: $needsupdate = 1;
5028: } else {
5029: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
5030: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
5031: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
5032: $needsupdate = 1;
5033: }
5034: }
5035: if ($needsupdate) {
5036: my %needshash = (
5037: 'internal.releaserequired' => $needsrelease,
5038: );
5039: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
5040: if ($putresult eq 'ok') {
5041: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
5042: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
5043: if (ref($crsinfo{$cid}) eq 'HASH') {
5044: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
5045: &courseidput($cdom,\%crsinfo,$chome,'notime');
5046: }
5047: }
5048: }
5049: }
5050: return;
5051: }
5052:
1.461 www 5053: # -------------------------------------------------See if a user is privileged
5054:
5055: sub privileged {
1.1219 raeburn 5056: my ($username,$domain,$possdomains,$possroles)=@_;
1.1170 droeschl 5057: my $now = time;
1.1219 raeburn 5058: my $roles;
5059: if (ref($possroles) eq 'ARRAY') {
5060: $roles = $possroles;
5061: } else {
5062: $roles = ['dc','su'];
5063: }
5064: if (ref($possdomains) eq 'ARRAY') {
5065: my %privileged = &privileged_by_domain($possdomains,$roles);
5066: foreach my $dom (@{$possdomains}) {
5067: if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
5068: (ref($privileged{$dom}) eq 'HASH')) {
5069: foreach my $role (@{$roles}) {
5070: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5071: if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
5072: my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
5073: return 1 unless (($end && $end < $now) ||
5074: ($start && $start > $now));
5075: }
5076: }
5077: }
5078: }
5079: }
5080: } else {
5081: my %rolesdump = &dump("roles", $domain, $username) or return 0;
5082: my $now = time;
1.1170 droeschl 5083:
1.1219 raeburn 5084: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys %rolesdump}) {
1.1170 droeschl 5085: my ($trole, $tend, $tstart) = split(/_/, $role);
1.1219 raeburn 5086: if (grep(/^\Q$trole\E$/,@{$roles})) {
1.1170 droeschl 5087: return 1 unless ($tend && $tend < $now)
1.1219 raeburn 5088: or ($tstart && $tstart > $now);
1.1170 droeschl 5089: }
1.1219 raeburn 5090: }
5091: }
5092: return 0;
5093: }
1.1170 droeschl 5094:
1.1219 raeburn 5095: sub privileged_by_domain {
5096: my ($domains,$roles) = @_;
5097: my %privileged = ();
5098: my $cachetime = 60*60*24;
5099: my $now = time;
5100: unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
5101: return %privileged;
5102: }
5103: foreach my $dom (@{$domains}) {
5104: next if (ref($privileged{$dom}) eq 'HASH');
5105: my $needroles;
5106: foreach my $role (@{$roles}) {
5107: my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
5108: if (defined($cached)) {
5109: if (ref($result) eq 'HASH') {
5110: $privileged{$dom}{$role} = $result;
5111: }
5112: } else {
5113: $needroles = 1;
5114: }
5115: }
5116: if ($needroles) {
5117: my %dompersonnel = &get_domain_roles($dom,$roles);
5118: $privileged{$dom} = {};
5119: foreach my $server (keys(%dompersonnel)) {
5120: if (ref($dompersonnel{$server}) eq 'HASH') {
5121: foreach my $item (keys(%{$dompersonnel{$server}})) {
5122: my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
5123: my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
5124: next if ($end && $end < $now);
5125: $privileged{$dom}{$trole}{$uname.':'.$udom} =
5126: $dompersonnel{$server}{$item};
5127: }
5128: }
5129: }
5130: if (ref($privileged{$dom}) eq 'HASH') {
5131: foreach my $role (@{$roles}) {
5132: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5133: &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
5134: } else {
5135: my %hash = ();
5136: &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
5137: }
5138: }
5139: }
5140: }
5141: }
5142: return %privileged;
1.9 www 5143: }
1.1 albertel 5144:
1.103 harris41 5145: # -------------------------------------------------------- Get user privileges
1.11 www 5146:
5147: sub rolesinit {
1.1169 droeschl 5148: my ($domain, $username) = @_;
5149: my %userroles = ('user.login.time' => time);
5150: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
5151:
5152: # firstaccess and timerinterval are related to timed maps/resources.
5153: # also, blocking can be triggered by an activating timer
5154: # it's saved in the user's %env.
5155: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
5156: my %timerinterval = &dump('timerinterval', $domain, $username);
5157: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
5158: %timerintchk, %timerintenv);
5159:
1.1162 raeburn 5160: foreach my $key (keys(%firstaccess)) {
1.1169 droeschl 5161: my ($cid, $rest) = split(/\0/, $key);
1.1162 raeburn 5162: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
5163: }
1.1169 droeschl 5164:
1.1162 raeburn 5165: foreach my $key (keys(%timerinterval)) {
5166: my ($cid,$rest) = split(/\0/,$key);
5167: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
5168: }
1.1169 droeschl 5169:
1.11 www 5170: my %allroles=();
1.1162 raeburn 5171: my %allgroups=();
1.11 www 5172:
1.1169 droeschl 5173: for my $area (grep { ! /^rolesdef_/ } keys %rolesdump) {
5174: my $role = $rolesdump{$area};
5175: $area =~ s/\_\w\w$//;
5176:
5177: my ($trole, $tend, $tstart, $group_privs);
5178:
5179: if ($role =~ /^cr/) {
5180: # Custom role, defined by a user
5181: # e.g., user.role.cr/msu/smith/mynewrole
5182: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
5183: $trole = $1;
5184: ($tend, $tstart) = split('_', $2);
5185: } else {
5186: $trole = $role;
5187: }
5188: } elsif ($role =~ m|^gr/|) {
5189: # Role of member in a group, defined within a course/community
5190: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
5191: ($trole, $tend, $tstart) = split(/_/, $role);
5192: next if $tstart eq '-1';
5193: ($trole, $group_privs) = split(/\//, $trole);
5194: $group_privs = &unescape($group_privs);
5195: } else {
5196: # Just a normal role, defined in roles.tab
5197: ($trole, $tend, $tstart) = split(/_/,$role);
5198: }
5199:
5200: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
5201: $username);
5202: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
5203:
5204: # role expired or not available yet?
5205: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
5206: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
5207:
5208: next if $area eq '' or $trole eq '';
5209:
5210: my $spec = "$trole.$area";
5211: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
5212:
5213: if ($trole =~ /^cr\//) {
5214: # Custom role, defined by a user
5215: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5216: } elsif ($trole eq 'gr') {
5217: # Role of a member in a group, defined within a course/community
5218: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
5219: next;
5220: } else {
5221: # Normal role, defined in roles.tab
5222: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5223: }
5224:
5225: my $cid = $tdomain.'_'.$trest;
5226: unless ($firstaccchk{$cid}) {
5227: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
5228: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
5229: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
5230: $coursetimerstarts{$cid}{$item};
5231: }
5232: }
5233: $firstaccchk{$cid} = 1;
5234: }
5235: unless ($timerintchk{$cid}) {
5236: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
5237: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
5238: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
5239: $coursetimerintervals{$cid}{$item};
1.1162 raeburn 5240: }
1.12 www 5241: }
1.1169 droeschl 5242: $timerintchk{$cid} = 1;
1.191 harris41 5243: }
1.11 www 5244: }
1.1169 droeschl 5245:
5246: @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
5247: \%allroles, \%allgroups);
5248: $env{'user.adv'} = $userroles{'user.adv'};
5249:
1.1162 raeburn 5250: return (\%userroles,\%firstaccenv,\%timerintenv);
1.11 www 5251: }
5252:
1.567 raeburn 5253: sub set_arearole {
1.1215 raeburn 5254: my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
5255: unless ($nolog) {
1.567 raeburn 5256: # log the associated role with the area
1.1215 raeburn 5257: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
5258: }
1.743 albertel 5259: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 5260: }
5261:
5262: sub custom_roleprivs {
5263: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
5264: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1250 raeburn 5265: my $homsvr = &homeserver($rauthor,$rdomain);
1.838 albertel 5266: if (&hostname($homsvr) ne '') {
1.567 raeburn 5267: my ($rdummy,$roledef)=
5268: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
5269: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
5270: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
5271: if (defined($syspriv)) {
1.1043 raeburn 5272: if ($trest =~ /^$match_community$/) {
5273: $syspriv =~ s/bre\&S//;
5274: }
1.567 raeburn 5275: $$allroles{'cm./'}.=':'.$syspriv;
5276: $$allroles{$spec.'./'}.=':'.$syspriv;
5277: }
5278: if ($tdomain ne '') {
5279: if (defined($dompriv)) {
5280: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
5281: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
5282: }
5283: if (($trest ne '') && (defined($coursepriv))) {
5284: $$allroles{'cm.'.$area}.=':'.$coursepriv;
5285: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
5286: }
5287: }
5288: }
5289: }
5290: }
5291:
1.678 raeburn 5292: sub group_roleprivs {
5293: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
5294: my $access = 1;
5295: my $now = time;
5296: if (($tend!=0) && ($tend<$now)) { $access = 0; }
5297: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
5298: if ($access) {
1.811 albertel 5299: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 5300: $$allgroups{$course}{$group} .=':'.$group_privs;
5301: }
5302: }
1.567 raeburn 5303:
5304: sub standard_roleprivs {
5305: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
5306: if (defined($pr{$trole.':s'})) {
5307: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
5308: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
5309: }
5310: if ($tdomain ne '') {
5311: if (defined($pr{$trole.':d'})) {
5312: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5313: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5314: }
5315: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
5316: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
5317: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
5318: }
5319: }
5320: }
5321:
5322: sub set_userprivs {
1.1064 raeburn 5323: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 5324: my $author=0;
5325: my $adv=0;
1.678 raeburn 5326: my %grouproles = ();
5327: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 5328: my @groupkeys;
1.1000 raeburn 5329: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 5330: push(@groupkeys,$role);
5331: }
5332: if (ref($groups_roles) eq 'HASH') {
5333: foreach my $key (keys(%{$groups_roles})) {
5334: unless (grep(/^\Q$key\E$/,@groupkeys)) {
5335: push(@groupkeys,$key);
5336: }
5337: }
5338: }
5339: if (@groupkeys > 0) {
5340: foreach my $role (@groupkeys) {
5341: my ($trole,$area,$sec,$extendedarea);
5342: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
5343: $trole = $1;
5344: $area = $2;
5345: $sec = $3;
5346: $extendedarea = $area.$sec;
5347: if (exists($$allgroups{$area})) {
5348: foreach my $group (keys(%{$$allgroups{$area}})) {
5349: my $spec = $trole.'.'.$extendedarea;
5350: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 5351: $$allgroups{$area}{$group};
1.1064 raeburn 5352: }
1.678 raeburn 5353: }
5354: }
5355: }
5356: }
5357: }
1.800 albertel 5358: foreach my $group (keys(%grouproles)) {
5359: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 5360: }
1.800 albertel 5361: foreach my $role (keys(%{$allroles})) {
5362: my %thesepriv;
1.941 raeburn 5363: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 5364: foreach my $item (split(/:/,$$allroles{$role})) {
5365: if ($item ne '') {
5366: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 5367: if ($restrictions eq '') {
5368: $thesepriv{$privilege}='F';
5369: } elsif ($thesepriv{$privilege} ne 'F') {
5370: $thesepriv{$privilege}.=$restrictions;
5371: }
5372: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
5373: }
5374: }
5375: my $thesestr='';
1.1104 raeburn 5376: foreach my $priv (sort(keys(%thesepriv))) {
1.800 albertel 5377: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
5378: }
5379: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 5380: }
5381: return ($author,$adv);
5382: }
5383:
1.994 raeburn 5384: sub role_status {
1.1104 raeburn 5385: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 5386: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1250 raeburn 5387: my ($one,$two) = split(m{\./},$rolekey,2);
5388: (undef,undef,$$role) = split(/\./,$one,3);
1.994 raeburn 5389: unless (!defined($$role) || $$role eq '') {
1.1251 raeburn 5390: $$where = '/'.$two;
1.994 raeburn 5391: $$trolecode=$$role.'.'.$$where;
5392: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
5393: $$tstatus='is';
1.1104 raeburn 5394: if ($$tstart && $$tstart>$update) {
1.994 raeburn 5395: $$tstatus='future';
1.1034 raeburn 5396: if ($$tstart<$now) {
5397: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 5398: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 5399: my (%allroles,%allgroups,$group_privs,
5400: %groups_roles,@rolecodes);
1.1002 raeburn 5401: my %userroles = (
5402: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
5403: );
1.1064 raeburn 5404: @rolecodes = ('cm');
1.1002 raeburn 5405: my $spec=$$role.'.'.$$where;
5406: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
5407: if ($$role =~ /^cr\//) {
5408: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 5409: push(@rolecodes,'cr');
1.1002 raeburn 5410: } elsif ($$role eq 'gr') {
1.1064 raeburn 5411: push(@rolecodes,$$role);
1.1002 raeburn 5412: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
5413: $env{'user.name'});
1.1064 raeburn 5414: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 5415: (undef,my $group_privs) = split(/\//,$trole);
5416: $group_privs = &unescape($group_privs);
5417: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 5418: 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 5419: &get_groups_roles($tdomain,$trest,
5420: \%course_roles,\@rolecodes,
5421: \%groups_roles);
1.1002 raeburn 5422: } else {
1.1064 raeburn 5423: push(@rolecodes,$$role);
1.1002 raeburn 5424: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
5425: }
1.1064 raeburn 5426: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
5427: &appenv(\%userroles,\@rolecodes);
1.1002 raeburn 5428: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
5429: }
5430: }
1.1034 raeburn 5431: $$tstatus = 'is';
1.1002 raeburn 5432: }
1.994 raeburn 5433: }
5434: if ($$tend) {
1.1104 raeburn 5435: if ($$tend<$update) {
1.994 raeburn 5436: $$tstatus='expired';
5437: } elsif ($$tend<$now) {
5438: $$tstatus='will_not';
5439: }
5440: }
5441: }
5442: }
5443: }
5444:
1.1104 raeburn 5445: sub get_groups_roles {
5446: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
5447: return unless((ref($cdom_courseroles) eq 'HASH') &&
5448: (ref($rolecodes) eq 'ARRAY') &&
5449: (ref($groups_roles) eq 'HASH'));
5450: if (keys(%{$cdom_courseroles}) > 0) {
5451: my ($cnum) = ($rest =~ /^($match_courseid)/);
5452: if ($cdom ne '' && $cnum ne '') {
5453: foreach my $key (keys(%{$cdom_courseroles})) {
5454: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
5455: my $crsrole = $1;
5456: my $crssec = $2;
5457: if ($crsrole =~ /^cr/) {
5458: unless (grep(/^cr$/,@{$rolecodes})) {
5459: push(@{$rolecodes},'cr');
5460: }
5461: } else {
5462: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
5463: push(@{$rolecodes},$crsrole);
5464: }
5465: }
5466: my $rolekey = "$crsrole./$cdom/$cnum";
5467: if ($crssec ne '') {
5468: $rolekey .= "/$crssec";
5469: }
5470: $rolekey .= './';
5471: $groups_roles->{$rolekey} = $rolecodes;
5472: }
5473: }
5474: }
5475: }
5476: return;
5477: }
5478:
5479: sub delete_env_groupprivs {
5480: my ($where,$courseroles,$possroles) = @_;
5481: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
5482: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
5483: unless (ref($courseroles->{$udom}) eq 'HASH') {
5484: %{$courseroles->{$udom}} =
5485: &get_my_roles('','','userroles',['active'],
5486: $possroles,[$udom],1);
5487: }
5488: if (ref($courseroles->{$udom}) eq 'HASH') {
5489: foreach my $item (keys(%{$courseroles->{$udom}})) {
5490: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
5491: my $area = '/'.$cdom.'/'.$cnum;
5492: my $privkey = "user.priv.$crsrole.$area";
5493: if ($crssec ne '') {
5494: $privkey .= '/'.$crssec;
5495: }
5496: $privkey .= ".$area/$group";
5497: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
5498: }
5499: }
5500: return;
5501: }
5502:
1.994 raeburn 5503: sub check_adhoc_privs {
1.1104 raeburn 5504: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994 raeburn 5505: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1185 raeburn 5506: my $setprivs;
1.994 raeburn 5507: if ($env{$cckey}) {
5508: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104 raeburn 5509: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 5510: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088 raeburn 5511: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185 raeburn 5512: $setprivs = 1;
1.994 raeburn 5513: }
5514: } else {
1.1088 raeburn 5515: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185 raeburn 5516: $setprivs = 1;
1.994 raeburn 5517: }
1.1185 raeburn 5518: return $setprivs;
1.994 raeburn 5519: }
5520:
5521: sub set_adhoc_privileges {
5522: # role can be cc or ca
1.1088 raeburn 5523: my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994 raeburn 5524: my $area = '/'.$dcdom.'/'.$pickedcourse;
5525: my $spec = $role.'.'.$area;
5526: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1215 raeburn 5527: $env{'user.name'},1);
1.994 raeburn 5528: my %ccrole = ();
5529: &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
5530: my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
5531: &appenv(\%userroles,[$role,'cm']);
5532: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088 raeburn 5533: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
5534: &appenv( {'request.role' => $spec,
5535: 'request.role.domain' => $dcdom,
5536: 'request.course.sec' => ''
5537: }
5538: );
5539: my $tadv=0;
5540: if (&allowed('adv') eq 'F') { $tadv=1; }
5541: &appenv({'request.role.adv' => $tadv});
5542: }
1.994 raeburn 5543: }
5544:
1.12 www 5545: # --------------------------------------------------------------- get interface
5546:
5547: sub get {
1.131 albertel 5548: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 5549: my $items='';
1.800 albertel 5550: foreach my $item (@$storearr) {
5551: $items.=&escape($item).'&';
1.191 harris41 5552: }
1.12 www 5553: $items=~s/\&$//;
1.620 albertel 5554: if (!$udomain) { $udomain=$env{'user.domain'}; }
5555: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 5556: my $uhome=&homeserver($uname,$udomain);
5557:
1.133 albertel 5558: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 5559: my @pairs=split(/\&/,$rep);
1.273 albertel 5560: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
5561: return @pairs;
5562: }
1.15 www 5563: my %returnhash=();
1.42 www 5564: my $i=0;
1.800 albertel 5565: foreach my $item (@$storearr) {
5566: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 5567: $i++;
1.191 harris41 5568: }
1.15 www 5569: return %returnhash;
1.27 www 5570: }
5571:
5572: # --------------------------------------------------------------- del interface
5573:
5574: sub del {
1.133 albertel 5575: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 5576: my $items='';
1.800 albertel 5577: foreach my $item (@$storearr) {
5578: $items.=&escape($item).'&';
1.191 harris41 5579: }
1.984 neumanie 5580:
1.27 www 5581: $items=~s/\&$//;
1.620 albertel 5582: if (!$udomain) { $udomain=$env{'user.domain'}; }
5583: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 5584: my $uhome=&homeserver($uname,$udomain);
5585: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 5586: }
5587:
5588: # -------------------------------------------------------------- dump interface
5589:
1.1180 droeschl 5590: sub unserialize {
5591: my ($rep, $escapedkeys) = @_;
5592:
5593: return {} if $rep =~ /^error/;
5594:
5595: my %returnhash=();
1.1252 raeburn 5596: foreach my $item (split(/\&/,$rep)) {
1.1180 droeschl 5597: my ($key, $value) = split(/=/, $item, 2);
5598: $key = unescape($key) unless $escapedkeys;
5599: next if $key =~ /^error: 2 /;
1.1252 raeburn 5600: $returnhash{$key} = &thaw_unescape($value);
1.1180 droeschl 5601: }
5602: #return %returnhash;
5603: return \%returnhash;
5604: }
5605:
5606: # see Lond::dump_with_regexp
5607: # if $escapedkeys hash keys won't get unescaped.
1.15 www 5608: sub dump {
1.1180 droeschl 5609: my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755 albertel 5610: if (!$udomain) { $udomain=$env{'user.domain'}; }
5611: if (!$uname) { $uname=$env{'user.name'}; }
5612: my $uhome=&homeserver($uname,$udomain);
1.1167 droeschl 5613:
1.1180 droeschl 5614: my $reply;
5615: if (grep { $_ eq $uhome } current_machine_ids()) {
5616: # user is hosted on this machine
5617: $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
1.1226 raeburn 5618: $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1180 droeschl 5619: return %{unserialize($reply, $escapedkeys)};
5620: }
1.755 albertel 5621: if ($regexp) {
5622: $regexp=&escape($regexp);
5623: } else {
5624: $regexp='.';
5625: }
1.1166 raeburn 5626: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755 albertel 5627: my @pairs=split(/\&/,$rep);
5628: my %returnhash=();
1.1098 foxr 5629: if (!($rep =~ /^error/ )) {
5630: foreach my $item (@pairs) {
5631: my ($key,$value)=split(/=/,$item,2);
1.1180 droeschl 5632: $key = unescape($key) unless $escapedkeys;
5633: #$key = &unescape($key);
1.1098 foxr 5634: next if ($key =~ /^error: 2 /);
5635: $returnhash{$key}=&thaw_unescape($value);
5636: }
1.755 albertel 5637: }
5638: return %returnhash;
1.407 www 5639: }
5640:
1.1098 foxr 5641:
1.717 albertel 5642: # --------------------------------------------------------- dumpstore interface
5643:
5644: sub dumpstore {
5645: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180 droeschl 5646: # same as dump but keys must be escaped. They may contain colon separated
5647: # lists of values that may themself contain colons (e.g. symbs).
5648: return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717 albertel 5649: }
5650:
1.407 www 5651: # -------------------------------------------------------------- keys interface
5652:
5653: sub getkeys {
5654: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 5655: if (!$udomain) { $udomain=$env{'user.domain'}; }
5656: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 5657: my $uhome=&homeserver($uname,$udomain);
5658: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
5659: my @keyarray=();
1.800 albertel 5660: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 5661: next if ($key =~ /^error: 2 /);
1.800 albertel 5662: push(@keyarray,&unescape($key));
1.407 www 5663: }
5664: return @keyarray;
1.318 matthew 5665: }
5666:
1.319 matthew 5667: # --------------------------------------------------------------- currentdump
5668: sub currentdump {
1.328 matthew 5669: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 5670: $courseid = $env{'request.course.id'} if (! defined($courseid));
5671: $sdom = $env{'user.domain'} if (! defined($sdom));
5672: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 5673: my $uhome = &homeserver($sname,$sdom);
1.1180 droeschl 5674: my $rep;
5675:
5676: if (grep { $_ eq $uhome } current_machine_ids()) {
5677: $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
5678: $courseid)));
5679: } else {
5680: $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
5681: }
5682:
1.318 matthew 5683: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 5684: #
1.318 matthew 5685: my %returnhash=();
1.319 matthew 5686: #
5687: if ($rep eq "unknown_cmd") {
5688: # an old lond will not know currentdump
5689: # Do a dump and make it look like a currentdump
1.822 albertel 5690: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 5691: return if ($tmp[0] =~ /^(error:|no_such_host)/);
5692: my %hash = @tmp;
5693: @tmp=();
1.424 matthew 5694: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 5695: } else {
5696: my @pairs=split(/\&/,$rep);
1.800 albertel 5697: foreach my $pair (@pairs) {
5698: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 5699: my ($symb,$param) = split(/:/,$key);
5700: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 5701: &thaw_unescape($value);
1.319 matthew 5702: }
1.191 harris41 5703: }
1.12 www 5704: return %returnhash;
1.424 matthew 5705: }
5706:
5707: sub convert_dump_to_currentdump{
5708: my %hash = %{shift()};
5709: my %returnhash;
5710: # Code ripped from lond, essentially. The only difference
5711: # here is the unescaping done by lonnet::dump(). Conceivably
5712: # we might run in to problems with parameter names =~ /^v\./
5713: while (my ($key,$value) = each(%hash)) {
5714: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 5715: $symb = &unescape($symb);
5716: $param = &unescape($param);
1.424 matthew 5717: next if ($v eq 'version' || $symb eq 'keys');
5718: next if (exists($returnhash{$symb}) &&
5719: exists($returnhash{$symb}->{$param}) &&
5720: $returnhash{$symb}->{'v.'.$param} > $v);
5721: $returnhash{$symb}->{$param}=$value;
5722: $returnhash{$symb}->{'v.'.$param}=$v;
5723: }
5724: #
5725: # Remove all of the keys in the hashes which keep track of
5726: # the version of the parameter.
5727: while (my ($symb,$param_hash) = each(%returnhash)) {
5728: # use a foreach because we are going to delete from the hash.
5729: foreach my $key (keys(%$param_hash)) {
5730: delete($param_hash->{$key}) if ($key =~ /^v\./);
5731: }
5732: }
5733: return \%returnhash;
1.12 www 5734: }
5735:
1.627 albertel 5736: # ------------------------------------------------------ critical inc interface
5737:
5738: sub cinc {
5739: return &inc(@_,'critical');
5740: }
5741:
1.449 matthew 5742: # --------------------------------------------------------------- inc interface
5743:
5744: sub inc {
1.627 albertel 5745: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 5746: if (!$udomain) { $udomain=$env{'user.domain'}; }
5747: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 5748: my $uhome=&homeserver($uname,$udomain);
5749: my $items='';
5750: if (! ref($store)) {
5751: # got a single value, so use that instead
5752: $items = &escape($store).'=&';
5753: } elsif (ref($store) eq 'SCALAR') {
5754: $items = &escape($$store).'=&';
5755: } elsif (ref($store) eq 'ARRAY') {
5756: $items = join('=&',map {&escape($_);} @{$store});
5757: } elsif (ref($store) eq 'HASH') {
5758: while (my($key,$value) = each(%{$store})) {
5759: $items.= &escape($key).'='.&escape($value).'&';
5760: }
5761: }
5762: $items=~s/\&$//;
1.627 albertel 5763: if ($critical) {
5764: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
5765: } else {
5766: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
5767: }
1.449 matthew 5768: }
5769:
1.12 www 5770: # --------------------------------------------------------------- put interface
5771:
5772: sub put {
1.134 albertel 5773: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 5774: if (!$udomain) { $udomain=$env{'user.domain'}; }
5775: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 5776: my $uhome=&homeserver($uname,$udomain);
1.12 www 5777: my $items='';
1.800 albertel 5778: foreach my $item (keys(%$storehash)) {
5779: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 5780: }
1.12 www 5781: $items=~s/\&$//;
1.134 albertel 5782: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 5783: }
5784:
1.631 albertel 5785: # ------------------------------------------------------------ newput interface
5786:
5787: sub newput {
5788: my ($namespace,$storehash,$udomain,$uname)=@_;
5789: if (!$udomain) { $udomain=$env{'user.domain'}; }
5790: if (!$uname) { $uname=$env{'user.name'}; }
5791: my $uhome=&homeserver($uname,$udomain);
5792: my $items='';
5793: foreach my $key (keys(%$storehash)) {
5794: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
5795: }
5796: $items=~s/\&$//;
5797: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
5798: }
5799:
5800: # --------------------------------------------------------- putstore interface
5801:
1.524 raeburn 5802: sub putstore {
1.715 albertel 5803: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620 albertel 5804: if (!$udomain) { $udomain=$env{'user.domain'}; }
5805: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 5806: my $uhome=&homeserver($uname,$udomain);
5807: my $items='';
1.715 albertel 5808: foreach my $key (keys(%$storehash)) {
5809: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 5810: }
1.715 albertel 5811: $items=~s/\&$//;
1.716 albertel 5812: my $esc_symb=&escape($symb);
5813: my $esc_v=&escape($version);
1.715 albertel 5814: my $reply =
1.716 albertel 5815: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 5816: $uhome);
5817: if ($reply eq 'unknown_cmd') {
1.716 albertel 5818: # gfall back to way things use to be done
1.715 albertel 5819: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
5820: $uname);
1.524 raeburn 5821: }
1.715 albertel 5822: return $reply;
5823: }
5824:
5825: sub old_putstore {
1.716 albertel 5826: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
5827: if (!$udomain) { $udomain=$env{'user.domain'}; }
5828: if (!$uname) { $uname=$env{'user.name'}; }
5829: my $uhome=&homeserver($uname,$udomain);
5830: my %newstorehash;
1.800 albertel 5831: foreach my $item (keys(%$storehash)) {
5832: my $key = $version.':'.&escape($symb).':'.$item;
5833: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 5834: }
5835: my $items='';
5836: my %allitems = ();
1.800 albertel 5837: foreach my $item (keys(%newstorehash)) {
5838: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 5839: my $key = $1.':keys:'.$2;
5840: $allitems{$key} .= $3.':';
5841: }
1.800 albertel 5842: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 5843: }
1.800 albertel 5844: foreach my $item (keys(%allitems)) {
5845: $allitems{$item} =~ s/\:$//;
5846: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 5847: }
5848: $items=~s/\&$//;
5849: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 5850: }
5851:
1.47 www 5852: # ------------------------------------------------------ critical put interface
5853:
5854: sub cput {
1.134 albertel 5855: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 5856: if (!$udomain) { $udomain=$env{'user.domain'}; }
5857: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 5858: my $uhome=&homeserver($uname,$udomain);
1.47 www 5859: my $items='';
1.800 albertel 5860: foreach my $item (keys(%$storehash)) {
5861: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 5862: }
1.47 www 5863: $items=~s/\&$//;
1.134 albertel 5864: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 5865: }
5866:
5867: # -------------------------------------------------------------- eget interface
5868:
5869: sub eget {
1.133 albertel 5870: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 5871: my $items='';
1.800 albertel 5872: foreach my $item (@$storearr) {
5873: $items.=&escape($item).'&';
1.191 harris41 5874: }
1.12 www 5875: $items=~s/\&$//;
1.620 albertel 5876: if (!$udomain) { $udomain=$env{'user.domain'}; }
5877: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 5878: my $uhome=&homeserver($uname,$udomain);
5879: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 5880: my @pairs=split(/\&/,$rep);
5881: my %returnhash=();
1.42 www 5882: my $i=0;
1.800 albertel 5883: foreach my $item (@$storearr) {
5884: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 5885: $i++;
1.191 harris41 5886: }
1.12 www 5887: return %returnhash;
5888: }
5889:
1.667 albertel 5890: # ------------------------------------------------------------ tmpput interface
5891: sub tmpput {
1.802 raeburn 5892: my ($storehash,$server,$context)=@_;
1.667 albertel 5893: my $items='';
1.800 albertel 5894: foreach my $item (keys(%$storehash)) {
5895: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 5896: }
5897: $items=~s/\&$//;
1.802 raeburn 5898: if (defined($context)) {
5899: $items .= ':'.&escape($context);
5900: }
1.667 albertel 5901: return &reply("tmpput:$items",$server);
5902: }
5903:
5904: # ------------------------------------------------------------ tmpget interface
5905: sub tmpget {
1.688 albertel 5906: my ($token,$server)=@_;
5907: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5908: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 5909: my %returnhash;
5910: foreach my $item (split(/\&/,$rep)) {
5911: my ($key,$value)=split(/=/,$item);
1.951 raeburn 5912: next if ($key =~ /^error: 2 /);
1.667 albertel 5913: $returnhash{&unescape($key)}=&thaw_unescape($value);
5914: }
5915: return %returnhash;
5916: }
5917:
1.1113 raeburn 5918: # ------------------------------------------------------------ tmpdel interface
1.688 albertel 5919: sub tmpdel {
5920: my ($token,$server)=@_;
5921: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5922: return &reply("tmpdel:$token",$server);
5923: }
5924:
1.1198 raeburn 5925: # ------------------------------------------------------------ get_timebased_id
5926:
5927: sub get_timebased_id {
5928: my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
5929: $maxtries) = @_;
5930: my ($newid,$error,$dellock);
5931: unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
5932: return ('','ok','invalid call to get suffix');
5933: }
5934:
5935: # set defaults for any optional args for which values were not supplied
5936: if ($who eq '') {
5937: $who = $env{'user.name'}.':'.$env{'user.domain'};
5938: }
5939: if (!$locktries) {
5940: $locktries = 3;
5941: }
5942: if (!$maxtries) {
5943: $maxtries = 10;
5944: }
5945:
5946: if (($cdom eq '') || ($cnum eq '')) {
5947: if ($env{'request.course.id'}) {
5948: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
5949: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
5950: }
5951: if (($cdom eq '') || ($cnum eq '')) {
5952: return ('','ok','call to get suffix not in course context');
5953: }
5954: }
5955:
5956: # construct locking item
5957: my $lockhash = {
5958: $prefix."\0".'locked_'.$keyid => $who,
5959: };
5960: my $tries = 0;
5961:
5962: # attempt to get lock on nohist_$namespace file
5963: my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
5964: while (($gotlock ne 'ok') && $tries <$locktries) {
5965: $tries ++;
5966: sleep 1;
5967: $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
5968: }
5969:
5970: # attempt to get unique identifier, based on current timestamp
5971: if ($gotlock eq 'ok') {
5972: my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
5973: my $id = time;
5974: $newid = $id;
5975: my $idtries = 0;
5976: while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
5977: if ($idtype eq 'concat') {
5978: $newid = $id.$idtries;
5979: } else {
5980: $newid ++;
5981: }
5982: $idtries ++;
5983: }
5984: if (!exists($inuse{$prefix."\0".$newid})) {
5985: my %new_item = (
5986: $prefix."\0".$newid => $who,
5987: );
5988: my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
5989: $cdom,$cnum);
5990: if ($putresult ne 'ok') {
5991: undef($newid);
5992: $error = 'error saving new item: '.$putresult;
5993: }
5994: } else {
5995: $error = ('error: no unique suffix available for the new item ');
5996: }
5997: # remove lock
5998: my @del_lock = ($prefix."\0".'locked_'.$keyid);
5999: $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
6000: } else {
6001: $error = "error: could not obtain lockfile\n";
6002: $dellock = 'ok';
6003: }
6004: return ($newid,$dellock,$error);
6005: }
6006:
1.765 albertel 6007: # -------------------------------------------------- portfolio access checking
6008:
6009: sub portfolio_access {
1.766 albertel 6010: my ($requrl) = @_;
1.765 albertel 6011: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
6012: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814 raeburn 6013: if ($result) {
6014: my %setters;
6015: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6016: my ($startblock,$endblock) =
6017: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
6018: if ($startblock && $endblock) {
6019: return 'B';
6020: }
6021: } else {
6022: my ($startblock,$endblock) =
6023: &Apache::loncommon::blockcheck(\%setters,'port');
6024: if ($startblock && $endblock) {
6025: return 'B';
6026: }
6027: }
6028: }
1.765 albertel 6029: if ($result eq 'ok') {
1.766 albertel 6030: return 'F';
1.765 albertel 6031: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 6032: return 'A';
1.765 albertel 6033: }
1.766 albertel 6034: return '';
1.765 albertel 6035: }
6036:
6037: sub get_portfolio_access {
1.767 albertel 6038: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
6039:
6040: if (!ref($access_hash)) {
6041: my $current_perms = &get_portfile_permissions($udom,$unum);
6042: my %access_controls = &get_access_controls($current_perms,$group,
6043: $file_name);
6044: $access_hash = $access_controls{$file_name};
6045: }
6046:
1.765 albertel 6047: my ($public,$guest,@domains,@users,@courses,@groups);
6048: my $now = time;
6049: if (ref($access_hash) eq 'HASH') {
6050: foreach my $key (keys(%{$access_hash})) {
6051: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
6052: if ($start > $now) {
6053: next;
6054: }
6055: if ($end && $end<$now) {
6056: next;
6057: }
6058: if ($scope eq 'public') {
6059: $public = $key;
6060: last;
6061: } elsif ($scope eq 'guest') {
6062: $guest = $key;
6063: } elsif ($scope eq 'domains') {
6064: push(@domains,$key);
6065: } elsif ($scope eq 'users') {
6066: push(@users,$key);
6067: } elsif ($scope eq 'course') {
6068: push(@courses,$key);
6069: } elsif ($scope eq 'group') {
6070: push(@groups,$key);
6071: }
6072: }
6073: if ($public) {
6074: return 'ok';
6075: }
6076: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6077: if ($guest) {
6078: return $guest;
6079: }
6080: } else {
6081: if (@domains > 0) {
6082: foreach my $domkey (@domains) {
6083: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
6084: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
6085: return 'ok';
6086: }
6087: }
6088: }
6089: }
6090: if (@users > 0) {
6091: foreach my $userkey (@users) {
1.865 raeburn 6092: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
6093: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
6094: if (ref($item) eq 'HASH') {
6095: if (($item->{'uname'} eq $env{'user.name'}) &&
6096: ($item->{'udom'} eq $env{'user.domain'})) {
6097: return 'ok';
6098: }
6099: }
6100: }
6101: }
1.765 albertel 6102: }
6103: }
6104: my %roleshash;
6105: my @courses_and_groups = @courses;
6106: push(@courses_and_groups,@groups);
6107: if (@courses_and_groups > 0) {
6108: my (%allgroups,%allroles);
6109: my ($start,$end,$role,$sec,$group);
6110: foreach my $envkey (%env) {
1.1060 raeburn 6111: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6112: my $cid = $2.'_'.$3;
6113: if ($1 eq 'gr') {
6114: $group = $4;
6115: $allgroups{$cid}{$group} = $env{$envkey};
6116: } else {
6117: if ($4 eq '') {
6118: $sec = 'none';
6119: } else {
6120: $sec = $4;
6121: }
6122: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6123: }
1.811 albertel 6124: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6125: my $cid = $2.'_'.$3;
6126: if ($4 eq '') {
6127: $sec = 'none';
6128: } else {
6129: $sec = $4;
6130: }
6131: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6132: }
6133: }
6134: if (keys(%allroles) == 0) {
6135: return;
6136: }
6137: foreach my $key (@courses_and_groups) {
6138: my %content = %{$$access_hash{$key}};
6139: my $cnum = $content{'number'};
6140: my $cdom = $content{'domain'};
6141: my $cid = $cdom.'_'.$cnum;
6142: if (!exists($allroles{$cid})) {
6143: next;
6144: }
6145: foreach my $role_id (keys(%{$content{'roles'}})) {
6146: my @sections = @{$content{'roles'}{$role_id}{'section'}};
6147: my @groups = @{$content{'roles'}{$role_id}{'group'}};
6148: my @status = @{$content{'roles'}{$role_id}{'access'}};
6149: my @roles = @{$content{'roles'}{$role_id}{'role'}};
6150: foreach my $role (keys(%{$allroles{$cid}})) {
6151: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
6152: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
6153: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
6154: if (grep/^all$/,@sections) {
6155: return 'ok';
6156: } else {
6157: if (grep/^$sec$/,@sections) {
6158: return 'ok';
6159: }
6160: }
6161: }
6162: }
6163: if (keys(%{$allgroups{$cid}}) == 0) {
6164: if (grep/^none$/,@groups) {
6165: return 'ok';
6166: }
6167: } else {
6168: if (grep/^all$/,@groups) {
6169: return 'ok';
6170: }
6171: foreach my $group (keys(%{$allgroups{$cid}})) {
6172: if (grep/^$group$/,@groups) {
6173: return 'ok';
6174: }
6175: }
6176: }
6177: }
6178: }
6179: }
6180: }
6181: }
6182: if ($guest) {
6183: return $guest;
6184: }
6185: }
6186: }
6187: return;
6188: }
6189:
6190: sub course_group_datechecker {
6191: my ($dates,$now,$status) = @_;
6192: my ($start,$end) = split(/\./,$dates);
6193: if (!$start && !$end) {
6194: return 'ok';
6195: }
6196: if (grep/^active$/,@{$status}) {
6197: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
6198: return 'ok';
6199: }
6200: }
6201: if (grep/^previous$/,@{$status}) {
6202: if ($end > $now ) {
6203: return 'ok';
6204: }
6205: }
6206: if (grep/^future$/,@{$status}) {
6207: if ($start > $now) {
6208: return 'ok';
6209: }
6210: }
6211: return;
6212: }
6213:
6214: sub parse_portfolio_url {
6215: my ($url) = @_;
6216:
6217: my ($type,$udom,$unum,$group,$file_name);
6218:
1.823 albertel 6219: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 6220: $type = 1;
6221: $udom = $1;
6222: $unum = $2;
6223: $file_name = $3;
1.823 albertel 6224: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 6225: $type = 2;
6226: $udom = $1;
6227: $unum = $2;
6228: $group = $3;
6229: $file_name = $3.'/'.$4;
6230: }
6231: if (wantarray) {
6232: return ($type,$udom,$unum,$file_name,$group);
6233: }
6234: return $type;
6235: }
6236:
6237: sub is_portfolio_url {
6238: my ($url) = @_;
6239: return scalar(&parse_portfolio_url($url));
6240: }
6241:
1.798 raeburn 6242: sub is_portfolio_file {
6243: my ($file) = @_;
1.820 raeburn 6244: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 6245: return 1;
6246: }
6247: return;
6248: }
6249:
1.976 raeburn 6250: sub usertools_access {
1.1084 raeburn 6251: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 6252: my ($access,%tools);
6253: if ($context eq '') {
6254: $context = 'tools';
6255: }
6256: if ($context eq 'requestcourses') {
6257: %tools = (
6258: official => 1,
6259: unofficial => 1,
1.1006 raeburn 6260: community => 1,
1.1246 raeburn 6261: textbook => 1,
1.985 raeburn 6262: );
1.1183 raeburn 6263: } elsif ($context eq 'requestauthor') {
6264: %tools = (
6265: requestauthor => 1,
6266: );
1.985 raeburn 6267: } else {
6268: %tools = (
6269: aboutme => 1,
6270: blog => 1,
1.1177 raeburn 6271: webdav => 1,
1.985 raeburn 6272: portfolio => 1,
6273: );
6274: }
1.976 raeburn 6275: return if (!defined($tools{$tool}));
6276:
1.1242 raeburn 6277: if (($udom eq '') || ($uname eq '')) {
1.976 raeburn 6278: $udom = $env{'user.domain'};
6279: $uname = $env{'user.name'};
6280: }
6281:
1.978 raeburn 6282: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
6283: if ($action ne 'reload') {
1.985 raeburn 6284: if ($context eq 'requestcourses') {
6285: return $env{'environment.canrequest.'.$tool};
1.1183 raeburn 6286: } elsif ($context eq 'requestauthor') {
6287: return $env{'environment.canrequest.author'};
1.985 raeburn 6288: } else {
6289: return $env{'environment.availabletools.'.$tool};
6290: }
6291: }
1.976 raeburn 6292: }
6293:
1.1183 raeburn 6294: my ($toolstatus,$inststatus,$envkey);
6295: if ($context eq 'requestauthor') {
6296: $envkey = $context;
6297: } else {
6298: $envkey = $context.'.'.$tool;
6299: }
1.976 raeburn 6300:
1.985 raeburn 6301: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
6302: ($action ne 'reload')) {
1.1183 raeburn 6303: $toolstatus = $env{'environment.'.$envkey};
1.976 raeburn 6304: $inststatus = $env{'environment.inststatus'};
6305: } else {
1.1084 raeburn 6306: if (ref($userenvref) eq 'HASH') {
1.1183 raeburn 6307: $toolstatus = $userenvref->{$envkey};
1.1084 raeburn 6308: $inststatus = $userenvref->{'inststatus'};
6309: } else {
1.1183 raeburn 6310: my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
6311: $toolstatus = $userenv{$envkey};
1.1084 raeburn 6312: $inststatus = $userenv{'inststatus'};
6313: }
1.976 raeburn 6314: }
6315:
6316: if ($toolstatus ne '') {
6317: if ($toolstatus) {
6318: $access = 1;
6319: } else {
6320: $access = 0;
6321: }
6322: return $access;
6323: }
6324:
1.1084 raeburn 6325: my ($is_adv,%domdef);
6326: if (ref($is_advref) eq 'HASH') {
6327: $is_adv = $is_advref->{'is_adv'};
6328: } else {
6329: $is_adv = &is_advanced_user($udom,$uname);
6330: }
6331: if (ref($domdefref) eq 'HASH') {
6332: %domdef = %{$domdefref};
6333: } else {
6334: %domdef = &get_domain_defaults($udom);
6335: }
1.976 raeburn 6336: if (ref($domdef{$tool}) eq 'HASH') {
6337: if ($is_adv) {
6338: if ($domdef{$tool}{'_LC_adv'} ne '') {
6339: if ($domdef{$tool}{'_LC_adv'}) {
6340: $access = 1;
6341: } else {
6342: $access = 0;
6343: }
6344: return $access;
6345: }
6346: }
6347: if ($inststatus ne '') {
6348: my ($hasaccess,$hasnoaccess);
6349: foreach my $affiliation (split(/:/,$inststatus)) {
6350: if ($domdef{$tool}{$affiliation} ne '') {
6351: if ($domdef{$tool}{$affiliation}) {
6352: $hasaccess = 1;
6353: } else {
6354: $hasnoaccess = 1;
6355: }
6356: }
6357: }
6358: if ($hasaccess || $hasnoaccess) {
6359: if ($hasaccess) {
6360: $access = 1;
6361: } elsif ($hasnoaccess) {
6362: $access = 0;
6363: }
6364: return $access;
6365: }
6366: } else {
6367: if ($domdef{$tool}{'default'} ne '') {
6368: if ($domdef{$tool}{'default'}) {
6369: $access = 1;
6370: } elsif ($domdef{$tool}{'default'} == 0) {
6371: $access = 0;
6372: }
6373: return $access;
6374: }
6375: }
6376: } else {
1.1177 raeburn 6377: if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985 raeburn 6378: $access = 1;
6379: } else {
6380: $access = 0;
6381: }
1.976 raeburn 6382: return $access;
6383: }
6384: }
6385:
1.1050 raeburn 6386: sub is_course_owner {
6387: my ($cdom,$cnum,$udom,$uname) = @_;
6388: if (($udom eq '') || ($uname eq '')) {
6389: $udom = $env{'user.domain'};
6390: $uname = $env{'user.name'};
6391: }
6392: unless (($udom eq '') || ($uname eq '')) {
6393: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
6394: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
6395: return 1;
6396: } else {
6397: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
6398: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
6399: return 1;
6400: }
6401: }
6402: }
6403: }
6404: return;
6405: }
6406:
1.976 raeburn 6407: sub is_advanced_user {
6408: my ($udom,$uname) = @_;
1.1085 raeburn 6409: if ($udom ne '' && $uname ne '') {
6410: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128 raeburn 6411: if (wantarray) {
6412: return ($env{'user.adv'},$env{'user.author'});
6413: } else {
6414: return $env{'user.adv'};
6415: }
1.1085 raeburn 6416: }
6417: }
1.976 raeburn 6418: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
6419: my %allroles;
1.1128 raeburn 6420: my ($is_adv,$is_author);
1.976 raeburn 6421: foreach my $role (keys(%roleshash)) {
6422: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
6423: my $area = '/'.$tdomain.'/'.$trest;
6424: if ($sec ne '') {
6425: $area .= '/'.$sec;
6426: }
6427: if (($area ne '') && ($trole ne '')) {
6428: my $spec=$trole.'.'.$area;
6429: if ($trole =~ /^cr\//) {
6430: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
6431: } elsif ($trole ne 'gr') {
6432: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
6433: }
1.1128 raeburn 6434: if ($trole eq 'au') {
6435: $is_author = 1;
6436: }
1.976 raeburn 6437: }
6438: }
6439: foreach my $role (keys(%allroles)) {
6440: last if ($is_adv);
6441: foreach my $item (split(/:/,$allroles{$role})) {
6442: if ($item ne '') {
6443: my ($privilege,$restrictions)=split(/&/,$item);
6444: if ($privilege eq 'adv') {
6445: $is_adv = 1;
6446: last;
6447: }
6448: }
6449: }
6450: }
1.1128 raeburn 6451: if (wantarray) {
6452: return ($is_adv,$is_author);
6453: }
1.976 raeburn 6454: return $is_adv;
6455: }
1.798 raeburn 6456:
1.1035 raeburn 6457: sub check_can_request {
1.1036 raeburn 6458: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 6459: my $canreq = 0;
6460: my ($types,$typename) = &Apache::loncommon::course_types();
6461: my @options = ('approval','validate','autolimit');
6462: my $optregex = join('|',@options);
6463: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
6464: foreach my $type (@{$types}) {
6465: if (&usertools_access($env{'user.name'},
6466: $env{'user.domain'},
6467: $type,undef,'requestcourses')) {
6468: $canreq ++;
1.1036 raeburn 6469: if (ref($request_domains) eq 'HASH') {
6470: push(@{$request_domains->{$type}},$env{'user.domain'});
6471: }
1.1035 raeburn 6472: if ($dom eq $env{'user.domain'}) {
6473: $can_request->{$type} = 1;
6474: }
6475: }
6476: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
6477: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
6478: if (@curr > 0) {
1.1036 raeburn 6479: foreach my $item (@curr) {
6480: if (ref($request_domains) eq 'HASH') {
6481: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
6482: if ($otherdom ne '') {
6483: if (ref($request_domains->{$type}) eq 'ARRAY') {
6484: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
6485: push(@{$request_domains->{$type}},$otherdom);
6486: }
6487: } else {
6488: push(@{$request_domains->{$type}},$otherdom);
6489: }
6490: }
6491: }
6492: }
6493: unless($dom eq $env{'user.domain'}) {
6494: $canreq ++;
1.1035 raeburn 6495: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
6496: $can_request->{$type} = 1;
6497: }
6498: }
6499: }
6500: }
6501: }
6502: }
6503: return $canreq;
6504: }
6505:
1.341 www 6506: # ---------------------------------------------- Custom access rule evaluation
6507:
6508: sub customaccess {
6509: my ($priv,$uri)=@_;
1.807 albertel 6510: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 6511: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 6512: $udom = &LONCAPA::clean_domain($udom);
6513: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 6514: my $access=0;
1.800 albertel 6515: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 6516: my ($effect,$realm,$role,$type)=split(/\:/,$right);
6517: if ($type eq 'user') {
6518: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 6519: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 6520: if ($tdom) {
6521: if ($tdom ne $env{'user.domain'}) { next; }
6522: }
1.896 albertel 6523: if ($tuname) {
6524: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 6525: }
6526: $access=($effect eq 'allow');
6527: last;
6528: }
6529: } else {
6530: if ($role) {
6531: if ($role ne $urole) { next; }
6532: }
6533: foreach my $scope (split(/\s*\,\s*/,$realm)) {
6534: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
6535: if ($tdom) {
6536: if ($tdom ne $udom) { next; }
6537: }
6538: if ($tcrs) {
6539: if ($tcrs ne $ucrs) { next; }
6540: }
6541: if ($tsec) {
6542: if ($tsec ne $usec) { next; }
6543: }
6544: $access=($effect eq 'allow');
6545: last;
6546: }
6547: if ($realm eq '' && $role eq '') {
6548: $access=($effect eq 'allow');
6549: }
1.402 bowersj2 6550: }
1.341 www 6551: }
6552: return $access;
6553: }
6554:
1.103 harris41 6555: # ------------------------------------------------- Check for a user privilege
1.12 www 6556:
6557: sub allowed {
1.810 raeburn 6558: my ($priv,$uri,$symb,$role)=@_;
1.705 albertel 6559: my $ver_orguri=$uri;
1.439 www 6560: $uri=&deversion($uri);
1.152 www 6561: my $orguri=$uri;
1.52 www 6562: $uri=&declutter($uri);
1.809 raeburn 6563:
1.810 raeburn 6564: if ($priv eq 'evb') {
6565: # Evade communication block restrictions for specified role in a course
6566: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
6567: return $1;
6568: } else {
6569: return;
6570: }
6571: }
6572:
1.620 albertel 6573: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 6574: # Free bre access to adm and meta resources
1.775 albertel 6575: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 6576: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
6577: && ($priv eq 'bre')) {
1.14 www 6578: return 'F';
1.159 www 6579: }
6580:
1.545 banghart 6581: # Free bre access to user's own portfolio contents
1.714 raeburn 6582: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 6583: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 6584: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 6585: my %setters;
6586: my ($startblock,$endblock) =
6587: &Apache::loncommon::blockcheck(\%setters,'port');
6588: if ($startblock && $endblock) {
6589: return 'B';
6590: } else {
6591: return 'F';
6592: }
1.545 banghart 6593: }
6594:
1.762 raeburn 6595: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 6596: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
6597: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
6598: if (exists($env{'request.course.id'})) {
6599: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6600: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6601: if (($domain eq $cdom) && ($name eq $cnum)) {
6602: my $courseprivid=$env{'request.course.id'};
6603: $courseprivid=~s/\_/\//;
6604: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
6605: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
6606: return $1;
1.762 raeburn 6607: } else {
6608: if ($env{'request.course.sec'}) {
6609: $courseprivid.='/'.$env{'request.course.sec'};
6610: }
6611: if ($env{'user.priv.'.$env{'request.role'}.'./'.
6612: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
6613: return $2;
6614: }
1.714 raeburn 6615: }
6616: }
6617: }
6618: }
6619:
1.159 www 6620: # Free bre to public access
6621:
6622: if ($priv eq 'bre') {
1.238 www 6623: my $copyright=&metadata($uri,'copyright');
1.620 albertel 6624: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 6625: return 'F';
6626: }
1.238 www 6627: if ($copyright eq 'priv') {
6628: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 6629: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 6630: return '';
6631: }
6632: }
6633: if ($copyright eq 'domain') {
6634: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 6635: unless (($env{'user.domain'} eq $1) ||
6636: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 6637: return '';
6638: }
1.262 matthew 6639: }
1.620 albertel 6640: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 6641: # Library role, so allow browsing of resources in this domain.
6642: return 'F';
1.238 www 6643: }
1.341 www 6644: if ($copyright eq 'custom') {
6645: unless (&customaccess($priv,$uri)) { return ''; }
6646: }
1.14 www 6647: }
1.264 matthew 6648: # Domain coordinator is trying to create a course
1.620 albertel 6649: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 6650: # uri is the requested domain in this case.
6651: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 6652: # a role of dc for the domain in question.
1.620 albertel 6653: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 6654: }
1.29 www 6655:
1.52 www 6656: my $thisallowed='';
6657: my $statecond=0;
6658: my $courseprivid='';
6659:
1.1039 raeburn 6660: my $ownaccess;
1.1043 raeburn 6661: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 6662: if (($priv eq 'bro') && ($env{'user.author'})) {
6663: if ($uri eq '') {
6664: $ownaccess = 1;
6665: } else {
6666: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
6667: my $udom = $env{'user.domain'};
6668: my $uname = $env{'user.name'};
6669: if ($uri =~ m{^\Q$udom\E/?$}) {
6670: $ownaccess = 1;
1.1040 raeburn 6671: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 6672: unless ($uri =~ m{\.\./}) {
6673: $ownaccess = 1;
6674: }
6675: } elsif (($udom ne 'public') && ($uname ne 'public')) {
6676: my $now = time;
6677: if ($uri =~ m{^([^/]+)/?$}) {
6678: my $adom = $1;
6679: foreach my $key (keys(%env)) {
1.1042 raeburn 6680: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 6681: my ($start,$end) = split('.',$env{$key});
6682: if (($now >= $start) && (!$end || $end < $now)) {
6683: $ownaccess = 1;
6684: last;
6685: }
6686: }
6687: }
6688: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
6689: my $adom = $1;
6690: my $aname = $2;
1.1042 raeburn 6691: foreach my $role ('ca','aa') {
6692: if ($env{"user.role.$role./$adom/$aname"}) {
6693: my ($start,$end) =
6694: split('.',$env{"user.role.$role./$adom/$aname"});
6695: if (($now >= $start) && (!$end || $end < $now)) {
6696: $ownaccess = 1;
6697: last;
6698: }
1.1039 raeburn 6699: }
6700: }
6701: }
6702: }
6703: }
6704: }
6705: }
6706:
1.52 www 6707: # Course
6708:
1.620 albertel 6709: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6710: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6711: $thisallowed.=$1;
6712: }
1.52 www 6713: }
1.29 www 6714:
1.52 www 6715: # Domain
6716:
1.620 albertel 6717: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 6718: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6719: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6720: $thisallowed.=$1;
6721: }
1.12 www 6722: }
1.52 www 6723:
1.1141 raeburn 6724: # User who is not author or co-author might still be able to edit
6725: # resource of an author in the domain (e.g., if Domain Coordinator).
6726: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
6727: (&allowed('mdc',$env{'request.course.id'}))) {
6728: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
6729: $thisallowed.=$1;
6730: }
6731: }
6732:
1.52 www 6733: # Course: uri itself is a course
1.66 www 6734: my $courseuri=$uri;
6735: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 6736: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 6737:
1.620 albertel 6738: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 6739: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6740: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6741: $thisallowed.=$1;
6742: }
1.12 www 6743: }
1.29 www 6744:
1.665 albertel 6745: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 6746: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 6747: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 6748: $thisallowed='';
1.671 raeburn 6749: my ($match)=&is_on_map($uri);
6750: if ($match) {
6751: if ($env{'user.priv.'.$env{'request.role'}.'./'}
6752: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6753: my @blockers = &has_comm_blocking($priv,$symb,$uri);
6754: if (@blockers > 0) {
6755: $thisallowed = 'B';
6756: } else {
6757: $thisallowed.=$1;
6758: }
1.671 raeburn 6759: }
6760: } else {
1.705 albertel 6761: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 6762: if ($refuri) {
6763: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 6764: $thisallowed='F';
1.671 raeburn 6765: } else {
6766: $refuri=&declutter($refuri);
6767: my ($match) = &is_on_map($refuri);
6768: if ($match) {
1.1162 raeburn 6769: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
6770: if (@blockers > 0) {
6771: $thisallowed = 'B';
6772: } else {
6773: $thisallowed='F';
6774: }
1.671 raeburn 6775: }
1.669 raeburn 6776: }
1.671 raeburn 6777: }
6778: }
1.314 www 6779: }
1.492 albertel 6780:
1.766 albertel 6781: if ($priv eq 'bre'
6782: && $thisallowed ne 'F'
6783: && $thisallowed ne '2'
6784: && &is_portfolio_url($uri)) {
6785: $thisallowed = &portfolio_access($uri);
6786: }
1.1250 raeburn 6787:
1.52 www 6788: # Full access at system, domain or course-wide level? Exit.
1.29 www 6789: if ($thisallowed=~/F/) {
6790: return 'F';
6791: }
6792:
1.52 www 6793: # If this is generating or modifying users, exit with special codes
1.29 www 6794:
1.643 www 6795: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
6796: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 6797: my ($audom,$auname)=split('/',$uri);
1.643 www 6798: # no author name given, so this just checks on the general right to make a co-author in this domain
6799: unless ($auname) { return $thisallowed; }
6800: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 6801: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
6802: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
6803: ($audom ne $env{'request.role.domain'}))) { return ''; }
6804: }
1.52 www 6805: return $thisallowed;
6806: }
6807: #
1.103 harris41 6808: # Gathered so far: system, domain and course wide privileges
1.52 www 6809: #
6810: # Course: See if uri or referer is an individual resource that is part of
6811: # the course
6812:
1.620 albertel 6813: if ($env{'request.course.id'}) {
1.232 www 6814:
1.620 albertel 6815: $courseprivid=$env{'request.course.id'};
6816: if ($env{'request.course.sec'}) {
6817: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 6818: }
6819: $courseprivid=~s/\_/\//;
6820: my $checkreferer=1;
1.232 www 6821: my ($match,$cond)=&is_on_map($uri);
6822: if ($match) {
6823: $statecond=$cond;
1.620 albertel 6824: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 6825: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6826: my $value = $1;
6827: if ($priv eq 'bre') {
6828: my @blockers = &has_comm_blocking($priv,$symb,$uri);
6829: if (@blockers > 0) {
6830: $thisallowed = 'B';
6831: } else {
6832: $thisallowed.=$value;
6833: }
6834: } else {
6835: $thisallowed.=$value;
6836: }
1.52 www 6837: $checkreferer=0;
6838: }
1.29 www 6839: }
1.83 www 6840:
1.148 www 6841: if ($checkreferer) {
1.620 albertel 6842: my $refuri=$env{'httpref.'.$orguri};
1.148 www 6843: unless ($refuri) {
1.800 albertel 6844: foreach my $key (keys(%env)) {
6845: if ($key=~/^httpref\..*\*/) {
6846: my $pattern=$key;
1.156 www 6847: $pattern=~s/^httpref\.\/res\///;
1.148 www 6848: $pattern=~s/\*/\[\^\/\]\+/g;
6849: $pattern=~s/\//\\\//g;
1.152 www 6850: if ($orguri=~/$pattern/) {
1.800 albertel 6851: $refuri=$env{$key};
1.148 www 6852: }
6853: }
1.191 harris41 6854: }
1.148 www 6855: }
1.232 www 6856:
1.148 www 6857: if ($refuri) {
1.152 www 6858: $refuri=&declutter($refuri);
1.232 www 6859: my ($match,$cond)=&is_on_map($refuri);
6860: if ($match) {
6861: my $refstatecond=$cond;
1.620 albertel 6862: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 6863: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6864: my $value = $1;
6865: if ($priv eq 'bre') {
6866: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
6867: if (@blockers > 0) {
6868: $thisallowed = 'B';
6869: } else {
6870: $thisallowed.=$value;
6871: }
6872: } else {
6873: $thisallowed.=$value;
6874: }
1.53 www 6875: $uri=$refuri;
6876: $statecond=$refstatecond;
1.52 www 6877: }
6878: }
1.148 www 6879: }
1.29 www 6880: }
1.52 www 6881: }
1.29 www 6882:
1.52 www 6883: #
1.103 harris41 6884: # Gathered now: all privileges that could apply, and condition number
1.52 www 6885: #
6886: #
6887: # Full or no access?
6888: #
1.29 www 6889:
1.52 www 6890: if ($thisallowed=~/F/) {
6891: return 'F';
6892: }
1.29 www 6893:
1.52 www 6894: unless ($thisallowed) {
6895: return '';
6896: }
1.29 www 6897:
1.52 www 6898: # Restrictions exist, deal with them
6899: #
6900: # C:according to course preferences
6901: # R:according to resource settings
6902: # L:unless locked
6903: # X:according to user session state
6904: #
6905:
6906: # Possibly locked functionality, check all courses
1.54 www 6907: # Locks might take effect only after 10 minutes cache expiration for other
6908: # courses, and 2 minutes for current course
1.52 www 6909:
6910: my $envkey;
6911: if ($thisallowed=~/L/) {
1.1000 raeburn 6912: foreach $envkey (keys(%env)) {
1.54 www 6913: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
6914: my $courseid=$2;
6915: my $roleid=$1.'.'.$2;
1.92 www 6916: $courseid=~s/^\///;
1.54 www 6917: my $expiretime=600;
1.620 albertel 6918: if ($env{'request.role'} eq $roleid) {
1.54 www 6919: $expiretime=120;
6920: }
6921: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
6922: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 6923: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 6924: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 6925: }
1.620 albertel 6926: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
6927: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
6928: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
6929: &log($env{'user.domain'},$env{'user.name'},
6930: $env{'user.home'},
1.57 www 6931: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 6932: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 6933: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 6934: return '';
6935: }
6936: }
1.620 albertel 6937: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
6938: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
6939: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
6940: &log($env{'user.domain'},$env{'user.name'},
6941: $env{'user.home'},
1.57 www 6942: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 6943: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 6944: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 6945: return '';
6946: }
6947: }
6948: }
1.29 www 6949: }
1.52 www 6950: }
6951:
6952: #
6953: # Rest of the restrictions depend on selected course
6954: #
6955:
1.620 albertel 6956: unless ($env{'request.course.id'}) {
1.766 albertel 6957: if ($thisallowed eq 'A') {
6958: return 'A';
1.814 raeburn 6959: } elsif ($thisallowed eq 'B') {
6960: return 'B';
1.766 albertel 6961: } else {
6962: return '1';
6963: }
1.52 www 6964: }
1.29 www 6965:
1.52 www 6966: #
6967: # Now user is definitely in a course
6968: #
1.53 www 6969:
6970:
6971: # Course preferences
6972:
6973: if ($thisallowed=~/C/) {
1.620 albertel 6974: my $rolecode=(split(/\./,$env{'request.role'}))[0];
6975: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
6976: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 6977: =~/\Q$rolecode\E/) {
1.1103 raeburn 6978: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 6979: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
6980: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
6981: $env{'request.course.id'});
6982: }
1.237 www 6983: return '';
6984: }
6985:
1.620 albertel 6986: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 6987: =~/\Q$unamedom\E/) {
1.1103 raeburn 6988: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 6989: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
6990: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
6991: $env{'request.course.id'});
6992: }
1.54 www 6993: return '';
6994: }
1.53 www 6995: }
6996:
6997: # Resource preferences
6998:
6999: if ($thisallowed=~/R/) {
1.620 albertel 7000: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 7001: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103 raeburn 7002: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7003: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
7004: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
7005: }
7006: return '';
1.54 www 7007: }
1.53 www 7008: }
1.30 www 7009:
1.246 www 7010: # Restricted by state or randomout?
1.30 www 7011:
1.52 www 7012: if ($thisallowed=~/X/) {
1.620 albertel 7013: if ($env{'acc.randomout'}) {
1.579 albertel 7014: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 7015: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 7016: return '';
7017: }
1.247 www 7018: }
7019: if (&condval($statecond)) {
1.52 www 7020: return '2';
7021: } else {
7022: return '';
7023: }
7024: }
1.30 www 7025:
1.766 albertel 7026: if ($thisallowed eq 'A') {
7027: return 'A';
1.814 raeburn 7028: } elsif ($thisallowed eq 'B') {
7029: return 'B';
1.766 albertel 7030: }
1.52 www 7031: return 'F';
1.232 www 7032: }
1.1162 raeburn 7033:
1.1192 raeburn 7034: # ------------------------------------------- Check construction space access
7035:
7036: sub constructaccess {
7037: my ($url,$setpriv)=@_;
7038:
7039: # We do not allow editing of previous versions of files
7040: if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
7041:
7042: # Get username and domain from URL
7043: my ($ownername,$ownerdomain,$ownerhome);
7044:
7045: ($ownerdomain,$ownername) =
7046: ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
7047:
7048: # The URL does not really point to any authorspace, forget it
7049: unless (($ownername) && ($ownerdomain)) { return ''; }
7050:
7051: # Now we need to see if the user has access to the authorspace of
7052: # $ownername at $ownerdomain
7053:
7054: if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
7055: # Real author for this?
7056: $ownerhome = $env{'user.home'};
7057: if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
7058: return ($ownername,$ownerdomain,$ownerhome);
7059: }
7060: } else {
7061: # Co-author for this?
7062: if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
7063: exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
7064: $ownerhome = &homeserver($ownername,$ownerdomain);
7065: return ($ownername,$ownerdomain,$ownerhome);
7066: }
7067: }
7068:
7069: # We don't have any access right now. If we are not possibly going to do anything about this,
7070: # we might as well leave
7071: unless ($setpriv) { return ''; }
7072:
7073: # Backdoor access?
7074: my $allowed=&allowed('eco',$ownerdomain);
7075: # Nope
7076: unless ($allowed) { return ''; }
7077: # Looks like we may have access, but could be locked by the owner of the construction space
7078: if ($allowed eq 'U') {
7079: my %blocked=&get('environment',['domcoord.author'],
7080: $ownerdomain,$ownername);
7081: # Is blocked by owner
7082: if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
7083: }
7084: if (($allowed eq 'F') || ($allowed eq 'U')) {
7085: # Grant temporary access
7086: my $then=$env{'user.login.time'};
1.1209 raeburn 7087: my $update=$env{'user.update.time'};
1.1192 raeburn 7088: if (!$update) { $update = $then; }
7089: my $refresh=$env{'user.refresh.time'};
7090: if (!$refresh) { $refresh = $update; }
7091: my $now = time;
7092: &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
7093: $now,'ca','constructaccess');
7094: $ownerhome = &homeserver($ownername,$ownerdomain);
7095: return($ownername,$ownerdomain,$ownerhome);
7096: }
7097: # No business here
7098: return '';
7099: }
7100:
1.1162 raeburn 7101: sub get_comm_blocks {
7102: my ($cdom,$cnum) = @_;
7103: if ($cdom eq '' || $cnum eq '') {
7104: return unless ($env{'request.course.id'});
7105: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7106: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7107: }
7108: my %commblocks;
7109: my $hashid=$cdom.'_'.$cnum;
7110: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
7111: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
7112: %commblocks = %{$blocksref};
7113: } else {
7114: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
7115: my $cachetime = 600;
7116: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
7117: }
7118: return %commblocks;
7119: }
7120:
7121: sub has_comm_blocking {
7122: my ($priv,$symb,$uri,$blocks) = @_;
7123: return unless ($env{'request.course.id'});
7124: return unless ($priv eq 'bre');
7125: return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
7126: my %commblocks;
7127: if (ref($blocks) eq 'HASH') {
7128: %commblocks = %{$blocks};
7129: } else {
7130: %commblocks = &get_comm_blocks();
7131: }
7132: return unless (keys(%commblocks) > 0);
7133: if (!$symb) { $symb=&symbread($uri,1); }
7134: my ($map,$resid,undef)=&decode_symb($symb);
7135: my %tocheck = (
7136: maps => $map,
7137: resources => $symb,
7138: );
7139: my @blockers;
7140: my $now = time;
1.1163 raeburn 7141: my $navmap = Apache::lonnavmaps::navmap->new();
1.1162 raeburn 7142: foreach my $block (keys(%commblocks)) {
7143: if ($block =~ /^(\d+)____(\d+)$/) {
7144: my ($start,$end) = ($1,$2);
7145: if ($start <= $now && $end >= $now) {
7146: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7147: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
7148: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
7149: if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
7150: unless (grep(/^\Q$block\E$/,@blockers)) {
7151: push(@blockers,$block);
7152: }
7153: }
7154: }
7155: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
7156: if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
7157: unless (grep(/^\Q$block\E$/,@blockers)) {
7158: push(@blockers,$block);
7159: }
7160: }
7161: }
7162: }
7163: }
7164: }
7165: } elsif ($block =~ /^firstaccess____(.+)$/) {
7166: my $item = $1;
1.1163 raeburn 7167: my @to_test;
1.1162 raeburn 7168: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7169: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
7170: my $check_interval;
7171: if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
7172: my @interval;
7173: my $type = 'map';
7174: if ($item eq 'course') {
7175: $type = 'course';
7176: @interval=&EXT("resource.0.interval");
7177: } else {
7178: if ($item =~ /___\d+___/) {
7179: $type = 'resource';
7180: @interval=&EXT("resource.0.interval",$item);
1.1163 raeburn 7181: if (ref($navmap)) {
7182: my $res = $navmap->getBySymb($item);
7183: push(@to_test,$res);
7184: }
1.1162 raeburn 7185: } else {
7186: my $mapsymb = &symbread($item,1);
7187: if ($mapsymb) {
7188: if (ref($navmap)) {
7189: my $mapres = $navmap->getBySymb($mapsymb);
1.1163 raeburn 7190: @to_test = $mapres->retrieveResources($mapres,undef,0,1);
7191: foreach my $res (@to_test) {
1.1162 raeburn 7192: my $symb = $res->symb();
7193: next if ($symb eq $mapsymb);
7194: if ($symb ne '') {
7195: @interval=&EXT("resource.0.interval",$symb);
7196: last;
7197: }
7198: }
7199: }
7200: }
7201: }
7202: }
7203: if ($interval[0] =~ /\d+/) {
7204: my $first_access;
7205: if ($type eq 'resource') {
7206: $first_access=&get_first_access($interval[1],$item);
7207: } elsif ($type eq 'map') {
7208: $first_access=&get_first_access($interval[1],undef,$item);
7209: } else {
7210: $first_access=&get_first_access($interval[1]);
7211: }
7212: if ($first_access) {
7213: my $timesup = $first_access+$interval[0];
7214: if ($timesup > $now) {
1.1163 raeburn 7215: foreach my $res (@to_test) {
7216: if ($res->is_problem()) {
7217: if ($res->completable()) {
7218: unless (grep(/^\Q$block\E$/,@blockers)) {
7219: push(@blockers,$block);
7220: }
7221: last;
7222: }
7223: }
1.1162 raeburn 7224: }
7225: }
7226: }
7227: }
7228: }
7229: }
7230: }
7231: }
7232: }
7233: return @blockers;
7234: }
7235:
7236: sub check_docs_block {
7237: my ($docsblock,$tocheck) =@_;
7238: if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
7239: return;
7240: }
7241: if (ref($docsblock->{'maps'}) eq 'HASH') {
7242: if ($tocheck->{'maps'}) {
7243: if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
7244: return 1;
7245: }
7246: }
7247: }
7248: if (ref($docsblock->{'resources'}) eq 'HASH') {
7249: if ($tocheck->{'resources'}) {
7250: if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
7251: return 1;
7252: }
7253: }
7254: }
7255: return;
7256: }
7257:
1.1133 foxr 7258: #
7259: # Removes the versino from a URI and
7260: # splits it in to its filename and path to the filename.
7261: # Seems like File::Basename could have done this more clearly.
7262: # Parameters:
7263: # $uri - input URI
7264: # Returns:
7265: # Two element list consisting of
7266: # $pathname - the URI up to and excluding the trailing /
7267: # $filename - The part of the URI following the last /
7268: # NOTE:
7269: # Another realization of this is simply:
7270: # use File::Basename;
7271: # ...
7272: # $uri = shift;
7273: # $filename = basename($uri);
7274: # $path = dirname($uri);
7275: # return ($filename, $path);
7276: #
7277: # The implementation below is probably faster however.
7278: #
1.710 albertel 7279: sub split_uri_for_cond {
7280: my $uri=&deversion(&declutter(shift));
7281: my @uriparts=split(/\//,$uri);
7282: my $filename=pop(@uriparts);
7283: my $pathname=join('/',@uriparts);
7284: return ($pathname,$filename);
7285: }
1.232 www 7286: # --------------------------------------------------- Is a resource on the map?
7287:
7288: sub is_on_map {
1.710 albertel 7289: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 7290: #Trying to find the conditional for the file
1.620 albertel 7291: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 7292: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 7293: if ($match) {
1.289 bowersj2 7294: return (1,$1);
7295: } else {
1.434 www 7296: return (0,0);
1.289 bowersj2 7297: }
1.12 www 7298: }
7299:
1.427 www 7300: # --------------------------------------------------------- Get symb from alias
7301:
7302: sub get_symb_from_alias {
7303: my $symb=shift;
7304: my ($map,$resid,$url)=&decode_symb($symb);
7305: # Already is a symb
7306: if ($url) { return $symb; }
7307: # Must be an alias
7308: my $aliassymb='';
7309: my %bighash;
1.620 albertel 7310: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 7311: &GDBM_READER(),0640)) {
7312: my $rid=$bighash{'mapalias_'.$symb};
7313: if ($rid) {
7314: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 7315: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
7316: $resid,$bighash{'src_'.$rid});
1.427 www 7317: }
7318: untie %bighash;
7319: }
7320: return $aliassymb;
7321: }
7322:
1.12 www 7323: # ----------------------------------------------------------------- Define Role
7324:
7325: sub definerole {
7326: if (allowed('mcr','/')) {
7327: my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800 albertel 7328: foreach my $role (split(':',$sysrole)) {
7329: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7330: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
7331: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
7332: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 7333: return "refused:s:$crole&$cqual";
7334: }
7335: }
1.191 harris41 7336: }
1.800 albertel 7337: foreach my $role (split(':',$domrole)) {
7338: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7339: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
7340: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
7341: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 7342: return "refused:d:$crole&$cqual";
7343: }
7344: }
1.191 harris41 7345: }
1.800 albertel 7346: foreach my $role (split(':',$courole)) {
7347: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7348: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
7349: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
7350: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 7351: return "refused:c:$crole&$cqual";
7352: }
7353: }
1.191 harris41 7354: }
1.620 albertel 7355: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
7356: "$env{'user.domain'}:$env{'user.name'}:".
1.21 www 7357: "rolesdef_$rolename=".
7358: escape($sysrole.'_'.$domrole.'_'.$courole);
1.620 albertel 7359: return reply($command,$env{'user.home'});
1.12 www 7360: } else {
7361: return 'refused';
7362: }
1.105 harris41 7363: }
7364:
7365: # ---------------- Make a metadata query against the network of library servers
7366:
7367: sub metadata_query {
1.1237 raeburn 7368: my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120 harris41 7369: my %rhash;
1.845 albertel 7370: my %libserv = &all_library();
1.244 matthew 7371: my @server_list = (defined($server_array) ? @$server_array
7372: : keys(%libserv) );
7373: for my $server (@server_list) {
1.1237 raeburn 7374: my $domains = '';
7375: if (ref($domains_hash) eq 'HASH') {
7376: $domains = $domains_hash->{$server};
7377: }
1.118 harris41 7378: unless ($custom or $customshow) {
1.1237 raeburn 7379: my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118 harris41 7380: $rhash{$server}=$reply;
7381: }
7382: else {
7383: my $reply=&reply("querysend:".&escape($query).':'.
1.1237 raeburn 7384: &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118 harris41 7385: $server);
7386: $rhash{$server}=$reply;
7387: }
1.112 harris41 7388: }
1.118 harris41 7389: return \%rhash;
1.240 www 7390: }
7391:
7392: # ----------------------------------------- Send log queries and wait for reply
7393:
7394: sub log_query {
7395: my ($uname,$udom,$query,%filters)=@_;
7396: my $uhome=&homeserver($uname,$udom);
7397: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 7398: my $uhost=&hostname($uhome);
1.800 albertel 7399: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 7400: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
7401: $uhome);
1.479 albertel 7402: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 7403: return get_query_reply($queryid);
7404: }
7405:
1.818 raeburn 7406: # -------------------------- Update MySQL table for portfolio file
7407:
7408: sub update_portfolio_table {
1.821 raeburn 7409: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 7410: if ($group ne '') {
7411: $file_name =~s /^\Q$group\E//;
7412: }
1.818 raeburn 7413: my $homeserver = &homeserver($uname,$udom);
7414: my $queryid=
1.821 raeburn 7415: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
7416: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 7417: my $reply = &get_query_reply($queryid);
7418: return $reply;
7419: }
7420:
1.899 raeburn 7421: # -------------------------- Update MySQL allusers table
7422:
7423: sub update_allusers_table {
7424: my ($uname,$udom,$names) = @_;
7425: my $homeserver = &homeserver($uname,$udom);
7426: my $queryid=
7427: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
7428: 'lastname='.&escape($names->{'lastname'}).'%%'.
7429: 'firstname='.&escape($names->{'firstname'}).'%%'.
7430: 'middlename='.&escape($names->{'middlename'}).'%%'.
7431: 'generation='.&escape($names->{'generation'}).'%%'.
7432: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
7433: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 7434: return;
1.899 raeburn 7435: }
7436:
1.508 raeburn 7437: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 7438:
7439: sub fetch_enrollment_query {
1.511 raeburn 7440: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508 raeburn 7441: my $homeserver;
1.547 raeburn 7442: my $maxtries = 1;
1.508 raeburn 7443: if ($context eq 'automated') {
7444: $homeserver = $perlvar{'lonHostID'};
1.547 raeburn 7445: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 7446: } else {
7447: $homeserver = &homeserver($cnum,$dom);
7448: }
1.838 albertel 7449: my $host=&hostname($homeserver);
1.506 raeburn 7450: my $cmd = '';
1.1000 raeburn 7451: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 7452: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 7453: }
7454: $cmd =~ s/%%$//;
7455: $cmd = &escape($cmd);
7456: my $query = 'fetchenrollment';
1.620 albertel 7457: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 7458: unless ($queryid=~/^\Q$host\E\_/) {
7459: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
7460: return 'error: '.$queryid;
7461: }
1.506 raeburn 7462: my $reply = &get_query_reply($queryid);
1.547 raeburn 7463: my $tries = 1;
7464: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
7465: $reply = &get_query_reply($queryid);
7466: $tries ++;
7467: }
1.526 raeburn 7468: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 7469: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 7470: } else {
1.901 albertel 7471: my @responses = split(/:/,$reply);
1.515 raeburn 7472: if ($homeserver eq $perlvar{'lonHostID'}) {
1.800 albertel 7473: foreach my $line (@responses) {
7474: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 7475: $$replyref{$key} = $value;
7476: }
7477: } else {
1.1117 foxr 7478: my $pathname = LONCAPA::tempdir();
1.800 albertel 7479: foreach my $line (@responses) {
7480: my ($key,$value) = split(/=/,$line);
1.506 raeburn 7481: $$replyref{$key} = $value;
7482: if ($value > 0) {
1.800 albertel 7483: foreach my $item (@{$$affiliatesref{$key}}) {
7484: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 7485: my $destname = $pathname.'/'.$filename;
7486: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 7487: if ($xml_classlist =~ /^error/) {
7488: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
7489: } else {
1.506 raeburn 7490: if ( open(FILE,">$destname") ) {
7491: print FILE &unescape($xml_classlist);
7492: close(FILE);
1.526 raeburn 7493: } else {
7494: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 7495: }
7496: }
7497: }
7498: }
7499: }
7500: }
7501: return 'ok';
7502: }
7503: return 'error';
7504: }
7505:
1.242 www 7506: sub get_query_reply {
7507: my $queryid=shift;
1.1117 foxr 7508: my $replyfile=LONCAPA::tempdir().$queryid;
1.240 www 7509: my $reply='';
7510: for (1..100) {
7511: sleep 2;
7512: if (-e $replyfile.'.end') {
1.448 albertel 7513: if (open(my $fh,$replyfile)) {
1.904 albertel 7514: $reply = join('',<$fh>);
7515: close($fh);
1.240 www 7516: } else { return 'error: reply_file_error'; }
1.242 www 7517: return &unescape($reply);
7518: }
1.240 www 7519: }
1.242 www 7520: return 'timeout:'.$queryid;
1.240 www 7521: }
7522:
7523: sub courselog_query {
1.241 www 7524: #
7525: # possible filters:
7526: # url: url or symb
7527: # username
7528: # domain
7529: # action: view, submit, grade
7530: # start: timestamp
7531: # end: timestamp
7532: #
1.240 www 7533: my (%filters)=@_;
1.620 albertel 7534: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 7535: if ($filters{'url'}) {
7536: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
7537: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
7538: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
7539: }
1.620 albertel 7540: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
7541: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 7542: return &log_query($cname,$cdom,'courselog',%filters);
7543: }
7544:
7545: sub userlog_query {
1.858 raeburn 7546: #
7547: # possible filters:
7548: # action: log check role
7549: # start: timestamp
7550: # end: timestamp
7551: #
1.240 www 7552: my ($uname,$udom,%filters)=@_;
7553: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 7554: }
7555:
1.506 raeburn 7556: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
7557:
7558: sub auto_run {
1.508 raeburn 7559: my ($cnum,$cdom) = @_;
1.876 raeburn 7560: my $response = 0;
7561: my $settings;
7562: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
7563: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
7564: $settings = $domconfig{'autoenroll'};
7565: if ($settings->{'run'} eq '1') {
7566: $response = 1;
7567: }
7568: } else {
1.934 raeburn 7569: my $homeserver;
7570: if (&is_course($cdom,$cnum)) {
7571: $homeserver = &homeserver($cnum,$cdom);
7572: } else {
7573: $homeserver = &domain($cdom,'primary');
7574: }
7575: if ($homeserver ne 'no_host') {
7576: $response = &reply('autorun:'.$cdom,$homeserver);
7577: }
1.876 raeburn 7578: }
1.506 raeburn 7579: return $response;
7580: }
1.776 albertel 7581:
1.506 raeburn 7582: sub auto_get_sections {
1.508 raeburn 7583: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 7584: my $homeserver;
7585: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7586: $homeserver = &homeserver($cnum,$cdom);
7587: }
7588: if (!defined($homeserver)) {
7589: if ($cdom =~ /^$match_domain$/) {
7590: $homeserver = &domain($cdom,'primary');
7591: }
7592: }
7593: my @secs;
7594: if (defined($homeserver)) {
7595: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
7596: unless ($response eq 'refused') {
7597: @secs = split(/:/,$response);
7598: }
1.506 raeburn 7599: }
7600: return @secs;
7601: }
1.776 albertel 7602:
1.506 raeburn 7603: sub auto_new_course {
1.1099 raeburn 7604: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 7605: my $homeserver = &homeserver($cnum,$cdom);
1.1099 raeburn 7606: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 7607: return $response;
7608: }
1.776 albertel 7609:
1.506 raeburn 7610: sub auto_validate_courseID {
1.508 raeburn 7611: my ($cnum,$cdom,$inst_course_id) = @_;
7612: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 7613: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 7614: return $response;
7615: }
1.776 albertel 7616:
1.1007 raeburn 7617: sub auto_validate_instcode {
1.1020 raeburn 7618: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 7619: my ($homeserver,$response);
7620: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7621: $homeserver = &homeserver($cnum,$cdom);
7622: }
7623: if (!defined($homeserver)) {
7624: if ($cdom =~ /^$match_domain$/) {
7625: $homeserver = &domain($cdom,'primary');
7626: }
7627: }
1.1065 raeburn 7628: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
7629: &escape($instcode).':'.&escape($owner),$homeserver));
1.1216 raeburn 7630: my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
7631: return ($outcome,$description,$defaultcredits);
1.1007 raeburn 7632: }
7633:
1.506 raeburn 7634: sub auto_create_password {
1.873 raeburn 7635: my ($cnum,$cdom,$authparam,$udom) = @_;
7636: my ($homeserver,$response);
1.506 raeburn 7637: my $create_passwd = 0;
7638: my $authchk = '';
1.873 raeburn 7639: if ($udom =~ /^$match_domain$/) {
7640: $homeserver = &domain($udom,'primary');
7641: }
7642: if ($homeserver eq '') {
7643: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7644: $homeserver = &homeserver($cnum,$cdom);
7645: }
7646: }
7647: if ($homeserver eq '') {
7648: $authchk = 'nodomain';
1.506 raeburn 7649: } else {
1.873 raeburn 7650: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
7651: if ($response eq 'refused') {
7652: $authchk = 'refused';
7653: } else {
1.901 albertel 7654: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 7655: }
1.506 raeburn 7656: }
7657: return ($authparam,$create_passwd,$authchk);
7658: }
7659:
1.706 raeburn 7660: sub auto_photo_permission {
7661: my ($cnum,$cdom,$students) = @_;
7662: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 7663: my ($outcome,$perm_reqd,$conditions) =
7664: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 7665: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7666: return (undef,undef);
7667: }
1.706 raeburn 7668: return ($outcome,$perm_reqd,$conditions);
7669: }
7670:
7671: sub auto_checkphotos {
7672: my ($uname,$udom,$pid) = @_;
7673: my $homeserver = &homeserver($uname,$udom);
7674: my ($result,$resulttype);
7675: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 7676: &escape($uname).':'.&escape($pid),
7677: $homeserver));
1.709 albertel 7678: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7679: return (undef,undef);
7680: }
1.706 raeburn 7681: if ($outcome) {
7682: ($result,$resulttype) = split(/:/,$outcome);
7683: }
7684: return ($result,$resulttype);
7685: }
7686:
7687: sub auto_photochoice {
7688: my ($cnum,$cdom) = @_;
7689: my $homeserver = &homeserver($cnum,$cdom);
7690: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 7691: &escape($cdom),
7692: $homeserver)));
1.709 albertel 7693: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7694: return (undef,undef);
7695: }
1.706 raeburn 7696: return ($update,$comment);
7697: }
7698:
7699: sub auto_photoupdate {
7700: my ($affiliatesref,$dom,$cnum,$photo) = @_;
7701: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 7702: my $host=&hostname($homeserver);
1.706 raeburn 7703: my $cmd = '';
7704: my $maxtries = 1;
1.800 albertel 7705: foreach my $affiliate (keys(%{$affiliatesref})) {
7706: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 7707: }
7708: $cmd =~ s/%%$//;
7709: $cmd = &escape($cmd);
7710: my $query = 'institutionalphotos';
7711: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
7712: unless ($queryid=~/^\Q$host\E\_/) {
7713: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
7714: return 'error: '.$queryid;
7715: }
7716: my $reply = &get_query_reply($queryid);
7717: my $tries = 1;
7718: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
7719: $reply = &get_query_reply($queryid);
7720: $tries ++;
7721: }
7722: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
7723: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
7724: } else {
7725: my @responses = split(/:/,$reply);
7726: my $outcome = shift(@responses);
7727: foreach my $item (@responses) {
7728: my ($key,$value) = split(/=/,$item);
7729: $$photo{$key} = $value;
7730: }
7731: return $outcome;
7732: }
7733: return 'error';
7734: }
7735:
1.521 raeburn 7736: sub auto_instcode_format {
1.793 albertel 7737: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
7738: $cat_order) = @_;
1.521 raeburn 7739: my $courses = '';
1.772 raeburn 7740: my @homeservers;
1.521 raeburn 7741: if ($caller eq 'global') {
1.841 albertel 7742: my %servers = &get_servers($codedom,'library');
7743: foreach my $tryserver (keys(%servers)) {
7744: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7745: push(@homeservers,$tryserver);
7746: }
1.584 raeburn 7747: }
1.1022 raeburn 7748: } elsif ($caller eq 'requests') {
7749: if ($codedom =~ /^$match_domain$/) {
7750: my $chome = &domain($codedom,'primary');
7751: unless ($chome eq 'no_host') {
7752: push(@homeservers,$chome);
7753: }
7754: }
1.521 raeburn 7755: } else {
1.772 raeburn 7756: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 7757: }
1.793 albertel 7758: foreach my $code (keys(%{$instcodes})) {
7759: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 7760: }
7761: chop($courses);
1.772 raeburn 7762: my $ok_response = 0;
7763: my $response;
7764: while (@homeservers > 0 && $ok_response == 0) {
7765: my $server = shift(@homeservers);
7766: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
7767: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
7768: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 7769: split(/:/,$response);
1.772 raeburn 7770: %{$codes} = (%{$codes},&str2hash($codes_str));
7771: push(@{$codetitles},&str2array($codetitles_str));
7772: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
7773: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
7774: $ok_response = 1;
7775: }
7776: }
7777: if ($ok_response) {
1.521 raeburn 7778: return 'ok';
1.772 raeburn 7779: } else {
7780: return $response;
1.521 raeburn 7781: }
7782: }
7783:
1.792 raeburn 7784: sub auto_instcode_defaults {
7785: my ($domain,$returnhash,$code_order) = @_;
7786: my @homeservers;
1.841 albertel 7787:
7788: my %servers = &get_servers($domain,'library');
7789: foreach my $tryserver (keys(%servers)) {
7790: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7791: push(@homeservers,$tryserver);
7792: }
1.792 raeburn 7793: }
1.841 albertel 7794:
1.792 raeburn 7795: my $response;
1.841 albertel 7796: foreach my $server (@homeservers) {
1.792 raeburn 7797: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 7798: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
7799:
7800: foreach my $pair (split(/\&/,$response)) {
7801: my ($name,$value)=split(/\=/,$pair);
7802: if ($name eq 'code_order') {
7803: @{$code_order} = split(/\&/,&unescape($value));
7804: } else {
7805: $returnhash->{&unescape($name)}=&unescape($value);
7806: }
7807: }
7808: return 'ok';
1.792 raeburn 7809: }
1.841 albertel 7810:
7811: return $response;
1.1003 raeburn 7812: }
7813:
7814: sub auto_possible_instcodes {
1.1007 raeburn 7815: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
7816: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
7817: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
7818: return;
7819: }
1.1003 raeburn 7820: my (@homeservers,$uhome);
7821: if (defined(&domain($domain,'primary'))) {
7822: $uhome=&domain($domain,'primary');
7823: push(@homeservers,&domain($domain,'primary'));
7824: } else {
7825: my %servers = &get_servers($domain,'library');
7826: foreach my $tryserver (keys(%servers)) {
7827: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7828: push(@homeservers,$tryserver);
7829: }
7830: }
7831: }
7832: my $response;
7833: foreach my $server (@homeservers) {
7834: $response=&reply('autopossibleinstcodes:'.$domain,$server);
7835: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 7836: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
7837: split(':',$response);
7838: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
7839: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 7840: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 7841: my ($name,$value)=split('=',$item);
7842: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 7843: }
7844: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 7845: my ($name,$value)=split('=',$item);
7846: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 7847: }
7848: return 'ok';
7849: }
7850: return $response;
7851: }
1.792 raeburn 7852:
1.1010 raeburn 7853: sub auto_courserequest_checks {
7854: my ($dom) = @_;
1.1020 raeburn 7855: my ($homeserver,%validations);
7856: if ($dom =~ /^$match_domain$/) {
7857: $homeserver = &domain($dom,'primary');
7858: }
7859: unless ($homeserver eq 'no_host') {
7860: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
7861: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
7862: my @items = split(/&/,$response);
7863: foreach my $item (@items) {
7864: my ($key,$value) = split('=',$item);
7865: $validations{&unescape($key)} = &thaw_unescape($value);
7866: }
7867: }
7868: }
1.1010 raeburn 7869: return %validations;
7870: }
7871:
1.1020 raeburn 7872: sub auto_courserequest_validation {
1.1255 raeburn 7873: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020 raeburn 7874: my ($homeserver,$response);
7875: if ($dom =~ /^$match_domain$/) {
7876: $homeserver = &domain($dom,'primary');
7877: }
1.1255 raeburn 7878: unless ($homeserver eq 'no_host') {
7879: my $customdata;
7880: if (ref($custominfo) eq 'HASH') {
7881: $customdata = &freeze_escape($custominfo);
7882: }
1.1020 raeburn 7883: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 7884: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1255 raeburn 7885: ':'.&escape($instcode).':'.&escape($instseclist).':'.
7886: $customdata,$homeserver));
1.1020 raeburn 7887: }
7888: return $response;
7889: }
7890:
1.777 albertel 7891: sub auto_validate_class_sec {
1.918 raeburn 7892: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 7893: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 7894: my $ownerlist;
7895: if (ref($owners) eq 'ARRAY') {
7896: $ownerlist = join(',',@{$owners});
7897: } else {
7898: $ownerlist = $owners;
7899: }
1.773 raeburn 7900: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 7901: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 7902: return $response;
7903: }
7904:
1.1248 raeburn 7905: sub auto_crsreq_update {
7906: my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1257 raeburn 7907: $code,$accessstart,$accessend,$inbound) = @_;
1.1248 raeburn 7908: my ($homeserver,%crsreqresponse);
7909: if ($cdom =~ /^$match_domain$/) {
7910: $homeserver = &domain($cdom,'primary');
7911: }
7912: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
7913: my $info;
7914: if (ref($inbound) eq 'HASH') {
7915: $info = &freeze_escape($inbound);
7916: }
7917: my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
7918: ':'.&escape($action).':'.&escape($ownername).':'.
7919: &escape($ownerdomain).':'.&escape($fullname).':'.
1.1257 raeburn 7920: &escape($title).':'.&escape($code).':'.
7921: &escape($accessstart).':'.&escape($accessend).':'.$info,
7922: $homeserver);
1.1248 raeburn 7923: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
7924: my @items = split(/&/,$response);
7925: foreach my $item (@items) {
7926: my ($key,$value) = split('=',$item);
7927: $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
7928: }
7929: }
7930: }
7931: return \%crsreqresponse;
7932: }
7933:
1.679 raeburn 7934: # ------------------------------------------------------- Course Group routines
7935:
7936: sub get_coursegroups {
1.809 raeburn 7937: my ($cdom,$cnum,$group,$namespace) = @_;
7938: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 7939: }
7940:
1.679 raeburn 7941: sub modify_coursegroup {
7942: my ($cdom,$cnum,$groupsettings) = @_;
7943: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
7944: }
7945:
1.809 raeburn 7946: sub toggle_coursegroup_status {
7947: my ($cdom,$cnum,$group,$action) = @_;
7948: my ($from_namespace,$to_namespace);
7949: if ($action eq 'delete') {
7950: $from_namespace = 'coursegroups';
7951: $to_namespace = 'deleted_groups';
7952: } else {
7953: $from_namespace = 'deleted_groups';
7954: $to_namespace = 'coursegroups';
7955: }
7956: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 7957: if (my $tmp = &error(%curr_group)) {
7958: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
7959: return ('read error',$tmp);
7960: } else {
7961: my %savedsettings = %curr_group;
1.809 raeburn 7962: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 7963: my $deloutcome;
7964: if ($result eq 'ok') {
1.809 raeburn 7965: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 7966: } else {
7967: return ('write error',$result);
7968: }
7969: if ($deloutcome eq 'ok') {
7970: return 'ok';
7971: } else {
7972: return ('delete error',$deloutcome);
7973: }
7974: }
7975: }
7976:
1.679 raeburn 7977: sub modify_group_roles {
1.957 raeburn 7978: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 7979: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
7980: my $role = 'gr/'.&escape($userprivs);
7981: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 7982: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 7983: if ($result eq 'ok') {
7984: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
7985: }
1.679 raeburn 7986: return $result;
7987: }
7988:
7989: sub modify_coursegroup_membership {
7990: my ($cdom,$cnum,$membership) = @_;
7991: my $result = &put('groupmembership',$membership,$cdom,$cnum);
7992: return $result;
7993: }
7994:
1.682 raeburn 7995: sub get_active_groups {
7996: my ($udom,$uname,$cdom,$cnum) = @_;
7997: my $now = time;
7998: my %groups = ();
7999: foreach my $key (keys(%env)) {
1.811 albertel 8000: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 8001: my ($start,$end) = split(/\./,$env{$key});
8002: if (($end!=0) && ($end<$now)) { next; }
8003: if (($start!=0) && ($start>$now)) { next; }
8004: if ($1 eq $cdom && $2 eq $cnum) {
8005: $groups{$3} = $env{$key} ;
8006: }
8007: }
8008: }
8009: return %groups;
8010: }
8011:
1.683 raeburn 8012: sub get_group_membership {
8013: my ($cdom,$cnum,$group) = @_;
8014: return(&dump('groupmembership',$cdom,$cnum,$group));
8015: }
8016:
8017: sub get_users_groups {
8018: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 8019: my @usersgroups;
1.683 raeburn 8020: my $cachetime=1800;
8021:
8022: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 8023: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
8024: if (defined($cached)) {
1.734 albertel 8025: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 8026: } else {
8027: $grouplist = '';
1.816 raeburn 8028: my $courseurl = &courseid_to_courseurl($courseid);
1.1166 raeburn 8029: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 8030: my $access_end = $env{'course.'.$courseid.
8031: '.default_enrollment_end_date'};
8032: my $now = time;
8033: foreach my $key (keys(%roleshash)) {
8034: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
8035: my $group = $1;
8036: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
8037: my $start = $2;
8038: my $end = $1;
8039: if ($start == -1) { next; } # deleted from group
8040: if (($start!=0) && ($start>$now)) { next; }
8041: if (($end!=0) && ($end<$now)) {
8042: if ($access_end && $access_end < $now) {
8043: if ($access_end - $end < 86400) {
8044: push(@usersgroups,$group);
1.733 raeburn 8045: }
8046: }
1.817 raeburn 8047: next;
1.733 raeburn 8048: }
1.817 raeburn 8049: push(@usersgroups,$group);
1.683 raeburn 8050: }
8051: }
8052: }
1.817 raeburn 8053: @usersgroups = &sort_course_groups($courseid,@usersgroups);
8054: $grouplist = join(':',@usersgroups);
8055: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 8056: }
1.733 raeburn 8057: return @usersgroups;
1.683 raeburn 8058: }
8059:
8060: sub devalidate_getgroups_cache {
8061: my ($udom,$uname,$cdom,$cnum)=@_;
8062: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 8063:
1.683 raeburn 8064: my $hashid="$udom:$uname:$courseid";
8065: &devalidate_cache_new('getgroups',$hashid);
8066: }
8067:
1.12 www 8068: # ------------------------------------------------------------------ Plain Text
8069:
8070: sub plaintext {
1.988 raeburn 8071: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 8072: if ($short =~ m{^cr/}) {
1.758 albertel 8073: return (split('/',$short))[-1];
8074: }
1.742 raeburn 8075: if (!defined($cid)) {
8076: $cid = $env{'request.course.id'};
8077: }
8078: my %rolenames = (
1.1008 raeburn 8079: Course => 'std',
8080: Community => 'alt1',
1.742 raeburn 8081: );
1.1037 raeburn 8082: if ($cid ne '') {
8083: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
8084: unless ($forcedefault) {
8085: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
8086: &Apache::lonlocal::mt_escape(\$roletext);
8087: return &Apache::lonlocal::mt($roletext);
8088: }
8089: }
8090: }
8091: if ((defined($type)) && (defined($rolenames{$type})) &&
8092: (defined($rolenames{$type})) &&
8093: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 8094: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 8095: } elsif ($cid ne '') {
8096: my $crstype = $env{'course.'.$cid.'.type'};
8097: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
8098: (defined($prp{$short}{$rolenames{$crstype}}))) {
8099: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
8100: }
1.742 raeburn 8101: }
1.1037 raeburn 8102: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 8103: }
8104:
8105: # ----------------------------------------------------------------- Assign Role
8106:
8107: sub assignrole {
1.957 raeburn 8108: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
8109: $context)=@_;
1.21 www 8110: my $mrole;
8111: if ($role =~ /^cr\//) {
1.393 www 8112: my $cwosec=$url;
1.811 albertel 8113: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 8114: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 8115: my $refused = 1;
8116: if ($context eq 'requestcourses') {
8117: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
8118: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
8119: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
8120: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8121: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8122: if ($crsenv{'internal.courseowner'} eq
8123: $env{'user.name'}.':'.$env{'user.domain'}) {
8124: $refused = '';
8125: }
8126: }
8127: }
8128: }
8129: }
8130: if ($refused) {
8131: &logthis('Refused custom assignrole: '.
8132: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
8133: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
8134: return 'refused';
8135: }
1.104 www 8136: }
1.21 www 8137: $mrole='cr';
1.678 raeburn 8138: } elsif ($role =~ /^gr\//) {
8139: my $cwogrp=$url;
1.811 albertel 8140: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 8141: unless (&allowed('mdg',$cwogrp)) {
8142: &logthis('Refused group assignrole: '.
8143: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
8144: $env{'user.name'}.' at '.$env{'user.domain'});
8145: return 'refused';
8146: }
8147: $mrole='gr';
1.21 www 8148: } else {
1.82 www 8149: my $cwosec=$url;
1.811 albertel 8150: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 8151: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
8152: my $refused;
8153: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
8154: if (!(&allowed('c'.$role,$url))) {
8155: $refused = 1;
8156: }
8157: } else {
8158: $refused = 1;
8159: }
1.947 raeburn 8160: if ($refused) {
1.1045 raeburn 8161: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8162: if (!$selfenroll && $context eq 'course') {
8163: my %crsenv;
8164: if ($role eq 'cc' || $role eq 'co') {
8165: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8166: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
8167: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
8168: if ($crsenv{'internal.courseowner'} eq
8169: $env{'user.name'}.':'.$env{'user.domain'}) {
8170: $refused = '';
8171: }
8172: }
8173: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
8174: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
8175: if ($crsenv{'internal.courseowner'} eq
8176: $env{'user.name'}.':'.$env{'user.domain'}) {
8177: $refused = '';
8178: }
8179: }
8180: }
8181: }
8182: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 8183: $refused = '';
1.1017 raeburn 8184: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 8185: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 8186: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 8187: my $wrongcc;
8188: if ($cnum =~ /^$match_community$/) {
8189: $wrongcc = 1 if ($role eq 'cc');
8190: } else {
8191: $wrongcc = 1 if ($role eq 'co');
8192: }
8193: unless ($wrongcc) {
8194: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8195: if ($crsenv{'internal.courseowner'} eq
8196: $env{'user.name'}.':'.$env{'user.domain'}) {
8197: $refused = '';
8198: }
1.1017 raeburn 8199: }
8200: }
1.1183 raeburn 8201: } elsif ($context eq 'requestauthor') {
8202: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
8203: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
8204: if ($env{'environment.requestauthor'} eq 'automatic') {
8205: $refused = '';
8206: } else {
8207: my %domdefaults = &get_domain_defaults($udom);
8208: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
8209: my $checkbystatus;
8210: if ($env{'user.adv'}) {
8211: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
8212: if ($disposition eq 'automatic') {
8213: $refused = '';
8214: } elsif ($disposition eq '') {
8215: $checkbystatus = 1;
8216: }
8217: } else {
8218: $checkbystatus = 1;
8219: }
8220: if ($checkbystatus) {
8221: if ($env{'environment.inststatus'}) {
8222: my @inststatuses = split(/,/,$env{'environment.inststatus'});
8223: foreach my $type (@inststatuses) {
8224: if (($type ne '') &&
8225: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
8226: $refused = '';
8227: }
8228: }
8229: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
8230: $refused = '';
8231: }
8232: }
8233: }
8234: }
8235: }
1.1017 raeburn 8236: }
8237: if ($refused) {
1.947 raeburn 8238: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
8239: ' '.$role.' '.$end.' '.$start.' by '.
8240: $env{'user.name'}.' at '.$env{'user.domain'});
8241: return 'refused';
8242: }
1.932 raeburn 8243: }
1.1131 raeburn 8244: } elsif ($role eq 'au') {
8245: if ($url ne '/'.$udom.'/') {
8246: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
8247: ' to assign author role for '.$uname.':'.$udom.
8248: ' in domain: '.$url.' refused (wrong domain).');
8249: return 'refused';
8250: }
1.104 www 8251: }
1.21 www 8252: $mrole=$role;
8253: }
1.620 albertel 8254: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 8255: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 8256: if ($end) { $command.='_'.$end; }
1.21 www 8257: if ($start) {
8258: if ($end) {
1.81 www 8259: $command.='_'.$start;
1.21 www 8260: } else {
1.81 www 8261: $command.='_0_'.$start;
1.21 www 8262: }
8263: }
1.739 raeburn 8264: my $origstart = $start;
8265: my $origend = $end;
1.957 raeburn 8266: my $delflag;
1.357 www 8267: # actually delete
8268: if ($deleteflag) {
1.373 www 8269: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 8270: # modify command to delete the role
1.620 albertel 8271: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 8272: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 8273: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 8274: # set start and finish to negative values for userrolelog
8275: $start=-1;
8276: $end=-1;
1.957 raeburn 8277: $delflag = 1;
1.357 www 8278: }
8279: }
8280: # send command
1.349 www 8281: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 8282: # log new user role if status is ok
1.349 www 8283: if ($answer eq 'ok') {
1.663 raeburn 8284: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.1184 raeburn 8285: if (($role eq 'cc') || ($role eq 'in') ||
8286: ($role eq 'ep') || ($role eq 'ad') ||
8287: ($role eq 'ta') || ($role eq 'st') ||
8288: ($role=~/^cr/) || ($role eq 'gr') ||
8289: ($role eq 'co')) {
1.1200 raeburn 8290: # for course roles, perform group memberships changes triggered by role change.
8291: unless ($role =~ /^gr/) {
8292: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
8293: $origstart,$selfenroll,$context);
8294: }
1.1184 raeburn 8295: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8296: $selfenroll,$context);
8297: } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
8298: ($role eq 'au') || ($role eq 'dc')) {
8299: &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8300: $context);
8301: } elsif (($role eq 'ca') || ($role eq 'aa')) {
8302: &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8303: $context);
8304: }
1.1053 raeburn 8305: if ($role eq 'cc') {
8306: &autoupdate_coowners($url,$end,$start,$uname,$udom);
8307: }
1.349 www 8308: }
8309: return $answer;
1.169 harris41 8310: }
8311:
1.1053 raeburn 8312: sub autoupdate_coowners {
8313: my ($url,$end,$start,$uname,$udom) = @_;
8314: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
8315: if (($cdom ne '') && ($cnum ne '')) {
8316: my $now = time;
8317: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
8318: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
8319: my %coursehash = &coursedescription($cdom.'_'.$cnum);
8320: my $instcode = $coursehash{'internal.coursecode'};
8321: if ($instcode ne '') {
1.1056 raeburn 8322: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
8323: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 8324: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 8325: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
8326: if ($result eq 'valid') {
8327: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 8328: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
8329: push(@newcoowners,$coowner);
8330: }
8331: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
8332: push(@newcoowners,$uname.':'.$udom);
8333: }
8334: @newcoowners = sort(@newcoowners);
8335: } else {
8336: push(@newcoowners,$uname.':'.$udom);
8337: }
8338: } else {
8339: if ($coursehash{'internal.co-owners'}) {
8340: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
8341: unless ($coowner eq $uname.':'.$udom) {
8342: push(@newcoowners,$coowner);
8343: }
8344: }
8345: unless (@newcoowners > 0) {
8346: $delcoowners = 1;
8347: $coowners = '';
8348: }
8349: }
8350: }
8351: if (@newcoowners || $delcoowners) {
8352: &store_coowners($cdom,$cnum,$coursehash{'home'},
8353: $delcoowners,@newcoowners);
8354: }
8355: }
8356: }
8357: }
8358: }
8359: }
8360: }
8361:
8362: sub store_coowners {
8363: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
8364: my $cid = $cdom.'_'.$cnum;
8365: my ($coowners,$delresult,$putresult);
8366: if (@newcoowners) {
8367: $coowners = join(',',@newcoowners);
8368: my %coownershash = (
8369: 'internal.co-owners' => $coowners,
8370: );
8371: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
8372: if ($putresult eq 'ok') {
8373: if ($env{'course.'.$cid.'.num'} eq $cnum) {
8374: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
8375: }
8376: }
8377: }
8378: if ($delcoowners) {
8379: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
8380: if ($delresult eq 'ok') {
8381: if ($env{'course.'.$cid.'.internal.co-owners'}) {
8382: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
8383: }
8384: }
8385: }
8386: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
8387: my %crsinfo =
8388: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
8389: if (ref($crsinfo{$cid}) eq 'HASH') {
8390: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
8391: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
8392: }
8393: }
8394: }
8395:
1.169 harris41 8396: # -------------------------------------------------- Modify user authentication
1.197 www 8397: # Overrides without validation
8398:
1.169 harris41 8399: sub modifyuserauth {
8400: my ($udom,$uname,$umode,$upass)=@_;
8401: my $uhome=&homeserver($uname,$udom);
1.197 www 8402: unless (&allowed('mau',$udom)) { return 'refused'; }
8403: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 8404: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
8405: ' in domain '.$env{'request.role.domain'});
1.169 harris41 8406: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
8407: &escape($upass),$uhome);
1.620 albertel 8408: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 8409: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
8410: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
8411: &log($udom,,$uname,$uhome,
1.620 albertel 8412: 'Authentication changed by '.$env{'user.domain'}.', '.
8413: $env{'user.name'}.', '.$umode.
1.197 www 8414: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 8415: unless ($reply eq 'ok') {
1.197 www 8416: &logthis('Authentication mode error: '.$reply);
1.169 harris41 8417: return 'error: '.$reply;
8418: }
1.170 harris41 8419: return 'ok';
1.80 www 8420: }
8421:
1.81 www 8422: # --------------------------------------------------------------- Modify a user
1.80 www 8423:
1.81 www 8424: sub modifyuser {
1.206 matthew 8425: my ($udom, $uname, $uid,
8426: $umode, $upass, $first,
8427: $middle, $last, $gene,
1.1058 raeburn 8428: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 8429: $udom= &LONCAPA::clean_domain($udom);
8430: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 8431: my $showcandelete = 'none';
8432: if (ref($candelete) eq 'ARRAY') {
8433: if (@{$candelete} > 0) {
8434: $showcandelete = join(', ',@{$candelete});
8435: }
8436: }
1.81 www 8437: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 8438: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 8439: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 8440: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
8441: ' desiredhome not specified').
1.620 albertel 8442: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
8443: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 8444: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 8445: my $newuser;
8446: if ($uhome eq 'no_host') {
8447: $newuser = 1;
8448: }
1.80 www 8449: # ----------------------------------------------------------------- Create User
1.406 albertel 8450: if (($uhome eq 'no_host') &&
8451: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 8452: my $unhome='';
1.844 albertel 8453: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 8454: $unhome = $desiredhome;
1.620 albertel 8455: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
8456: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 8457: } else { # load balancing routine for determining $unhome
1.81 www 8458: my $loadm=10000000;
1.841 albertel 8459: my %servers = &get_servers($udom,'library');
8460: foreach my $tryserver (keys(%servers)) {
8461: my $answer=reply('load',$tryserver);
8462: if (($answer=~/\d+/) && ($answer<$loadm)) {
8463: $loadm=$answer;
8464: $unhome=$tryserver;
8465: }
1.80 www 8466: }
8467: }
8468: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 8469: return 'error: unable to find a home server for '.$uname.
8470: ' in domain '.$udom;
1.80 www 8471: }
8472: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
8473: &escape($upass),$unhome);
8474: unless ($reply eq 'ok') {
8475: return 'error: '.$reply;
8476: }
1.230 stredwic 8477: $uhome=&homeserver($uname,$udom,'true');
1.80 www 8478: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 8479: return 'error: unable verify users home machine.';
1.80 www 8480: }
1.209 matthew 8481: } # End of creation of new user
1.80 www 8482: # ---------------------------------------------------------------------- Add ID
8483: if ($uid) {
8484: $uid=~tr/A-Z/a-z/;
8485: my %uidhash=&idrget($udom,$uname);
1.196 www 8486: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
8487: && (!$forceid)) {
1.80 www 8488: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 8489: return 'error: user id "'.$uid.'" does not match '.
8490: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 8491: }
8492: } else {
8493: &idput($udom,($uname => $uid));
8494: }
8495: }
8496: # -------------------------------------------------------------- Add names, etc
1.313 matthew 8497: my @tmp=&get('environment',
1.899 raeburn 8498: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 8499: 'permanentemail','inststatus'],
1.134 albertel 8500: $udom,$uname);
1.1075 raeburn 8501: my (%names,%oldnames);
1.313 matthew 8502: if ($tmp[0] =~ m/^error:.*/) {
8503: %names=();
8504: } else {
8505: %names = @tmp;
1.1075 raeburn 8506: %oldnames = %names;
1.313 matthew 8507: }
1.388 www 8508: #
1.1058 raeburn 8509: # If name, email and/or uid are blank (e.g., because an uploaded file
8510: # of users did not contain them), do not overwrite existing values
8511: # unless field is in $candelete array ref.
8512: #
8513:
8514: my @fields = ('firstname','middlename','lastname','generation',
8515: 'permanentemail','id');
8516: my %newvalues;
8517: if (ref($candelete) eq 'ARRAY') {
8518: foreach my $field (@fields) {
8519: if (grep(/^\Q$field\E$/,@{$candelete})) {
8520: if ($field eq 'firstname') {
8521: $names{$field} = $first;
8522: } elsif ($field eq 'middlename') {
8523: $names{$field} = $middle;
8524: } elsif ($field eq 'lastname') {
8525: $names{$field} = $last;
8526: } elsif ($field eq 'generation') {
8527: $names{$field} = $gene;
8528: } elsif ($field eq 'permanentemail') {
8529: $names{$field} = $email;
8530: } elsif ($field eq 'id') {
8531: $names{$field} = $uid;
8532: }
8533: }
8534: }
8535: }
1.388 www 8536: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 8537: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 8538: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 8539: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 8540: if ($email) {
8541: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 8542: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 8543: }
1.899 raeburn 8544: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 8545: if (defined($inststatus)) {
8546: $names{'inststatus'} = '';
8547: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
8548: if (ref($usertypes) eq 'HASH') {
8549: my @okstatuses;
8550: foreach my $item (split(/:/,$inststatus)) {
8551: if (defined($usertypes->{$item})) {
8552: push(@okstatuses,$item);
8553: }
8554: }
8555: if (@okstatuses) {
8556: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
8557: }
8558: }
8559: }
1.1075 raeburn 8560: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 8561: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 8562: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 8563: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
8564: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
8565: } else {
8566: $logmsg .= ' during self creation';
8567: }
1.1075 raeburn 8568: my $changed;
8569: if ($newuser) {
8570: $changed = 1;
8571: } else {
8572: foreach my $field (@fields) {
8573: if ($names{$field} ne $oldnames{$field}) {
8574: $changed = 1;
8575: last;
8576: }
8577: }
8578: }
8579: unless ($changed) {
8580: $logmsg = 'No changes in user information needed for: '.$logmsg;
8581: &logthis($logmsg);
8582: return 'ok';
8583: }
8584: my $reply = &put('environment', \%names, $udom,$uname);
8585: if ($reply ne 'ok') {
8586: return 'error: '.$reply;
8587: }
1.1087 raeburn 8588: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
8589: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
8590: }
1.1075 raeburn 8591: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
8592: &devalidate_cache_new('namescache',$uname.':'.$udom);
8593: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 8594: &logthis($logmsg);
1.134 albertel 8595: return 'ok';
1.80 www 8596: }
8597:
1.81 www 8598: # -------------------------------------------------------------- Modify student
1.80 www 8599:
1.81 www 8600: sub modifystudent {
8601: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 8602: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1216 raeburn 8603: $selfenroll,$context,$inststatus,$credits)=@_;
1.455 albertel 8604: if (!$cid) {
1.620 albertel 8605: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 8606: return 'not_in_class';
8607: }
1.80 www 8608: }
8609: # --------------------------------------------------------------- Make the user
1.81 www 8610: my $reply=&modifyuser
1.209 matthew 8611: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 8612: $desiredhome,$email,$inststatus);
1.80 www 8613: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 8614: # This will cause &modify_student_enrollment to get the uid from the
1.1235 raeburn 8615: # student's environment
1.297 matthew 8616: $uid = undef if (!$forceid);
1.455 albertel 8617: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1216 raeburn 8618: $gene,$usec,$end,$start,$type,$locktype,
8619: $cid,$selfenroll,$context,$credits);
1.297 matthew 8620: return $reply;
8621: }
8622:
8623: sub modify_student_enrollment {
1.1216 raeburn 8624: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
8625: $locktype,$cid,$selfenroll,$context,$credits) = @_;
1.455 albertel 8626: my ($cdom,$cnum,$chome);
8627: if (!$cid) {
1.620 albertel 8628: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 8629: return 'not_in_class';
8630: }
1.620 albertel 8631: $cdom=$env{'course.'.$cid.'.domain'};
8632: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 8633: } else {
8634: ($cdom,$cnum)=split(/_/,$cid);
8635: }
1.620 albertel 8636: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 8637: if (!$chome) {
1.457 raeburn 8638: $chome=&homeserver($cnum,$cdom);
1.297 matthew 8639: }
1.455 albertel 8640: if (!$chome) { return 'unknown_course'; }
1.297 matthew 8641: # Make sure the user exists
1.81 www 8642: my $uhome=&homeserver($uname,$udom);
8643: if (($uhome eq '') || ($uhome eq 'no_host')) {
8644: return 'error: no such user';
8645: }
1.297 matthew 8646: # Get student data if we were not given enough information
8647: if (!defined($first) || $first eq '' ||
8648: !defined($last) || $last eq '' ||
8649: !defined($uid) || $uid eq '' ||
8650: !defined($middle) || $middle eq '' ||
8651: !defined($gene) || $gene eq '') {
1.294 matthew 8652: # They did not supply us with enough data to enroll the student, so
8653: # we need to pick up more information.
1.297 matthew 8654: my %tmp = &get('environment',
1.294 matthew 8655: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 8656: ,$udom,$uname);
8657:
1.800 albertel 8658: #foreach my $key (keys(%tmp)) {
8659: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 8660: #}
1.294 matthew 8661: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
8662: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
8663: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 8664: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 8665: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
8666: }
1.556 albertel 8667: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148 raeburn 8668: my $user = "$uname:$udom";
8669: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487 albertel 8670: my $reply=cput('classlist',
1.1148 raeburn 8671: {$user =>
1.1216 raeburn 8672: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits) },
1.487 albertel 8673: $cdom,$cnum);
1.1148 raeburn 8674: if (($reply eq 'ok') || ($reply eq 'delayed')) {
8675: &devalidate_getsection_cache($udom,$uname,$cid);
8676: } else {
1.81 www 8677: return 'error: '.$reply;
8678: }
1.297 matthew 8679: # Add student role to user
1.83 www 8680: my $uurl='/'.$cid;
1.81 www 8681: $uurl=~s/\_/\//g;
8682: if ($usec) {
8683: $uurl.='/'.$usec;
8684: }
1.1148 raeburn 8685: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
8686: $selfenroll,$context);
8687: if ($result ne 'ok') {
8688: if ($old_entry{$user} ne '') {
8689: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
8690: } else {
8691: $reply = &del('classlist',[$user],$cdom,$cnum);
8692: }
8693: }
8694: return $result;
1.21 www 8695: }
8696:
1.556 albertel 8697: sub format_name {
8698: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
8699: my $name;
8700: if ($first ne 'lastname') {
8701: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
8702: } else {
8703: if ($lastname=~/\S/) {
8704: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
8705: $name=~s/\s+,/,/;
8706: } else {
8707: $name.= $firstname.' '.$middlename.' '.$generation;
8708: }
8709: }
8710: $name=~s/^\s+//;
8711: $name=~s/\s+$//;
8712: $name=~s/\s+/ /g;
8713: return $name;
8714: }
8715:
1.84 www 8716: # ------------------------------------------------- Write to course preferences
8717:
8718: sub writecoursepref {
8719: my ($courseid,%prefs)=@_;
8720: $courseid=~s/^\///;
8721: $courseid=~s/\_/\//g;
8722: my ($cdomain,$cnum)=split(/\//,$courseid);
8723: my $chome=homeserver($cnum,$cdomain);
8724: if (($chome eq '') || ($chome eq 'no_host')) {
8725: return 'error: no such course';
8726: }
8727: my $cstring='';
1.800 albertel 8728: foreach my $pref (keys(%prefs)) {
8729: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 8730: }
1.84 www 8731: $cstring=~s/\&$//;
8732: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
8733: }
8734:
8735: # ---------------------------------------------------------- Make/modify course
8736:
8737: sub createcourse {
1.741 raeburn 8738: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 8739: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 8740: $url=&declutter($url);
8741: my $cid='';
1.1028 raeburn 8742: if ($context eq 'requestcourses') {
8743: my $can_create = 0;
8744: my ($ownername,$ownerdom) = split(':',$course_owner);
8745: if ($udom eq $ownerdom) {
8746: if (&usertools_access($ownername,$ownerdom,$category,undef,
8747: $context)) {
8748: $can_create = 1;
8749: }
8750: } else {
8751: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
8752: $category);
8753: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
8754: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
8755: if (@curr > 0) {
8756: my @options = qw(approval validate autolimit);
8757: my $optregex = join('|',@options);
8758: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
8759: $can_create = 1;
8760: }
8761: }
8762: }
8763: }
8764: if ($can_create) {
8765: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
8766: unless (&allowed('ccc',$udom)) {
8767: return 'refused';
8768: }
1.1017 raeburn 8769: }
8770: } else {
8771: return 'refused';
8772: }
1.1028 raeburn 8773: } elsif (!&allowed('ccc',$udom)) {
8774: return 'refused';
1.84 www 8775: }
1.1011 raeburn 8776: # --------------------------------------------------------------- Get Unique ID
8777: my $uname;
8778: if ($cnum =~ /^$match_courseid$/) {
8779: my $chome=&homeserver($cnum,$udom,'true');
8780: if (($chome eq '') || ($chome eq 'no_host')) {
8781: $uname = $cnum;
8782: } else {
1.1038 raeburn 8783: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 8784: }
8785: } else {
1.1038 raeburn 8786: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 8787: }
8788: return $uname if ($uname =~ /^error/);
8789: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 8790: if (!defined($course_server)) {
8791: if (defined(&domain($udom,'primary'))) {
8792: $course_server = &domain($udom,'primary');
8793: } else {
8794: $course_server = $env{'user.home'};
8795: }
8796: }
8797: my %host_servers =
8798: &Apache::lonnet::get_servers($udom,'library');
8799: unless ($host_servers{$course_server}) {
8800: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 8801: }
1.84 www 8802: # ------------------------------------------------------------- Make the course
8803: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 8804: $course_server);
1.84 www 8805: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 8806: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 8807: if (($uhome eq '') || ($uhome eq 'no_host')) {
8808: return 'error: no such course';
8809: }
1.271 www 8810: # ----------------------------------------------------------------- Course made
1.516 raeburn 8811: # log existence
1.1029 raeburn 8812: my $now = time;
1.918 raeburn 8813: my $newcourse = {
8814: $udom.'_'.$uname => {
1.921 raeburn 8815: description => $description,
8816: inst_code => $inst_code,
8817: owner => $course_owner,
8818: type => $crstype,
1.1029 raeburn 8819: creator => $env{'user.name'}.':'.
8820: $env{'user.domain'},
8821: created => $now,
8822: context => $context,
1.918 raeburn 8823: },
8824: };
1.921 raeburn 8825: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 8826: # set toplevel url
1.271 www 8827: my $topurl=$url;
8828: unless ($nonstandard) {
8829: # ------------------------------------------ For standard courses, make top url
8830: my $mapurl=&clutter($url);
1.278 www 8831: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 8832: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 8833: <map>
8834: <resource id="1" type="start"></resource>
8835: <resource id="2" src="$mapurl"></resource>
8836: <resource id="3" type="finish"></resource>
8837: <link index="1" from="1" to="2"></link>
8838: <link index="2" from="2" to="3"></link>
8839: </map>
8840: ENDINITMAP
8841: $topurl=&declutter(
1.638 albertel 8842: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 8843: );
8844: }
8845: # ----------------------------------------------------------- Write preferences
1.84 www 8846: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 8847: ('description' => $description,
8848: 'url' => $topurl,
8849: 'internal.creator' => $env{'user.name'}.':'.
8850: $env{'user.domain'},
8851: 'internal.created' => $now,
8852: 'internal.creationcontext' => $context)
8853: );
1.84 www 8854: return '/'.$udom.'/'.$uname;
8855: }
8856:
1.1011 raeburn 8857: # ------------------------------------------------------------------- Create ID
8858: sub generate_coursenum {
1.1038 raeburn 8859: my ($udom,$crstype) = @_;
1.1011 raeburn 8860: my $domdesc = &domain($udom);
8861: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 8862: my $first;
8863: if ($crstype eq 'Community') {
8864: $first = '0';
8865: } else {
8866: $first = int(1+rand(9));
8867: }
8868: my $uname=$first.
1.1011 raeburn 8869: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
8870: substr($$.time,0,5).unpack("H8",pack("I32",time)).
8871: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
8872: # ----------------------------------------------- Make sure that does not exist
8873: my $uhome=&homeserver($uname,$udom,'true');
8874: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 8875: if ($crstype eq 'Community') {
8876: $first = '0';
8877: } else {
8878: $first = int(1+rand(9));
8879: }
8880: $uname=$first.
1.1011 raeburn 8881: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
8882: substr($$.time,0,5).unpack("H8",pack("I32",time)).
8883: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
8884: $uhome=&homeserver($uname,$udom,'true');
8885: unless (($uhome eq '') || ($uhome eq 'no_host')) {
8886: return 'error: unable to generate unique course-ID';
8887: }
8888: }
8889: return $uname;
8890: }
8891:
1.813 albertel 8892: sub is_course {
1.1167 droeschl 8893: my ($cdom, $cnum) = scalar(@_) == 1 ?
8894: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
8895:
8896: return unless $cdom and $cnum;
8897:
8898: my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
8899: '.');
8900:
1.1219 raeburn 8901: return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167 droeschl 8902: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813 albertel 8903: }
8904:
1.1015 raeburn 8905: sub store_userdata {
8906: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 8907: my $result;
1.1016 raeburn 8908: if ($datakey ne '') {
1.1013 raeburn 8909: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 8910: if ($udom eq '' || $uname eq '') {
8911: $udom = $env{'user.domain'};
8912: $uname = $env{'user.name'};
8913: }
8914: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 8915: if (($uhome eq '') || ($uhome eq 'no_host')) {
8916: $result = 'error: no_host';
8917: } else {
8918: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
8919: $storehash->{'host'} = $perlvar{'lonHostID'};
8920:
8921: my $namevalue='';
8922: foreach my $key (keys(%{$storehash})) {
8923: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
8924: }
8925: $namevalue=~s/\&$//;
1.1224 raeburn 8926: unless ($namespace eq 'courserequests') {
8927: $datakey = &escape($datakey);
8928: }
1.1105 raeburn 8929: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
8930: $namevalue,$uhome);
1.1013 raeburn 8931: }
8932: } else {
8933: $result = 'error: data to store was not a hash reference';
8934: }
8935: } else {
8936: $result= 'error: invalid requestkey';
8937: }
8938: return $result;
8939: }
8940:
1.21 www 8941: # ---------------------------------------------------------- Assign Custom Role
8942:
8943: sub assigncustomrole {
1.957 raeburn 8944: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 8945: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 8946: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 8947: }
8948:
8949: # ----------------------------------------------------------------- Revoke Role
8950:
8951: sub revokerole {
1.957 raeburn 8952: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 8953: my $now=time;
1.965 raeburn 8954: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 8955: }
8956:
8957: # ---------------------------------------------------------- Revoke Custom Role
8958:
8959: sub revokecustomrole {
1.957 raeburn 8960: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 8961: my $now=time;
1.357 www 8962: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 8963: $deleteflag,$selfenroll,$context);
1.17 www 8964: }
8965:
1.533 banghart 8966: # ------------------------------------------------------------ Disk usage
1.535 albertel 8967: sub diskusage {
1.955 raeburn 8968: my ($udom,$uname,$directorypath,$getpropath)=@_;
8969: $directorypath =~ s/\/$//;
8970: my $listing=&reply('du2:'.&escape($directorypath).':'
8971: .&escape($getpropath).':'.&escape($uname).':'
8972: .&escape($udom),homeserver($uname,$udom));
8973: if ($listing eq 'unknown_cmd') {
8974: if ($getpropath) {
8975: $directorypath = &propath($udom,$uname).'/'.$directorypath;
8976: }
8977: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
8978: }
1.514 albertel 8979: return $listing;
1.512 banghart 8980: }
8981:
1.566 banghart 8982: sub is_locked {
1.1096 raeburn 8983: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 8984: my @check;
8985: my $is_locked;
1.1093 raeburn 8986: push (@check,$file_name);
1.613 albertel 8987: my %locked = &get('file_permissions',\@check,
1.620 albertel 8988: $env{'user.domain'},$env{'user.name'});
1.615 albertel 8989: my ($tmp)=keys(%locked);
8990: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 8991:
1.566 banghart 8992: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 8993: $is_locked = 'false';
8994: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 8995: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 8996: $is_locked = 'true';
1.1096 raeburn 8997: if (ref($which) eq 'ARRAY') {
8998: push(@{$which},$entry);
8999: } else {
9000: last;
9001: }
1.745 raeburn 9002: }
9003: }
1.566 banghart 9004: } else {
9005: $is_locked = 'false';
9006: }
1.1093 raeburn 9007: return $is_locked;
1.566 banghart 9008: }
9009:
1.759 albertel 9010: sub declutter_portfile {
9011: my ($file) = @_;
1.833 albertel 9012: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 9013: return $file;
9014: }
9015:
1.559 banghart 9016: # ------------------------------------------------------------- Mark as Read Only
9017:
9018: sub mark_as_readonly {
9019: my ($domain,$user,$files,$what) = @_;
1.613 albertel 9020: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 9021: my ($tmp)=keys(%current_permissions);
9022: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 9023: foreach my $file (@{$files}) {
1.759 albertel 9024: $file = &declutter_portfile($file);
1.561 banghart 9025: push(@{$current_permissions{$file}},$what);
1.559 banghart 9026: }
1.613 albertel 9027: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 9028: return;
9029: }
9030:
1.572 banghart 9031: # ------------------------------------------------------------Save Selected Files
9032:
9033: sub save_selected_files {
9034: my ($user, $path, @files) = @_;
9035: my $filename = $user."savedfiles";
1.573 banghart 9036: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 9037: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 9038: foreach my $file (@files) {
1.620 albertel 9039: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 9040: }
9041: foreach my $file (@other_files) {
1.574 banghart 9042: print (OUT $file."\n");
1.572 banghart 9043: }
1.574 banghart 9044: close (OUT);
1.572 banghart 9045: return 'ok';
9046: }
9047:
1.574 banghart 9048: sub clear_selected_files {
9049: my ($user) = @_;
9050: my $filename = $user."savedfiles";
1.1117 foxr 9051: open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574 banghart 9052: print (OUT undef);
9053: close (OUT);
9054: return ("ok");
9055: }
9056:
1.572 banghart 9057: sub files_in_path {
9058: my ($user, $path) = @_;
9059: my $filename = $user."savedfiles";
9060: my %return_files;
1.1117 foxr 9061: open (IN, '<'.LONCAPA::tempdir().$filename);
1.573 banghart 9062: while (my $line_in = <IN>) {
1.574 banghart 9063: chomp ($line_in);
9064: my @paths_and_file = split (m!/!, $line_in);
9065: my $file_part = pop (@paths_and_file);
9066: my $path_part = join ('/', @paths_and_file);
1.573 banghart 9067: $path_part.='/';
9068: my $path_and_file = $path_part.$file_part;
9069: if ($path_part eq $path) {
9070: $return_files{$file_part}= 'selected';
9071: }
9072: }
1.574 banghart 9073: close (IN);
9074: return (\%return_files);
1.572 banghart 9075: }
9076:
9077: # called in portfolio select mode, to show files selected NOT in current directory
9078: sub files_not_in_path {
9079: my ($user, $path) = @_;
9080: my $filename = $user."savedfiles";
9081: my @return_files;
9082: my $path_part;
1.1117 foxr 9083: open(IN, '<'.LONCAPA::.$filename);
1.800 albertel 9084: while (my $line = <IN>) {
1.572 banghart 9085: #ok, I know it's clunky, but I want it to work
1.800 albertel 9086: my @paths_and_file = split(m|/|, $line);
9087: my $file_part = pop(@paths_and_file);
9088: chomp($file_part);
9089: my $path_part = join('/', @paths_and_file);
1.572 banghart 9090: $path_part .= '/';
9091: my $path_and_file = $path_part.$file_part;
9092: if ($path_part ne $path) {
1.800 albertel 9093: push(@return_files, ($path_and_file));
1.572 banghart 9094: }
9095: }
1.800 albertel 9096: close(OUT);
1.574 banghart 9097: return (@return_files);
1.572 banghart 9098: }
9099:
1.745 raeburn 9100: #----------------------------------------------Get portfolio file permissions
1.629 banghart 9101:
1.745 raeburn 9102: sub get_portfile_permissions {
9103: my ($domain,$user) = @_;
1.613 albertel 9104: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 9105: my ($tmp)=keys(%current_permissions);
9106: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 9107: return \%current_permissions;
9108: }
9109:
9110: #---------------------------------------------Get portfolio file access controls
9111:
1.749 raeburn 9112: sub get_access_controls {
1.745 raeburn 9113: my ($current_permissions,$group,$file) = @_;
1.769 albertel 9114: my %access;
9115: my $real_file = $file;
9116: $file =~ s/\.meta$//;
1.745 raeburn 9117: if (defined($file)) {
1.749 raeburn 9118: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
9119: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 9120: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 9121: }
9122: }
1.745 raeburn 9123: } else {
1.749 raeburn 9124: foreach my $key (keys(%{$current_permissions})) {
9125: if ($key =~ /\0accesscontrol$/) {
9126: if (defined($group)) {
9127: if ($key !~ m-^\Q$group\E/-) {
9128: next;
9129: }
9130: }
9131: my ($fullpath) = split(/\0/,$key);
9132: if (ref($$current_permissions{$key}) eq 'HASH') {
9133: foreach my $control (keys(%{$$current_permissions{$key}})) {
9134: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
9135: }
9136: }
9137: }
9138: }
9139: }
9140: return %access;
9141: }
9142:
9143: sub modify_access_controls {
9144: my ($file_name,$changes,$domain,$user)=@_;
9145: my ($outcome,$deloutcome);
9146: my %store_permissions;
9147: my %new_values;
9148: my %new_control;
9149: my %translation;
9150: my @deletions = ();
9151: my $now = time;
9152: if (exists($$changes{'activate'})) {
9153: if (ref($$changes{'activate'}) eq 'HASH') {
9154: my @newitems = sort(keys(%{$$changes{'activate'}}));
9155: my $numnew = scalar(@newitems);
9156: for (my $i=0; $i<$numnew; $i++) {
9157: my $newkey = $newitems[$i];
9158: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 9159: if ($newkey =~ /^\d+:/) {
9160: $newkey =~ s/^(\d+)/$newid/;
9161: $translation{$1} = $newid;
9162: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
9163: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
9164: $translation{$1} = $newid;
9165: }
1.749 raeburn 9166: $new_values{$file_name."\0".$newkey} =
9167: $$changes{'activate'}{$newitems[$i]};
9168: $new_control{$newkey} = $now;
9169: }
9170: }
9171: }
9172: my %todelete;
9173: my %changed_items;
9174: foreach my $action ('delete','update') {
9175: if (exists($$changes{$action})) {
9176: if (ref($$changes{$action}) eq 'HASH') {
9177: foreach my $key (keys(%{$$changes{$action}})) {
9178: my ($itemnum) = ($key =~ /^([^:]+):/);
9179: if ($action eq 'delete') {
9180: $todelete{$itemnum} = 1;
9181: } else {
9182: $changed_items{$itemnum} = $key;
9183: }
9184: }
1.745 raeburn 9185: }
9186: }
1.749 raeburn 9187: }
9188: # get lock on access controls for file.
9189: my $lockhash = {
9190: $file_name."\0".'locked_access_records' => $env{'user.name'}.
9191: ':'.$env{'user.domain'},
9192: };
9193: my $tries = 0;
9194: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9195:
9196: while (($gotlock ne 'ok') && $tries <3) {
9197: $tries ++;
9198: sleep 1;
9199: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9200: }
9201: if ($gotlock eq 'ok') {
9202: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
9203: my ($tmp)=keys(%curr_permissions);
9204: if ($tmp=~/^error:/) { undef(%curr_permissions); }
9205: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
9206: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
9207: if (ref($curr_controls) eq 'HASH') {
9208: foreach my $control_item (keys(%{$curr_controls})) {
9209: my ($itemnum) = ($control_item =~ /^([^:]+):/);
9210: if (defined($todelete{$itemnum})) {
9211: push(@deletions,$file_name."\0".$control_item);
9212: } else {
9213: if (defined($changed_items{$itemnum})) {
9214: $new_control{$changed_items{$itemnum}} = $now;
9215: push(@deletions,$file_name."\0".$control_item);
9216: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
9217: } else {
9218: $new_control{$control_item} = $$curr_controls{$control_item};
9219: }
9220: }
1.745 raeburn 9221: }
9222: }
9223: }
1.970 raeburn 9224: my ($group);
9225: if (&is_course($domain,$user)) {
9226: ($group,my $file) = split(/\//,$file_name,2);
9227: }
1.749 raeburn 9228: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
9229: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
9230: $outcome = &put('file_permissions',\%new_values,$domain,$user);
9231: # remove lock
9232: my @del_lock = ($file_name."\0".'locked_access_records');
9233: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 9234: my $sqlresult =
1.970 raeburn 9235: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 9236: $group);
1.749 raeburn 9237: } else {
9238: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 9239: }
1.749 raeburn 9240: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 9241: }
9242:
1.827 raeburn 9243: sub make_public_indefinitely {
9244: my ($requrl) = @_;
9245: my $now = time;
9246: my $action = 'activate';
9247: my $aclnum = 0;
9248: if (&is_portfolio_url($requrl)) {
9249: my (undef,$udom,$unum,$file_name,$group) =
9250: &parse_portfolio_url($requrl);
9251: my $current_perms = &get_portfile_permissions($udom,$unum);
9252: my %access_controls = &get_access_controls($current_perms,
9253: $group,$file_name);
9254: foreach my $key (keys(%{$access_controls{$file_name}})) {
9255: my ($num,$scope,$end,$start) =
9256: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
9257: if ($scope eq 'public') {
9258: if ($start <= $now && $end == 0) {
9259: $action = 'none';
9260: } else {
9261: $action = 'update';
9262: $aclnum = $num;
9263: }
9264: last;
9265: }
9266: }
9267: if ($action eq 'none') {
9268: return 'ok';
9269: } else {
9270: my %changes;
9271: my $newend = 0;
9272: my $newstart = $now;
9273: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
9274: $changes{$action}{$newkey} = {
9275: type => 'public',
9276: time => {
9277: start => $newstart,
9278: end => $newend,
9279: },
9280: };
9281: my ($outcome,$deloutcome,$new_values,$translation) =
9282: &modify_access_controls($file_name,\%changes,$udom,$unum);
9283: return $outcome;
9284: }
9285: } else {
9286: return 'invalid';
9287: }
9288: }
9289:
1.745 raeburn 9290: #------------------------------------------------------Get Marked as Read Only
9291:
9292: sub get_marked_as_readonly {
9293: my ($domain,$user,$what,$group) = @_;
9294: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 9295: my @readonly_files;
1.629 banghart 9296: my $cmp1=$what;
9297: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 9298: while (my ($file_name,$value) = each(%{$current_permissions})) {
9299: if (defined($group)) {
9300: if ($file_name !~ m-^\Q$group\E/-) {
9301: next;
9302: }
9303: }
1.561 banghart 9304: if (ref($value) eq "ARRAY"){
9305: foreach my $stored_what (@{$value}) {
1.629 banghart 9306: my $cmp2=$stored_what;
1.759 albertel 9307: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 9308: $cmp2=join('',@{$stored_what});
1.745 raeburn 9309: }
1.629 banghart 9310: if ($cmp1 eq $cmp2) {
1.561 banghart 9311: push(@readonly_files, $file_name);
1.745 raeburn 9312: last;
1.563 banghart 9313: } elsif (!defined($what)) {
9314: push(@readonly_files, $file_name);
1.745 raeburn 9315: last;
1.561 banghart 9316: }
9317: }
1.745 raeburn 9318: }
1.561 banghart 9319: }
9320: return @readonly_files;
9321: }
1.577 banghart 9322: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 9323:
1.577 banghart 9324: sub get_marked_as_readonly_hash {
1.745 raeburn 9325: my ($current_permissions,$group,$what) = @_;
1.577 banghart 9326: my %readonly_files;
1.745 raeburn 9327: while (my ($file_name,$value) = each(%{$current_permissions})) {
9328: if (defined($group)) {
9329: if ($file_name !~ m-^\Q$group\E/-) {
9330: next;
9331: }
9332: }
1.577 banghart 9333: if (ref($value) eq "ARRAY"){
9334: foreach my $stored_what (@{$value}) {
1.745 raeburn 9335: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 9336: foreach my $lock_descriptor(@{$stored_what}) {
9337: if ($lock_descriptor eq 'graded') {
9338: $readonly_files{$file_name} = 'graded';
9339: } elsif ($lock_descriptor eq 'handback') {
9340: $readonly_files{$file_name} = 'handback';
9341: } else {
9342: if (!exists($readonly_files{$file_name})) {
9343: $readonly_files{$file_name} = 'locked';
9344: }
9345: }
1.745 raeburn 9346: }
1.750 banghart 9347: }
1.577 banghart 9348: }
9349: }
9350: }
9351: return %readonly_files;
9352: }
1.559 banghart 9353: # ------------------------------------------------------------ Unmark as Read Only
9354:
9355: sub unmark_as_readonly {
1.629 banghart 9356: # unmarks $file_name (if $file_name is defined), or all files locked by $what
9357: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 9358: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 9359: $file_name = &declutter_portfile($file_name);
1.634 albertel 9360: my $symb_crs = $what;
9361: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 9362: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 9363: my ($tmp)=keys(%current_permissions);
9364: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 9365: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 9366: foreach my $file (@readonly_files) {
1.759 albertel 9367: my $clean_file = &declutter_portfile($file);
9368: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 9369: my $current_locks = $current_permissions{$file};
1.563 banghart 9370: my @new_locks;
9371: my @del_keys;
9372: if (ref($current_locks) eq "ARRAY"){
9373: foreach my $locker (@{$current_locks}) {
1.632 albertel 9374: my $compare=$locker;
1.749 raeburn 9375: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 9376: $compare=join('',@{$locker});
1.746 raeburn 9377: if ($compare ne $symb_crs) {
9378: push(@new_locks, $locker);
9379: }
1.563 banghart 9380: }
9381: }
1.650 albertel 9382: if (scalar(@new_locks) > 0) {
1.563 banghart 9383: $current_permissions{$file} = \@new_locks;
9384: } else {
9385: push(@del_keys, $file);
1.613 albertel 9386: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 9387: delete($current_permissions{$file});
1.563 banghart 9388: }
9389: }
1.561 banghart 9390: }
1.613 albertel 9391: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 9392: return;
9393: }
1.512 banghart 9394:
1.17 www 9395: # ------------------------------------------------------------ Directory lister
9396:
9397: sub dirlist {
1.955 raeburn 9398: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 9399: $uri=~s/^\///;
9400: $uri=~s/\/$//;
1.253 stredwic 9401: my ($udom, $uname);
1.955 raeburn 9402: if ($getuserdir) {
1.253 stredwic 9403: $udom = $userdomain;
9404: $uname = $username;
1.955 raeburn 9405: } else {
9406: (undef,$udom,$uname)=split(/\//,$uri);
9407: if(defined($userdomain)) {
9408: $udom = $userdomain;
9409: }
9410: if(defined($username)) {
9411: $uname = $username;
9412: }
1.253 stredwic 9413: }
1.955 raeburn 9414: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 9415:
1.955 raeburn 9416: $dirRoot = $perlvar{'lonDocRoot'};
9417: if (defined($getpropath)) {
9418: $dirRoot = &propath($udom,$uname);
1.253 stredwic 9419: $dirRoot =~ s/\/$//;
1.955 raeburn 9420: } elsif (defined($getuserdir)) {
9421: my $subdir=$uname.'__';
9422: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
9423: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
9424: ."/$udom/$subdir/$uname";
9425: } elsif (defined($alternateRoot)) {
9426: $dirRoot = $alternateRoot;
1.751 banghart 9427: }
1.253 stredwic 9428:
9429: if($udom) {
9430: if($uname) {
1.1135 raeburn 9431: my $uhome = &homeserver($uname,$udom);
1.1136 raeburn 9432: if ($uhome eq 'no_host') {
9433: return ([],'no_host');
9434: }
1.955 raeburn 9435: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 9436: .$getuserdir.':'.&escape($dirRoot)
1.1135 raeburn 9437: .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955 raeburn 9438: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 9439: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955 raeburn 9440: } else {
9441: @listing_results = map { &unescape($_); } split(/:/,$listing);
9442: }
1.605 matthew 9443: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 9444: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605 matthew 9445: @listing_results = split(/:/,$listing);
9446: } else {
9447: @listing_results = map { &unescape($_); } split(/:/,$listing);
9448: }
1.1135 raeburn 9449: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
1.1136 raeburn 9450: ($listing eq 'rejected') || ($listing eq 'refused') ||
9451: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
9452: return ([],$listing);
9453: } else {
9454: return (\@listing_results);
1.1135 raeburn 9455: }
1.955 raeburn 9456: } elsif(!$alternateRoot) {
1.1136 raeburn 9457: my (%allusers,%listerror);
1.841 albertel 9458: my %servers = &get_servers($udom,'library');
1.955 raeburn 9459: foreach my $tryserver (keys(%servers)) {
9460: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
9461: &escape($udom),$tryserver);
9462: if ($listing eq 'unknown_cmd') {
9463: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
9464: $udom, $tryserver);
9465: } else {
9466: @listing_results = map { &unescape($_); } split(/:/,$listing);
9467: }
1.841 albertel 9468: if ($listing eq 'unknown_cmd') {
9469: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
9470: $udom, $tryserver);
9471: @listing_results = split(/:/,$listing);
9472: } else {
9473: @listing_results =
9474: map { &unescape($_); } split(/:/,$listing);
9475: }
1.1136 raeburn 9476: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
9477: ($listing eq 'rejected') || ($listing eq 'refused') ||
9478: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
9479: $listerror{$tryserver} = $listing;
9480: } else {
1.841 albertel 9481: foreach my $line (@listing_results) {
9482: my ($entry) = split(/&/,$line,2);
9483: $allusers{$entry} = 1;
9484: }
9485: }
1.253 stredwic 9486: }
1.1136 raeburn 9487: my @alluserslist=();
1.800 albertel 9488: foreach my $user (sort(keys(%allusers))) {
1.1136 raeburn 9489: push(@alluserslist,$user.'&user');
1.253 stredwic 9490: }
1.1136 raeburn 9491: return (\@alluserslist);
1.253 stredwic 9492: } else {
1.1136 raeburn 9493: return ([],'missing username');
1.253 stredwic 9494: }
1.955 raeburn 9495: } elsif(!defined($getpropath)) {
1.1136 raeburn 9496: my $path = $perlvar{'lonDocRoot'}.'/res/';
9497: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
9498: return (\@all_domains);
1.955 raeburn 9499: } else {
1.1136 raeburn 9500: return ([],'missing domain');
1.275 stredwic 9501: }
9502: }
9503:
9504: # --------------------------------------------- GetFileTimestamp
9505: # This function utilizes dirlist and returns the date stamp for
9506: # when it was last modified. It will also return an error of -1
9507: # if an error occurs
9508:
9509: sub GetFileTimestamp {
1.955 raeburn 9510: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 9511: $studentDomain = &LONCAPA::clean_domain($studentDomain);
9512: $studentName = &LONCAPA::clean_username($studentName);
1.1136 raeburn 9513: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
9514: undef,$getuserdir);
9515: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
9516: return -1;
9517: }
9518: if (ref($fileref) eq 'ARRAY') {
9519: my @stats = split('&',$fileref->[0]);
1.375 matthew 9520: # @stats contains first the filename, then the stat output
9521: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 9522: } else {
9523: return -1;
1.253 stredwic 9524: }
1.26 www 9525: }
9526:
1.712 albertel 9527: sub stat_file {
9528: my ($uri) = @_;
1.787 albertel 9529: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 9530:
1.955 raeburn 9531: my ($udom,$uname,$file);
1.712 albertel 9532: if ($uri =~ m-^/(uploaded|editupload)/-) {
9533: ($udom,$uname,$file) =
1.811 albertel 9534: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 9535: $file = 'userfiles/'.$file;
9536: }
9537: if ($uri =~ m-^/res/-) {
9538: ($udom,$uname) =
1.807 albertel 9539: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 9540: $file = $uri;
9541: }
9542:
9543: if (!$udom || !$uname || !$file) {
9544: # unable to handle the uri
9545: return ();
9546: }
1.956 raeburn 9547: my $getpropath;
9548: if ($file =~ /^userfiles\//) {
9549: $getpropath = 1;
9550: }
1.1136 raeburn 9551: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
9552: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
9553: return ();
9554: } else {
9555: if (ref($listref) eq 'ARRAY') {
9556: my @stats = split('&',$listref->[0]);
9557: shift(@stats); #filename is first
9558: return @stats;
9559: }
1.712 albertel 9560: }
9561: return ();
9562: }
9563:
1.26 www 9564: # -------------------------------------------------------- Value of a Condition
9565:
1.713 albertel 9566: # gets the value of a specific preevaluated condition
9567: # stored in the string $env{user.state.<cid>}
9568: # or looks up a condition reference in the bighash and if if hasn't
9569: # already been evaluated recurses into docondval to get the value of
9570: # the condition, then memoizing it to
9571: # $env{user.state.<cid>.<condition>}
1.40 www 9572: sub directcondval {
9573: my $number=shift;
1.620 albertel 9574: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 9575: &Apache::lonuserstate::evalstate();
9576: }
1.713 albertel 9577: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
9578: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
9579: } elsif ($number =~ /^_/) {
9580: my $sub_condition;
9581: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
9582: &GDBM_READER(),0640)) {
9583: $sub_condition=$bighash{'conditions'.$number};
9584: untie(%bighash);
9585: }
9586: my $value = &docondval($sub_condition);
1.949 raeburn 9587: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 9588: return $value;
9589: }
1.620 albertel 9590: if ($env{'user.state.'.$env{'request.course.id'}}) {
9591: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 9592: } else {
9593: return 2;
9594: }
9595: }
9596:
1.713 albertel 9597: # get the collection of conditions for this resource
1.26 www 9598: sub condval {
9599: my $condidx=shift;
1.54 www 9600: my $allpathcond='';
1.713 albertel 9601: foreach my $cond (split(/\|/,$condidx)) {
9602: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
9603: $allpathcond.=
9604: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
9605: }
1.191 harris41 9606: }
1.54 www 9607: $allpathcond=~s/\|$//;
1.713 albertel 9608: return &docondval($allpathcond);
9609: }
9610:
9611: #evaluates an expression of conditions
9612: sub docondval {
9613: my ($allpathcond) = @_;
9614: my $result=0;
9615: if ($env{'request.course.id'}
9616: && defined($allpathcond)) {
9617: my $operand='|';
9618: my @stack;
9619: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
9620: if ($chunk eq '(') {
9621: push @stack,($operand,$result);
9622: } elsif ($chunk eq ')') {
9623: my $before=pop @stack;
9624: if (pop @stack eq '&') {
9625: $result=$result>$before?$before:$result;
9626: } else {
9627: $result=$result>$before?$result:$before;
9628: }
9629: } elsif (($chunk eq '&') || ($chunk eq '|')) {
9630: $operand=$chunk;
9631: } else {
9632: my $new=directcondval($chunk);
9633: if ($operand eq '&') {
9634: $result=$result>$new?$new:$result;
9635: } else {
9636: $result=$result>$new?$result:$new;
9637: }
9638: }
9639: }
1.26 www 9640: }
9641: return $result;
1.421 albertel 9642: }
9643:
9644: # ---------------------------------------------------- Devalidate courseresdata
9645:
9646: sub devalidatecourseresdata {
9647: my ($coursenum,$coursedomain)=@_;
9648: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 9649: &devalidate_cache_new('courseres',$hashid);
1.28 www 9650: }
9651:
1.763 www 9652:
1.200 www 9653: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 9654: #
9655: # Parameters:
9656: # $coursenum - Number of the course.
9657: # $coursedomain - Domain at which the course was created.
9658: # Returns:
9659: # A hash of the course parameters along (I think) with timestamps
9660: # and version info.
1.877 foxr 9661:
1.624 albertel 9662: sub get_courseresdata {
9663: my ($coursenum,$coursedomain)=@_;
1.200 www 9664: my $coursehom=&homeserver($coursenum,$coursedomain);
9665: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 9666: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 9667: my %dumpreply;
1.417 albertel 9668: unless (defined($cached)) {
1.624 albertel 9669: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 9670: $result=\%dumpreply;
1.251 albertel 9671: my ($tmp) = keys(%dumpreply);
9672: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 9673: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 9674: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
9675: return $tmp;
1.416 albertel 9676: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 9677: $result=undef;
1.599 albertel 9678: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 9679: }
9680: }
1.624 albertel 9681: return $result;
9682: }
9683:
1.633 albertel 9684: sub devalidateuserresdata {
9685: my ($uname,$udom)=@_;
9686: my $hashid="$udom:$uname";
9687: &devalidate_cache_new('userres',$hashid);
9688: }
9689:
1.624 albertel 9690: sub get_userresdata {
9691: my ($uname,$udom)=@_;
9692: #most student don\'t have any data set, check if there is some data
9693: if (&EXT_cache_status($udom,$uname)) { return undef; }
9694:
9695: my $hashid="$udom:$uname";
9696: my ($result,$cached)=&is_cached_new('userres',$hashid);
9697: if (!defined($cached)) {
9698: my %resourcedata=&dump('resourcedata',$udom,$uname);
9699: $result=\%resourcedata;
9700: &do_cache_new('userres',$hashid,$result,600);
9701: }
9702: my ($tmp)=keys(%$result);
9703: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
9704: return $result;
9705: }
9706: #error 2 occurs when the .db doesn't exist
9707: if ($tmp!~/error: 2 /) {
1.672 albertel 9708: &logthis("<font color=\"blue\">WARNING:".
1.624 albertel 9709: " Trying to get resource data for ".
9710: $uname." at ".$udom.": ".
9711: $tmp."</font>");
9712: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 9713: #&EXT_cache_set($udom,$uname);
9714: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 9715: undef($tmp); # not really an error so don't send it back
1.624 albertel 9716: }
9717: return $tmp;
9718: }
1.879 foxr 9719: #----------------------------------------------- resdata - return resource data
9720: # Purpose:
9721: # Return resource data for either users or for a course.
9722: # Parameters:
9723: # $name - Course/user name.
9724: # $domain - Name of the domain the user/course is registered on.
9725: # $type - Type of thing $name is (must be 'course' or 'user'
9726: # @which - Array of names of resources desired.
9727: # Returns:
9728: # The value of the first reasource in @which that is found in the
9729: # resource hash.
9730: # Exceptional Conditions:
9731: # If the $type passed in is not valid (not the string 'course' or
9732: # 'user', an undefined reference is returned.
9733: # If none of the resources are found, an undef is returned
1.624 albertel 9734: sub resdata {
9735: my ($name,$domain,$type,@which)=@_;
9736: my $result;
9737: if ($type eq 'course') {
9738: $result=&get_courseresdata($name,$domain);
9739: } elsif ($type eq 'user') {
9740: $result=&get_userresdata($name,$domain);
9741: }
9742: if (!ref($result)) { return $result; }
1.251 albertel 9743: foreach my $item (@which) {
1.927 albertel 9744: if (defined($result->{$item->[0]})) {
9745: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 9746: }
1.250 albertel 9747: }
1.291 albertel 9748: return undef;
1.200 www 9749: }
9750:
1.1236 raeburn 9751: sub get_numsuppfiles {
9752: my ($cnum,$cdom,$ignorecache)=@_;
9753: my $hashid=$cnum.':'.$cdom;
9754: my ($suppcount,$cached);
9755: unless ($ignorecache) {
9756: ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
9757: }
9758: unless (defined($cached)) {
9759: my $chome=&homeserver($cnum,$cdom);
9760: unless ($chome eq 'no_host') {
9761: ($suppcount,my $errors) = (0,0);
9762: my $suppmap = 'supplemental.sequence';
9763: ($suppcount,$errors) =
9764: &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
9765: }
9766: &do_cache_new('suppcount',$hashid,$suppcount,600);
9767: }
9768: return $suppcount;
9769: }
9770:
1.379 matthew 9771: #
9772: # EXT resource caching routines
9773: #
9774:
9775: sub clear_EXT_cache_status {
1.383 albertel 9776: &delenv('cache.EXT.');
1.379 matthew 9777: }
9778:
9779: sub EXT_cache_status {
9780: my ($target_domain,$target_user) = @_;
1.383 albertel 9781: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 9782: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 9783: # We know already the user has no data
9784: return 1;
9785: } else {
9786: return 0;
9787: }
9788: }
9789:
9790: sub EXT_cache_set {
9791: my ($target_domain,$target_user) = @_;
1.383 albertel 9792: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 9793: #&appenv({$cachename => time});
1.379 matthew 9794: }
9795:
1.28 www 9796: # --------------------------------------------------------- Value of a Variable
1.58 www 9797: sub EXT {
1.715 albertel 9798:
1.1228 raeburn 9799: my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68 www 9800: unless ($varname) { return ''; }
1.218 albertel 9801: #get real user name/domain, courseid and symb
9802: my $courseid;
1.359 albertel 9803: my $publicuser;
1.427 www 9804: if ($symbparm) {
9805: $symbparm=&get_symb_from_alias($symbparm);
9806: }
1.218 albertel 9807: if (!($uname && $udom)) {
1.790 albertel 9808: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 9809: if (!$symbparm) { $symbparm=$cursymb; }
9810: } else {
1.620 albertel 9811: $courseid=$env{'request.course.id'};
1.218 albertel 9812: }
1.48 www 9813: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
9814: my $rest;
1.320 albertel 9815: if (defined($therest[0])) {
1.48 www 9816: $rest=join('.',@therest);
9817: } else {
9818: $rest='';
9819: }
1.320 albertel 9820:
1.57 www 9821: my $qualifierrest=$qualifier;
9822: if ($rest) { $qualifierrest.='.'.$rest; }
9823: my $spacequalifierrest=$space;
9824: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 9825: if ($realm eq 'user') {
1.48 www 9826: # --------------------------------------------------------------- user.resource
9827: if ($space eq 'resource') {
1.651 albertel 9828: if ( (defined($Apache::lonhomework::parsing_a_problem)
9829: || defined($Apache::lonhomework::parsing_a_task))
9830: &&
1.744 albertel 9831: ($symbparm eq &symbread()) ) {
9832: # if we are in the middle of processing the resource the
9833: # get the value we are planning on committing
9834: if (defined($Apache::lonhomework::results{$qualifierrest})) {
9835: return $Apache::lonhomework::results{$qualifierrest};
9836: } else {
9837: return $Apache::lonhomework::history{$qualifierrest};
9838: }
1.335 albertel 9839: } else {
1.359 albertel 9840: my %restored;
1.620 albertel 9841: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 9842: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
9843: } else {
9844: %restored=&restore($symbparm,$courseid,$udom,$uname);
9845: }
1.335 albertel 9846: return $restored{$qualifierrest};
9847: }
1.48 www 9848: # ----------------------------------------------------------------- user.access
9849: } elsif ($space eq 'access') {
1.218 albertel 9850: # FIXME - not supporting calls for a specific user
1.48 www 9851: return &allowed($qualifier,$rest);
9852: # ------------------------------------------ user.preferences, user.environment
9853: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 9854: if (($uname eq $env{'user.name'}) &&
9855: ($udom eq $env{'user.domain'})) {
9856: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 9857: } else {
1.359 albertel 9858: my %returnhash;
9859: if (!$publicuser) {
9860: %returnhash=&userenvironment($udom,$uname,
9861: $qualifierrest);
9862: }
1.218 albertel 9863: return $returnhash{$qualifierrest};
9864: }
1.48 www 9865: # ----------------------------------------------------------------- user.course
9866: } elsif ($space eq 'course') {
1.218 albertel 9867: # FIXME - not supporting calls for a specific user
1.620 albertel 9868: return $env{join('.',('request.course',$qualifier))};
1.48 www 9869: # ------------------------------------------------------------------- user.role
9870: } elsif ($space eq 'role') {
1.218 albertel 9871: # FIXME - not supporting calls for a specific user
1.620 albertel 9872: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 9873: if ($qualifier eq 'value') {
9874: return $role;
9875: } elsif ($qualifier eq 'extent') {
9876: return $where;
9877: }
9878: # ----------------------------------------------------------------- user.domain
9879: } elsif ($space eq 'domain') {
1.218 albertel 9880: return $udom;
1.48 www 9881: # ------------------------------------------------------------------- user.name
9882: } elsif ($space eq 'name') {
1.218 albertel 9883: return $uname;
1.48 www 9884: # ---------------------------------------------------- Any other user namespace
1.29 www 9885: } else {
1.359 albertel 9886: my %reply;
9887: if (!$publicuser) {
9888: %reply=&get($space,[$qualifierrest],$udom,$uname);
9889: }
9890: return $reply{$qualifierrest};
1.48 www 9891: }
1.236 www 9892: } elsif ($realm eq 'query') {
9893: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 9894: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
9895: [$spacequalifierrest]);
1.620 albertel 9896: return $env{'form.'.$spacequalifierrest};
1.236 www 9897: } elsif ($realm eq 'request') {
1.48 www 9898: # ------------------------------------------------------------- request.browser
9899: if ($space eq 'browser') {
1.1145 bisitz 9900: return $env{'browser.'.$qualifier};
1.57 www 9901: # ------------------------------------------------------------ request.filename
9902: } else {
1.620 albertel 9903: return $env{'request.'.$spacequalifierrest};
1.29 www 9904: }
1.28 www 9905: } elsif ($realm eq 'course') {
1.48 www 9906: # ---------------------------------------------------------- course.description
1.620 albertel 9907: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 9908: } elsif ($realm eq 'resource') {
1.165 www 9909:
1.620 albertel 9910: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 9911: if (!$symbparm) { $symbparm=&symbread(); }
9912: }
1.693 albertel 9913:
1.1232 raeburn 9914: if ($qualifier eq '') {
9915: if ($space eq 'title') {
9916: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
9917: return &gettitle($symbparm);
9918: }
1.693 albertel 9919:
1.1232 raeburn 9920: if ($space eq 'map') {
9921: my ($map) = &decode_symb($symbparm);
9922: return &symbread($map);
9923: }
9924: if ($space eq 'maptitle') {
9925: my ($map) = &decode_symb($symbparm);
9926: return &gettitle($map);
9927: }
9928: if ($space eq 'filename') {
9929: if ($symbparm) {
9930: return &clutter((&decode_symb($symbparm))[2]);
9931: }
9932: return &hreflocation('',$env{'request.filename'});
1.905 albertel 9933: }
1.1232 raeburn 9934:
1.1233 raeburn 9935: if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
9936: if ($space eq 'visibleparts') {
9937: my $navmap = Apache::lonnavmaps::navmap->new();
9938: my $item;
9939: if (ref($navmap)) {
9940: my $res = $navmap->getBySymb($symbparm);
9941: my $parts = $res->parts();
9942: if (ref($parts) eq 'ARRAY') {
9943: $item = join(',',@{$parts});
9944: }
9945: undef($navmap);
1.1232 raeburn 9946: }
1.1233 raeburn 9947: return $item;
1.1232 raeburn 9948: }
9949: }
9950: }
1.693 albertel 9951:
9952: my ($section, $group, @groups);
1.593 albertel 9953: my ($courselevelm,$courselevel);
1.1228 raeburn 9954: if (($courseid eq '') && ($cid)) {
9955: $courseid = $cid;
9956: }
9957: if (($symbparm && $courseid) &&
9958: (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165 www 9959:
1.218 albertel 9960: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 9961:
1.60 www 9962: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 9963: my $symbp=$symbparm;
1.735 albertel 9964: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 9965:
9966: my $symbparm=$symbp.'.'.$spacequalifierrest;
9967: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
9968:
1.620 albertel 9969: if (($env{'user.name'} eq $uname) &&
9970: ($env{'user.domain'} eq $udom)) {
9971: $section=$env{'request.course.sec'};
1.733 raeburn 9972: @groups = split(/:/,$env{'request.course.groups'});
9973: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 9974: } else {
1.539 albertel 9975: if (! defined($usection)) {
1.551 albertel 9976: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 9977: } else {
9978: $section = $usection;
9979: }
1.733 raeburn 9980: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 9981: }
9982:
9983: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
9984: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
9985: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
9986:
1.593 albertel 9987: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 9988: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 9989: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 9990:
1.60 www 9991: # ----------------------------------------------------------- first, check user
1.624 albertel 9992:
9993: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 9994: ([$courselevelr,'resource'],
9995: [$courselevelm,'map' ],
9996: [$courselevel, 'course' ]));
1.931 albertel 9997: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 9998:
1.594 albertel 9999: # ------------------------------------------------ second, check some of course
1.684 raeburn 10000: my $coursereply;
1.691 raeburn 10001: if (@groups > 0) {
10002: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
10003: $mapparm,$spacequalifierrest);
1.927 albertel 10004: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 10005: }
1.96 www 10006:
1.684 raeburn 10007: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 10008: $env{'course.'.$courseid.'.domain'},
10009: 'course',
10010: ([$seclevelr, 'resource'],
10011: [$seclevelm, 'map' ],
10012: [$seclevel, 'course' ],
10013: [$courselevelr,'resource']));
10014: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 10015:
1.60 www 10016: # ------------------------------------------------------ third, check map parms
1.218 albertel 10017: my %parmhash=();
10018: my $thisparm='';
10019: if (tie(%parmhash,'GDBM_File',
1.620 albertel 10020: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 10021: &GDBM_READER(),0640)) {
1.218 albertel 10022: $thisparm=$parmhash{$symbparm};
10023: untie(%parmhash);
10024: }
1.927 albertel 10025: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 10026: }
1.594 albertel 10027: # ------------------------------------------ fourth, look in resource metadata
1.71 www 10028:
1.218 albertel 10029: $spacequalifierrest=~s/\./\_/;
1.282 albertel 10030: my $filename;
10031: if (!$symbparm) { $symbparm=&symbread(); }
10032: if ($symbparm) {
1.409 www 10033: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 10034: } else {
1.620 albertel 10035: $filename=$env{'request.filename'};
1.282 albertel 10036: }
10037: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 10038: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 10039: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 10040: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 10041:
1.927 albertel 10042: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 10043: if ($symbparm && defined($courseid) &&
1.620 albertel 10044: $courseid eq $env{'request.course.id'}) {
1.624 albertel 10045: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
10046: $env{'course.'.$courseid.'.domain'},
10047: 'course',
1.927 albertel 10048: ([$courselevelm,'map' ],
10049: [$courselevel, 'course']));
10050: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 10051: }
1.145 www 10052: # ------------------------------------------------------------------ Cascade up
1.218 albertel 10053: unless ($space eq '0') {
1.336 albertel 10054: my @parts=split(/_/,$space);
10055: my $id=pop(@parts);
10056: my $part=join('_',@parts);
10057: if ($part eq '') { $part='0'; }
1.927 albertel 10058: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 10059: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 10060: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 10061: }
1.395 albertel 10062: if ($recurse) { return undef; }
10063: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 10064: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 10065: # ---------------------------------------------------- Any other user namespace
10066: } elsif ($realm eq 'environment') {
10067: # ----------------------------------------------------------------- environment
1.620 albertel 10068: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
10069: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 10070: } else {
1.770 albertel 10071: if ($uname eq 'anonymous' && $udom eq '') {
10072: return '';
10073: }
1.219 albertel 10074: my %returnhash=&userenvironment($udom,$uname,
10075: $spacequalifierrest);
10076: return $returnhash{$spacequalifierrest};
10077: }
1.28 www 10078: } elsif ($realm eq 'system') {
1.48 www 10079: # ----------------------------------------------------------------- system.time
10080: if ($space eq 'time') {
10081: return time;
10082: }
1.696 albertel 10083: } elsif ($realm eq 'server') {
10084: # ----------------------------------------------------------------- system.time
10085: if ($space eq 'name') {
10086: return $ENV{'SERVER_NAME'};
10087: }
1.28 www 10088: }
1.48 www 10089: return '';
1.61 www 10090: }
10091:
1.927 albertel 10092: sub get_reply {
10093: my ($reply_value) = @_;
1.940 raeburn 10094: if (ref($reply_value) eq 'ARRAY') {
10095: if (wantarray) {
10096: return @$reply_value;
10097: }
10098: return $reply_value->[0];
10099: } else {
10100: return $reply_value;
1.927 albertel 10101: }
10102: }
10103:
1.691 raeburn 10104: sub check_group_parms {
10105: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
10106: my @groupitems = ();
10107: my $resultitem;
1.927 albertel 10108: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 10109: foreach my $group (@{$groups}) {
10110: foreach my $level (@levels) {
1.927 albertel 10111: my $item = $courseid.'.['.$group.'].'.$level->[0];
10112: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 10113: }
10114: }
10115: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
10116: $env{'course.'.$courseid.'.domain'},
10117: 'course',@groupitems);
10118: return $coursereply;
10119: }
10120:
10121: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 10122: my ($courseid,@groups) = @_;
10123: @groups = sort(@groups);
1.691 raeburn 10124: return @groups;
10125: }
10126:
1.395 albertel 10127: sub packages_tab_default {
10128: my ($uri,$varname)=@_;
10129: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 10130:
10131: my (@extension,@specifics,$do_default);
10132: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 10133: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 10134: if ($pack_type eq 'default') {
10135: $do_default=1;
10136: } elsif ($pack_type eq 'extension') {
10137: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 10138: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 10139: # only look at packages defaults for packages that this id is
1.738 albertel 10140: push(@specifics,[$package,$pack_type,$pack_part]);
10141: }
10142: }
10143: # first look for a package that matches the requested part id
10144: foreach my $package (@specifics) {
10145: my (undef,$pack_type,$pack_part)=@{$package};
10146: next if ($pack_part ne $part);
10147: if (defined($packagetab{"$pack_type&$name&default"})) {
10148: return $packagetab{"$pack_type&$name&default"};
10149: }
10150: }
10151: # look for any possible matching non extension_ package
10152: foreach my $package (@specifics) {
10153: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 10154: if (defined($packagetab{"$pack_type&$name&default"})) {
10155: return $packagetab{"$pack_type&$name&default"};
10156: }
1.585 albertel 10157: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 10158: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
10159: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 10160: }
10161: }
1.738 albertel 10162: # look for any posible extension_ match
10163: foreach my $package (@extension) {
10164: my ($package,$pack_type)=@{$package};
10165: if (defined($packagetab{"$pack_type&$name&default"})) {
10166: return $packagetab{"$pack_type&$name&default"};
10167: }
10168: if (defined($packagetab{$package."&$name&default"})) {
10169: return $packagetab{$package."&$name&default"};
10170: }
10171: }
10172: # look for a global default setting
10173: if ($do_default && defined($packagetab{"default&$name&default"})) {
10174: return $packagetab{"default&$name&default"};
10175: }
1.395 albertel 10176: return undef;
10177: }
10178:
1.334 albertel 10179: sub add_prefix_and_part {
10180: my ($prefix,$part)=@_;
10181: my $keyroot;
10182: if (defined($prefix) && $prefix !~ /^__/) {
10183: # prefix that has a part already
10184: $keyroot=$prefix;
10185: } elsif (defined($prefix)) {
10186: # prefix that is missing a part
10187: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
10188: } else {
10189: # no prefix at all
10190: if (defined($part)) { $keyroot='_'.$part; }
10191: }
10192: return $keyroot;
10193: }
10194:
1.71 www 10195: # ---------------------------------------------------------------- Get metadata
10196:
1.599 albertel 10197: my %metaentry;
1.1070 www 10198: my %importedpartids;
1.71 www 10199: sub metadata {
1.176 www 10200: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 10201: $uri=&declutter($uri);
1.288 albertel 10202: # if it is a non metadata possible uri return quickly
1.529 albertel 10203: if (($uri eq '') ||
10204: (($uri =~ m|^/*adm/|) &&
1.1217 raeburn 10205: ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108 raeburn 10206: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 10207: return undef;
10208: }
1.1140 www 10209: if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/)
1.924 albertel 10210: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 10211: return undef;
1.288 albertel 10212: }
1.73 www 10213: my $filename=$uri;
10214: $uri=~s/\.meta$//;
1.172 www 10215: #
10216: # Is the metadata already cached?
1.177 www 10217: # Look at timestamp of caching
1.172 www 10218: # Everything is cached by the main uri, libraries are never directly cached
10219: #
1.428 albertel 10220: if (!defined($liburi)) {
1.599 albertel 10221: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 10222: if (defined($cached)) { return $result->{':'.$what}; }
10223: }
10224: {
1.1069 www 10225: # Imported parts would go here
1.1070 www 10226: my %importedids=();
10227: my @origfileimportpartids=();
1.1069 www 10228: my $importedparts=0;
1.172 www 10229: #
10230: # Is this a recursive call for a library?
10231: #
1.599 albertel 10232: # if (! exists($metacache{$uri})) {
10233: # $metacache{$uri}={};
10234: # }
1.924 albertel 10235: my $cachetime = 60*60;
1.171 www 10236: if ($liburi) {
10237: $liburi=&declutter($liburi);
10238: $filename=$liburi;
1.401 bowersj2 10239: } else {
1.599 albertel 10240: &devalidate_cache_new('meta',$uri);
10241: undef(%metaentry);
1.401 bowersj2 10242: }
1.140 www 10243: my %metathesekeys=();
1.73 www 10244: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 10245: my $metastring;
1.1140 www 10246: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929 albertel 10247: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 10248: $metastring =
1.929 albertel 10249: &Apache::lonnet::ssi_body($which,
1.924 albertel 10250: ('grade_target' => 'meta'));
10251: $cachetime = 1; # only want this cached in the child not long term
1.1108 raeburn 10252: } elsif (($uri !~ m -^(editupload)/-) &&
10253: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 10254: my $file=&filelocation('',&clutter($filename));
1.599 albertel 10255: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 10256: $metastring=&getfile($file);
1.489 albertel 10257: }
1.208 albertel 10258: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 10259: my $token;
1.140 www 10260: undef %metathesekeys;
1.71 www 10261: while ($token=$parser->get_token) {
1.339 albertel 10262: if ($token->[0] eq 'S') {
10263: if (defined($token->[2]->{'package'})) {
1.172 www 10264: #
10265: # This is a package - get package info
10266: #
1.339 albertel 10267: my $package=$token->[2]->{'package'};
10268: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10269: if (defined($token->[2]->{'id'})) {
10270: $keyroot.='_'.$token->[2]->{'id'};
10271: }
1.599 albertel 10272: if ($metaentry{':packages'}) {
10273: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 10274: } else {
1.599 albertel 10275: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 10276: }
1.736 albertel 10277: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 10278: my $part=$keyroot;
10279: $part=~s/^\_//;
1.736 albertel 10280: if ($pack_entry=~/^\Q$package\E\&/ ||
10281: $pack_entry=~/^\Q$package\E_0\&/) {
10282: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 10283: # ignore package.tab specified default values
10284: # here &package_tab_default() will fetch those
10285: if ($subp eq 'default') { next; }
1.736 albertel 10286: my $value=$packagetab{$pack_entry};
1.432 albertel 10287: my $unikey;
10288: if ($pack =~ /_0$/) {
10289: $unikey='parameter_0_'.$name;
10290: $part=0;
10291: } else {
10292: $unikey='parameter'.$keyroot.'_'.$name;
10293: }
1.339 albertel 10294: if ($subp eq 'display') {
10295: $value.=' [Part: '.$part.']';
10296: }
1.599 albertel 10297: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 10298: $metathesekeys{$unikey}=1;
1.599 albertel 10299: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10300: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 10301: }
1.599 albertel 10302: if (defined($metaentry{':'.$unikey.'.default'})) {
10303: $metaentry{':'.$unikey}=
10304: $metaentry{':'.$unikey.'.default'};
1.356 albertel 10305: }
1.339 albertel 10306: }
10307: }
10308: } else {
1.172 www 10309: #
10310: # This is not a package - some other kind of start tag
1.339 albertel 10311: #
10312: my $entry=$token->[1];
1.1068 www 10313: my $unikey='';
1.175 www 10314:
1.339 albertel 10315: if ($entry eq 'import') {
1.175 www 10316: #
10317: # Importing a library here
1.339 albertel 10318: #
1.1067 www 10319: my $location=$parser->get_text('/import');
10320: my $dir=$filename;
10321: $dir=~s|[^/]*$||;
10322: $location=&filelocation($dir,$location);
1.1069 www 10323:
1.1068 www 10324: my $importmode=$token->[2]->{'importmode'};
10325: if ($importmode eq 'problem') {
1.1069 www 10326: # Import as problem/response
1.1068 www 10327: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10328: } elsif ($importmode eq 'part') {
10329: # Import as part(s)
1.1069 www 10330: $importedparts=1;
10331: # We need to get the original file and the imported file to get the part order correct
10332: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
10333: # Load and inspect original file
1.1070 www 10334: if ($#origfileimportpartids<0) {
10335: undef(%importedpartids);
10336: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
10337: my $origfile=&getfile($origfilelocation);
10338: @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10339: }
10340:
1.1069 www 10341: # Load and inspect imported file
10342: my $impfile=&getfile($location);
10343: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10344: if ($#impfilepartids>=0) {
10345: # This problem had parts
1.1070 www 10346: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 10347: } else {
10348: # Importing by turning a single problem into a problem part
10349: # It gets the import-tags ID as part-ID
10350: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 10351: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 10352: }
1.1068 www 10353: } else {
10354: # Normal import
10355: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10356: if (defined($token->[2]->{'id'})) {
10357: $unikey.='_'.$token->[2]->{'id'};
10358: }
1.1067 www 10359: }
10360:
1.339 albertel 10361: if ($depthcount<20) {
1.736 albertel 10362: my $metadata =
10363: &metadata($uri,'keys', $location,$unikey,
10364: $depthcount+1);
10365: foreach my $meta (split(',',$metadata)) {
10366: $metaentry{':'.$meta}=$metaentry{':'.$meta};
10367: $metathesekeys{$meta}=1;
1.339 albertel 10368: }
1.1068 www 10369:
10370: }
1.1067 www 10371: } else {
10372: #
10373: # Not importing, some other kind of non-package, non-library start tag
10374: #
10375: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
10376: if (defined($token->[2]->{'id'})) {
10377: $unikey.='_'.$token->[2]->{'id'};
10378: }
1.339 albertel 10379: if (defined($token->[2]->{'name'})) {
10380: $unikey.='_'.$token->[2]->{'name'};
10381: }
10382: $metathesekeys{$unikey}=1;
1.736 albertel 10383: foreach my $param (@{$token->[3]}) {
10384: $metaentry{':'.$unikey.'.'.$param} =
10385: $token->[2]->{$param};
1.339 albertel 10386: }
10387: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 10388: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 10389: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
10390: # only ws inside the tag, and not in default, so use default
10391: # as value
1.599 albertel 10392: $metaentry{':'.$unikey}=$default;
1.908 albertel 10393: } elsif ( $internaltext =~ /\S/ ) {
10394: # something interesting inside the tag
10395: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 10396: } else {
1.908 albertel 10397: # no interesting values, don't set a default
1.339 albertel 10398: }
1.172 www 10399: # end of not-a-package not-a-library import
1.339 albertel 10400: }
1.172 www 10401: # end of not-a-package start tag
1.339 albertel 10402: }
1.172 www 10403: # the next is the end of "start tag"
1.339 albertel 10404: }
10405: }
1.483 albertel 10406: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 10407: $extension = lc($extension);
10408: if ($extension eq 'htm') { $extension='html'; }
10409:
1.737 albertel 10410: foreach my $key (keys(%packagetab)) {
1.483 albertel 10411: #no specific packages #how's our extension
10412: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 10413: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 10414: \%metathesekeys);
10415: }
1.883 albertel 10416:
10417: if (!exists($metaentry{':packages'})
10418: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 10419: foreach my $key (keys(%packagetab)) {
1.483 albertel 10420: #no specific packages well let's get default then
10421: if ($key!~/^default&/) { next; }
1.488 albertel 10422: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 10423: \%metathesekeys);
10424: }
10425: }
1.338 www 10426: # are there custom rights to evaluate
1.599 albertel 10427: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 10428:
1.338 www 10429: #
10430: # Importing a rights file here
1.339 albertel 10431: #
10432: unless ($depthcount) {
1.599 albertel 10433: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 10434: my $dir=$filename;
10435: $dir=~s|[^/]*$||;
10436: $location=&filelocation($dir,$location);
1.736 albertel 10437: my $rights_metadata =
10438: &metadata($uri,'keys',$location,'_rights',
10439: $depthcount+1);
10440: foreach my $rights (split(',',$rights_metadata)) {
10441: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
10442: $metathesekeys{$rights}=1;
1.339 albertel 10443: }
10444: }
10445: }
1.737 albertel 10446: # uniqifiy package listing
10447: my %seen;
10448: my @uniq_packages =
10449: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
10450: $metaentry{':packages'} = join(',',@uniq_packages);
10451:
1.1070 www 10452: if ($importedparts) {
10453: # We had imported parts and need to rebuild partorder
10454: $metaentry{':partorder'}='';
10455: $metathesekeys{'partorder'}=1;
10456: for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
10457: if ($origfileimportpartids[$index] eq 'part') {
10458: # original part, part of the problem
10459: $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
10460: } else {
10461: # we have imported parts at this position
10462: $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
10463: }
10464: }
10465: $metaentry{':partorder'}=~s/^\,//;
10466: }
10467:
1.737 albertel 10468: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 10469: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
10470: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924 albertel 10471: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 10472: # this is the end of "was not already recently cached
1.71 www 10473: }
1.599 albertel 10474: return $metaentry{':'.$what};
1.261 albertel 10475: }
10476:
1.488 albertel 10477: sub metadata_create_package_def {
1.483 albertel 10478: my ($uri,$key,$package,$metathesekeys)=@_;
10479: my ($pack,$name,$subp)=split(/\&/,$key);
10480: if ($subp eq 'default') { next; }
10481:
1.599 albertel 10482: if (defined($metaentry{':packages'})) {
10483: $metaentry{':packages'}.=','.$package;
1.483 albertel 10484: } else {
1.599 albertel 10485: $metaentry{':packages'}=$package;
1.483 albertel 10486: }
10487: my $value=$packagetab{$key};
10488: my $unikey;
10489: $unikey='parameter_0_'.$name;
1.599 albertel 10490: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 10491: $$metathesekeys{$unikey}=1;
1.599 albertel 10492: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10493: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 10494: }
1.599 albertel 10495: if (defined($metaentry{':'.$unikey.'.default'})) {
10496: $metaentry{':'.$unikey}=
10497: $metaentry{':'.$unikey.'.default'};
1.483 albertel 10498: }
10499: }
10500:
1.261 albertel 10501: sub metadata_generate_part0 {
10502: my ($metadata,$metacache,$uri) = @_;
10503: my %allnames;
1.737 albertel 10504: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 10505: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 10506: my $part=$$metacache{':'.$metakey.'.part'};
10507: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 10508: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 10509: $allnames{$name}=$part;
10510: }
10511: }
10512: }
10513: foreach my $name (keys(%allnames)) {
10514: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 10515: my $key=":parameter_0_$name";
1.261 albertel 10516: $$metacache{"$key.part"}='0';
10517: $$metacache{"$key.name"}=$name;
1.428 albertel 10518: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 10519: $allnames{$name}.'_'.$name.
10520: '.type'};
1.428 albertel 10521: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 10522: '.display'};
1.644 www 10523: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 10524: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 10525: $$metacache{"$key.display"}=$olddis;
10526: }
1.71 www 10527: }
10528:
1.764 albertel 10529: # ------------------------------------------------------ Devalidate title cache
10530:
10531: sub devalidate_title_cache {
10532: my ($url)=@_;
10533: if (!$env{'request.course.id'}) { return; }
10534: my $symb=&symbread($url);
10535: if (!$symb) { return; }
10536: my $key=$env{'request.course.id'}."\0".$symb;
10537: &devalidate_cache_new('title',$key);
10538: }
10539:
1.1014 droeschl 10540: # ------------------------------------------------- Get the title of a course
10541:
10542: sub current_course_title {
10543: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
10544: }
1.301 www 10545: # ------------------------------------------------- Get the title of a resource
10546:
10547: sub gettitle {
10548: my $urlsymb=shift;
10549: my $symb=&symbread($urlsymb);
1.534 albertel 10550: if ($symb) {
1.620 albertel 10551: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 10552: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 10553: if (defined($cached)) {
10554: return $result;
10555: }
1.534 albertel 10556: my ($map,$resid,$url)=&decode_symb($symb);
10557: my $title='';
1.907 albertel 10558: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
10559: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
10560: } else {
10561: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10562: &GDBM_READER(),0640)) {
10563: my $mapid=$bighash{'map_pc_'.&clutter($map)};
10564: $title=$bighash{'title_'.$mapid.'.'.$resid};
10565: untie(%bighash);
10566: }
1.534 albertel 10567: }
10568: $title=~s/\&colon\;/\:/gs;
10569: if ($title) {
1.1159 www 10570: # Remember both $symb and $title for dynamic metadata
10571: $accesshash{$symb.'___crstitle'}=$title;
1.1161 www 10572: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159 www 10573: # Cache this title and then return it
1.599 albertel 10574: return &do_cache_new('title',$key,$title,600);
1.534 albertel 10575: }
10576: $urlsymb=$url;
10577: }
10578: my $title=&metadata($urlsymb,'title');
10579: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
10580: return $title;
1.301 www 10581: }
1.613 albertel 10582:
1.614 albertel 10583: sub get_slot {
10584: my ($which,$cnum,$cdom)=@_;
10585: if (!$cnum || !$cdom) {
1.790 albertel 10586: (undef,my $courseid)=&whichuser();
1.620 albertel 10587: $cdom=$env{'course.'.$courseid.'.domain'};
10588: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 10589: }
1.703 albertel 10590: my $key=join("\0",'slots',$cdom,$cnum,$which);
10591: my %slotinfo;
10592: if (exists($remembered{$key})) {
10593: $slotinfo{$which} = $remembered{$key};
10594: } else {
10595: %slotinfo=&get('slots',[$which],$cdom,$cnum);
10596: &Apache::lonhomework::showhash(%slotinfo);
10597: my ($tmp)=keys(%slotinfo);
10598: if ($tmp=~/^error:/) { return (); }
10599: $remembered{$key} = $slotinfo{$which};
10600: }
1.616 albertel 10601: if (ref($slotinfo{$which}) eq 'HASH') {
10602: return %{$slotinfo{$which}};
10603: }
10604: return $slotinfo{$which};
1.614 albertel 10605: }
1.1150 raeburn 10606:
10607: sub get_reservable_slots {
10608: my ($cnum,$cdom,$uname,$udom) = @_;
10609: my $now = time;
10610: my $reservable_info;
10611: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
10612: if (exists($remembered{$key})) {
10613: $reservable_info = $remembered{$key};
10614: } else {
10615: my %resv;
10616: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
10617: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
10618: $reservable_info = \%resv;
10619: $remembered{$key} = $reservable_info;
10620: }
10621: return $reservable_info;
10622: }
10623:
10624: sub get_course_slots {
10625: my ($cnum,$cdom) = @_;
10626: my $hashid=$cnum.':'.$cdom;
10627: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
10628: if (defined($cached)) {
10629: if (ref($result) eq 'HASH') {
10630: return %{$result};
10631: }
10632: } else {
10633: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
10634: my ($tmp) = keys(%slots);
10635: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1219 raeburn 10636: &do_cache_new('allslots',$hashid,\%slots,600);
1.1150 raeburn 10637: return %slots;
10638: }
10639: }
10640: return;
10641: }
10642:
10643: sub devalidate_slots_cache {
10644: my ($cnum,$cdom)=@_;
10645: my $hashid=$cnum.':'.$cdom;
10646: &devalidate_cache_new('allslots',$hashid);
10647: }
10648:
1.1181 raeburn 10649: sub get_coursechange {
10650: my ($cdom,$cnum) = @_;
10651: if ($cdom eq '' || $cnum eq '') {
10652: return unless ($env{'request.course.id'});
10653: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10654: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10655: }
10656: my $hashid=$cdom.'_'.$cnum;
10657: my ($change,$cached)=&is_cached_new('crschange',$hashid);
10658: if ((defined($cached)) && ($change ne '')) {
10659: return $change;
10660: } else {
10661: my %crshash;
10662: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
10663: if ($crshash{'internal.contentchange'} eq '') {
10664: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
10665: if ($change eq '') {
10666: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
10667: $change = $crshash{'internal.created'};
10668: }
10669: } else {
10670: $change = $crshash{'internal.contentchange'};
10671: }
10672: my $cachetime = 600;
10673: &do_cache_new('crschange',$hashid,$change,$cachetime);
10674: }
10675: return $change;
10676: }
10677:
10678: sub devalidate_coursechange_cache {
10679: my ($cnum,$cdom)=@_;
10680: my $hashid=$cnum.':'.$cdom;
10681: &devalidate_cache_new('crschange',$hashid);
10682: }
10683:
1.31 www 10684: # ------------------------------------------------- Update symbolic store links
10685:
10686: sub symblist {
10687: my ($mapname,%newhash)=@_;
1.438 www 10688: $mapname=&deversion(&declutter($mapname));
1.31 www 10689: my %hash;
1.620 albertel 10690: if (($env{'request.course.fn'}) && (%newhash)) {
10691: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 10692: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 10693: foreach my $url (keys(%newhash)) {
1.711 albertel 10694: next if ($url eq 'last_known'
10695: && $env{'form.no_update_last_known'});
10696: $hash{declutter($url)}=&encode_symb($mapname,
10697: $newhash{$url}->[1],
10698: $newhash{$url}->[0]);
1.191 harris41 10699: }
1.31 www 10700: if (untie(%hash)) {
10701: return 'ok';
10702: }
10703: }
10704: }
10705: return 'error';
1.212 www 10706: }
10707:
10708: # --------------------------------------------------------------- Verify a symb
10709:
10710: sub symbverify {
1.1190 raeburn 10711: my ($symb,$thisurl,$encstate)=@_;
1.510 www 10712: my $thisfn=$thisurl;
1.439 www 10713: $thisfn=&declutter($thisfn);
1.215 www 10714: # direct jump to resource in page or to a sequence - will construct own symbs
10715: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
10716: # check URL part
1.409 www 10717: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 10718:
1.431 www 10719: unless ($url eq $thisfn) { return 0; }
1.213 www 10720:
1.216 www 10721: $symb=&symbclean($symb);
1.510 www 10722: $thisurl=&deversion($thisurl);
1.439 www 10723: $thisfn=&deversion($thisfn);
1.213 www 10724:
10725: my %bighash;
10726: my $okay=0;
1.431 www 10727:
1.620 albertel 10728: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 10729: &GDBM_READER(),0640)) {
1.1204 raeburn 10730: my $noclutter;
1.1032 raeburn 10731: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
10732: $thisurl =~ s/\?.+$//;
1.1204 raeburn 10733: if ($map =~ m{^uploaded/.+\.page$}) {
10734: $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
10735: $thisurl =~ s{^\Qhttp://https://\E}{https://};
10736: $noclutter = 1;
10737: }
10738: }
10739: my $ids;
10740: if ($noclutter) {
10741: $ids=$bighash{'ids_'.$thisurl};
10742: } else {
10743: $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032 raeburn 10744: }
1.1102 raeburn 10745: unless ($ids) {
10746: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
10747: $ids=$bighash{$idkey};
1.216 www 10748: }
10749: if ($ids) {
10750: # ------------------------------------------------------------------- Has ID(s)
1.1202 raeburn 10751: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
1.1203 raeburn 10752: $symb =~ s/\?.+$//;
1.1202 raeburn 10753: }
1.800 albertel 10754: foreach my $id (split(/\,/,$ids)) {
10755: my ($mapid,$resid)=split(/\./,$id);
1.216 www 10756: if (
10757: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190 raeburn 10758: eq $symb) {
10759: if (ref($encstate)) {
10760: $$encstate = $bighash{'encrypted_'.$id};
10761: }
1.620 albertel 10762: if (($env{'request.role.adv'}) ||
1.1101 raeburn 10763: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
10764: ($thisurl eq '/adm/navmaps')) {
1.1190 raeburn 10765: $okay=1;
1.1202 raeburn 10766: last;
1.582 albertel 10767: }
10768: }
1.216 www 10769: }
10770: }
1.213 www 10771: untie(%bighash);
10772: }
10773: return $okay;
1.31 www 10774: }
10775:
1.210 www 10776: # --------------------------------------------------------------- Clean-up symb
10777:
10778: sub symbclean {
10779: my $symb=shift;
1.568 albertel 10780: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 10781: # remove version from map
10782: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 10783:
1.210 www 10784: # remove version from URL
10785: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 10786:
1.507 www 10787: # remove wrapper
10788:
1.510 www 10789: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 10790: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 10791: return $symb;
1.409 www 10792: }
10793:
10794: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 10795:
10796: sub encode_symb {
10797: my ($map,$resid,$url)=@_;
10798: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
10799: }
1.409 www 10800:
10801: sub decode_symb {
1.568 albertel 10802: my $symb=shift;
10803: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
10804: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 10805: return (&fixversion($map),$resid,&fixversion($url));
10806: }
10807:
10808: sub fixversion {
10809: my $fn=shift;
1.609 banghart 10810: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 10811: my %bighash;
10812: my $uri=&clutter($fn);
1.620 albertel 10813: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 10814: # is this cached?
1.599 albertel 10815: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 10816: if (defined($cached)) { return $result; }
10817: # unfortunately not cached, or expired
1.620 albertel 10818: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 10819: &GDBM_READER(),0640)) {
10820: if ($bighash{'version_'.$uri}) {
10821: my $version=$bighash{'version_'.$uri};
1.444 www 10822: unless (($version eq 'mostrecent') ||
10823: ($version==&getversion($uri))) {
1.440 www 10824: $uri=~s/\.(\w+)$/\.$version\.$1/;
10825: }
10826: }
10827: untie %bighash;
1.413 www 10828: }
1.599 albertel 10829: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 10830: }
10831:
10832: sub deversion {
10833: my $url=shift;
10834: $url=~s/\.\d+\.(\w+)$/\.$1/;
10835: return $url;
1.210 www 10836: }
10837:
1.31 www 10838: # ------------------------------------------------------ Return symb list entry
10839:
10840: sub symbread {
1.249 www 10841: my ($thisfn,$donotrecurse)=@_;
1.1206 raeburn 10842: my $cache_str;
10843: if ($thisfn ne '') {
10844: $cache_str='request.symbread.cached.'.$thisfn;
10845: if ($env{$cache_str} ne '') {
1.1179 raeburn 10846: return $env{$cache_str};
10847: }
1.1206 raeburn 10848: } else {
1.242 www 10849: # no filename provided? try from environment
1.620 albertel 10850: if ($env{'request.symb'}) {
10851: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 10852: }
1.620 albertel 10853: $thisfn=$env{'request.filename'};
1.44 www 10854: }
1.569 albertel 10855: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 10856: # is that filename actually a symb? Verify, clean, and return
10857: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 10858: if (&symbverify($thisfn,$1)) {
1.620 albertel 10859: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 10860: }
1.242 www 10861: }
1.44 www 10862: $thisfn=declutter($thisfn);
1.31 www 10863: my %hash;
1.37 www 10864: my %bighash;
10865: my $syval='';
1.620 albertel 10866: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 10867: my $targetfn = $thisfn;
1.609 banghart 10868: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 10869: $targetfn = 'adm/wrapper/'.$thisfn;
10870: }
1.687 albertel 10871: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
10872: $targetfn=$1;
10873: }
1.620 albertel 10874: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 10875: &GDBM_READER(),0640)) {
1.481 raeburn 10876: $syval=$hash{$targetfn};
1.37 www 10877: untie(%hash);
10878: }
10879: # ---------------------------------------------------------- There was an entry
10880: if ($syval) {
1.601 albertel 10881: #unless ($syval=~/\_\d+$/) {
1.620 albertel 10882: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 10883: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 10884: #return $env{$cache_str}='';
1.601 albertel 10885: #}
10886: #$syval.=$1;
10887: #}
1.37 www 10888: } else {
10889: # ------------------------------------------------------- Was not in symb table
1.620 albertel 10890: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 10891: &GDBM_READER(),0640)) {
1.37 www 10892: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 10893: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 10894: unless ($ids) {
10895: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 10896: }
10897: unless ($ids) {
10898: # alias?
10899: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 10900: }
1.37 www 10901: if ($ids) {
10902: # ------------------------------------------------------------------- Has ID(s)
10903: my @possibilities=split(/\,/,$ids);
1.39 www 10904: if ($#possibilities==0) {
10905: # ----------------------------------------------- There is only one possibility
1.37 www 10906: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 10907: $syval=&encode_symb($bighash{'map_id_'.$mapid},
10908: $resid,$thisfn);
1.249 www 10909: } elsif (!$donotrecurse) {
1.39 www 10910: # ------------------------------------------ There is more than one possibility
10911: my $realpossible=0;
1.800 albertel 10912: foreach my $id (@possibilities) {
10913: my $file=$bighash{'src_'.$id};
1.39 www 10914: if (&allowed('bre',$file)) {
1.800 albertel 10915: my ($mapid,$resid)=split(/\./,$id);
1.39 www 10916: if ($bighash{'map_type_'.$mapid} ne 'page') {
10917: $realpossible++;
1.626 albertel 10918: $syval=&encode_symb($bighash{'map_id_'.$mapid},
10919: $resid,$thisfn);
1.39 www 10920: }
10921: }
1.191 harris41 10922: }
1.39 www 10923: if ($realpossible!=1) { $syval=''; }
1.249 www 10924: } else {
10925: $syval='';
1.37 www 10926: }
10927: }
10928: untie(%bighash)
1.481 raeburn 10929: }
1.31 www 10930: }
1.62 www 10931: if ($syval) {
1.620 albertel 10932: return $env{$cache_str}=$syval;
1.62 www 10933: }
1.31 www 10934: }
1.949 raeburn 10935: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 10936: return $env{$cache_str}='';
1.31 www 10937: }
10938:
10939: # ---------------------------------------------------------- Return random seed
10940:
1.32 www 10941: sub numval {
10942: my $txt=shift;
10943: $txt=~tr/A-J/0-9/;
10944: $txt=~tr/a-j/0-9/;
10945: $txt=~tr/K-T/0-9/;
10946: $txt=~tr/k-t/0-9/;
10947: $txt=~tr/U-Z/0-5/;
10948: $txt=~tr/u-z/0-5/;
10949: $txt=~s/\D//g;
1.564 albertel 10950: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 10951: return int($txt);
1.368 albertel 10952: }
10953:
1.484 albertel 10954: sub numval2 {
10955: my $txt=shift;
10956: $txt=~tr/A-J/0-9/;
10957: $txt=~tr/a-j/0-9/;
10958: $txt=~tr/K-T/0-9/;
10959: $txt=~tr/k-t/0-9/;
10960: $txt=~tr/U-Z/0-5/;
10961: $txt=~tr/u-z/0-5/;
10962: $txt=~s/\D//g;
10963: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10964: my $total;
10965: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 10966: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 10967: return int($total);
10968: }
10969:
1.575 albertel 10970: sub numval3 {
10971: use integer;
10972: my $txt=shift;
10973: $txt=~tr/A-J/0-9/;
10974: $txt=~tr/a-j/0-9/;
10975: $txt=~tr/K-T/0-9/;
10976: $txt=~tr/k-t/0-9/;
10977: $txt=~tr/U-Z/0-5/;
10978: $txt=~tr/u-z/0-5/;
10979: $txt=~s/\D//g;
10980: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10981: my $total;
10982: foreach my $val (@txts) { $total+=$val; }
10983: if ($_64bit) { $total=(($total<<32)>>32); }
10984: return $total;
10985: }
10986:
1.675 albertel 10987: sub digest {
10988: my ($data)=@_;
10989: my $digest=&Digest::MD5::md5($data);
10990: my ($a,$b,$c,$d)=unpack("iiii",$digest);
10991: my ($e,$f);
10992: {
10993: use integer;
10994: $e=($a+$b);
10995: $f=($c+$d);
10996: if ($_64bit) {
10997: $e=(($e<<32)>>32);
10998: $f=(($f<<32)>>32);
10999: }
11000: }
11001: if (wantarray) {
11002: return ($e,$f);
11003: } else {
11004: my $g;
11005: {
11006: use integer;
11007: $g=($e+$f);
11008: if ($_64bit) {
11009: $g=(($g<<32)>>32);
11010: }
11011: }
11012: return $g;
11013: }
11014: }
11015:
1.368 albertel 11016: sub latest_rnd_algorithm_id {
1.675 albertel 11017: return '64bit5';
1.366 albertel 11018: }
1.32 www 11019:
1.503 albertel 11020: sub get_rand_alg {
11021: my ($courseid)=@_;
1.790 albertel 11022: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 11023: if ($courseid) {
1.620 albertel 11024: return $env{"course.$courseid.rndseed"};
1.503 albertel 11025: }
11026: return &latest_rnd_algorithm_id();
11027: }
11028:
1.562 albertel 11029: sub validCODE {
11030: my ($CODE)=@_;
11031: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
11032: return 0;
11033: }
11034:
1.491 albertel 11035: sub getCODE {
1.620 albertel 11036: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 11037: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
11038: defined($Apache::lonhomework::parsing_a_task) ) &&
11039: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 11040: return $Apache::lonhomework::history{'resource.CODE'};
11041: }
11042: return undef;
11043: }
1.1133 foxr 11044: #
11045: # Determines the random seed for a specific context:
11046: #
11047: # parameters:
11048: # symb - in course context the symb for the seed.
11049: # course_id - The course id of the form domain_coursenum.
11050: # domain - Domain for the user.
11051: # course - Course for the user.
11052: # cenv - environment of the course.
11053: #
11054: # NOTE:
11055: # All parameters are picked out of the environment if missing
11056: # or not defined.
11057: # If a symb cannot be determined the current time is used instead.
11058: #
11059: # For a given well defined symb, courside, domain, username,
11060: # and course environment, the seed is reproducible.
11061: #
1.31 www 11062: sub rndseed {
1.1133 foxr 11063: my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790 albertel 11064: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 11065: if (!defined($symb)) {
1.366 albertel 11066: unless ($symb=$wsymb) { return time; }
11067: }
1.1146 foxr 11068: if (!defined $courseid) {
11069: $courseid=$wcourseid;
11070: }
11071: if (!defined $domain) { $domain=$wdomain; }
11072: if (!defined $username) { $username=$wusername }
1.1133 foxr 11073:
11074: my $which;
11075: if (defined($cenv->{'rndseed'})) {
11076: $which = $cenv->{'rndseed'};
11077: } else {
11078: $which =&get_rand_alg($courseid);
11079: }
1.491 albertel 11080: if (defined(&getCODE())) {
1.1133 foxr 11081:
1.675 albertel 11082: if ($which eq '64bit5') {
11083: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
11084: } elsif ($which eq '64bit4') {
1.575 albertel 11085: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
11086: } else {
11087: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
11088: }
1.675 albertel 11089: } elsif ($which eq '64bit5') {
11090: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 11091: } elsif ($which eq '64bit4') {
11092: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 11093: } elsif ($which eq '64bit3') {
11094: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 11095: } elsif ($which eq '64bit2') {
11096: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 11097: } elsif ($which eq '64bit') {
11098: return &rndseed_64bit($symb,$courseid,$domain,$username);
11099: }
11100: return &rndseed_32bit($symb,$courseid,$domain,$username);
11101: }
11102:
11103: sub rndseed_32bit {
11104: my ($symb,$courseid,$domain,$username)=@_;
11105: {
11106: use integer;
11107: my $symbchck=unpack("%32C*",$symb) << 27;
11108: my $symbseed=numval($symb) << 22;
11109: my $namechck=unpack("%32C*",$username) << 17;
11110: my $nameseed=numval($username) << 12;
11111: my $domainseed=unpack("%32C*",$domain) << 7;
11112: my $courseseed=unpack("%32C*",$courseid);
11113: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 11114: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11115: #&logthis("rndseed :$num:$symb");
1.564 albertel 11116: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 11117: return $num;
11118: }
11119: }
11120:
11121: sub rndseed_64bit {
11122: my ($symb,$courseid,$domain,$username)=@_;
11123: {
11124: use integer;
11125: my $symbchck=unpack("%32S*",$symb) << 21;
11126: my $symbseed=numval($symb) << 10;
11127: my $namechck=unpack("%32S*",$username);
11128:
11129: my $nameseed=numval($username) << 21;
11130: my $domainseed=unpack("%32S*",$domain) << 10;
11131: my $courseseed=unpack("%32S*",$courseid);
11132:
11133: my $num1=$symbchck+$symbseed+$namechck;
11134: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11135: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11136: #&logthis("rndseed :$num:$symb");
1.564 albertel 11137: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 11138: return "$num1,$num2";
1.155 albertel 11139: }
1.366 albertel 11140: }
11141:
1.443 albertel 11142: sub rndseed_64bit2 {
11143: my ($symb,$courseid,$domain,$username)=@_;
11144: {
11145: use integer;
11146: # strings need to be an even # of cahracters long, it it is odd the
11147: # last characters gets thrown away
11148: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11149: my $symbseed=numval($symb) << 10;
11150: my $namechck=unpack("%32S*",$username.' ');
11151:
11152: my $nameseed=numval($username) << 21;
1.501 albertel 11153: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11154: my $courseseed=unpack("%32S*",$courseid.' ');
11155:
11156: my $num1=$symbchck+$symbseed+$namechck;
11157: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11158: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11159: #&logthis("rndseed :$num:$symb");
1.803 albertel 11160: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 11161: return "$num1,$num2";
11162: }
11163: }
11164:
11165: sub rndseed_64bit3 {
11166: my ($symb,$courseid,$domain,$username)=@_;
11167: {
11168: use integer;
11169: # strings need to be an even # of cahracters long, it it is odd the
11170: # last characters gets thrown away
11171: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11172: my $symbseed=numval2($symb) << 10;
11173: my $namechck=unpack("%32S*",$username.' ');
11174:
11175: my $nameseed=numval2($username) << 21;
1.443 albertel 11176: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11177: my $courseseed=unpack("%32S*",$courseid.' ');
11178:
11179: my $num1=$symbchck+$symbseed+$namechck;
11180: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11181: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11182: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 11183: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 11184:
1.503 albertel 11185: return "$num1:$num2";
1.443 albertel 11186: }
11187: }
11188:
1.575 albertel 11189: sub rndseed_64bit4 {
11190: my ($symb,$courseid,$domain,$username)=@_;
11191: {
11192: use integer;
11193: # strings need to be an even # of cahracters long, it it is odd the
11194: # last characters gets thrown away
11195: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11196: my $symbseed=numval3($symb) << 10;
11197: my $namechck=unpack("%32S*",$username.' ');
11198:
11199: my $nameseed=numval3($username) << 21;
11200: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11201: my $courseseed=unpack("%32S*",$courseid.' ');
11202:
11203: my $num1=$symbchck+$symbseed+$namechck;
11204: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11205: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11206: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 11207: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 11208:
1.575 albertel 11209: return "$num1:$num2";
11210: }
11211: }
11212:
1.675 albertel 11213: sub rndseed_64bit5 {
11214: my ($symb,$courseid,$domain,$username)=@_;
11215: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
11216: return "$num1:$num2";
11217: }
11218:
1.366 albertel 11219: sub rndseed_CODE_64bit {
11220: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 11221: {
1.366 albertel 11222: use integer;
1.443 albertel 11223: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 11224: my $symbseed=numval2($symb);
1.491 albertel 11225: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11226: my $CODEseed=numval(&getCODE());
1.443 albertel 11227: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 11228: my $num1=$symbseed+$CODEchck;
11229: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 11230: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11231: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 11232: if ($_64bit) { $num1=(($num1<<32)>>32); }
11233: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 11234: return "$num1:$num2";
1.366 albertel 11235: }
11236: }
11237:
1.575 albertel 11238: sub rndseed_CODE_64bit4 {
11239: my ($symb,$courseid,$domain,$username)=@_;
11240: {
11241: use integer;
11242: my $symbchck=unpack("%32S*",$symb.' ') << 16;
11243: my $symbseed=numval3($symb);
11244: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11245: my $CODEseed=numval3(&getCODE());
11246: my $courseseed=unpack("%32S*",$courseid.' ');
11247: my $num1=$symbseed+$CODEchck;
11248: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 11249: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11250: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 11251: if ($_64bit) { $num1=(($num1<<32)>>32); }
11252: if ($_64bit) { $num2=(($num2<<32)>>32); }
11253: return "$num1:$num2";
11254: }
11255: }
11256:
1.675 albertel 11257: sub rndseed_CODE_64bit5 {
11258: my ($symb,$courseid,$domain,$username)=@_;
11259: my $code = &getCODE();
11260: my ($num1,$num2)=&digest("$symb,$courseid,$code");
11261: return "$num1:$num2";
11262: }
11263:
1.366 albertel 11264: sub setup_random_from_rndseed {
11265: my ($rndseed)=@_;
1.503 albertel 11266: if ($rndseed =~/([,:])/) {
11267: my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366 albertel 11268: &Math::Random::random_set_seed(abs($num1),abs($num2));
11269: } else {
11270: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 11271: }
1.36 albertel 11272: }
11273:
1.474 albertel 11274: sub latest_receipt_algorithm_id {
1.835 albertel 11275: return 'receipt3';
1.474 albertel 11276: }
11277:
1.480 www 11278: sub recunique {
11279: my $fucourseid=shift;
11280: my $unique;
1.835 albertel 11281: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
11282: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 11283: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 11284: } else {
11285: $unique=$perlvar{'lonReceipt'};
11286: }
11287: return unpack("%32C*",$unique);
11288: }
11289:
11290: sub recprefix {
11291: my $fucourseid=shift;
11292: my $prefix;
1.835 albertel 11293: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
11294: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 11295: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 11296: } else {
11297: $prefix=$perlvar{'lonHostID'};
11298: }
11299: return unpack("%32C*",$prefix);
11300: }
11301:
1.76 www 11302: sub ireceipt {
1.474 albertel 11303: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 11304:
11305: my $return =&recprefix($fucourseid).'-';
11306:
11307: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
11308: $env{'request.state'} eq 'construct') {
11309: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
11310: return $return;
11311: }
11312:
1.76 www 11313: my $cuname=unpack("%32C*",$funame);
11314: my $cudom=unpack("%32C*",$fudom);
11315: my $cucourseid=unpack("%32C*",$fucourseid);
11316: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 11317: my $cunique=&recunique($fucourseid);
1.474 albertel 11318: my $cpart=unpack("%32S*",$part);
1.835 albertel 11319: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
11320:
1.790 albertel 11321: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 11322:
11323: $return.= ($cunique%$cuname+
11324: $cunique%$cudom+
11325: $cusymb%$cuname+
11326: $cusymb%$cudom+
11327: $cucourseid%$cuname+
11328: $cucourseid%$cudom+
11329: $cpart%$cuname+
11330: $cpart%$cudom);
11331: } else {
11332: $return.= ($cunique%$cuname+
11333: $cunique%$cudom+
11334: $cusymb%$cuname+
11335: $cusymb%$cudom+
11336: $cucourseid%$cuname+
11337: $cucourseid%$cudom);
11338: }
11339: return $return;
1.76 www 11340: }
11341:
11342: sub receipt {
1.474 albertel 11343: my ($part)=@_;
1.790 albertel 11344: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 11345: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 11346: }
1.260 ng 11347:
1.790 albertel 11348: sub whichuser {
11349: my ($passedsymb)=@_;
11350: my ($symb,$courseid,$domain,$name,$publicuser);
11351: if (defined($env{'form.grade_symb'})) {
11352: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
11353: my $allowed=&allowed('vgr',$tmp_courseid);
11354: if (!$allowed &&
11355: exists($env{'request.course.sec'}) &&
11356: $env{'request.course.sec'} !~ /^\s*$/) {
11357: $allowed=&allowed('vgr',$tmp_courseid.
11358: '/'.$env{'request.course.sec'});
11359: }
11360: if ($allowed) {
11361: ($symb)=&get_env_multiple('form.grade_symb');
11362: $courseid=$tmp_courseid;
11363: ($domain)=&get_env_multiple('form.grade_domain');
11364: ($name)=&get_env_multiple('form.grade_username');
11365: return ($symb,$courseid,$domain,$name,$publicuser);
11366: }
11367: }
11368: if (!$passedsymb) {
11369: $symb=&symbread();
11370: } else {
11371: $symb=$passedsymb;
11372: }
11373: $courseid=$env{'request.course.id'};
11374: $domain=$env{'user.domain'};
11375: $name=$env{'user.name'};
11376: if ($name eq 'public' && $domain eq 'public') {
11377: if (!defined($env{'form.username'})) {
11378: $env{'form.username'}.=time.rand(10000000);
11379: }
11380: $name.=$env{'form.username'};
11381: }
11382: return ($symb,$courseid,$domain,$name,$publicuser);
11383:
11384: }
11385:
1.36 albertel 11386: # ------------------------------------------------------------ Serves up a file
1.472 albertel 11387: # returns either the contents of the file or
11388: # -1 if the file doesn't exist
1.481 raeburn 11389: #
11390: # if the target is a file that was uploaded via DOCS,
11391: # a check will be made to see if a current copy exists on the local server,
11392: # if it does this will be served, otherwise a copy will be retrieved from
11393: # the home server for the course and stored in /home/httpd/html/userfiles on
11394: # the local server.
1.472 albertel 11395:
1.36 albertel 11396: sub getfile {
1.538 albertel 11397: my ($file) = @_;
1.609 banghart 11398: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 11399: &repcopy($file);
11400: return &readfile($file);
11401: }
11402:
11403: sub repcopy_userfile {
11404: my ($file)=@_;
1.1142 raeburn 11405: my $londocroot = $perlvar{'lonDocRoot'};
11406: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164 raeburn 11407: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538 albertel 11408: my ($cdom,$cnum,$filename) =
1.811 albertel 11409: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 11410: my $uri="/uploaded/$cdom/$cnum/$filename";
11411: if (-e "$file") {
1.828 www 11412: # we already have a local copy, check it out
1.538 albertel 11413: my @fileinfo = stat($file);
1.828 www 11414: my $rtncode;
11415: my $info;
1.538 albertel 11416: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 11417: if ($lwpresp ne 'ok') {
1.828 www 11418: # there is no such file anymore, even though we had a local copy
1.482 albertel 11419: if ($rtncode eq '404') {
1.538 albertel 11420: unlink($file);
1.482 albertel 11421: }
11422: return -1;
11423: }
11424: if ($info < $fileinfo[9]) {
1.828 www 11425: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 11426: return 'ok';
1.828 www 11427: } else {
11428: # the file is outdated, get rid of it
11429: unlink($file);
1.482 albertel 11430: }
1.828 www 11431: }
11432: # one way or the other, at this point, we don't have the file
11433: # construct the correct path for the file
11434: my @parts = ($cdom,$cnum);
11435: if ($filename =~ m|^(.+)/[^/]+$|) {
11436: push @parts, split(/\//,$1);
11437: }
11438: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
11439: foreach my $part (@parts) {
11440: $path .= '/'.$part;
11441: if (!-e $path) {
11442: mkdir($path,0770);
1.482 albertel 11443: }
11444: }
1.828 www 11445: # now the path exists for sure
11446: # get a user agent
11447: my $ua=new LWP::UserAgent;
11448: my $transferfile=$file.'.in.transfer';
11449: # FIXME: this should flock
11450: if (-e $transferfile) { return 'ok'; }
11451: my $request;
11452: $uri=~s/^\///;
1.980 raeburn 11453: my $homeserver = &homeserver($cnum,$cdom);
11454: my $protocol = $protocol{$homeserver};
11455: $protocol = 'http' if ($protocol ne 'https');
11456: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 11457: my $response=$ua->request($request,$transferfile);
11458: # did it work?
11459: if ($response->is_error()) {
11460: unlink($transferfile);
11461: &logthis("Userfile repcopy failed for $uri");
11462: return -1;
11463: }
11464: # worked, rename the transfer file
11465: rename($transferfile,$file);
1.607 raeburn 11466: return 'ok';
1.481 raeburn 11467: }
11468:
1.517 albertel 11469: sub tokenwrapper {
11470: my $uri=shift;
1.980 raeburn 11471: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 11472: $uri=~s|^/||;
1.620 albertel 11473: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 11474: my $token=$1;
1.552 albertel 11475: my (undef,$udom,$uname,$file)=split('/',$uri,4);
11476: if ($udom && $uname && $file) {
11477: $file=~s|(\?\.*)*$||;
1.949 raeburn 11478: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 11479: my $homeserver = &homeserver($uname,$udom);
11480: my $protocol = $protocol{$homeserver};
11481: $protocol = 'http' if ($protocol ne 'https');
11482: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 11483: (($uri=~/\?/)?'&':'?').'token='.$token.
11484: '&tokenissued='.$perlvar{'lonHostID'};
11485: } else {
11486: return '/adm/notfound.html';
11487: }
11488: }
11489:
1.828 www 11490: # call with reqtype HEAD: get last modification time
11491: # call with reqtype GET: get the file contents
11492: # Do not call this with reqtype GET for large files! It loads everything into memory
11493: #
1.481 raeburn 11494: sub getuploaded {
11495: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
11496: $uri=~s/^\///;
1.980 raeburn 11497: my $homeserver = &homeserver($cnum,$cdom);
11498: my $protocol = $protocol{$homeserver};
11499: $protocol = 'http' if ($protocol ne 'https');
11500: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 11501: my $ua=new LWP::UserAgent;
11502: my $request=new HTTP::Request($reqtype,$uri);
11503: my $response=$ua->request($request);
11504: $$rtncode = $response->code;
1.482 albertel 11505: if (! $response->is_success()) {
11506: return 'failed';
11507: }
11508: if ($reqtype eq 'HEAD') {
1.486 www 11509: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 11510: } elsif ($reqtype eq 'GET') {
11511: $$info = $response->content;
1.472 albertel 11512: }
1.482 albertel 11513: return 'ok';
1.36 albertel 11514: }
11515:
1.481 raeburn 11516: sub readfile {
11517: my $file = shift;
11518: if ( (! -e $file ) || ($file eq '') ) { return -1; };
11519: my $fh;
11520: open($fh,"<$file");
11521: my $a='';
1.800 albertel 11522: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 11523: return $a;
11524: }
11525:
1.36 albertel 11526: sub filelocation {
1.590 banghart 11527: my ($dir,$file) = @_;
11528: my $location;
11529: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 11530:
11531: if ($file =~ m-^/adm/-) {
11532: $file=~s-^/adm/wrapper/-/-;
11533: $file=~s-^/adm/coursedocs/showdoc/-/-;
11534: }
1.882 albertel 11535:
1.1139 www 11536: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956 raeburn 11537: $location = $file;
1.609 banghart 11538: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 11539: my ($udom,$uname,$filename)=
1.811 albertel 11540: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 11541: my $home=&homeserver($uname,$udom);
11542: my $is_me=0;
11543: my @ids=¤t_machine_ids();
11544: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
11545: if ($is_me) {
1.1117 foxr 11546: $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 11547: } else {
11548: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
11549: $udom.'/'.$uname.'/'.$filename;
11550: }
1.882 albertel 11551: } elsif ($file =~ m-^/adm/-) {
11552: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 11553: } else {
11554: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139 www 11555: $file=~s:^/(res|priv)/:/:;
11556: my $space=$1;
1.590 banghart 11557: if ( !( $file =~ m:^/:) ) {
11558: $location = $dir. '/'.$file;
11559: } else {
1.1142 raeburn 11560: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590 banghart 11561: }
1.59 albertel 11562: }
1.590 banghart 11563: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 11564: while ($location=~m{/\.\./}) {
11565: if ($location =~ m{/[^/]+/\.\./}) {
11566: $location=~ s{/[^/]+/\.\./}{/}g;
11567: } else {
11568: $location=~ s{/\.\./}{/}g;
11569: }
11570: } #remove dir/..
1.590 banghart 11571: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
11572: return $location;
1.46 www 11573: }
1.36 albertel 11574:
1.46 www 11575: sub hreflocation {
11576: my ($dir,$file)=@_;
1.980 raeburn 11577: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 11578: $file=filelocation($dir,$file);
1.700 albertel 11579: } elsif ($file=~m-^/adm/-) {
11580: $file=~s-^/adm/wrapper/-/-;
11581: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 11582: }
11583: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
11584: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
11585: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143 raeburn 11586: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
11587: {/uploaded/$1/$2/}x;
1.46 www 11588: }
1.913 albertel 11589: if ($file=~ m{^/userfiles/}) {
11590: $file =~ s{^/userfiles/}{/uploaded/};
11591: }
1.462 albertel 11592: return $file;
1.465 albertel 11593: }
11594:
1.1139 www 11595:
11596:
11597:
11598:
1.465 albertel 11599: sub current_machine_domains {
1.853 albertel 11600: return &machine_domains(&hostname($perlvar{'lonHostID'}));
11601: }
11602:
11603: sub machine_domains {
11604: my ($hostname) = @_;
1.465 albertel 11605: my @domains;
1.838 albertel 11606: my %hostname = &all_hostnames();
1.465 albertel 11607: while( my($id, $name) = each(%hostname)) {
1.467 matthew 11608: # &logthis("-$id-$name-$hostname-");
1.465 albertel 11609: if ($hostname eq $name) {
1.844 albertel 11610: push(@domains,&host_domain($id));
1.465 albertel 11611: }
11612: }
11613: return @domains;
11614: }
11615:
11616: sub current_machine_ids {
1.853 albertel 11617: return &machine_ids(&hostname($perlvar{'lonHostID'}));
11618: }
11619:
11620: sub machine_ids {
11621: my ($hostname) = @_;
11622: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 11623: my @ids;
1.888 albertel 11624: my %name_to_host = &all_names();
1.889 albertel 11625: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
11626: return @{ $name_to_host{$hostname} };
11627: }
11628: return;
1.31 www 11629: }
11630:
1.824 raeburn 11631: sub additional_machine_domains {
11632: my @domains;
11633: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
11634: while( my $line = <$fh>) {
11635: $line =~ s/\s//g;
11636: push(@domains,$line);
11637: }
11638: return @domains;
11639: }
11640:
11641: sub default_login_domain {
11642: my $domain = $perlvar{'lonDefDomain'};
11643: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
11644: foreach my $posdom (¤t_machine_domains(),
11645: &additional_machine_domains()) {
11646: if (lc($posdom) eq lc($testdomain)) {
11647: $domain=$posdom;
11648: last;
11649: }
11650: }
11651: return $domain;
11652: }
11653:
1.31 www 11654: # ------------------------------------------------------------- Declutters URLs
11655:
11656: sub declutter {
11657: my $thisfn=shift;
1.569 albertel 11658: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479 albertel 11659: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31 www 11660: $thisfn=~s/^\///;
1.697 albertel 11661: $thisfn=~s|^adm/wrapper/||;
11662: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 11663: $thisfn=~s/^res\///;
1.1172 bisitz 11664: $thisfn=~s/^priv\///;
1.1032 raeburn 11665: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
11666: $thisfn=~s/\?.+$//;
11667: }
1.268 www 11668: return $thisfn;
11669: }
11670:
11671: # ------------------------------------------------------------- Clutter up URLs
11672:
11673: sub clutter {
11674: my $thisfn='/'.&declutter(shift);
1.887 albertel 11675: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 11676: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 11677: $thisfn='/res'.$thisfn;
11678: }
1.1031 raeburn 11679: if ($thisfn !~m|^/adm|) {
11680: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 11681: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 11682: } else {
11683: my ($ext) = ($thisfn =~ /\.(\w+)$/);
11684: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 11685: if ($embstyle eq 'ssi'
11686: || ($embstyle eq 'hdn')
11687: || ($embstyle eq 'rat')
11688: || ($embstyle eq 'prv')
11689: || ($embstyle eq 'ign')) {
11690: #do nothing with these
11691: } elsif (($embstyle eq 'img')
1.695 albertel 11692: || ($embstyle eq 'emb')
11693: || ($embstyle eq 'wrp')) {
11694: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 11695: } elsif ($embstyle eq 'unk'
11696: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 11697: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 11698: } else {
1.718 www 11699: # &logthis("Got a blank emb style");
1.695 albertel 11700: }
1.694 albertel 11701: }
11702: }
1.31 www 11703: return $thisfn;
1.12 www 11704: }
11705:
1.787 albertel 11706: sub clutter_with_no_wrapper {
11707: my $uri = &clutter(shift);
11708: if ($uri =~ m-^/adm/-) {
11709: $uri =~ s-^/adm/wrapper/-/-;
11710: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
11711: }
11712: return $uri;
11713: }
11714:
1.557 albertel 11715: sub freeze_escape {
11716: my ($value)=@_;
11717: if (ref($value)) {
11718: $value=&nfreeze($value);
11719: return '__FROZEN__'.&escape($value);
11720: }
11721: return &escape($value);
11722: }
11723:
1.11 www 11724:
1.557 albertel 11725: sub thaw_unescape {
11726: my ($value)=@_;
11727: if ($value =~ /^__FROZEN__/) {
11728: substr($value,0,10,undef);
11729: $value=&unescape($value);
11730: return &thaw($value);
11731: }
11732: return &unescape($value);
11733: }
11734:
1.436 albertel 11735: sub correct_line_ends {
11736: my ($result)=@_;
11737: $$result =~s/\r\n/\n/mg;
11738: $$result =~s/\r/\n/mg;
1.415 albertel 11739: }
1.1 albertel 11740: # ================================================================ Main Program
11741:
1.184 www 11742: sub goodbye {
1.204 albertel 11743: &logthis("Starting Shut down");
1.443 albertel 11744: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 11745: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 11746: #converted
1.599 albertel 11747: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 11748: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
11749: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
11750: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 11751: #1.1 only
1.870 albertel 11752: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
11753: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
11754: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
11755: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
11756: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 11757: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
11758: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 11759: &flushcourselogs();
11760: &logthis("Shutting down");
11761: }
11762:
1.852 albertel 11763: sub get_dns {
1.1210 raeburn 11764: my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869 albertel 11765: if (!$ignore_cache) {
11766: my ($content,$cached)=
11767: &Apache::lonnet::is_cached_new('dns',$url);
11768: if ($cached) {
1.1210 raeburn 11769: &$func($content,$hashref);
1.869 albertel 11770: return;
11771: }
11772: }
11773:
11774: my %alldns;
1.852 albertel 11775: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11776: foreach my $dns (<$config>) {
11777: next if ($dns !~ /^\^(\S*)/x);
1.979 raeburn 11778: my $line = $1;
11779: my ($host,$protocol) = split(/:/,$line);
11780: if ($protocol ne 'https') {
11781: $protocol = 'http';
11782: }
11783: $alldns{$host} = $protocol;
1.869 albertel 11784: }
11785: while (%alldns) {
11786: my ($dns) = keys(%alldns);
1.852 albertel 11787: my $ua=new LWP::UserAgent;
1.1134 raeburn 11788: $ua->timeout(30);
1.979 raeburn 11789: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 11790: my $response=$ua->request($request);
1.979 raeburn 11791: delete($alldns{$dns});
1.852 albertel 11792: next if ($response->is_error());
11793: my @content = split("\n",$response->content);
1.1210 raeburn 11794: unless ($nocache) {
1.1219 raeburn 11795: &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1210 raeburn 11796: }
11797: &$func(\@content,$hashref);
1.869 albertel 11798: return;
1.852 albertel 11799: }
11800: close($config);
1.871 albertel 11801: my $which = (split('/',$url))[3];
11802: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
11803: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 11804: my @content = <$config>;
1.1210 raeburn 11805: &$func(\@content,$hashref);
11806: return;
11807: }
11808:
11809: # ------------------------------------------------------Get DNS checksums file
1.1211 raeburn 11810: sub parse_dns_checksums_tab {
1.1210 raeburn 11811: my ($lines,$hashref) = @_;
11812: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
11813: my $loncaparev = &get_server_loncaparev($machine_dom);
11814: my ($release,$timestamp) = split(/\-/,$loncaparev);
11815: my (%chksum,%revnum);
11816: if (ref($lines) eq 'ARRAY') {
11817: chomp(@{$lines});
1.1238 raeburn 11818: my $version = shift(@{$lines});
11819: if ($version eq $release) {
1.1210 raeburn 11820: foreach my $line (@{$lines}) {
1.1238 raeburn 11821: my ($file,$version,$shasum) = split(/,/,$line);
11822: $chksum{$file} = $shasum;
11823: $revnum{$file} = $version;
1.1210 raeburn 11824: }
11825: if (ref($hashref) eq 'HASH') {
11826: %{$hashref} = (
11827: sums => \%chksum,
11828: versions => \%revnum,
11829: );
11830: }
11831: }
11832: }
1.869 albertel 11833: return;
1.852 albertel 11834: }
1.1210 raeburn 11835:
11836: sub fetch_dns_checksums {
1.1238 raeburn 11837: my %checksums;
11838: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
11839: my $loncaparev = &get_server_loncaparev($machine_dom);
11840: my ($release,$timestamp) = split(/\-/,$loncaparev);
11841: &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1211 raeburn 11842: \%checksums);
1.1210 raeburn 11843: return \%checksums;
11844: }
11845:
1.327 albertel 11846: # ------------------------------------------------------------ Read domain file
11847: {
1.852 albertel 11848: my $loaded;
1.846 albertel 11849: my %domain;
11850:
1.852 albertel 11851: sub parse_domain_tab {
11852: my ($lines) = @_;
11853: foreach my $line (@$lines) {
11854: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 11855:
1.846 albertel 11856: chomp($line);
1.852 albertel 11857: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 11858: my %this_domain;
11859: foreach my $field ('description', 'auth_def', 'auth_arg_def',
11860: 'lang_def', 'city', 'longi', 'lati',
11861: 'primary') {
11862: $this_domain{$field} = shift(@elements);
11863: }
11864: $domain{$name} = \%this_domain;
1.852 albertel 11865: }
11866: }
1.864 albertel 11867:
11868: sub reset_domain_info {
11869: undef($loaded);
11870: undef(%domain);
11871: }
11872:
1.852 albertel 11873: sub load_domain_tab {
1.869 albertel 11874: my ($ignore_cache) = @_;
11875: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852 albertel 11876: my $fh;
11877: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
11878: my @lines = <$fh>;
11879: &parse_domain_tab(\@lines);
1.448 albertel 11880: }
1.852 albertel 11881: close($fh);
11882: $loaded = 1;
1.327 albertel 11883: }
1.846 albertel 11884:
11885: sub domain {
1.852 albertel 11886: &load_domain_tab() if (!$loaded);
11887:
1.846 albertel 11888: my ($name,$what) = @_;
11889: return if ( !exists($domain{$name}) );
11890:
11891: if (!$what) {
11892: return $domain{$name}{'description'};
11893: }
11894: return $domain{$name}{$what};
11895: }
1.974 raeburn 11896:
11897: sub domain_info {
11898: &load_domain_tab() if (!$loaded);
11899: return %domain;
11900: }
11901:
1.327 albertel 11902: }
11903:
11904:
1.1 albertel 11905: # ------------------------------------------------------------- Read hosts file
11906: {
1.838 albertel 11907: my %hostname;
1.844 albertel 11908: my %hostdom;
1.845 albertel 11909: my %libserv;
1.852 albertel 11910: my $loaded;
1.888 albertel 11911: my %name_to_host;
1.1074 raeburn 11912: my %internetdom;
1.1107 raeburn 11913: my %LC_dns_serv;
1.852 albertel 11914:
11915: sub parse_hosts_tab {
11916: my ($file) = @_;
11917: foreach my $configline (@$file) {
11918: next if ($configline =~ /^(\#|\s*$ )/x);
1.1107 raeburn 11919: chomp($configline);
11920: if ($configline =~ /^\^/) {
11921: if ($configline =~ /^\^([\w.\-]+)/) {
11922: $LC_dns_serv{$1} = 1;
11923: }
11924: next;
11925: }
1.1074 raeburn 11926: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 11927: $name=~s/\s//g;
11928: if ($id && $domain && $role && $name) {
11929: $hostname{$id}=$name;
1.888 albertel 11930: push(@{$name_to_host{$name}}, $id);
1.852 albertel 11931: $hostdom{$id}=$domain;
11932: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 11933: if (defined($protocol)) {
11934: if ($protocol eq 'https') {
11935: $protocol{$id} = $protocol;
11936: } else {
11937: $protocol{$id} = 'http';
11938: }
1.968 raeburn 11939: } else {
1.969 raeburn 11940: $protocol{$id} = 'http';
1.968 raeburn 11941: }
1.1074 raeburn 11942: if (defined($intdom)) {
11943: $internetdom{$id} = $intdom;
11944: }
1.852 albertel 11945: }
11946: }
11947: }
1.864 albertel 11948:
11949: sub reset_hosts_info {
1.897 albertel 11950: &purge_remembered();
1.864 albertel 11951: &reset_domain_info();
11952: &reset_hosts_ip_info();
1.892 albertel 11953: undef(%name_to_host);
1.864 albertel 11954: undef(%hostname);
11955: undef(%hostdom);
11956: undef(%libserv);
11957: undef($loaded);
11958: }
1.1 albertel 11959:
1.852 albertel 11960: sub load_hosts_tab {
1.869 albertel 11961: my ($ignore_cache) = @_;
11962: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852 albertel 11963: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11964: my @config = <$config>;
11965: &parse_hosts_tab(\@config);
11966: close($config);
11967: $loaded=1;
1.1 albertel 11968: }
1.852 albertel 11969:
1.838 albertel 11970: sub hostname {
1.852 albertel 11971: &load_hosts_tab() if (!$loaded);
11972:
1.838 albertel 11973: my ($lonid) = @_;
11974: return $hostname{$lonid};
11975: }
1.845 albertel 11976:
1.838 albertel 11977: sub all_hostnames {
1.852 albertel 11978: &load_hosts_tab() if (!$loaded);
11979:
1.838 albertel 11980: return %hostname;
11981: }
1.845 albertel 11982:
1.888 albertel 11983: sub all_names {
11984: &load_hosts_tab() if (!$loaded);
11985:
11986: return %name_to_host;
11987: }
11988:
1.974 raeburn 11989: sub all_host_domain {
11990: &load_hosts_tab() if (!$loaded);
11991: return %hostdom;
11992: }
11993:
1.845 albertel 11994: sub is_library {
1.852 albertel 11995: &load_hosts_tab() if (!$loaded);
11996:
1.845 albertel 11997: return exists($libserv{$_[0]});
11998: }
11999:
12000: sub all_library {
1.852 albertel 12001: &load_hosts_tab() if (!$loaded);
12002:
1.845 albertel 12003: return %libserv;
12004: }
12005:
1.1062 droeschl 12006: sub unique_library {
12007: #2x reverse removes all hostnames that appear more than once
12008: my %unique = reverse &all_library();
12009: return reverse %unique;
12010: }
12011:
1.841 albertel 12012: sub get_servers {
1.852 albertel 12013: &load_hosts_tab() if (!$loaded);
12014:
1.841 albertel 12015: my ($domain,$type) = @_;
12016: my %possible_hosts = ($type eq 'library') ? %libserv
12017: : %hostname;
12018: my %result;
1.842 albertel 12019: if (ref($domain) eq 'ARRAY') {
12020: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 12021: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 12022: $result{$host} = $hostname;
12023: }
12024: }
12025: } else {
12026: while ( my ($host,$hostname) = each(%possible_hosts)) {
12027: if ($hostdom{$host} eq $domain) {
12028: $result{$host} = $hostname;
12029: }
1.841 albertel 12030: }
12031: }
12032: return %result;
12033: }
1.845 albertel 12034:
1.1062 droeschl 12035: sub get_unique_servers {
12036: my %unique = reverse &get_servers(@_);
12037: return reverse %unique;
12038: }
12039:
1.844 albertel 12040: sub host_domain {
1.852 albertel 12041: &load_hosts_tab() if (!$loaded);
12042:
1.844 albertel 12043: my ($lonid) = @_;
12044: return $hostdom{$lonid};
12045: }
12046:
1.841 albertel 12047: sub all_domains {
1.852 albertel 12048: &load_hosts_tab() if (!$loaded);
12049:
1.841 albertel 12050: my %seen;
12051: my @uniq = grep(!$seen{$_}++, values(%hostdom));
12052: return @uniq;
12053: }
1.1074 raeburn 12054:
12055: sub internet_dom {
12056: &load_hosts_tab() if (!$loaded);
12057:
12058: my ($lonid) = @_;
12059: return $internetdom{$lonid};
12060: }
1.1107 raeburn 12061:
12062: sub is_LC_dns {
12063: &load_hosts_tab() if (!$loaded);
12064:
12065: my ($hostname) = @_;
12066: return exists($LC_dns_serv{$hostname});
12067: }
12068:
1.1 albertel 12069: }
12070:
1.847 albertel 12071: {
12072: my %iphost;
1.856 albertel 12073: my %name_to_ip;
12074: my %lonid_to_ip;
1.869 albertel 12075:
1.847 albertel 12076: sub get_hosts_from_ip {
12077: my ($ip) = @_;
12078: my %iphosts = &get_iphost();
12079: if (ref($iphosts{$ip})) {
12080: return @{$iphosts{$ip}};
12081: }
12082: return;
1.839 albertel 12083: }
1.864 albertel 12084:
12085: sub reset_hosts_ip_info {
12086: undef(%iphost);
12087: undef(%name_to_ip);
12088: undef(%lonid_to_ip);
12089: }
1.856 albertel 12090:
12091: sub get_host_ip {
12092: my ($lonid) = @_;
12093: if (exists($lonid_to_ip{$lonid})) {
12094: return $lonid_to_ip{$lonid};
12095: }
12096: my $name=&hostname($lonid);
12097: my $ip = gethostbyname($name);
12098: return if (!$ip || length($ip) ne 4);
12099: $ip=inet_ntoa($ip);
12100: $name_to_ip{$name} = $ip;
12101: $lonid_to_ip{$lonid} = $ip;
12102: return $ip;
12103: }
1.847 albertel 12104:
12105: sub get_iphost {
1.869 albertel 12106: my ($ignore_cache) = @_;
1.894 albertel 12107:
1.869 albertel 12108: if (!$ignore_cache) {
12109: if (%iphost) {
12110: return %iphost;
12111: }
12112: my ($ip_info,$cached)=
12113: &Apache::lonnet::is_cached_new('iphost','iphost');
12114: if ($cached) {
12115: %iphost = %{$ip_info->[0]};
12116: %name_to_ip = %{$ip_info->[1]};
12117: %lonid_to_ip = %{$ip_info->[2]};
12118: return %iphost;
12119: }
12120: }
1.894 albertel 12121:
12122: # get yesterday's info for fallback
12123: my %old_name_to_ip;
12124: my ($ip_info,$cached)=
12125: &Apache::lonnet::is_cached_new('iphost','iphost');
12126: if ($cached) {
12127: %old_name_to_ip = %{$ip_info->[1]};
12128: }
12129:
1.888 albertel 12130: my %name_to_host = &all_names();
12131: foreach my $name (keys(%name_to_host)) {
1.847 albertel 12132: my $ip;
12133: if (!exists($name_to_ip{$name})) {
12134: $ip = gethostbyname($name);
12135: if (!$ip || length($ip) ne 4) {
1.894 albertel 12136: if (defined($old_name_to_ip{$name})) {
12137: $ip = $old_name_to_ip{$name};
12138: &logthis("Can't find $name defaulting to old $ip");
12139: } else {
12140: &logthis("Name $name no IP found");
12141: next;
12142: }
12143: } else {
12144: $ip=inet_ntoa($ip);
1.847 albertel 12145: }
12146: $name_to_ip{$name} = $ip;
12147: } else {
12148: $ip = $name_to_ip{$name};
1.653 albertel 12149: }
1.888 albertel 12150: foreach my $id (@{ $name_to_host{$name} }) {
12151: $lonid_to_ip{$id} = $ip;
12152: }
12153: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 12154: }
1.1219 raeburn 12155: &do_cache_new('iphost','iphost',
12156: [\%iphost,\%name_to_ip,\%lonid_to_ip],
12157: 48*60*60);
1.869 albertel 12158:
1.847 albertel 12159: return %iphost;
1.598 albertel 12160: }
12161:
1.992 raeburn 12162: #
12163: # Given a DNS returns the loncapa host name for that DNS
12164: #
12165: sub host_from_dns {
12166: my ($dns) = @_;
12167: my @hosts;
12168: my $ip;
12169:
1.993 raeburn 12170: if (exists($name_to_ip{$dns})) {
1.992 raeburn 12171: $ip = $name_to_ip{$dns};
12172: }
12173: if (!$ip) {
12174: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
12175: if (length($ip) == 4) {
12176: $ip = &IO::Socket::inet_ntoa($ip);
12177: }
12178: }
12179: if ($ip) {
12180: @hosts = get_hosts_from_ip($ip);
12181: return $hosts[0];
12182: }
12183: return undef;
1.986 foxr 12184: }
1.992 raeburn 12185:
1.1074 raeburn 12186: sub get_internet_names {
12187: my ($lonid) = @_;
12188: return if ($lonid eq '');
12189: my ($idnref,$cached)=
12190: &Apache::lonnet::is_cached_new('internetnames',$lonid);
12191: if ($cached) {
12192: return $idnref;
12193: }
12194: my $ip = &get_host_ip($lonid);
12195: my @hosts = &get_hosts_from_ip($ip);
12196: my %iphost = &get_iphost();
12197: my (@idns,%seen);
12198: foreach my $id (@hosts) {
12199: my $dom = &host_domain($id);
12200: my $prim_id = &domain($dom,'primary');
12201: my $prim_ip = &get_host_ip($prim_id);
12202: next if ($seen{$prim_ip});
12203: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
12204: foreach my $id (@{$iphost{$prim_ip}}) {
12205: my $intdom = &internet_dom($id);
12206: unless (grep(/^\Q$intdom\E$/,@idns)) {
12207: push(@idns,$intdom);
12208: }
12209: }
12210: }
12211: $seen{$prim_ip} = 1;
12212: }
1.1219 raeburn 12213: return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074 raeburn 12214: }
12215:
1.986 foxr 12216: }
12217:
1.1079 raeburn 12218: sub all_loncaparevs {
1.1249 raeburn 12219: 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 2.11);
1.1079 raeburn 12220: }
12221:
1.1227 raeburn 12222: # ---------------------------------------------------------- Read loncaparev table
12223: {
12224: sub load_loncaparevs {
12225: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
12226: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
12227: while (my $configline=<$config>) {
12228: chomp($configline);
12229: my ($hostid,$loncaparev)=split(/:/,$configline);
12230: $loncaparevs{$hostid}=$loncaparev;
12231: }
12232: close($config);
12233: }
12234: }
12235: }
12236: }
12237:
12238: # ---------------------------------------------------------- Read serverhostID table
12239: {
12240: sub load_serverhomeIDs {
12241: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
12242: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
12243: while (my $configline=<$config>) {
12244: chomp($configline);
12245: my ($name,$id)=split(/:/,$configline);
12246: $serverhomeIDs{$name}=$id;
12247: }
12248: close($config);
12249: }
12250: }
12251: }
12252: }
12253:
12254:
1.862 albertel 12255: BEGIN {
12256:
12257: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
12258: unless ($readit) {
12259: {
12260: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
12261: %perlvar = (%perlvar,%{$configvars});
12262: }
12263:
12264:
1.1 albertel 12265: # ------------------------------------------------------ Read spare server file
12266: {
1.448 albertel 12267: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 12268:
12269: while (my $configline=<$config>) {
12270: chomp($configline);
1.284 matthew 12271: if ($configline) {
1.784 albertel 12272: my ($host,$type) = split(':',$configline,2);
1.785 albertel 12273: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 12274: push(@{ $spareid{$type} }, $host);
1.1 albertel 12275: }
12276: }
1.448 albertel 12277: close($config);
1.1 albertel 12278: }
1.11 www 12279: # ------------------------------------------------------------ Read permissions
12280: {
1.448 albertel 12281: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 12282:
12283: while (my $configline=<$config>) {
1.448 albertel 12284: chomp($configline);
12285: if ($configline) {
12286: my ($role,$perm)=split(/ /,$configline);
12287: if ($perm ne '') { $pr{$role}=$perm; }
12288: }
1.11 www 12289: }
1.448 albertel 12290: close($config);
1.11 www 12291: }
12292:
12293: # -------------------------------------------- Read plain texts for permissions
12294: {
1.448 albertel 12295: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 12296:
12297: while (my $configline=<$config>) {
1.448 albertel 12298: chomp($configline);
12299: if ($configline) {
1.742 raeburn 12300: my ($short,@plain)=split(/:/,$configline);
12301: %{$prp{$short}} = ();
12302: if (@plain > 0) {
12303: $prp{$short}{'std'} = $plain[0];
12304: for (my $i=1; $i<@plain; $i++) {
12305: $prp{$short}{'alt'.$i} = $plain[$i];
12306: }
12307: }
1.448 albertel 12308: }
1.135 www 12309: }
1.448 albertel 12310: close($config);
1.135 www 12311: }
12312:
12313: # ---------------------------------------------------------- Read package table
12314: {
1.448 albertel 12315: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 12316:
12317: while (my $configline=<$config>) {
1.483 albertel 12318: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 12319: chomp($configline);
12320: my ($short,$plain)=split(/:/,$configline);
12321: my ($pack,$name)=split(/\&/,$short);
12322: if ($plain ne '') {
12323: $packagetab{$pack.'&'.$name.'&name'}=$name;
12324: $packagetab{$short}=$plain;
12325: }
1.11 www 12326: }
1.448 albertel 12327: close($config);
1.329 matthew 12328: }
12329:
1.1073 raeburn 12330: # ---------------------------------------------------------- Read loncaparev table
1.1227 raeburn 12331:
12332: &load_loncaparevs();
1.1073 raeburn 12333:
1.1074 raeburn 12334: # ---------------------------------------------------------- Read serverhostID table
12335:
1.1227 raeburn 12336: &load_serverhomeIDs();
12337:
12338: # ---------------------------------------------------------- Read releaseslist XML
1.1079 raeburn 12339: {
12340: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
12341: if (-e $file) {
12342: my $parser = HTML::LCParser->new($file);
12343: while (my $token = $parser->get_token()) {
12344: if ($token->[0] eq 'S') {
12345: my $item = $token->[1];
12346: my $name = $token->[2]{'name'};
12347: my $value = $token->[2]{'value'};
12348: if ($item ne '' && $name ne '' && $value ne '') {
12349: my $release = $parser->get_text();
12350: $release =~ s/(^\s*|\s*$ )//gx;
12351: $needsrelease{$item.':'.$name.':'.$value} = $release;
12352: }
12353: }
12354: }
12355: }
1.1073 raeburn 12356: }
12357:
1.1138 raeburn 12358: # ---------------------------------------------------------- Read managers table
12359: {
12360: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
12361: if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
12362: while (my $configline=<$config>) {
12363: chomp($configline);
12364: next if ($configline =~ /^\#/);
12365: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
12366: $managerstab{$configline} = 1;
12367: }
12368: }
12369: close($config);
12370: }
12371: }
12372: }
12373:
1.329 matthew 12374: # ------------- set up temporary directory
12375: {
1.1117 foxr 12376: $tmpdir = LONCAPA::tempdir();
1.329 matthew 12377:
1.11 www 12378: }
12379:
1.794 albertel 12380: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
12381: 'compress_threshold'=> 20_000,
12382: });
1.185 www 12383:
1.281 www 12384: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 12385: $dumpcount=0;
1.958 www 12386: $locknum=0;
1.22 www 12387:
1.163 harris41 12388: &logtouch();
1.672 albertel 12389: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 12390: $readit=1;
1.564 albertel 12391: {
12392: use integer;
12393: my $test=(2**32)+1;
1.568 albertel 12394: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 12395: &logthis(" Detected 64bit platform ($_64bit)");
12396: }
1.195 www 12397: }
1.1 albertel 12398: }
1.179 www 12399:
1.1 albertel 12400: 1;
1.191 harris41 12401: __END__
12402:
1.243 albertel 12403: =pod
12404:
1.191 harris41 12405: =head1 NAME
12406:
1.243 albertel 12407: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 12408:
12409: =head1 SYNOPSIS
12410:
1.243 albertel 12411: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 12412:
12413: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
12414:
1.243 albertel 12415: Common parameters:
12416:
12417: =over 4
12418:
12419: =item *
12420:
12421: $uname : an internal username (if $cname expecting a course Id specifically)
12422:
12423: =item *
12424:
12425: $udom : a domain (if $cdom expecting a course's domain specifically)
12426:
12427: =item *
12428:
12429: $symb : a resource instance identifier
12430:
12431: =item *
12432:
12433: $namespace : the name of a .db file that contains the data needed or
12434: being set.
12435:
12436: =back
12437:
1.394 bowersj2 12438: =head1 OVERVIEW
1.191 harris41 12439:
1.394 bowersj2 12440: lonnet provides subroutines which interact with the
12441: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
12442: about classes, users, and resources.
1.243 albertel 12443:
12444: For many of these objects you can also use this to store data about
12445: them or modify them in various ways.
1.191 harris41 12446:
1.394 bowersj2 12447: =head2 Symbs
1.191 harris41 12448:
1.394 bowersj2 12449: To identify a specific instance of a resource, LON-CAPA uses symbols
12450: or "symbs"X<symb>. These identifiers are built from the URL of the
12451: map, the resource number of the resource in the map, and the URL of
12452: the resource itself. The latter is somewhat redundant, but might help
12453: if maps change.
12454:
12455: An example is
12456:
12457: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
12458:
12459: The respective map entry is
12460:
12461: <resource id="19" src="/res/msu/korte/tests/part12.problem"
12462: title="Problem 2">
12463: </resource>
12464:
12465: Symbs are used by the random number generator, as well as to store and
12466: restore data specific to a certain instance of for example a problem.
12467:
12468: =head2 Storing And Retrieving Data
12469:
12470: X<store()>X<cstore()>X<restore()>Three of the most important functions
12471: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
12472: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
12473: is is the non-critical message twin of cstore. These functions are for
12474: handlers to store a perl hash to a user's permanent data space in an
12475: easy manner, and to retrieve it again on another call. It is expected
12476: that a handler would use this once at the beginning to retrieve data,
12477: and then again once at the end to send only the new data back.
12478:
12479: The data is stored in the user's data directory on the user's
12480: homeserver under the ID of the course.
12481:
12482: The hash that is returned by restore will have all of the previous
12483: value for all of the elements of the hash.
12484:
12485: Example:
12486:
12487: #creating a hash
12488: my %hash;
12489: $hash{'foo'}='bar';
12490:
12491: #storing it
12492: &Apache::lonnet::cstore(\%hash);
12493:
12494: #changing a value
12495: $hash{'foo'}='notbar';
12496:
12497: #adding a new value
12498: $hash{'bar'}='foo';
12499: &Apache::lonnet::cstore(\%hash);
12500:
12501: #retrieving the hash
12502: my %history=&Apache::lonnet::restore();
12503:
12504: #print the hash
12505: foreach my $key (sort(keys(%history))) {
12506: print("\%history{$key} = $history{$key}");
12507: }
12508:
12509: Will print out:
1.191 harris41 12510:
1.394 bowersj2 12511: %history{1:foo} = bar
12512: %history{1:keys} = foo:timestamp
12513: %history{1:timestamp} = 990455579
12514: %history{2:bar} = foo
12515: %history{2:foo} = notbar
12516: %history{2:keys} = foo:bar:timestamp
12517: %history{2:timestamp} = 990455580
12518: %history{bar} = foo
12519: %history{foo} = notbar
12520: %history{timestamp} = 990455580
12521: %history{version} = 2
12522:
12523: Note that the special hash entries C<keys>, C<version> and
12524: C<timestamp> were added to the hash. C<version> will be equal to the
12525: total number of versions of the data that have been stored. The
12526: C<timestamp> attribute will be the UNIX time the hash was
12527: stored. C<keys> is available in every historical section to list which
12528: keys were added or changed at a specific historical revision of a
12529: hash.
12530:
12531: B<Warning>: do not store the hash that restore returns directly. This
12532: will cause a mess since it will restore the historical keys as if the
12533: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 12534:
1.394 bowersj2 12535: Calling convention:
1.191 harris41 12536:
1.1225 raeburn 12537: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
12538: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname);
1.191 harris41 12539:
1.394 bowersj2 12540: For more detailed information, see lonnet specific documentation.
1.191 harris41 12541:
1.394 bowersj2 12542: =head1 RETURN MESSAGES
1.191 harris41 12543:
1.394 bowersj2 12544: =over 4
1.191 harris41 12545:
1.394 bowersj2 12546: =item * B<con_lost>: unable to contact remote host
1.191 harris41 12547:
1.394 bowersj2 12548: =item * B<con_delayed>: unable to contact remote host, message will be delivered
12549: when the connection is brought back up
1.191 harris41 12550:
1.394 bowersj2 12551: =item * B<con_failed>: unable to contact remote host and unable to save message
12552: for later delivery
1.191 harris41 12553:
1.967 bisitz 12554: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 12555:
1.394 bowersj2 12556: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 12557: that was requested
1.191 harris41 12558:
1.243 albertel 12559: =back
1.191 harris41 12560:
1.243 albertel 12561: =head1 PUBLIC SUBROUTINES
1.191 harris41 12562:
1.243 albertel 12563: =head2 Session Environment Functions
1.191 harris41 12564:
1.243 albertel 12565: =over 4
1.191 harris41 12566:
1.394 bowersj2 12567: =item *
12568: X<appenv()>
1.949 raeburn 12569: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 12570: the user envirnoment file, and will be restored for each access this
1.620 albertel 12571: user makes during this session, also modifies the %env for the current
1.949 raeburn 12572: process. Optional rolesarrayref - if defined contains a reference to an array
12573: of roles which are exempt from the restriction on modifying user.role entries
12574: in the user's environment.db and in %env.
1.191 harris41 12575:
12576: =item *
1.394 bowersj2 12577: X<delenv()>
1.987 raeburn 12578: B<delenv($delthis,$regexp)>: removes all items from the session
12579: environment file that begin with $delthis. If the
12580: optional second arg - $regexp - is true, $delthis is treated as a
12581: regular expression, otherwise \Q$delthis\E is used.
12582: The values are also deleted from the current processes %env.
1.191 harris41 12583:
1.795 albertel 12584: =item * get_env_multiple($name)
12585:
12586: gets $name from the %env hash, it seemlessly handles the cases where multiple
12587: values may be defined and end up as an array ref.
12588:
12589: returns an array of values
12590:
1.243 albertel 12591: =back
12592:
12593: =head2 User Information
1.191 harris41 12594:
1.243 albertel 12595: =over 4
1.191 harris41 12596:
12597: =item *
1.394 bowersj2 12598: X<queryauthenticate()>
12599: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 12600: authentication scheme
12601:
12602: =item *
1.394 bowersj2 12603: X<authenticate()>
1.1073 raeburn 12604: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 12605: authenticate user from domain's lib servers (first use the current
12606: one). C<$upass> should be the users password.
1.1073 raeburn 12607: $checkdefauth is optional (value is 1 if a check should be made to
12608: authenticate user using default authentication method, and allow
12609: account creation if username does not have account in the domain).
12610: $clientcancheckhost is optional (value is 1 if checking whether the
12611: server can host will occur on the client side in lonauth.pm).
1.191 harris41 12612:
12613: =item *
1.394 bowersj2 12614: X<homeserver()>
12615: B<homeserver($uname,$udom)>: find the server which has
12616: the user's directory and files (there must be only one), this caches
12617: the answer, and also caches if there is a borken connection.
1.191 harris41 12618:
12619: =item *
1.394 bowersj2 12620: X<idget()>
12621: B<idget($udom,@ids)>: find the usernames behind a list of IDs
12622: (IDs are a unique resource in a domain, there must be only 1 ID per
12623: username, and only 1 username per ID in a specific domain) (returns
12624: hash: id=>name,id=>name)
1.191 harris41 12625:
12626: =item *
1.394 bowersj2 12627: X<idrget()>
12628: B<idrget($udom,@unames)>: find the IDs behind a list of
12629: usernames (returns hash: name=>id,name=>id)
1.191 harris41 12630:
12631: =item *
1.394 bowersj2 12632: X<idput()>
12633: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 12634:
12635: =item *
1.394 bowersj2 12636: X<rolesinit()>
1.1169 droeschl 12637: B<rolesinit($udom,$username)>: get user privileges.
12638: returns user role, first access and timer interval hashes
1.243 albertel 12639:
12640: =item *
1.1171 droeschl 12641: X<privileged()>
12642: B<privileged($username,$domain)>: returns a true if user has a
12643: privileged and active role (i.e. su or dc), false otherwise.
12644:
12645: =item *
1.551 albertel 12646: X<getsection()>
12647: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 12648: course $cname, return section name/number or '' for "not in course"
12649: and '-1' for "no section"
12650:
12651: =item *
1.394 bowersj2 12652: X<userenvironment()>
12653: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 12654: passed in @what from the requested user's environment, returns a hash
12655:
1.858 raeburn 12656: =item *
12657: X<userlog_query()>
1.859 albertel 12658: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
12659: activity.log file. %filters defines filters applied when parsing the
12660: log file. These can be start or end timestamps, or the type of action
12661: - log to look for Login or Logout events, check for Checkin or
12662: Checkout, role for role selection. The response is in the form
12663: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
12664: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 12665:
1.243 albertel 12666: =back
12667:
12668: =head2 User Roles
12669:
12670: =over 4
12671:
12672: =item *
12673:
1.810 raeburn 12674: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243 albertel 12675: F: full access
12676: U,I,K: authentication modes (cxx only)
12677: '': forbidden
12678: 1: user needs to choose course
12679: 2: browse allowed
1.766 albertel 12680: A: passphrase authentication needed
1.243 albertel 12681:
12682: =item *
12683:
1.1192 raeburn 12684: constructaccess($url,$setpriv) : check for access to construction space URL
12685:
12686: See if the owner domain and name in the URL match those in the
12687: expected environment. If so, return three element list
12688: ($ownername,$ownerdomain,$ownerhome).
12689:
12690: Otherwise return the null string.
12691:
12692: If second argument 'setpriv' is true, it assigns the privileges,
12693: and returns the same three element list, unless the owner has
12694: blocked "ad hoc" Domain Coordinator access to the Author Space,
12695: in which case the null string is returned.
12696:
12697: =item *
12698:
1.243 albertel 12699: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
12700: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
12701: and course level
12702:
12703: =item *
12704:
1.988 raeburn 12705: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
12706: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 12707: $type is Course (default) or Community.
1.988 raeburn 12708: If $forcedefault evaluates to true, text returned will be default
12709: text for $type. Otherwise, if this is a course, the text returned
12710: will be a custom name for the role (if defined in the course's
12711: environment). If no custom name is defined the default is returned.
12712:
1.832 raeburn 12713: =item *
12714:
1.1219 raeburn 12715: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858 raeburn 12716: All arguments are optional. Returns a hash of a roles, either for
12717: co-author/assistant author roles for a user's Construction Space
1.906 albertel 12718: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 12719: In the hash, keys are set to colon-separated $uname,$udom,$role, and
12720: (optionally) if $withsec is true, a fourth colon-separated item - $section.
12721: For each key, value is set to colon-separated start and end times for
12722: the role. If no username and domain are specified, will default to
1.934 raeburn 12723: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 12724: of role statuses (active, future or previous), roles
12725: (e.g., cc,in, st etc.) and domains of the roles which can be used
12726: to restrict the list of roles reported. If no array ref is
12727: provided for types, will default to return only active roles.
1.834 albertel 12728:
1.1195 raeburn 12729: =item *
12730:
12731: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196 raeburn 12732: user: $uname:$udom has a role in the course: $cdom_$cnum.
12733:
12734: Additional optional arguments are: $type (if role checking is to be restricted
12735: to certain user status types -- previous (expired roles), active (currently
1.1195 raeburn 12736: available roles) or future (roles available in the future), and
12737: $hideprivileged -- if true will not report course roles for users who
1.1219 raeburn 12738: have active Domain Coordinator role in course's domain or in additional
12739: domains (specified in 'Domains to check for privileged users' in course
12740: environment -- set via: Course Settings -> Classlists and staff listing).
12741:
12742: =item *
12743:
12744: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
12745: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
12746: $possdomains and $possroles are optional array refs -- to domains to check and
12747: roles to check. If $possdomains is not specified, a dump will be done of the
12748: users' roles.db to check for a dc or su role in any domain. This can be
12749: time consuming if &privileged is called repeatedly (e.g., when displaying a
12750: classlist), so in such cases, supplying a $possdomains array is preferred, as
12751: this then allows &privileged_by_domain() to be used, which caches the identity
12752: of privileged users, eliminating the need for repeated calls to &dump().
12753:
12754: =item *
12755:
12756: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
12757: where the outer hash keys are domains specified in the $possdomains array ref,
12758: next inner hash keys are privileged roles specified in the $roles array ref,
12759: and the innermost hash contains key = value pairs for username:domain = end:start
12760: for active or future "privileged" users with that role in that domain. To avoid
12761: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
12762: innerhash are cached using priv_$role and $dom as the identifiers.
1.1195 raeburn 12763:
1.243 albertel 12764: =back
12765:
12766: =head2 User Modification
12767:
12768: =over 4
12769:
12770: =item *
12771:
1.957 raeburn 12772: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 12773: user for the level given by URL. Optional start and end dates (leave empty
12774: string or zero for "no date")
1.191 harris41 12775:
12776: =item *
12777:
1.243 albertel 12778: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
12779: change a users, password, possible return values are: ok,
12780: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
12781: refused
1.191 harris41 12782:
12783: =item *
12784:
1.243 albertel 12785: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 12786:
12787: =item *
12788:
1.1058 raeburn 12789: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
12790: $forceid,$desiredhome,$email,$inststatus,$candelete) :
12791:
12792: will update user information (firstname,middlename,lastname,generation,
12793: permanentemail), and if forceid is true, student/employee ID also.
12794: A user's institutional affiliation(s) can also be updated.
12795: User information fields will not be overwritten with empty entries
12796: unless the field is included in the $candelete array reference.
12797: This array is included when a single user is modified via "Manage Users",
12798: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 12799:
12800: =item *
12801:
1.286 matthew 12802: modifystudent
12803:
1.957 raeburn 12804: modify a student's enrollment and identification information.
1.1235 raeburn 12805: The course id is resolved based on the current user's environment.
12806: This means the invoking user must be a course coordinator or otherwise
1.286 matthew 12807: associated with a course.
12808:
1.297 matthew 12809: This call is essentially a wrapper for lonnet::modifyuser and
12810: lonnet::modify_student_enrollment
1.286 matthew 12811:
12812: Inputs:
12813:
12814: =over 4
12815:
1.957 raeburn 12816: =item B<$udom> Student's loncapa domain
1.286 matthew 12817:
1.957 raeburn 12818: =item B<$uname> Student's loncapa login name
1.286 matthew 12819:
1.964 bisitz 12820: =item B<$uid> Student/Employee ID
1.286 matthew 12821:
1.957 raeburn 12822: =item B<$umode> Student's authentication mode
1.286 matthew 12823:
1.957 raeburn 12824: =item B<$upass> Student's password
1.286 matthew 12825:
1.957 raeburn 12826: =item B<$first> Student's first name
1.286 matthew 12827:
1.957 raeburn 12828: =item B<$middle> Student's middle name
1.286 matthew 12829:
1.957 raeburn 12830: =item B<$last> Student's last name
1.286 matthew 12831:
1.957 raeburn 12832: =item B<$gene> Student's generation
1.286 matthew 12833:
1.957 raeburn 12834: =item B<$usec> Student's section in course
1.286 matthew 12835:
12836: =item B<$end> Unix time of the roles expiration
12837:
12838: =item B<$start> Unix time of the roles start date
12839:
12840: =item B<$forceid> If defined, allow $uid to be changed
12841:
12842: =item B<$desiredhome> server to use as home server for student
12843:
1.957 raeburn 12844: =item B<$email> Student's permanent e-mail address
12845:
12846: =item B<$type> Type of enrollment (auto or manual)
12847:
1.963 raeburn 12848: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
12849:
12850: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 12851:
1.963 raeburn 12852: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 12853:
1.963 raeburn 12854: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 12855:
1.1216 raeburn 12856: =item B<$inststatus> institutional status of user - : separated string of escaped status types
12857:
12858: =item B<$credits> Number of credits student will earn from this class - only needs to be supplied if value needs to be different from default credits for class.
1.957 raeburn 12859:
1.286 matthew 12860: =back
1.297 matthew 12861:
12862: =item *
12863:
12864: modify_student_enrollment
12865:
1.1235 raeburn 12866: Change a student's enrollment status in a class. The environment variable
1.297 matthew 12867: 'role.request.course' must be defined for this function to proceed.
12868:
12869: Inputs:
12870:
12871: =over 4
12872:
1.1235 raeburn 12873: =item $udom, student's domain
1.297 matthew 12874:
1.1235 raeburn 12875: =item $uname, student's name
1.297 matthew 12876:
1.1235 raeburn 12877: =item $uid, student's user id
1.297 matthew 12878:
1.1235 raeburn 12879: =item $first, student's first name
1.297 matthew 12880:
12881: =item $middle
12882:
12883: =item $last
12884:
12885: =item $gene
12886:
12887: =item $usec
12888:
12889: =item $end
12890:
12891: =item $start
12892:
1.957 raeburn 12893: =item $type
12894:
12895: =item $locktype
12896:
12897: =item $cid
12898:
12899: =item $selfenroll
12900:
12901: =item $context
12902:
1.1216 raeburn 12903: =item $credits, number of credits student will earn from this class
12904:
1.297 matthew 12905: =back
12906:
1.191 harris41 12907:
12908: =item *
12909:
1.243 albertel 12910: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
12911: custom role; give a custom role to a user for the level given by URL. Specify
12912: name and domain of role author, and role name
1.191 harris41 12913:
12914: =item *
12915:
1.243 albertel 12916: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 12917:
12918: =item *
12919:
1.243 albertel 12920: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
12921:
12922: =back
12923:
12924: =head2 Course Infomation
12925:
12926: =over 4
1.191 harris41 12927:
12928: =item *
12929:
1.1118 foxr 12930: coursedescription($courseid,$options) : returns a hash of information about the
1.631 albertel 12931: specified course id, including all environment settings for the
12932: course, the description of the course will be in the hash under the
12933: key 'description'
1.191 harris41 12934:
1.1118 foxr 12935: $options is an optional parameter that if supplied is a hash reference that controls
12936: what how this function works. It has the following key/values:
12937:
12938: =over 4
12939:
12940: =item freshen_cache
12941:
12942: If defined, and the environment cache for the course is valid, it is
12943: returned in the returned hash.
12944:
12945: =item one_time
12946:
12947: If defined, the last cache time is set to _now_
12948:
12949: =item user
12950:
12951: If defined, the supplied username is used instead of the current user.
12952:
12953:
12954: =back
12955:
1.191 harris41 12956: =item *
12957:
1.624 albertel 12958: resdata($name,$domain,$type,@which) : request for current parameter
12959: setting for a specific $type, where $type is either 'course' or 'user',
12960: @what should be a list of parameters to ask about. This routine caches
1.1235 raeburn 12961: answers for 10 minutes.
1.243 albertel 12962:
1.877 foxr 12963: =item *
12964:
12965: get_courseresdata($courseid, $domain) : dump the entire course resource
12966: data base, returning a hash that is keyed by the resource name and has
12967: values that are the resource value. I believe that the timestamps and
12968: versions are also returned.
12969:
1.1236 raeburn 12970: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
12971: supplemental content area. This routine caches the number of files for
12972: 10 minutes.
12973:
1.243 albertel 12974: =back
12975:
12976: =head2 Course Modification
12977:
12978: =over 4
1.191 harris41 12979:
12980: =item *
12981:
1.243 albertel 12982: writecoursepref($courseid,%prefs) : write preferences (environment
12983: database) for a course
1.191 harris41 12984:
12985: =item *
12986:
1.1011 raeburn 12987: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
12988:
12989: =item *
12990:
1.1038 raeburn 12991: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 12992:
1.1167 droeschl 12993: =item *
12994:
12995: is_course($courseid), is_course($cdom, $cnum)
12996:
12997: Accepts either a combined $courseid (in the form of domain_courseid) or the
12998: two component version $cdom, $cnum. It checks if the specified course exists.
12999:
13000: Returns:
13001: undef if the course doesn't exist, otherwise
13002: in scalar context the combined courseid.
13003: in list context the two components of the course identifier, domain and
13004: courseid.
13005:
1.243 albertel 13006: =back
13007:
13008: =head2 Resource Subroutines
13009:
13010: =over 4
1.191 harris41 13011:
13012: =item *
13013:
1.243 albertel 13014: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 13015:
13016: =item *
13017:
1.243 albertel 13018: repcopy($filename) : subscribes to the requested file, and attempts to
13019: replicate from the owning library server, Might return
1.607 raeburn 13020: 'unavailable', 'not_found', 'forbidden', 'ok', or
13021: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 13022: resource. Expects the local filesystem pathname
13023: (/home/httpd/html/res/....)
13024:
13025: =back
13026:
13027: =head2 Resource Information
13028:
13029: =over 4
1.191 harris41 13030:
13031: =item *
13032:
1.1228 raeburn 13033: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates
13034: and returns the value of a variety of different possible values,
13035: $varname should be a request string, and the other parameters can be
13036: used to specify who and what one is asking about. Ordinarily, $cid
13037: does not need to be specified, as it is retrived from
13038: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
13039: within lonuserstate::loadmap() when initializing a course, before
13040: $env{'request.course.id'} has been set, so it needs to be provided
13041: in that one case.
1.243 albertel 13042:
13043: Possible values for $varname are environment.lastname (or other item
13044: from the envirnment hash), user.name (or someother aspect about the
13045: user), resource.0.maxtries (or some other part and parameter of a
13046: resource)
1.204 albertel 13047:
13048: =item *
13049:
1.243 albertel 13050: directcondval($number) : get current value of a condition; reads from a state
13051: string
1.204 albertel 13052:
13053: =item *
13054:
1.243 albertel 13055: condval($condidx) : value of condition index based on state
1.204 albertel 13056:
13057: =item *
13058:
1.243 albertel 13059: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
13060: resource's metadata, $what should be either a specific key, or either
13061: 'keys' (to get a list of possible keys) or 'packages' to get a list of
13062: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
13063:
13064: this function automatically caches all requests
1.191 harris41 13065:
13066: =item *
13067:
1.243 albertel 13068: metadata_query($query,$custom,$customshow) : make a metadata query against the
13069: network of library servers; returns file handle of where SQL and regex results
13070: will be stored for query
1.191 harris41 13071:
13072: =item *
13073:
1.243 albertel 13074: symbread($filename) : return symbolic list entry (filename argument optional);
13075: returns the data handle
1.191 harris41 13076:
13077: =item *
13078:
1.1190 raeburn 13079: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
13080: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582 albertel 13081: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190 raeburn 13082: on failure, user must be in a course, as it assumes the existence of
13083: the course initial hash, and uses $env('request.course.id'}. The third
13084: arg is an optional reference to a scalar. If this arg is passed in the
13085: call to symbverify, it will be set to 1 if the symb has been set to be
13086: encrypted; otherwise it will be null.
1.191 harris41 13087:
13088: =item *
13089:
1.243 albertel 13090: symbclean($symb) : removes versions numbers from a symb, returns the
13091: cleaned symb
1.191 harris41 13092:
13093: =item *
13094:
1.243 albertel 13095: is_on_map($uri) : checks if the $uri is somewhere on the current
13096: course map, user must be in a course for it to work.
1.191 harris41 13097:
13098: =item *
13099:
1.243 albertel 13100: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 13101:
13102: =item *
13103:
1.243 albertel 13104: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
13105: a random seed, all arguments are optional, if they aren't sent it uses the
13106: environment to derive them. Note: if symb isn't sent and it can't get one
13107: from &symbread it will use the current time as its return value
1.191 harris41 13108:
13109: =item *
13110:
1.243 albertel 13111: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
13112: unfakeable, receipt
1.191 harris41 13113:
13114: =item *
13115:
1.620 albertel 13116: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 13117:
13118: =item *
13119:
1.243 albertel 13120: countacc($url) : count the number of accesses to a given URL
1.191 harris41 13121:
13122: =item *
13123:
1.243 albertel 13124: 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 13125:
13126: =item *
13127:
1.243 albertel 13128: 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 13129:
13130: =item *
13131:
1.243 albertel 13132: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 13133:
13134: =item *
13135:
1.243 albertel 13136: devalidate($symb) : devalidate temporary spreadsheet calculations,
13137: forcing spreadsheet to reevaluate the resource scores next time.
13138:
1.1195 raeburn 13139: =item *
13140:
1.1196 raeburn 13141: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
13142: when viewing in course context.
1.1195 raeburn 13143:
1.1196 raeburn 13144: input: six args -- filename (decluttered), course number, course domain,
13145: url, symb (if registered) and group (if this is a
13146: group item -- e.g., bulletin board, group page etc.).
1.1195 raeburn 13147:
1.1196 raeburn 13148: output: array of five scalars --
1.1195 raeburn 13149: $cfile -- url for file editing if editable on current server
13150: $home -- homeserver of resource (i.e., for author if published,
13151: or course if uploaded.).
13152: $switchserver -- 1 if server switch will be needed.
1.1196 raeburn 13153: $forceedit -- 1 if icon/link should be to go to edit mode
13154: $forceview -- 1 if icon/link should be to go to view mode
1.1195 raeburn 13155:
13156: =item *
13157:
13158: is_course_upload($file,$cnum,$cdom)
13159:
13160: Used in course context to determine if current file was uploaded to
13161: the course (i.e., would be found in /userfiles/docs on the course's
13162: homeserver.
13163:
13164: input: 3 args -- filename (decluttered), course number and course domain.
13165: output: boolean -- 1 if file was uploaded.
13166:
1.243 albertel 13167: =back
13168:
13169: =head2 Storing/Retreiving Data
13170:
13171: =over 4
1.191 harris41 13172:
13173: =item *
13174:
1.243 albertel 13175: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
13176: for this url; hashref needs to be given and should be a \%hashname; the
13177: remaining args aren't required and if they aren't passed or are '' they will
1.620 albertel 13178: be derived from the env
1.191 harris41 13179:
13180: =item *
13181:
1.243 albertel 13182: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
13183: uses critical subroutine
1.191 harris41 13184:
13185: =item *
13186:
1.243 albertel 13187: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
13188: all args are optional
1.191 harris41 13189:
13190: =item *
13191:
1.717 albertel 13192: dumpstore($namespace,$udom,$uname,$regexp,$range) :
13193: dumps the complete (or key matching regexp) namespace into a hash
13194: ($udom, $uname, $regexp, $range are optional) for a namespace that is
13195: normally &store()ed into
13196:
13197: $range should be either an integer '100' (give me the first 100
13198: matching records)
13199: or be two integers sperated by a - with no spaces
13200: '30-50' (give me the 30th through the 50th matching
13201: records)
13202:
13203:
13204: =item *
13205:
13206: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
13207: replaces a &store() version of data with a replacement set of data
13208: for a particular resource in a namespace passed in the $storehash hash
13209: reference
13210:
13211: =item *
13212:
1.243 albertel 13213: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
13214: works very similar to store/cstore, but all data is stored in a
13215: temporary location and can be reset using tmpreset, $storehash should
13216: be a hash reference, returns nothing on success
1.191 harris41 13217:
13218: =item *
13219:
1.243 albertel 13220: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
13221: similar to restore, but all data is stored in a temporary location and
13222: can be reset using tmpreset. Returns a hash of values on success,
13223: error string otherwise.
1.191 harris41 13224:
13225: =item *
13226:
1.243 albertel 13227: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
13228: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 13229:
13230: =item *
13231:
1.243 albertel 13232: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13233: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 13234:
13235: =item *
13236:
1.243 albertel 13237: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
13238: namesp ($udom and $uname are optional)
1.191 harris41 13239:
13240: =item *
13241:
1.702 albertel 13242: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 13243: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 13244: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 13245:
1.702 albertel 13246: $range should be either an integer '100' (give me the first 100
13247: matching records)
13248: or be two integers sperated by a - with no spaces
13249: '30-50' (give me the 30th through the 50th matching
13250: records)
1.449 matthew 13251: =item *
13252:
13253: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
13254: $store can be a scalar, an array reference, or if the amount to be
13255: incremented is > 1, a hash reference.
13256:
13257: ($udom and $uname are optional)
1.191 harris41 13258:
13259: =item *
13260:
1.243 albertel 13261: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
13262: ($udom and $uname are optional)
1.191 harris41 13263:
13264: =item *
13265:
1.243 albertel 13266: cput($namespace,$storehash,$udom,$uname) : critical put
13267: ($udom and $uname are optional)
1.191 harris41 13268:
13269: =item *
13270:
1.748 albertel 13271: newput($namespace,$storehash,$udom,$uname) :
13272:
13273: Attempts to store the items in the $storehash, but only if they don't
13274: currently exist, if this succeeds you can be certain that you have
13275: successfully created a new key value pair in the $namespace db.
13276:
13277:
13278: Args:
13279: $namespace: name of database to store values to
13280: $storehash: hashref to store to the db
13281: $udom: (optional) domain of user containing the db
13282: $uname: (optional) name of user caontaining the db
13283:
13284: Returns:
13285: 'ok' -> succeeded in storing all keys of $storehash
13286: 'key_exists: <key>' -> failed to anything out of $storehash, as at
13287: least <key> already existed in the db (other
13288: requested keys may also already exist)
1.967 bisitz 13289: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 13290: 'con_lost' -> unable to contact request server
13291: 'refused' -> action was not allowed by remote machine
13292:
13293:
13294: =item *
13295:
1.243 albertel 13296: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13297: reference filled in from namesp (encrypts the return communication)
13298: ($udom and $uname are optional)
1.191 harris41 13299:
13300: =item *
13301:
1.243 albertel 13302: log($udom,$name,$home,$message) : write to permanent log for user; use
13303: critical subroutine
13304:
1.806 raeburn 13305: =item *
13306:
1.860 raeburn 13307: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
13308: array reference filled in from namespace found in domain level on either
13309: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 13310:
13311: =item *
13312:
1.860 raeburn 13313: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
13314: domain level either on specified domain server ($uhome) or primary domain
13315: server ($udom and $uhome are optional)
1.806 raeburn 13316:
1.943 raeburn 13317: =item *
13318:
1.1240 raeburn 13319: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
13320: for: authentication, language, quotas, timezone, date locale, and portal URL in
13321: the target domain.
13322:
13323: May also include additional key => value pairs for the following groups:
13324:
13325: =over
13326:
13327: =item
13328: disk quotas (MB allocated by default to portfolios and authoring spaces).
13329:
13330: =over
13331:
13332: =item defaultquota, authorquota
13333:
13334: =back
13335:
13336: =item
13337: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
13338: portfolio for users).
13339:
13340: =over
13341:
13342: =item
13343: aboutme, blog, webdav, portfolio
13344:
13345: =back
13346:
13347: =item
13348: requestcourses: ability to request courses, and how requests are processed.
13349:
13350: =over
13351:
13352: =item
1.1246 raeburn 13353: official, unofficial, community, textbook
1.1240 raeburn 13354:
13355: =back
13356:
13357: =item
13358: inststatus: types of institutional affiliation, and order in which they are displayed.
13359:
13360: =over
13361:
13362: =item
1.1256 raeburn 13363: inststatustypes, inststatusorder, inststatusguest
1.1240 raeburn 13364:
13365: =back
13366:
13367: =item
13368: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
13369: for course's uploaded content.
13370:
13371: =over
13372:
13373: =item
1.1246 raeburn 13374: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
13375: communityquota, textbookquota
1.1240 raeburn 13376:
13377: =back
13378:
13379: =item
13380: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
13381: on your servers.
13382:
13383: =over
13384:
13385: =item
13386: remotesessions, hostedsessions
13387:
13388: =back
13389:
13390: =back
13391:
13392: In cases where a domain coordinator has never used the "Set Domain Configuration"
13393: utility to create a configuration.db file on a domain's primary library server
13394: only the following domain defaults: auth_def, auth_arg_def, lang_def
13395: -- corresponding values are authentication type (internal, krb4, krb5,
13396: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
13397: will be available. Values are retrieved from cache (if current), unless the
13398: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
13399: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
13400:
13401: Typical usage:
1.943 raeburn 13402:
1.1240 raeburn 13403: %domdefaults = &get_domain_defaults($target_domain);
1.943 raeburn 13404:
1.243 albertel 13405: =back
13406:
13407: =head2 Network Status Functions
13408:
13409: =over 4
1.191 harris41 13410:
13411: =item *
13412:
1.1137 raeburn 13413: dirlist() : return directory list based on URI (first arg).
13414:
13415: Inputs: 1 required, 5 optional.
13416:
13417: =over
13418:
13419: =item
13420: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
13421:
13422: =item
13423: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
13424:
13425: =item
13426: $username - username of user/course to be listed. Extracted from $uri if absent.
13427:
13428: =item
13429: $getpropath - boolean: 1 if prepend path using &propath().
13430:
13431: =item
13432: $getuserdir - boolean: 1 if prepend path for "userfiles".
13433:
13434: =item
13435: $alternateRoot - path to prepend in place of path from $uri.
13436:
13437: =back
13438:
13439: Returns: Array of up to two items.
13440:
13441: =over
13442:
13443: a reference to an array of files/subdirectories
13444:
13445: =over
13446:
13447: Each element in the array of files/subdirectories is a & separated list of
13448: item name and the result of running stat on the item. If dirlist was requested
13449: for a file instead of a directory, the item name will be ''. For a directory
13450: listing, if the item is a metadata file, the element will end &N&M
13451: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
13452: default copyright set (1).
13453:
13454: =back
13455:
13456: a scalar containing error condition (if encountered).
13457:
13458: =over
13459:
13460: =item
13461: no_host (no homeserver identified for $username:$domain).
13462:
13463: =item
13464: no_such_host (server contacted for listing not identified as valid host).
13465:
13466: =item
13467: con_lost (connection to remote server failed).
13468:
13469: =item
13470: refused (invalid $username:$domain received on lond side).
13471:
13472: =item
13473: no_such_dir (directory at specified path on lond side does not exist).
13474:
13475: =item
13476: empty (directory at specified path on lond side is empty).
13477:
13478: =over
13479:
13480: This is currently not encountered because the &ls3, &ls2,
13481: &ls (_handler) routines on the lond side do not filter out
13482: . and .. from a directory listing.
13483:
13484: =back
13485:
13486: =back
13487:
13488: =back
1.191 harris41 13489:
13490: =item *
13491:
1.243 albertel 13492: spareserver() : find server with least workload from spare.tab
13493:
1.986 foxr 13494:
13495: =item *
13496:
13497: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
13498: if there is no corresponding loncapa host.
13499:
1.243 albertel 13500: =back
13501:
1.986 foxr 13502:
1.243 albertel 13503: =head2 Apache Request
13504:
13505: =over 4
1.191 harris41 13506:
13507: =item *
13508:
1.243 albertel 13509: ssi($url,%hash) : server side include, does a complete request cycle on url to
13510: localhost, posts hash
13511:
13512: =back
13513:
13514: =head2 Data to String to Data
13515:
13516: =over 4
1.191 harris41 13517:
13518: =item *
13519:
1.243 albertel 13520: hash2str(%hash) : convert a hash into a string complete with escaping and '='
13521: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 13522:
13523: =item *
13524:
1.243 albertel 13525: hashref2str($hashref) : convert a hashref into a string complete with
13526: escaping and '=' and '&' separators, supports elements that are
13527: arrayrefs and hashrefs
1.191 harris41 13528:
13529: =item *
13530:
1.243 albertel 13531: arrayref2str($arrayref) : convert an arrayref into a string complete
13532: with escaping and '&' separators, supports elements that are arrayrefs
13533: and hashrefs
1.191 harris41 13534:
13535: =item *
13536:
1.243 albertel 13537: str2hash($string) : convert string to hash using unescaping and
13538: splitting on '=' and '&', supports elements that are arrayrefs and
13539: hashrefs
1.191 harris41 13540:
13541: =item *
13542:
1.243 albertel 13543: str2array($string) : convert string to hash using unescaping and
13544: splitting on '&', supports elements that are arrayrefs and hashrefs
13545:
13546: =back
13547:
13548: =head2 Logging Routines
13549:
13550:
13551: These routines allow one to make log messages in the lonnet.log and
13552: lonnet.perm logfiles.
1.191 harris41 13553:
1.1119 foxr 13554: =over 4
13555:
1.191 harris41 13556: =item *
13557:
1.243 albertel 13558: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 13559:
13560: =item *
13561:
1.243 albertel 13562: logthis() : append message to the normal lonnet.log file, it gets
13563: preiodically rolled over and deleted.
1.191 harris41 13564:
13565: =item *
13566:
1.243 albertel 13567: logperm() : append a permanent message to lonnet.perm.log, this log
13568: file never gets deleted by any automated portion of the system, only
13569: messages of critical importance should go in here.
13570:
1.1119 foxr 13571:
1.243 albertel 13572: =back
13573:
13574: =head2 General File Helper Routines
13575:
13576: =over 4
1.191 harris41 13577:
13578: =item *
13579:
1.481 raeburn 13580: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
13581: (a) files in /uploaded
13582: (i) If a local copy of the file exists -
13583: compares modification date of local copy with last-modified date for
13584: definitive version stored on home server for course. If local copy is
13585: stale, requests a new version from the home server and stores it.
13586: If the original has been removed from the home server, then local copy
13587: is unlinked.
13588: (ii) If local copy does not exist -
13589: requests the file from the home server and stores it.
13590:
13591: If $caller is 'uploadrep':
13592: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
13593: for request for files originally uploaded via DOCS.
13594: - returns 'ok' if fresh local copy now available, -1 otherwise.
13595:
13596: Otherwise:
13597: This indicates a call from the content generation phase of the request.
13598: - returns the entire contents of the file or -1.
13599:
13600: (b) files in /res
13601: - returns the entire contents of a file or -1;
13602: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 13603:
1.712 albertel 13604:
13605: =item *
13606:
13607: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
13608: reference
13609:
13610: returns either a stat() list of data about the file or an empty list
13611: if the file doesn't exist or couldn't find out about it (connection
13612: problems or user unknown)
13613:
1.191 harris41 13614: =item *
13615:
1.243 albertel 13616: filelocation($dir,$file) : returns file system location of a file
13617: based on URI; meant to be "fairly clean" absolute reference, $dir is a
13618: directory that relative $file lookups are to looked in ($dir of /a/dir
13619: and a file of ../bob will become /a/bob)
1.191 harris41 13620:
13621: =item *
13622:
13623: hreflocation($dir,$file) : returns file system location or a URL; same as
13624: filelocation except for hrefs
13625:
13626: =item *
13627:
13628: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
13629:
1.243 albertel 13630: =back
13631:
1.608 albertel 13632: =head2 Usererfile file routines (/uploaded*)
13633:
13634: =over 4
13635:
13636: =item *
13637:
13638: userfileupload(): main rotine for putting a file in a user or course's
13639: filespace, arguments are,
13640:
1.620 albertel 13641: formname - required - this is the name of the element in $env where the
1.608 albertel 13642: filename, and the contents of the file to create/modifed exist
1.620 albertel 13643: the filename is in $env{'form.'.$formname.'.filename'} and the
13644: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 13645: context - if coursedoc, store the file in the course of the active role
13646: of the current user;
13647: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
13648: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 13649: subdir - required - subdirectory to put the file in under ../userfiles/
13650: if undefined, it will be placed in "unknown"
13651:
13652: (This routine calls clean_filename() to remove any dangerous
13653: characters from the filename, and then calls finuserfileupload() to
13654: complete the transaction)
13655:
13656: returns either the url of the uploaded file (/uploaded/....) if successful
13657: and /adm/notfound.html if unsuccessful
13658:
13659: =item *
13660:
13661: clean_filename(): routine for cleaing a filename up for storage in
13662: userfile space, argument is:
13663:
13664: filename - proposed filename
13665:
13666: returns: the new clean filename
13667:
13668: =item *
13669:
1.1090 raeburn 13670: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 13671: userspace, probably shouldn't be called directly
13672:
13673: docuname: username or courseid of destination for the file
13674: docudom: domain of user/course of destination for the file
13675: formname: same as for userfileupload()
1.1090 raeburn 13676: fname: filename (including subdirectories) for the file
13677: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
13678: allfiles: reference to hash used to store objects found by parser
13679: codebase: reference to hash used for codebases of java objects found by parser
13680: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
13681: thumbheight: height (pixels) of thumbnail to be created for uploaded image
13682: resizewidth: width to be used to resize image using resizeImage from ImageMagick
13683: resizeheight: height to be used to resize image using resizeImage from ImageMagick
13684: context: if 'overwrite', will move the uploaded file from its temporary location to
13685: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 13686: mimetype: reference to scalar to accommodate mime type determined
13687: from File::MMagic if $parser = parse.
1.608 albertel 13688:
13689: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 13690: and /adm/notfound.html if unsuccessful (or an error message if context
13691: was 'overwrite').
13692:
1.608 albertel 13693:
13694: =item *
13695:
13696: renameuserfile(): renames an existing userfile to a new name
13697:
13698: Args:
13699: docuname: username or courseid of destination for the file
13700: docudom: domain of user/course of destination for the file
13701: old: current file name (including any subdirs under userfiles)
13702: new: desired file name (including any subdirs under userfiles)
13703:
13704: =item *
13705:
13706: mkdiruserfile(): creates a directory is a userfiles dir
13707:
13708: Args:
13709: docuname: username or courseid of destination for the file
13710: docudom: domain of user/course of destination for the file
13711: dir: dir to create (including any subdirs under userfiles)
13712:
13713: =item *
13714:
13715: removeuserfile(): removes a file that exists in userfiles
13716:
13717: Args:
13718: docuname: username or courseid of destination for the file
13719: docudom: domain of user/course of destination for the file
13720: fname: filname to delete (including any subdirs under userfiles)
13721:
13722: =item *
13723:
13724: removeuploadedurl(): convience function for removeuserfile()
13725:
13726: Args:
13727: url: a full /uploaded/... url to delete
13728:
1.747 albertel 13729: =item *
13730:
13731: get_portfile_permissions():
13732: Args:
13733: domain: domain of user or course contain the portfolio files
13734: user: name of user or num of course contain the portfolio files
13735: Returns:
13736: hashref of a dump of the proper file_permissions.db
13737:
13738:
13739: =item *
13740:
13741: get_access_controls():
13742:
13743: Args:
13744: current_permissions: the hash ref returned from get_portfile_permissions()
13745: group: (optional) the group you want the files associated with
13746: file: (optional) the file you want access info on
13747:
13748: Returns:
1.749 raeburn 13749: a hash (keys are file names) of hashes containing
13750: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
13751: values are XML containing access control settings (see below)
1.747 albertel 13752:
13753: Internal notes:
13754:
1.749 raeburn 13755: access controls are stored in file_permissions.db as key=value pairs.
13756: key -> path to file/file_name\0uniqueID:scope_end_start
13757: where scope -> public,guest,course,group,domains or users.
13758: end -> UNIX time for end of access (0 -> no end date)
13759: start -> UNIX time for start of access
13760:
13761: value -> XML description of access control
13762: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
13763: <start></start>
13764: <end></end>
13765:
13766: <password></password> for scope type = guest
13767:
13768: <domain></domain> for scope type = course or group
13769: <number></number>
13770: <roles id="">
13771: <role></role>
13772: <access></access>
13773: <section></section>
13774: <group></group>
13775: </roles>
13776:
13777: <dom></dom> for scope type = domains
13778:
13779: <users> for scope type = users
13780: <user>
13781: <uname></uname>
13782: <udom></udom>
13783: </user>
13784: </users>
13785: </scope>
13786:
13787: Access data is also aggregated for each file in an additional key=value pair:
13788: key -> path to file/file_name\0accesscontrol
13789: value -> reference to hash
13790: hash contains key = value pairs
13791: where key = uniqueID:scope_end_start
13792: value = UNIX time record was last updated
13793:
13794: Used to improve speed of look-ups of access controls for each file.
13795:
13796: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
13797:
1.1198 raeburn 13798: =item *
13799:
1.749 raeburn 13800: modify_access_controls():
13801:
13802: Modifies access controls for a portfolio file
13803: Args
13804: 1. file name
13805: 2. reference to hash of required changes,
13806: 3. domain
13807: 4. username
13808: where domain,username are the domain of the portfolio owner
13809: (either a user or a course)
13810:
13811: Returns:
13812: 1. result of additions or updates ('ok' or 'error', with error message).
13813: 2. result of deletions ('ok' or 'error', with error message).
13814: 3. reference to hash of any new or updated access controls.
13815: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
13816: key = integer (inbound ID)
1.1198 raeburn 13817: value = uniqueID
13818:
13819: =item *
13820:
13821: get_timebased_id():
13822:
13823: Attempts to get a unique timestamp-based suffix for use with items added to a
13824: course via the Course Editor (e.g., folders, composite pages,
13825: group bulletin boards).
13826:
13827: Args: (first three required; six others optional)
13828:
13829: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
13830: docssequence, or name of group
13831:
13832: 2. keyid (alphanumeric): name of temporary locking key in hash,
13833: e.g., num, boardids
13834:
13835: 3. namespace: name of gdbm file used to store suffixes already assigned;
13836: file will be named nohist_namespace.db
13837:
13838: 4. cdom: domain of course; default is current course domain from %env
13839:
13840: 5. cnum: course number; default is current course number from %env
13841:
13842: 6. idtype: set to concat if an additional digit is to be appended to the
13843: unix timestamp to form the suffix, if the plain timestamp is already
13844: in use. Default is to not do this, but simply increment the unix
13845: timestamp by 1 until a unique key is obtained.
13846:
13847: 7. who: holder of locking key; defaults to user:domain for user.
13848:
13849: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
13850: retrying); default is 3.
13851:
13852: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
13853:
13854: Returns:
13855:
13856: 1. suffix obtained (numeric)
13857:
13858: 2. result of deleting locking key (ok if deleted, or lock never obtained)
13859:
13860: 3. error: contains (localized) error message if an error occurred.
13861:
1.747 albertel 13862:
1.608 albertel 13863: =back
13864:
1.243 albertel 13865: =head2 HTTP Helper Routines
13866:
13867: =over 4
13868:
1.191 harris41 13869: =item *
13870:
13871: escape() : unpack non-word characters into CGI-compatible hex codes
13872:
13873: =item *
13874:
13875: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
13876:
1.243 albertel 13877: =back
13878:
13879: =head1 PRIVATE SUBROUTINES
13880:
13881: =head2 Underlying communication routines (Shouldn't call)
13882:
13883: =over 4
13884:
13885: =item *
13886:
13887: subreply() : tries to pass a message to lonc, returns con_lost if incapable
13888:
13889: =item *
13890:
13891: reply() : uses subreply to send a message to remote machine, logs all failures
13892:
13893: =item *
13894:
13895: critical() : passes a critical message to another server; if cannot
13896: get through then place message in connection buffer directory and
13897: returns con_delayed, if incapable of saving message, returns
13898: con_failed
13899:
13900: =item *
13901:
13902: reconlonc() : tries to reconnect lonc client processes.
13903:
13904: =back
13905:
13906: =head2 Resource Access Logging
13907:
13908: =over 4
13909:
13910: =item *
13911:
13912: flushcourselogs() : flush (save) buffer logs and access logs
13913:
13914: =item *
13915:
13916: courselog($what) : save message for course in hash
13917:
13918: =item *
13919:
13920: courseacclog($what) : save message for course using &courselog(). Perform
13921: special processing for specific resource types (problems, exams, quizzes, etc).
13922:
1.191 harris41 13923: =item *
13924:
13925: goodbye() : flush course logs and log shutting down; it is called in srm.conf
13926: as a PerlChildExitHandler
1.243 albertel 13927:
13928: =back
13929:
13930: =head2 Other
13931:
13932: =over 4
13933:
13934: =item *
13935:
13936: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 13937:
13938: =back
13939:
13940: =cut
1.877 foxr 13941:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>