Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1255
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1255 ! raeburn 4: # $Id: lonnet.pm,v 1.1254 2014/03/31 01:09:20 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')) {
1748: %returnhash = %{$domdefs{'inststatustypes'}};
1749: @order = @{$domdefs{'inststatusorder'}};
1750: } else {
1751: if (defined(&domain($udom,'primary'))) {
1752: my $uhome=&domain($udom,'primary');
1753: my $rep=&reply("inst_usertypes:$udom",$uhome);
1754: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1755: &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
1756: return (\%returnhash,\@order);
1757: }
1758: my ($hashitems,$orderitems) = split(/:/,$rep);
1759: my @pairs=split(/\&/,$hashitems);
1760: foreach my $item (@pairs) {
1761: my ($key,$value)=split(/=/,$item,2);
1762: $key = &unescape($key);
1763: next if ($key =~ /^error: 2 /);
1764: $returnhash{$key}=&thaw_unescape($value);
1765: }
1766: my @esc_order = split(/\&/,$orderitems);
1767: foreach my $item (@esc_order) {
1768: push(@order,&unescape($item));
1769: }
1770: } else {
1771: &logthis("get_dom failed - no primary domain server for $udom");
1.837 raeburn 1772: }
1773: }
1774: return (\%returnhash,\@order);
1775: }
1776:
1.868 raeburn 1777: sub is_domainimage {
1778: my ($url) = @_;
1779: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
1780: if (&domain($1) ne '') {
1781: return '1';
1782: }
1783: }
1784: return;
1785: }
1786:
1.899 raeburn 1787: sub inst_directory_query {
1788: my ($srch) = @_;
1789: my $udom = $srch->{'srchdomain'};
1790: my %results;
1791: my $homeserver = &domain($udom,'primary');
1.909 raeburn 1792: my $outcome;
1.899 raeburn 1793: if ($homeserver ne '') {
1.904 albertel 1794: my $queryid=&reply("querysend:instdirsearch:".
1795: &escape($srch->{'srchby'}).':'.
1796: &escape($srch->{'srchterm'}).':'.
1797: &escape($srch->{'srchtype'}),$homeserver);
1798: my $host=&hostname($homeserver);
1799: if ($queryid !~/^\Q$host\E\_/) {
1800: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1801: return;
1802: }
1803: my $response = &get_query_reply($queryid);
1804: my $maxtries = 5;
1805: my $tries = 1;
1806: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1807: $response = &get_query_reply($queryid);
1808: $tries ++;
1809: }
1810:
1811: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 1812: if ($response eq 'unavailable') {
1813: $outcome = $response;
1814: } else {
1815: $outcome = 'ok';
1816: my @matches = split(/\n/,$response);
1817: foreach my $match (@matches) {
1818: my ($key,$value) = split(/=/,$match);
1819: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1820: }
1.899 raeburn 1821: }
1822: }
1823: }
1.909 raeburn 1824: return ($outcome,%results);
1.899 raeburn 1825: }
1826:
1827: sub usersearch {
1828: my ($srch) = @_;
1829: my $dom = $srch->{'srchdomain'};
1830: my %results;
1831: my %libserv = &all_library();
1832: my $query = 'usersearch';
1833: foreach my $tryserver (keys(%libserv)) {
1834: if (&host_domain($tryserver) eq $dom) {
1835: my $host=&hostname($tryserver);
1836: my $queryid=
1.911 raeburn 1837: &reply("querysend:".&escape($query).':'.
1838: &escape($srch->{'srchby'}).':'.
1.899 raeburn 1839: &escape($srch->{'srchtype'}).':'.
1840: &escape($srch->{'srchterm'}),$tryserver);
1841: if ($queryid !~/^\Q$host\E\_/) {
1842: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 1843: next;
1.899 raeburn 1844: }
1845: my $reply = &get_query_reply($queryid);
1846: my $maxtries = 1;
1847: my $tries = 1;
1848: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1849: $reply = &get_query_reply($queryid);
1850: $tries ++;
1851: }
1852: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1853: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1854: } else {
1.911 raeburn 1855: my @matches;
1856: if ($reply =~ /\n/) {
1857: @matches = split(/\n/,$reply);
1858: } else {
1859: @matches = split(/\&/,$reply);
1860: }
1.899 raeburn 1861: foreach my $match (@matches) {
1862: my ($uname,$udom,%userhash);
1.911 raeburn 1863: foreach my $entry (split(/:/,$match)) {
1864: my ($key,$value) =
1865: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 1866: $userhash{$key} = $value;
1867: if ($key eq 'username') {
1868: $uname = $value;
1869: } elsif ($key eq 'domain') {
1870: $udom = $value;
1.911 raeburn 1871: }
1.899 raeburn 1872: }
1873: $results{$uname.':'.$udom} = \%userhash;
1874: }
1875: }
1876: }
1877: }
1878: return %results;
1879: }
1880:
1.912 raeburn 1881: sub get_instuser {
1882: my ($udom,$uname,$id) = @_;
1883: my $homeserver = &domain($udom,'primary');
1884: my ($outcome,%results);
1885: if ($homeserver ne '') {
1886: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1887: &escape($id).':'.&escape($udom),$homeserver);
1888: my $host=&hostname($homeserver);
1889: if ($queryid !~/^\Q$host\E\_/) {
1890: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1891: return;
1892: }
1893: my $response = &get_query_reply($queryid);
1894: my $maxtries = 5;
1895: my $tries = 1;
1896: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1897: $response = &get_query_reply($queryid);
1898: $tries ++;
1899: }
1900: if (!&error($response) && $response ne 'refused') {
1901: if ($response eq 'unavailable') {
1902: $outcome = $response;
1903: } else {
1904: $outcome = 'ok';
1905: my @matches = split(/\n/,$response);
1906: foreach my $match (@matches) {
1907: my ($key,$value) = split(/=/,$match);
1908: $results{&unescape($key)} = &thaw_unescape($value);
1909: }
1910: }
1911: }
1912: }
1913: my %userinfo;
1914: if (ref($results{$uname}) eq 'HASH') {
1915: %userinfo = %{$results{$uname}};
1916: }
1917: return ($outcome,%userinfo);
1918: }
1919:
1920: sub inst_rulecheck {
1.923 raeburn 1921: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 1922: my %returnhash;
1923: if ($udom ne '') {
1924: if (ref($rules) eq 'ARRAY') {
1925: @{$rules} = map {&escape($_);} (@{$rules});
1926: my $rulestr = join(':',@{$rules});
1927: my $homeserver=&domain($udom,'primary');
1928: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1929: my $response;
1930: if ($item eq 'username') {
1931: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
1932: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 1933: $homeserver));
1.923 raeburn 1934: } elsif ($item eq 'id') {
1935: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
1936: ':'.&escape($id).':'.$rulestr,
1937: $homeserver));
1.945 raeburn 1938: } elsif ($item eq 'selfcreate') {
1939: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 1940: &escape($udom).':'.&escape($uname).
1941: ':'.$rulestr,$homeserver));
1.923 raeburn 1942: }
1.912 raeburn 1943: if ($response ne 'refused') {
1944: my @pairs=split(/\&/,$response);
1945: foreach my $item (@pairs) {
1946: my ($key,$value)=split(/=/,$item,2);
1947: $key = &unescape($key);
1948: next if ($key =~ /^error: 2 /);
1949: $returnhash{$key}=&thaw_unescape($value);
1950: }
1951: }
1952: }
1953: }
1954: }
1955: return %returnhash;
1956: }
1957:
1958: sub inst_userrules {
1.923 raeburn 1959: my ($udom,$check) = @_;
1.912 raeburn 1960: my (%ruleshash,@ruleorder);
1961: if ($udom ne '') {
1962: my $homeserver=&domain($udom,'primary');
1963: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1964: my $response;
1965: if ($check eq 'id') {
1966: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 1967: $homeserver);
1.943 raeburn 1968: } elsif ($check eq 'email') {
1969: $response=&reply('instemailrules:'.&escape($udom),
1970: $homeserver);
1.923 raeburn 1971: } else {
1972: $response=&reply('instuserrules:'.&escape($udom),
1973: $homeserver);
1974: }
1.912 raeburn 1975: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 1976: ($response ne 'unknown_cmd') &&
1.912 raeburn 1977: ($response ne 'no_such_host')) {
1978: my ($hashitems,$orderitems) = split(/:/,$response);
1979: my @pairs=split(/\&/,$hashitems);
1980: foreach my $item (@pairs) {
1981: my ($key,$value)=split(/=/,$item,2);
1982: $key = &unescape($key);
1983: next if ($key =~ /^error: 2 /);
1984: $ruleshash{$key}=&thaw_unescape($value);
1985: }
1986: my @esc_order = split(/\&/,$orderitems);
1987: foreach my $item (@esc_order) {
1988: push(@ruleorder,&unescape($item));
1989: }
1990: }
1991: }
1992: }
1993: return (\%ruleshash,\@ruleorder);
1994: }
1995:
1.976 raeburn 1996: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 1997:
1998: sub get_domain_defaults {
1.1240 raeburn 1999: my ($domain,$ignore_cache) = @_;
1.1242 raeburn 2000: return if (($domain eq '') || ($domain eq 'public'));
1.943 raeburn 2001: my $cachetime = 60*60*24;
1.1240 raeburn 2002: unless ($ignore_cache) {
2003: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
2004: if (defined($cached)) {
2005: if (ref($result) eq 'HASH') {
2006: return %{$result};
2007: }
1.943 raeburn 2008: }
2009: }
2010: my %domdefaults;
2011: my %domconfig =
1.989 raeburn 2012: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 2013: 'requestcourses','inststatus',
1.1183 raeburn 2014: 'coursedefaults','usersessions',
1.1254 raeburn 2015: 'requestauthor','selfenrollment'],$domain);
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') {
2054: foreach my $item ('inststatustypes','inststatusorder') {
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.1219 raeburn 2107: &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943 raeburn 2108: return %domdefaults;
2109: }
2110:
1.344 www 2111: # --------------------------------------------------- Assign a key to a student
2112:
2113: sub assign_access_key {
1.364 www 2114: #
2115: # a valid key looks like uname:udom#comments
2116: # comments are being appended
2117: #
1.498 www 2118: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
2119: $kdom=
1.620 albertel 2120: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 2121: $knum=
1.620 albertel 2122: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 2123: $cdom=
1.620 albertel 2124: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2125: $cnum=
1.620 albertel 2126: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2127: $udom=$env{'user.name'} unless (defined($udom));
2128: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 2129: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 2130: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 2131: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 2132: # assigned to this person
2133: # - this should not happen,
1.345 www 2134: # unless something went wrong
2135: # the first time around
2136: # ready to assign
1.364 www 2137: $logentry=$1.'; '.$logentry;
1.496 www 2138: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 2139: $kdom,$knum) eq 'ok') {
1.345 www 2140: # key now belongs to user
1.346 www 2141: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 2142: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 2143: &appenv({'environment.'.$envkey => $ckey});
1.345 www 2144: return 'ok';
2145: } else {
2146: return
2147: 'error: Count not permanently assign key, will need to be re-entered later.';
2148: }
2149: } else {
2150: return 'error: Could not assign key, try again later.';
2151: }
1.364 www 2152: } elsif (!$existing{$ckey}) {
1.345 www 2153: # the key does not exist
2154: return 'error: The key does not exist';
2155: } else {
2156: # the key is somebody else's
2157: return 'error: The key is already in use';
2158: }
1.344 www 2159: }
2160:
1.364 www 2161: # ------------------------------------------ put an additional comment on a key
2162:
2163: sub comment_access_key {
2164: #
2165: # a valid key looks like uname:udom#comments
2166: # comments are being appended
2167: #
2168: my ($ckey,$cdom,$cnum,$logentry)=@_;
2169: $cdom=
1.620 albertel 2170: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 2171: $cnum=
1.620 albertel 2172: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 2173: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2174: if ($existing{$ckey}) {
2175: $existing{$ckey}.='; '.$logentry;
2176: # ready to assign
1.367 www 2177: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 2178: $cdom,$cnum) eq 'ok') {
2179: return 'ok';
2180: } else {
2181: return 'error: Count not store comment.';
2182: }
2183: } else {
2184: # the key does not exist
2185: return 'error: The key does not exist';
2186: }
2187: }
2188:
1.344 www 2189: # ------------------------------------------------------ Generate a set of keys
2190:
2191: sub generate_access_keys {
1.364 www 2192: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 2193: $cdom=
1.620 albertel 2194: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2195: $cnum=
1.620 albertel 2196: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 2197: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 2198: unless (($cdom) && ($cnum)) { return 0; }
2199: if ($number>10000) { return 0; }
2200: sleep(2); # make sure don't get same seed twice
2201: srand(time()^($$+($$<<15))); # from "Programming Perl"
2202: my $total=0;
2203: for (my $i=1;$i<=$number;$i++) {
2204: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
2205: sprintf("%lx",int(100000*rand)).'-'.
2206: sprintf("%lx",int(100000*rand));
2207: $newkey=~s/1/g/g; # folks mix up 1 and l
2208: $newkey=~s/0/h/g; # and also 0 and O
2209: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
2210: if ($existing{$newkey}) {
2211: $i--;
2212: } else {
1.364 www 2213: if (&put('accesskeys',
2214: { $newkey => '# generated '.localtime().
1.620 albertel 2215: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 2216: '; '.$logentry },
2217: $cdom,$cnum) eq 'ok') {
1.344 www 2218: $total++;
2219: }
2220: }
2221: }
1.620 albertel 2222: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 2223: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
2224: return $total;
2225: }
2226:
2227: # ------------------------------------------------------- Validate an accesskey
2228:
2229: sub validate_access_key {
2230: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
2231: $cdom=
1.620 albertel 2232: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2233: $cnum=
1.620 albertel 2234: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2235: $udom=$env{'user.domain'} unless (defined($udom));
2236: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 2237: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 2238: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 2239: }
2240:
2241: # ------------------------------------- Find the section of student in a course
1.652 albertel 2242: sub devalidate_getsection_cache {
2243: my ($udom,$unam,$courseid)=@_;
2244: my $hashid="$udom:$unam:$courseid";
2245: &devalidate_cache_new('getsection',$hashid);
2246: }
1.298 matthew 2247:
1.815 albertel 2248: sub courseid_to_courseurl {
2249: my ($courseid) = @_;
2250: #already url style courseid
2251: return $courseid if ($courseid =~ m{^/});
2252:
2253: if (exists($env{'course.'.$courseid.'.num'})) {
2254: my $cnum = $env{'course.'.$courseid.'.num'};
2255: my $cdom = $env{'course.'.$courseid.'.domain'};
2256: return "/$cdom/$cnum";
2257: }
2258:
2259: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
2260: if (exists($courseinfo{'num'})) {
2261: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
2262: }
2263:
2264: return undef;
2265: }
2266:
1.298 matthew 2267: sub getsection {
2268: my ($udom,$unam,$courseid)=@_;
1.599 albertel 2269: my $cachetime=1800;
1.551 albertel 2270:
2271: my $hashid="$udom:$unam:$courseid";
1.599 albertel 2272: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 2273: if (defined($cached)) { return $result; }
2274:
1.298 matthew 2275: my %Pending;
2276: my %Expired;
2277: #
2278: # Each role can either have not started yet (pending), be active,
2279: # or have expired.
2280: #
2281: # If there is an active role, we are done.
2282: #
2283: # If there is more than one role which has not started yet,
2284: # choose the one which will start sooner
2285: # If there is one role which has not started yet, return it.
2286: #
2287: # If there is more than one expired role, choose the one which ended last.
2288: # If there is a role which has expired, return it.
2289: #
1.815 albertel 2290: $courseid = &courseid_to_courseurl($courseid);
1.1166 raeburn 2291: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817 raeburn 2292: foreach my $key (keys(%roleshash)) {
1.479 albertel 2293: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 2294: my $section=$1;
2295: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 2296: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 2297: my $now=time;
1.548 albertel 2298: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 2299: $Expired{$end}=$section;
2300: next;
2301: }
1.548 albertel 2302: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 2303: $Pending{$start}=$section;
2304: next;
2305: }
1.599 albertel 2306: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 2307: }
2308: #
2309: # Presumedly there will be few matching roles from the above
2310: # loop and the sorting time will be negligible.
2311: if (scalar(keys(%Pending))) {
2312: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 2313: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 2314: }
2315: if (scalar(keys(%Expired))) {
2316: my @sorted = sort {$a <=> $b} keys(%Expired);
2317: my $time = pop(@sorted);
1.599 albertel 2318: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 2319: }
1.599 albertel 2320: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 2321: }
1.70 www 2322:
1.599 albertel 2323: sub save_cache {
2324: &purge_remembered();
1.722 albertel 2325: #&Apache::loncommon::validate_page();
1.620 albertel 2326: undef(%env);
1.780 albertel 2327: undef($env_loaded);
1.599 albertel 2328: }
1.452 albertel 2329:
1.599 albertel 2330: my $to_remember=-1;
2331: my %remembered;
2332: my %accessed;
2333: my $kicks=0;
2334: my $hits=0;
1.849 albertel 2335: sub make_key {
2336: my ($name,$id) = @_;
1.872 albertel 2337: if (length($id) > 65
2338: && length(&escape($id)) > 200) {
2339: $id=length($id).':'.&Digest::MD5::md5_hex($id);
2340: }
1.849 albertel 2341: return &escape($name.':'.$id);
2342: }
2343:
1.599 albertel 2344: sub devalidate_cache_new {
2345: my ($name,$id,$debug) = @_;
2346: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849 albertel 2347: $id=&make_key($name,$id);
1.599 albertel 2348: $memcache->delete($id);
2349: delete($remembered{$id});
2350: delete($accessed{$id});
2351: }
2352:
2353: sub is_cached_new {
2354: my ($name,$id,$debug) = @_;
1.849 albertel 2355: $id=&make_key($name,$id);
1.599 albertel 2356: if (exists($remembered{$id})) {
1.1133 foxr 2357: if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
1.599 albertel 2358: $accessed{$id}=[&gettimeofday()];
2359: $hits++;
2360: return ($remembered{$id},1);
2361: }
2362: my $value = $memcache->get($id);
2363: if (!(defined($value))) {
2364: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 2365: return (undef,undef);
1.416 albertel 2366: }
1.599 albertel 2367: if ($value eq '__undef__') {
2368: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
2369: $value=undef;
2370: }
2371: &make_room($id,$value,$debug);
2372: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
2373: return ($value,1);
2374: }
2375:
2376: sub do_cache_new {
2377: my ($name,$id,$value,$time,$debug) = @_;
1.849 albertel 2378: $id=&make_key($name,$id);
1.599 albertel 2379: my $setvalue=$value;
2380: if (!defined($setvalue)) {
2381: $setvalue='__undef__';
2382: }
1.623 albertel 2383: if (!defined($time) ) {
2384: $time=600;
2385: }
1.599 albertel 2386: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 2387: my $result = $memcache->set($id,$setvalue,$time);
2388: if (! $result) {
1.872 albertel 2389: &logthis("caching of id -> $id failed");
1.910 albertel 2390: $memcache->disconnect_all();
1.872 albertel 2391: }
1.600 albertel 2392: # need to make a copy of $value
1.919 albertel 2393: &make_room($id,$value,$debug);
1.599 albertel 2394: return $value;
2395: }
2396:
2397: sub make_room {
2398: my ($id,$value,$debug)=@_;
1.919 albertel 2399:
2400: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
2401: : $value;
1.599 albertel 2402: if ($to_remember<0) { return; }
2403: $accessed{$id}=[&gettimeofday()];
2404: if (scalar(keys(%remembered)) <= $to_remember) { return; }
2405: my $to_kick;
2406: my $max_time=0;
2407: foreach my $other (keys(%accessed)) {
2408: if (&tv_interval($accessed{$other}) > $max_time) {
2409: $to_kick=$other;
2410: $max_time=&tv_interval($accessed{$other});
2411: }
2412: }
2413: delete($remembered{$to_kick});
2414: delete($accessed{$to_kick});
2415: $kicks++;
2416: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 2417: return;
2418: }
2419:
1.599 albertel 2420: sub purge_remembered {
1.604 albertel 2421: #&logthis("Tossing ".scalar(keys(%remembered)));
2422: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 2423: undef(%remembered);
2424: undef(%accessed);
1.428 albertel 2425: }
1.70 www 2426: # ------------------------------------- Read an entry from a user's environment
2427:
2428: sub userenvironment {
2429: my ($udom,$unam,@what)=@_;
1.976 raeburn 2430: my $items;
2431: foreach my $item (@what) {
2432: $items.=&escape($item).'&';
2433: }
2434: $items=~s/\&$//;
1.70 www 2435: my %returnhash=();
1.1009 raeburn 2436: my $uhome = &homeserver($unam,$udom);
2437: unless ($uhome eq 'no_host') {
2438: my @answer=split(/\&/,
2439: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 2440: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
2441: return %returnhash;
2442: }
1.1009 raeburn 2443: my $i;
2444: for ($i=0;$i<=$#what;$i++) {
2445: $returnhash{$what[$i]}=&unescape($answer[$i]);
2446: }
1.70 www 2447: }
2448: return %returnhash;
1.1 albertel 2449: }
2450:
1.617 albertel 2451: # ---------------------------------------------------------- Get a studentphoto
2452: sub studentphoto {
2453: my ($udom,$unam,$ext) = @_;
2454: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 2455: if (defined($env{'request.course.id'})) {
1.708 raeburn 2456: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 2457: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
2458: return(&retrievestudentphoto($udom,$unam,$ext));
2459: } else {
2460: my ($result,$perm_reqd)=
1.707 albertel 2461: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2462: if ($result eq 'ok') {
2463: if (!($perm_reqd eq 'yes')) {
2464: return(&retrievestudentphoto($udom,$unam,$ext));
2465: }
2466: }
2467: }
2468: }
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: return '/adm/lonKaputt/lonlogo_broken.gif';
2479: }
2480:
2481: sub retrievestudentphoto {
2482: my ($udom,$unam,$ext,$type) = @_;
2483: my $home=&Apache::lonnet::homeserver($unam,$udom);
2484: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
2485: if ($ret eq 'ok') {
2486: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
2487: if ($type eq 'thumbnail') {
2488: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
2489: }
2490: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
2491: return $tokenurl;
2492: } else {
2493: if ($type eq 'thumbnail') {
2494: return '/adm/lonKaputt/genericstudent_tn.gif';
2495: } else {
2496: return '/adm/lonKaputt/lonlogo_broken.gif';
2497: }
1.617 albertel 2498: }
2499: }
2500:
1.263 www 2501: # -------------------------------------------------------------------- New chat
2502:
2503: sub chatsend {
1.724 raeburn 2504: my ($newentry,$anon,$group)=@_;
1.620 albertel 2505: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
2506: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2507: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 2508: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 2509: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 2510: &escape($newentry)).':'.$group,$chome);
1.292 www 2511: }
2512:
2513: # ------------------------------------------ Find current version of a resource
2514:
2515: sub getversion {
2516: my $fname=&clutter(shift);
1.1189 raeburn 2517: unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292 www 2518: return ¤tversion(&filelocation('',$fname));
2519: }
2520:
2521: sub currentversion {
2522: my $fname=shift;
2523: my $author=$fname;
2524: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2525: my ($udom,$uname)=split(/\//,$author);
1.1112 www 2526: my $home=&homeserver($uname,$udom);
1.292 www 2527: if ($home eq 'no_host') {
2528: return -1;
2529: }
1.1112 www 2530: my $answer=&reply("currentversion:$fname",$home);
1.292 www 2531: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2532: return -1;
2533: }
1.1112 www 2534: return $answer;
1.263 www 2535: }
2536:
1.1111 www 2537: #
2538: # Return special version number of resource if set by override, empty otherwise
2539: #
2540: sub usedversion {
2541: my $fname=shift;
2542: unless ($fname) { $fname=$env{'request.uri'}; }
2543: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
2544: if ($urlversion) { return $urlversion; }
2545: return '';
2546: }
2547:
1.1 albertel 2548: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 2549:
1.1 albertel 2550: sub subscribe {
2551: my $fname=shift;
1.761 raeburn 2552: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 2553: $fname=~s/[\n\r]//g;
1.1 albertel 2554: my $author=$fname;
2555: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2556: my ($udom,$uname)=split(/\//,$author);
2557: my $home=homeserver($uname,$udom);
1.335 albertel 2558: if ($home eq 'no_host') {
2559: return 'not_found';
1.1 albertel 2560: }
2561: my $answer=reply("sub:$fname",$home);
1.64 www 2562: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2563: $answer.=' by '.$home;
2564: }
1.1 albertel 2565: return $answer;
2566: }
2567:
1.8 www 2568: # -------------------------------------------------------------- Replicate file
2569:
2570: sub repcopy {
2571: my $filename=shift;
1.23 www 2572: $filename=~s/\/+/\//g;
1.1142 raeburn 2573: my $londocroot = $perlvar{'lonDocRoot'};
2574: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164 raeburn 2575: if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142 raeburn 2576: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
2577: $filename=~m{^/*(uploaded|editupload)/}) {
1.538 albertel 2578: return &repcopy_userfile($filename);
2579: }
1.532 albertel 2580: $filename=~s/[\n\r]//g;
1.8 www 2581: my $transname="$filename.in.transfer";
1.828 www 2582: # FIXME: this should flock
1.607 raeburn 2583: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 2584: my $remoteurl=subscribe($filename);
1.64 www 2585: if ($remoteurl =~ /^con_lost by/) {
2586: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2587: return 'unavailable';
1.8 www 2588: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 2589: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 2590: return 'not_found';
1.64 www 2591: } elsif ($remoteurl =~ /^rejected by/) {
2592: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2593: return 'forbidden';
1.20 www 2594: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 2595: return 'ok';
1.8 www 2596: } else {
1.290 www 2597: my $author=$filename;
2598: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2599: my ($udom,$uname)=split(/\//,$author);
2600: my $home=homeserver($uname,$udom);
2601: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 2602: my @parts=split(/\//,$filename);
2603: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142 raeburn 2604: if ($path ne "$londocroot/res") {
1.8 www 2605: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 2606: return 'bad_request';
1.8 www 2607: }
2608: my $count;
2609: for ($count=5;$count<$#parts;$count++) {
2610: $path.="/$parts[$count]";
2611: if ((-e $path)!=1) {
2612: mkdir($path,0777);
2613: }
2614: }
2615: my $ua=new LWP::UserAgent;
2616: my $request=new HTTP::Request('GET',"$remoteurl");
2617: my $response=$ua->request($request,$transname);
2618: if ($response->is_error()) {
2619: unlink($transname);
2620: my $message=$response->status_line;
1.672 albertel 2621: &logthis("<font color=\"blue\">WARNING:"
1.12 www 2622: ." LWP get: $message: $filename</font>");
1.607 raeburn 2623: return 'unavailable';
1.8 www 2624: } else {
1.16 www 2625: if ($remoteurl!~/\.meta$/) {
2626: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2627: my $mresponse=$ua->request($mrequest,$filename.'.meta');
2628: if ($mresponse->is_error()) {
2629: unlink($filename.'.meta');
2630: &logthis(
1.672 albertel 2631: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 2632: }
2633: }
1.8 www 2634: rename($transname,$filename);
1.607 raeburn 2635: return 'ok';
1.8 www 2636: }
1.290 www 2637: }
1.8 www 2638: }
1.330 www 2639: }
2640:
2641: # ------------------------------------------------ Get server side include body
2642: sub ssi_body {
1.381 albertel 2643: my ($filelink,%form)=@_;
1.606 matthew 2644: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
2645: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
2646: }
1.953 www 2647: my $output='';
2648: my $response;
1.980 raeburn 2649: if ($filelink=~/^https?\:/) {
1.954 raeburn 2650: ($output,$response)=&externalssi($filelink);
1.953 www 2651: } else {
1.1004 droeschl 2652: $filelink .= $filelink=~/\?/ ? '&' : '?';
2653: $filelink .= 'inhibitmenu=yes';
1.953 www 2654: ($output,$response)=&ssi($filelink,%form);
2655: }
1.778 albertel 2656: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 2657: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 2658: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 2659: if (wantarray) {
2660: return ($output, $response);
2661: } else {
2662: return $output;
2663: }
1.8 www 2664: }
2665:
1.15 www 2666: # --------------------------------------------------------- Server Side Include
2667:
1.782 albertel 2668: sub absolute_url {
2669: my ($host_name) = @_;
2670: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
2671: if ($host_name eq '') {
2672: $host_name = $ENV{'SERVER_NAME'};
2673: }
2674: return $protocol.$host_name;
2675: }
2676:
1.942 foxr 2677: #
2678: # Server side include.
2679: # Parameters:
2680: # fn Possibly encrypted resource name/id.
2681: # form Hash that describes how the rendering should be done
2682: # and other things.
1.944 foxr 2683: # Returns:
1.950 raeburn 2684: # Scalar context: The content of the response.
2685: # Array context: 2 element list of the content and the full response object.
1.942 foxr 2686: #
1.15 www 2687: sub ssi {
2688:
1.944 foxr 2689: my ($fn,%form)=@_;
1.15 www 2690: my $ua=new LWP::UserAgent;
1.23 www 2691: my $request;
1.711 albertel 2692:
2693: $form{'no_update_last_known'}=1;
1.895 albertel 2694: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 2695: if (%form) {
1.782 albertel 2696: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000 raeburn 2697: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23 www 2698: } else {
1.782 albertel 2699: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 2700: }
2701:
1.15 www 2702: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1173 foxr 2703: my $response= $ua->request($request);
1.1182 foxr 2704: my $content = $response->content;
2705:
2706:
1.944 foxr 2707: if (wantarray) {
1.1173 foxr 2708: return ($content, $response);
1.944 foxr 2709: } else {
1.1173 foxr 2710: return $content;
1.942 foxr 2711: }
1.324 www 2712: }
2713:
2714: sub externalssi {
2715: my ($url)=@_;
2716: my $ua=new LWP::UserAgent;
2717: my $request=new HTTP::Request('GET',$url);
2718: my $response=$ua->request($request);
1.954 raeburn 2719: if (wantarray) {
2720: return ($response->content, $response);
2721: } else {
2722: return $response->content;
2723: }
1.15 www 2724: }
1.254 www 2725:
1.492 albertel 2726: # -------------------------------- Allow a /uploaded/ URI to be vouched for
2727:
2728: sub allowuploaded {
2729: my ($srcurl,$url)=@_;
2730: $url=&clutter(&declutter($url));
2731: my $dir=$url;
2732: $dir=~s/\/[^\/]+$//;
2733: my %httpref=();
2734: my $httpurl=&hreflocation('',$url);
2735: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 2736: &Apache::lonnet::appenv(\%httpref);
1.254 www 2737: }
1.477 raeburn 2738:
1.1193 raeburn 2739: #
2740: # Determine if the current user should be able to edit a particular resource,
2741: # when viewing in course context.
2742: # (a) When viewing resource used to determine if "Edit" item is included in
2743: # Functions.
2744: # (b) When displaying folder contents in course editor, used to determine if
2745: # "Edit" link will be displayed alongside resource.
2746: #
1.1196 raeburn 2747: # input: six args -- filename (decluttered), course number, course domain,
2748: # url, symb (if registered) and group (if this is a group
2749: # item -- e.g., bulletin board, group page etc.).
2750: # output: array of five scalars --
1.1193 raeburn 2751: # $cfile -- url for file editing if editable on current server
2752: # $home -- homeserver of resource (i.e., for author if published,
2753: # or course if uploaded.).
2754: # $switchserver -- 1 if server switch will be needed.
1.1196 raeburn 2755: # $forceedit -- 1 if icon/link should be to go to edit mode
2756: # $forceview -- 1 if icon/link should be to go to view mode
1.1193 raeburn 2757: #
2758:
2759: sub can_edit_resource {
1.1194 raeburn 2760: my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
2761: my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
2762: #
2763: # For aboutme pages user can only edit his/her own.
2764: #
1.1199 raeburn 2765: if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
1.1194 raeburn 2766: my ($sdom,$sname) = ($1,$2);
2767: if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
2768: $home = $env{'user.home'};
2769: $cfile = $resurl;
2770: if ($env{'form.forceedit'}) {
2771: $forceview = 1;
2772: } else {
2773: $forceedit = 1;
2774: }
2775: return ($cfile,$home,$switchserver,$forceedit,$forceview);
2776: } else {
2777: return;
2778: }
2779: }
2780:
2781: if ($env{'request.course.id'}) {
2782: my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
2783: if ($group ne '') {
2784: # if this is a group homepage or group bulletin board, check group privs
2785: my $allowed = 0;
1.1197 raeburn 2786: if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
2787: if ((&allowed('mdg',$env{'request.course.id'}.
1.1198 raeburn 2788: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
1.1194 raeburn 2789: (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
2790: $allowed = 1;
2791: }
1.1197 raeburn 2792: } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
2793: if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
2794: (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
1.1194 raeburn 2795: $allowed = 1;
2796: }
2797: }
2798: if ($allowed) {
2799: $home=&homeserver($cnum,$cdom);
2800: if ($env{'form.forceedit'}) {
2801: $forceview = 1;
2802: } else {
2803: $forceedit = 1;
2804: }
2805: $cfile = $resurl;
2806: } else {
2807: return;
2808: }
2809: } else {
1.1208 raeburn 2810: if ($resurl =~ m{^/?adm/viewclasslist$}) {
2811: unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
2812: return;
2813: }
2814: } elsif (!$crsedit) {
1.1194 raeburn 2815: #
2816: # No edit allowed where CC has switched to student role.
2817: #
2818: return;
2819: }
2820: }
2821: }
2822:
1.1193 raeburn 2823: if ($file ne '') {
2824: if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
1.1194 raeburn 2825: if (&is_course_upload($file,$cnum,$cdom)) {
2826: $uploaded = 1;
2827: $incourse = 1;
1.1193 raeburn 2828: if ($file =~/\.(htm|html|css|js|txt)$/) {
2829: $cfile = &hreflocation('',$file);
1.1201 raeburn 2830: if ($env{'form.forceedit'}) {
2831: $forceview = 1;
2832: } else {
2833: $forceedit = 1;
2834: }
1.1194 raeburn 2835: }
2836: } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
2837: $incourse = 1;
2838: if ($env{'form.forceedit'}) {
2839: $forceview = 1;
2840: } else {
2841: $forceedit = 1;
2842: }
2843: $cfile = $resurl;
2844: } elsif (($resurl ne '') && (&is_on_map($resurl))) {
2845: if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
2846: $incourse = 1;
2847: if ($env{'form.forceedit'}) {
2848: $forceview = 1;
2849: } else {
2850: $forceedit = 1;
2851: }
2852: $cfile = $resurl;
1.1199 raeburn 2853: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
1.1194 raeburn 2854: $incourse = 1;
2855: $cfile = $resurl.'/smpedit';
1.1199 raeburn 2856: } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
1.1194 raeburn 2857: $incourse = 1;
1.1199 raeburn 2858: if ($env{'form.forceedit'}) {
2859: $forceview = 1;
2860: } else {
2861: $forceedit = 1;
2862: }
2863: $cfile = $resurl;
1.1208 raeburn 2864: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
2865: $incourse = 1;
2866: if ($env{'form.forceedit'}) {
2867: $forceview = 1;
2868: } else {
2869: $forceedit = 1;
2870: }
2871: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1194 raeburn 2872: }
2873: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
2874: my $template = '/res/lib/templates/simpleproblem.problem';
2875: if (&is_on_map($template)) {
2876: $incourse = 1;
2877: $forceview = 1;
2878: $cfile = $template;
1.1193 raeburn 2879: }
1.1199 raeburn 2880: } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
2881: $incourse = 1;
2882: if ($env{'form.forceedit'}) {
2883: $forceview = 1;
2884: } else {
2885: $forceedit = 1;
2886: }
2887: $cfile = $resurl;
2888: } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
2889: $incourse = 1;
2890: $forceview = 1;
2891: if ($symb) {
2892: my ($map,$id,$res)=&decode_symb($symb);
2893: $env{'request.symb'} = $symb;
2894: $cfile = &clutter($res);
2895: } else {
2896: $cfile = $env{'form.suppurl'};
2897: $cfile =~ s{^http://}{};
2898: $cfile = '/adm/wrapper/ext/'.$cfile;
2899: }
1.1234 raeburn 2900: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
2901: if ($env{'form.forceedit'}) {
2902: $forceview = 1;
2903: } else {
2904: $forceedit = 1;
2905: }
2906: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1193 raeburn 2907: }
2908: }
1.1194 raeburn 2909: if ($uploaded || $incourse) {
2910: $home=&homeserver($cnum,$cdom);
1.1207 raeburn 2911: } elsif ($file !~ m{/$}) {
1.1193 raeburn 2912: $file=~s{^(priv/$match_domain/$match_username)}{/$1};
2913: $file=~s{^($match_domain/$match_username)}{/priv/$1};
2914: # Check that the user has permission to edit this resource
2915: my $setpriv = 1;
2916: my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
2917: if (defined($cfudom)) {
2918: $home=&homeserver($cfuname,$cfudom);
2919: $cfile=$file;
2920: }
2921: }
1.1194 raeburn 2922: if (($cfile ne '') && (!$incourse || $uploaded) &&
2923: (($home ne '') && ($home ne 'no_host'))) {
1.1193 raeburn 2924: my @ids=¤t_machine_ids();
2925: unless (grep(/^\Q$home\E$/,@ids)) {
2926: $switchserver=1;
2927: }
2928: }
2929: }
1.1194 raeburn 2930: return ($cfile,$home,$switchserver,$forceedit,$forceview);
1.1193 raeburn 2931: }
2932:
2933: sub is_course_upload {
2934: my ($file,$cnum,$cdom) = @_;
2935: my $uploadpath = &LONCAPA::propath($cdom,$cnum);
2936: $uploadpath =~ s{^\/}{};
1.1201 raeburn 2937: if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
2938: ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
1.1193 raeburn 2939: return 1;
2940: }
2941: return;
2942: }
2943:
1.1194 raeburn 2944: sub in_course {
1.1195 raeburn 2945: my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
2946: if ($hideprivileged) {
2947: my $skipuser;
1.1219 raeburn 2948: my %coursehash = &coursedescription($cdom.'_'.$cnum);
2949: my @possdoms = ($cdom);
2950: if ($coursehash{'checkforpriv'}) {
2951: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
2952: }
2953: if (&privileged($uname,$udom,\@possdoms)) {
1.1195 raeburn 2954: $skipuser = 1;
2955: if ($coursehash{'nothideprivileged'}) {
2956: foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
2957: my $user;
2958: if ($item =~ /:/) {
2959: $user = $item;
2960: } else {
2961: $user = join(':',split(/[\@]/,$item));
2962: }
2963: if ($user eq $uname.':'.$udom) {
2964: undef($skipuser);
2965: last;
2966: }
2967: }
2968: }
2969: if ($skipuser) {
2970: return 0;
2971: }
2972: }
2973: }
1.1194 raeburn 2974: $type ||= 'any';
2975: if (!defined($cdom) || !defined($cnum)) {
2976: my $cid = $env{'request.course.id'};
2977: $cdom = $env{'course.'.$cid.'.domain'};
2978: $cnum = $env{'course.'.$cid.'.num'};
2979: }
2980: my $typesref;
1.1195 raeburn 2981: if (($type eq 'any') || ($type eq 'all')) {
1.1194 raeburn 2982: $typesref = ['active','previous','future'];
2983: } elsif ($type eq 'previous' || $type eq 'future') {
2984: $typesref = [$type];
2985: }
2986: my %roles = &get_my_roles($uname,$udom,'userroles',
2987: $typesref,undef,[$cdom]);
2988: my ($tmp) = keys(%roles);
2989: return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
2990: my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
2991: if (@course_roles > 0) {
2992: return 1;
2993: }
2994: return 0;
2995: }
2996:
1.478 albertel 2997: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 2998: # input: action, courseID, current domain, intended
1.637 raeburn 2999: # path to file, source of file, instruction to parse file for objects,
3000: # ref to hash for embedded objects,
3001: # ref to hash for codebase of java objects.
1.1095 raeburn 3002: # reference to scalar to accommodate mime type determined
3003: # from File::MMagic if $parser = parse.
1.637 raeburn 3004: #
1.485 raeburn 3005: # output: url to file (if action was uploaddoc),
3006: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 3007: #
1.478 albertel 3008: # Allows directory structure to be used within lonUsers/../userfiles/ for a
3009: # course.
1.477 raeburn 3010: #
1.478 albertel 3011: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3012: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
3013: # course's home server.
1.477 raeburn 3014: #
1.478 albertel 3015: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
3016: # be copied from $source (current location) to
3017: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3018: # and will then be copied to
3019: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
3020: # course's home server.
1.485 raeburn 3021: #
1.481 raeburn 3022: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 3023: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 3024: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3025: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
3026: # in course's home server.
1.637 raeburn 3027: #
1.477 raeburn 3028:
3029: sub process_coursefile {
1.1095 raeburn 3030: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
3031: $mimetype)=@_;
1.477 raeburn 3032: my $fetchresult;
1.638 albertel 3033: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 3034: if ($action eq 'propagate') {
1.638 albertel 3035: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
3036: $home);
1.481 raeburn 3037: } else {
1.477 raeburn 3038: my $fpath = '';
3039: my $fname = $file;
1.478 albertel 3040: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 3041: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 3042: my $filepath = &build_filepath($fpath);
1.481 raeburn 3043: if ($action eq 'copy') {
3044: if ($source eq '') {
3045: $fetchresult = 'no source file';
3046: return $fetchresult;
3047: } else {
3048: my $destination = $filepath.'/'.$fname;
3049: rename($source,$destination);
3050: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3051: $home);
1.481 raeburn 3052: }
3053: } elsif ($action eq 'uploaddoc') {
3054: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 3055: print $fh $env{'form.'.$source};
1.481 raeburn 3056: close($fh);
1.637 raeburn 3057: if ($parser eq 'parse') {
1.1024 raeburn 3058: my $mm = new File::MMagic;
1.1095 raeburn 3059: my $type = $mm->checktype_filename($filepath.'/'.$fname);
3060: if ($type eq 'text/html') {
1.1024 raeburn 3061: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
3062: unless ($parse_result eq 'ok') {
3063: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
3064: }
1.637 raeburn 3065: }
1.1095 raeburn 3066: if (ref($mimetype)) {
3067: $$mimetype = $type;
3068: }
1.637 raeburn 3069: }
1.477 raeburn 3070: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3071: $home);
1.481 raeburn 3072: if ($fetchresult eq 'ok') {
3073: return '/uploaded/'.$fpath.'/'.$fname;
3074: } else {
3075: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3076: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 3077: return '/adm/notfound.html';
3078: }
1.477 raeburn 3079: }
3080: }
1.485 raeburn 3081: unless ( $fetchresult eq 'ok') {
1.477 raeburn 3082: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3083: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 3084: }
3085: return $fetchresult;
3086: }
3087:
1.637 raeburn 3088: sub build_filepath {
3089: my ($fpath) = @_;
3090: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
3091: unless ($fpath eq '') {
3092: my @parts=split('/',$fpath);
3093: foreach my $part (@parts) {
3094: $filepath.= '/'.$part;
3095: if ((-e $filepath)!=1) {
3096: mkdir($filepath,0777);
3097: }
3098: }
3099: }
3100: return $filepath;
3101: }
3102:
3103: sub store_edited_file {
1.638 albertel 3104: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 3105: my $file = $primary_url;
3106: $file =~ s#^/uploaded/$docudom/$docuname/##;
3107: my $fpath = '';
3108: my $fname = $file;
3109: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
3110: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
3111: my $filepath = &build_filepath($fpath);
3112: open(my $fh,'>'.$filepath.'/'.$fname);
3113: print $fh $content;
3114: close($fh);
1.638 albertel 3115: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 3116: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3117: $home);
1.637 raeburn 3118: if ($$fetchresult eq 'ok') {
3119: return '/uploaded/'.$fpath.'/'.$fname;
3120: } else {
1.638 albertel 3121: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
3122: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 3123: return '/adm/notfound.html';
3124: }
3125: }
3126:
1.531 albertel 3127: sub clean_filename {
1.831 albertel 3128: my ($fname,$args)=@_;
1.315 www 3129: # Replace Windows backslashes by forward slashes
1.257 www 3130: $fname=~s/\\/\//g;
1.831 albertel 3131: if (!$args->{'keep_path'}) {
3132: # Get rid of everything but the actual filename
3133: $fname=~s/^.*\/([^\/]+)$/$1/;
3134: }
1.315 www 3135: # Replace spaces by underscores
3136: $fname=~s/\s+/\_/g;
3137: # Replace all other weird characters by nothing
1.831 albertel 3138: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 3139: # Replace all .\d. sequences with _\d. so they no longer look like version
3140: # numbers
3141: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 3142: return $fname;
3143: }
1.1051 raeburn 3144: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
3145: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
3146: # image with the same aspect ratio as the original, but with dimensions which do
3147: # not exceed $resizewidth and $resizeheight.
3148:
1.984 neumanie 3149: sub resizeImage {
1.1051 raeburn 3150: my ($img_path,$resizewidth,$resizeheight) = @_;
3151: my $ima = Image::Magick->new;
3152: my $resized;
3153: if (-e $img_path) {
3154: $ima->Read($img_path);
3155: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
3156: my $width = $ima->Get('width');
3157: my $height = $ima->Get('height');
3158: if ($width > $resizewidth) {
3159: my $factor = $width/$resizewidth;
3160: my $newheight = $height/$factor;
3161: $ima->Scale(width=>$resizewidth,height=>$newheight);
3162: $resized = 1;
3163: }
3164: }
3165: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
3166: my $width = $ima->Get('width');
3167: my $height = $ima->Get('height');
3168: if ($height > $resizeheight) {
3169: my $factor = $height/$resizeheight;
3170: my $newwidth = $width/$factor;
3171: $ima->Scale(width=>$newwidth,height=>$resizeheight);
3172: $resized = 1;
3173: }
3174: }
3175: if ($resized) {
3176: $ima->Write($img_path);
3177: }
3178: }
3179: return;
1.977 amueller 3180: }
3181:
1.608 albertel 3182: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 3183: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093 raeburn 3184: # the desired filename is in $env{"form.$formname.filename"}
1.1090 raeburn 3185: # $context - possible values: coursedoc, existingfile, overwrite,
3186: # canceloverwrite, or ''.
3187: # if 'coursedoc': upload to the current course
3188: # if 'existingfile': write file to tmp/overwrites directory
3189: # if 'canceloverwrite': delete file written to tmp/overwrites directory
3190: # $context is passed as argument to &finishuserfileupload
1.686 albertel 3191: # $subdir - directory in userfile to store the file into
1.858 raeburn 3192: # $parser - instruction to parse file for objects ($parser = parse)
3193: # $allfiles - reference to hash for embedded objects
3194: # $codebase - reference to hash for codebase of java objects
3195: # $desuname - username for permanent storage of uploaded file
3196: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 3197: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
3198: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 3199: # $resizewidth - width (pixels) to which to resize uploaded image
3200: # $resizeheight - height (pixels) to which to resize uploaded image
1.1095 raeburn 3201: # $mimetype - reference to scalar to accommodate mime type determined
1.1152 raeburn 3202: # from File::MMagic.
1.858 raeburn 3203: #
1.686 albertel 3204: # output: url of file in userspace, or error: <message>
3205: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 3206:
1.531 albertel 3207: sub userfileupload {
1.1090 raeburn 3208: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095 raeburn 3209: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531 albertel 3210: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 3211: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 3212: $fname=&clean_filename($fname);
1.1090 raeburn 3213: # See if there is anything left
1.257 www 3214: unless ($fname) { return 'error: no uploaded file'; }
1.1090 raeburn 3215: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
3216: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
3217: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
3218: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523 raeburn 3219: my $now = time;
1.1090 raeburn 3220: my $filepath;
1.1095 raeburn 3221: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090 raeburn 3222: $filepath = 'tmp/helprequests/'.$now;
3223: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
3224: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
3225: '_'.$env{'user.domain'}.'/pending';
3226: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
3227: my ($docuname,$docudom);
3228: if ($destudom) {
3229: $docudom = $destudom;
3230: } else {
3231: $docudom = $env{'user.domain'};
3232: }
3233: if ($destuname) {
3234: $docuname = $destuname;
3235: } else {
3236: $docuname = $env{'user.name'};
3237: }
3238: if (exists($env{'form.group'})) {
3239: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3240: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3241: }
3242: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
3243: if ($context eq 'canceloverwrite') {
3244: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
3245: if (-e $tempfile) {
3246: my @info = stat($tempfile);
3247: if ($info[9] eq $env{'form.timestamp'}) {
3248: unlink($tempfile);
3249: }
3250: }
3251: return;
1.523 raeburn 3252: }
3253: }
1.1090 raeburn 3254: # Create the directory if not present
1.741 raeburn 3255: my @parts=split(/\//,$filepath);
3256: my $fullpath = $perlvar{'lonDaemons'};
3257: for (my $i=0;$i<@parts;$i++) {
3258: $fullpath .= '/'.$parts[$i];
3259: if ((-e $fullpath)!=1) {
3260: mkdir($fullpath,0777);
3261: }
3262: }
3263: open(my $fh,'>'.$fullpath.'/'.$fname);
3264: print $fh $env{'form.'.$formname};
3265: close($fh);
1.1090 raeburn 3266: if ($context eq 'existingfile') {
3267: my @info = stat($fullpath.'/'.$fname);
3268: return ($fullpath.'/'.$fname,$info[9]);
3269: } else {
3270: return $fullpath.'/'.$fname;
3271: }
1.523 raeburn 3272: }
1.995 raeburn 3273: if ($subdir eq 'scantron') {
3274: $fname = 'scantron_orig_'.$fname;
1.1093 raeburn 3275: } else {
1.995 raeburn 3276: $fname="$subdir/$fname";
3277: }
1.1090 raeburn 3278: if ($context eq 'coursedoc') {
1.638 albertel 3279: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3280: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 3281: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 3282: return &finishuserfileupload($docuname,$docudom,
3283: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 3284: $codebase,$thumbwidth,$thumbheight,
1.1095 raeburn 3285: $resizewidth,$resizeheight,$context,$mimetype);
1.481 raeburn 3286: } else {
1.1218 raeburn 3287: if ($env{'form.folder'}) {
3288: $fname=$env{'form.folder'}.'/'.$fname;
3289: }
1.638 albertel 3290: return &process_coursefile('uploaddoc',$docuname,$docudom,
3291: $fname,$formname,$parser,
1.1095 raeburn 3292: $allfiles,$codebase,$mimetype);
1.481 raeburn 3293: }
1.719 banghart 3294: } elsif (defined($destuname)) {
3295: my $docuname=$destuname;
3296: my $docudom=$destudom;
1.860 raeburn 3297: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3298: $parser,$allfiles,$codebase,
1.1051 raeburn 3299: $thumbwidth,$thumbheight,
1.1095 raeburn 3300: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3301: } else {
1.638 albertel 3302: my $docuname=$env{'user.name'};
3303: my $docudom=$env{'user.domain'};
1.1220 raeburn 3304: if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714 raeburn 3305: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3306: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3307: }
1.860 raeburn 3308: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3309: $parser,$allfiles,$codebase,
1.1051 raeburn 3310: $thumbwidth,$thumbheight,
1.1095 raeburn 3311: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3312: }
1.271 www 3313: }
3314:
3315: sub finishuserfileupload {
1.860 raeburn 3316: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095 raeburn 3317: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477 raeburn 3318: my $path=$docudom.'/'.$docuname.'/';
1.258 www 3319: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 3320:
1.860 raeburn 3321: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 3322: $file=$fname;
3323: if ($fname=~m|/|) {
3324: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
3325: $path.=$fnamepath.'/';
3326: }
1.259 www 3327: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 3328: my $count;
3329: for ($count=4;$count<=$#parts;$count++) {
3330: $filepath.="/$parts[$count]";
3331: if ((-e $filepath)!=1) {
3332: mkdir($filepath,0777);
3333: }
3334: }
1.984 neumanie 3335:
1.258 www 3336: # Save the file
3337: {
1.701 albertel 3338: if (!open(FH,'>'.$filepath.'/'.$file)) {
3339: &logthis('Failed to create '.$filepath.'/'.$file);
3340: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
3341: return '/adm/notfound.html';
3342: }
1.1090 raeburn 3343: if ($context eq 'overwrite') {
1.1117 foxr 3344: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090 raeburn 3345: my $target = $filepath.'/'.$file;
3346: if (-e $source) {
3347: my @info = stat($source);
3348: if ($info[9] eq $env{'form.timestamp'}) {
3349: unless (&File::Copy::move($source,$target)) {
3350: &logthis('Failed to overwrite '.$filepath.'/'.$file);
3351: return "Moving from $source failed";
3352: }
3353: } else {
3354: return "Temporary file: $source had unexpected date/time for last modification";
3355: }
3356: } else {
3357: return "Temporary file: $source missing";
3358: }
3359: } elsif (!print FH ($env{'form.'.$formname})) {
1.701 albertel 3360: &logthis('Failed to write to '.$filepath.'/'.$file);
3361: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
3362: return '/adm/notfound.html';
3363: }
1.570 albertel 3364: close(FH);
1.1051 raeburn 3365: if ($resizewidth && $resizeheight) {
3366: my $mm = new File::MMagic;
3367: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
3368: if ($mime_type =~ m{^image/}) {
3369: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
3370: }
1.977 amueller 3371: }
1.258 www 3372: }
1.1152 raeburn 3373: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
3374: if (ref($mimetype)) {
3375: if ($$mimetype eq '') {
3376: my $mm = new File::MMagic;
3377: my $type = $mm->checktype_filename($filepath.'/'.$file);
3378: $$mimetype = $type;
3379: }
3380: }
3381: }
1.637 raeburn 3382: if ($parser eq 'parse') {
1.1152 raeburn 3383: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024 raeburn 3384: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
3385: $allfiles,$codebase);
3386: unless ($parse_result eq 'ok') {
3387: &logthis('Failed to parse '.$filepath.$file.
3388: ' for embedded media: '.$parse_result);
3389: }
1.637 raeburn 3390: }
3391: }
1.860 raeburn 3392: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
3393: my $input = $filepath.'/'.$file;
3394: my $output = $filepath.'/'.'tn-'.$file;
3395: my $thumbsize = $thumbwidth.'x'.$thumbheight;
3396: system("convert -sample $thumbsize $input $output");
3397: if (-e $filepath.'/'.'tn-'.$file) {
3398: $fetchthumb = 1;
3399: }
3400: }
1.858 raeburn 3401:
1.259 www 3402: # Notify homeserver to grep it
3403: #
1.984 neumanie 3404: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 3405: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 3406: if ($fetchresult eq 'ok') {
1.860 raeburn 3407: if ($fetchthumb) {
3408: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
3409: if ($thumbresult ne 'ok') {
3410: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
3411: $docuhome.': '.$thumbresult);
3412: }
3413: }
1.259 www 3414: #
1.258 www 3415: # Return the URL to it
1.494 albertel 3416: return '/uploaded/'.$path.$file;
1.263 www 3417: } else {
1.494 albertel 3418: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
3419: ': '.$fetchresult);
1.263 www 3420: return '/adm/notfound.html';
1.858 raeburn 3421: }
1.493 albertel 3422: }
3423:
1.637 raeburn 3424: sub extract_embedded_items {
1.961 raeburn 3425: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 3426: my @state = ();
1.1164 raeburn 3427: my (%lastids,%related,%shockwave,%flashvars);
1.637 raeburn 3428: my %javafiles = (
3429: codebase => '',
3430: code => '',
3431: archive => ''
3432: );
3433: my %mediafiles = (
3434: src => '',
3435: movie => '',
3436: );
1.648 raeburn 3437: my $p;
3438: if ($content) {
3439: $p = HTML::LCParser->new($content);
3440: } else {
1.961 raeburn 3441: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 3442: }
1.641 albertel 3443: while (my $t=$p->get_token()) {
1.640 albertel 3444: if ($t->[0] eq 'S') {
3445: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 3446: push(@state, $tagname);
1.648 raeburn 3447: if (lc($tagname) eq 'allow') {
3448: &add_filetype($allfiles,$attr->{'src'},'src');
3449: }
1.640 albertel 3450: if (lc($tagname) eq 'img') {
3451: &add_filetype($allfiles,$attr->{'src'},'src');
3452: }
1.886 albertel 3453: if (lc($tagname) eq 'a') {
1.1222 raeburn 3454: unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
1.1221 raeburn 3455: &add_filetype($allfiles,$attr->{'href'},'href');
3456: }
1.886 albertel 3457: }
1.645 raeburn 3458: if (lc($tagname) eq 'script') {
1.1164 raeburn 3459: my $src;
1.645 raeburn 3460: if ($attr->{'archive'} =~ /\.jar$/i) {
3461: &add_filetype($allfiles,$attr->{'archive'},'archive');
3462: } else {
1.1164 raeburn 3463: if ($attr->{'src'} ne '') {
3464: $src = $attr->{'src'};
3465: &add_filetype($allfiles,$src,'src');
3466: }
3467: }
3468: my $text = $p->get_trimmed_text();
3469: if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
3470: my @swfargs = split(/,/,$1);
3471: foreach my $item (@swfargs) {
3472: $item =~ s/["']//g;
3473: $item =~ s/^\s+//;
3474: $item =~ s/\s+$//;
3475: }
3476: if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
3477: if (ref($related{$swfargs[0]}) eq 'ARRAY') {
3478: push(@{$related{$swfargs[0]}},$swfargs[2]);
3479: } else {
3480: $related{$swfargs[0]} = [$swfargs[2]];
3481: }
3482: }
1.645 raeburn 3483: }
3484: }
3485: if (lc($tagname) eq 'link') {
3486: if (lc($attr->{'rel'}) eq 'stylesheet') {
3487: &add_filetype($allfiles,$attr->{'href'},'href');
3488: }
3489: }
1.640 albertel 3490: if (lc($tagname) eq 'object' ||
3491: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
3492: foreach my $item (keys(%javafiles)) {
3493: $javafiles{$item} = '';
3494: }
1.1164 raeburn 3495: if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
3496: $lastids{lc($tagname)} = $attr->{'id'};
3497: }
1.640 albertel 3498: }
3499: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
3500: my $name = lc($attr->{'name'});
3501: foreach my $item (keys(%javafiles)) {
3502: if ($name eq $item) {
3503: $javafiles{$item} = $attr->{'value'};
3504: last;
3505: }
3506: }
1.1164 raeburn 3507: my $pathfrom;
1.640 albertel 3508: foreach my $item (keys(%mediafiles)) {
3509: if ($name eq $item) {
1.1164 raeburn 3510: $pathfrom = $attr->{'value'};
3511: $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
3512: &add_filetype($allfiles,$pathfrom,$name);
1.640 albertel 3513: last;
3514: }
3515: }
1.1164 raeburn 3516: if ($name eq 'flashvars') {
3517: $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
3518: }
3519: if ($pathfrom ne '') {
3520: &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
3521: $pathfrom);
3522: }
1.640 albertel 3523: }
3524: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
3525: foreach my $item (keys(%javafiles)) {
3526: if ($attr->{$item}) {
3527: $javafiles{$item} = $attr->{$item};
3528: last;
3529: }
3530: }
3531: foreach my $item (keys(%mediafiles)) {
3532: if ($attr->{$item}) {
3533: &add_filetype($allfiles,$attr->{$item},$item);
3534: last;
3535: }
3536: }
1.1164 raeburn 3537: if (lc($tagname) eq 'embed') {
3538: if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
3539: &embedded_dependency($allfiles,\%related,$attr->{'name'},
3540: $attr->{'src'});
3541: }
3542: }
1.640 albertel 3543: }
1.1243 raeburn 3544: if (lc($tagname) eq 'iframe') {
3545: my $src = $attr->{'src'} ;
3546: if (($src ne '') && ($src !~ m{^(/|https?://)})) {
3547: &add_filetype($allfiles,$src,'src');
3548: } elsif ($src =~ m{^/}) {
3549: if ($env{'request.course.id'}) {
3550: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
3551: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
3552: my $url = &hreflocation('',$fullpath);
3553: if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
3554: my $relpath = $1;
3555: if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
3556: &add_filetype($allfiles,$1,'src');
3557: }
3558: }
3559: }
3560: }
3561: }
1.1164 raeburn 3562: if ($t->[4] =~ m{/>$}) {
1.1243 raeburn 3563: pop(@state);
1.1164 raeburn 3564: }
1.640 albertel 3565: } elsif ($t->[0] eq 'E') {
3566: my ($tagname) = ($t->[1]);
3567: if ($javafiles{'codebase'} ne '') {
3568: $javafiles{'codebase'} .= '/';
3569: }
3570: if (lc($tagname) eq 'applet' ||
3571: lc($tagname) eq 'object' ||
3572: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
3573: ) {
3574: foreach my $item (keys(%javafiles)) {
3575: if ($item ne 'codebase' && $javafiles{$item} ne '') {
3576: my $file=$javafiles{'codebase'}.$javafiles{$item};
3577: &add_filetype($allfiles,$file,$item);
3578: }
3579: }
3580: }
3581: pop @state;
3582: }
3583: }
1.1164 raeburn 3584: foreach my $id (sort(keys(%flashvars))) {
3585: if ($shockwave{$id} ne '') {
3586: my @pairs = split(/\&/,$flashvars{$id});
3587: foreach my $pair (@pairs) {
3588: my ($key,$value) = split(/\=/,$pair);
3589: if ($key eq 'thumb') {
3590: &add_filetype($allfiles,$value,$key);
3591: } elsif ($key eq 'content') {
3592: my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
3593: my ($ext) = ($value =~ /\.([^.]+)$/);
3594: if ($ext ne '') {
3595: &add_filetype($allfiles,$path.$value,$ext);
3596: }
3597: }
3598: }
3599: }
3600: }
1.637 raeburn 3601: return 'ok';
3602: }
3603:
1.639 albertel 3604: sub add_filetype {
3605: my ($allfiles,$file,$type)=@_;
3606: if (exists($allfiles->{$file})) {
3607: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
3608: push(@{$allfiles->{$file}}, &escape($type));
3609: }
3610: } else {
3611: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 3612: }
3613: }
3614:
1.1164 raeburn 3615: sub embedded_dependency {
3616: my ($allfiles,$related,$identifier,$pathfrom) = @_;
3617: if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
3618: if (($identifier ne '') &&
3619: (ref($related->{$identifier}) eq 'ARRAY') &&
3620: ($pathfrom ne '')) {
3621: my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
3622: foreach my $dep (@{$related->{$identifier}}) {
3623: &add_filetype($allfiles,$path.$dep,'object');
3624: }
3625: }
3626: }
3627: return;
3628: }
3629:
1.493 albertel 3630: sub removeuploadedurl {
1.984 neumanie 3631: my ($url)=@_;
3632: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 3633: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 3634: }
3635:
3636: sub removeuserfile {
3637: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 3638: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3639: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 3640: if ($result eq 'ok') {
1.798 raeburn 3641: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
3642: my $metafile = $fname.'.meta';
3643: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 3644: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 3645: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3646: my $sqlresult =
1.823 albertel 3647: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3648: 'portfolio_metadata',$group,
3649: 'delete');
1.798 raeburn 3650: }
3651: }
3652: return $result;
1.257 www 3653: }
1.15 www 3654:
1.530 albertel 3655: sub mkdiruserfile {
3656: my ($docuname,$docudom,$dir)=@_;
3657: my $home=&homeserver($docuname,$docudom);
3658: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
3659: }
3660:
1.531 albertel 3661: sub renameuserfile {
3662: my ($docuname,$docudom,$old,$new)=@_;
3663: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3664: my $result = &reply("renameuserfile:$docudom:$docuname:".
3665: &escape("$old").':'.&escape("$new"),$home);
3666: if ($result eq 'ok') {
3667: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
3668: my $oldmeta = $old.'.meta';
3669: my $newmeta = $new.'.meta';
3670: my $metaresult =
3671: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 3672: my $url = "/uploaded/$docudom/$docuname/$old";
3673: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3674: my $sqlresult =
1.823 albertel 3675: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3676: 'portfolio_metadata',$group,
3677: 'delete');
1.798 raeburn 3678: }
3679: }
3680: return $result;
1.531 albertel 3681: }
3682:
1.14 www 3683: # ------------------------------------------------------------------------- Log
3684:
3685: sub log {
3686: my ($dom,$nam,$hom,$what)=@_;
1.47 www 3687: return critical("log:$dom:$nam:$what",$hom);
1.157 www 3688: }
3689:
3690: # ------------------------------------------------------------------ Course Log
1.352 www 3691: #
3692: # This routine flushes several buffers of non-mission-critical nature
3693: #
1.157 www 3694:
3695: sub flushcourselogs {
1.352 www 3696: &logthis('Flushing log buffers');
3697: #
3698: # course logs
3699: # This is a log of all transactions in a course, which can be used
3700: # for data mining purposes
3701: #
3702: # It also collects the courseid database, which lists last transaction
3703: # times and course titles for all courseids
3704: #
3705: my %courseidbuffer=();
1.921 raeburn 3706: foreach my $crsid (keys(%courselogs)) {
1.352 www 3707: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 3708: &escape($courselogs{$crsid}),
3709: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 3710: delete $courselogs{$crsid};
3711: } else {
3712: &logthis('Failed to flush log buffer for '.$crsid);
3713: if (length($courselogs{$crsid})>40000) {
1.672 albertel 3714: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 3715: " exceeded maximum size, deleting.</font>");
3716: delete $courselogs{$crsid};
3717: }
1.352 www 3718: }
1.920 raeburn 3719: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 3720: 'description' => $coursedescrbuf{$crsid},
3721: 'inst_code' => $courseinstcodebuf{$crsid},
3722: 'type' => $coursetypebuf{$crsid},
3723: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 3724: };
1.191 harris41 3725: }
1.352 www 3726: #
3727: # Write course id database (reverse lookup) to homeserver of courses
3728: # Is used in pickcourse
3729: #
1.840 albertel 3730: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 3731: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 3732: $courseidbuffer{$crs_home},
3733: $crs_home,'timeonly');
1.352 www 3734: }
3735: #
3736: # File accesses
3737: # Writes to the dynamic metadata of resources to get hit counts, etc.
3738: #
1.449 matthew 3739: foreach my $entry (keys(%accesshash)) {
1.458 matthew 3740: if ($entry =~ /___count$/) {
3741: my ($dom,$name);
1.807 albertel 3742: ($dom,$name,undef)=
1.811 albertel 3743: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 3744: if (! defined($dom) || $dom eq '' ||
3745: ! defined($name) || $name eq '') {
1.620 albertel 3746: my $cid = $env{'request.course.id'};
3747: $dom = $env{'request.'.$cid.'.domain'};
3748: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 3749: }
1.450 matthew 3750: my $value = $accesshash{$entry};
3751: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
3752: my %temphash=($url => $value);
1.449 matthew 3753: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
3754: if ($result eq 'ok') {
3755: delete $accesshash{$entry};
3756: }
3757: } else {
1.811 albertel 3758: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159 www 3759: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450 matthew 3760: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 3761: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
3762: delete $accesshash{$entry};
3763: }
1.185 www 3764: }
1.191 harris41 3765: }
1.352 www 3766: #
3767: # Roles
3768: # Reverse lookup of user roles for course faculty/staff and co-authorship
3769: #
1.800 albertel 3770: foreach my $entry (keys(%userrolehash)) {
1.351 www 3771: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 3772: split(/\:/,$entry);
3773: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 3774: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 3775: $rudom,$runame) eq 'ok') {
3776: delete $userrolehash{$entry};
3777: }
3778: }
1.662 raeburn 3779: #
3780: # Reverse lookup of domain roles (dc, ad, li, sc, au)
3781: #
3782: my %domrolebuffer = ();
1.1000 raeburn 3783: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 3784: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 3785: if ($domrolebuffer{$rudom}) {
3786: $domrolebuffer{$rudom}.='&'.&escape($entry).
3787: '='.&escape($domainrolehash{$entry});
3788: } else {
3789: $domrolebuffer{$rudom}.=&escape($entry).
3790: '='.&escape($domainrolehash{$entry});
3791: }
3792: delete $domainrolehash{$entry};
3793: }
3794: foreach my $dom (keys(%domrolebuffer)) {
1.841 albertel 3795: my %servers = &get_servers($dom,'library');
3796: foreach my $tryserver (keys(%servers)) {
3797: unless (&reply('domroleput:'.$dom.':'.
3798: $domrolebuffer{$dom},$tryserver) eq 'ok') {
3799: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
3800: }
1.662 raeburn 3801: }
3802: }
1.186 www 3803: $dumpcount++;
1.157 www 3804: }
3805:
3806: sub courselog {
3807: my $what=shift;
1.158 www 3808: $what=time.':'.$what;
1.620 albertel 3809: unless ($env{'request.course.id'}) { return ''; }
3810: $coursedombuf{$env{'request.course.id'}}=
3811: $env{'course.'.$env{'request.course.id'}.'.domain'};
3812: $coursenumbuf{$env{'request.course.id'}}=
3813: $env{'course.'.$env{'request.course.id'}.'.num'};
3814: $coursehombuf{$env{'request.course.id'}}=
3815: $env{'course.'.$env{'request.course.id'}.'.home'};
3816: $coursedescrbuf{$env{'request.course.id'}}=
3817: $env{'course.'.$env{'request.course.id'}.'.description'};
3818: $courseinstcodebuf{$env{'request.course.id'}}=
3819: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
3820: $courseownerbuf{$env{'request.course.id'}}=
3821: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 3822: $coursetypebuf{$env{'request.course.id'}}=
3823: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 3824: if (defined $courselogs{$env{'request.course.id'}}) {
3825: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 3826: } else {
1.620 albertel 3827: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 3828: }
1.620 albertel 3829: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 3830: &flushcourselogs();
3831: }
1.158 www 3832: }
3833:
3834: sub courseacclog {
3835: my $fnsymb=shift;
1.620 albertel 3836: unless ($env{'request.course.id'}) { return ''; }
3837: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144 www 3838: if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187 www 3839: $what.=':POST';
1.583 matthew 3840: # FIXME: Probably ought to escape things....
1.800 albertel 3841: foreach my $key (keys(%env)) {
3842: if ($key=~/^form\.(.*)/) {
1.975 raeburn 3843: my $formitem = $1;
3844: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
3845: $what.=':'.$formitem.'='.$env{$key};
3846: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
3847: $what.=':'.$formitem.'='.$env{$key};
3848: }
1.158 www 3849: }
1.191 harris41 3850: }
1.583 matthew 3851: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
3852: # FIXME: We should not be depending on a form parameter that someone
3853: # editing lonsearchcat.pm might change in the future.
1.620 albertel 3854: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 3855: $what.= ':POST';
3856: # FIXME: Probably ought to escape things....
3857: foreach my $element ('courseexp','crsfulltext','crsrelated',
3858: 'crsdiscuss') {
1.620 albertel 3859: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 3860: }
3861: }
1.158 www 3862: }
3863: &courselog($what);
1.149 www 3864: }
3865:
1.185 www 3866: sub countacc {
3867: my $url=&declutter(shift);
1.458 matthew 3868: return if (! defined($url) || $url eq '');
1.620 albertel 3869: unless ($env{'request.course.id'}) { return ''; }
1.1158 www 3870: #
3871: # Mark that this url was used in this course
3872: #
1.620 albertel 3873: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158 www 3874: #
3875: # Increase the access count for this resource in this child process
3876: #
1.281 www 3877: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 3878: $accesshash{$key}++;
1.185 www 3879: }
1.349 www 3880:
1.361 www 3881: sub linklog {
3882: my ($from,$to)=@_;
3883: $from=&declutter($from);
3884: $to=&declutter($to);
3885: $accesshash{$from.'___'.$to.'___comefrom'}=1;
3886: $accesshash{$to.'___'.$from.'___goto'}=1;
3887: }
1.1160 www 3888:
3889: sub statslog {
3890: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
3891: if ($users<2) { return; }
3892: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
3893: 'course' => $env{'request.course.id'},
3894: 'sections' => '"all"',
3895: 'num_students' => $users,
3896: 'part' => $part,
3897: 'symb' => $symb,
3898: 'mean_tries' => $av_attempts,
3899: 'deg_of_diff' => $degdiff});
3900: foreach my $key (keys(%dynstore)) {
3901: $accesshash{$key}=$dynstore{$key};
3902: }
3903: }
1.361 www 3904:
1.349 www 3905: sub userrolelog {
3906: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169 droeschl 3907: if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350 www 3908: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3909: $userrolehash
3910: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 3911: =$tend.':'.$tstart;
1.662 raeburn 3912: }
1.1169 droeschl 3913: if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898 albertel 3914: $userrolehash
3915: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
3916: =$tend.':'.$tstart;
3917: }
1.1169 droeschl 3918: if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
1.662 raeburn 3919: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3920: $domainrolehash
3921: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
3922: = $tend.':'.$tstart;
3923: }
1.351 www 3924: }
3925:
1.957 raeburn 3926: sub courserolelog {
3927: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1184 raeburn 3928: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
3929: my $cdom = $1;
3930: my $cnum = $2;
3931: my $sec = $3;
3932: my $namespace = 'rolelog';
3933: my %storehash = (
3934: role => $trole,
3935: start => $tstart,
3936: end => $tend,
3937: selfenroll => $selfenroll,
3938: context => $context,
3939: );
3940: if ($trole eq 'gr') {
3941: $namespace = 'groupslog';
3942: $storehash{'group'} = $sec;
3943: } else {
3944: $storehash{'section'} = $sec;
3945: }
1.1188 raeburn 3946: &write_log('course',$namespace,\%storehash,$delflag,$username,
3947: $domain,$cnum,$cdom);
1.1184 raeburn 3948: if (($trole ne 'st') || ($sec ne '')) {
3949: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957 raeburn 3950: }
3951: }
3952: return;
3953: }
3954:
1.1184 raeburn 3955: sub domainrolelog {
3956: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
3957: if ($area =~ m{^/($match_domain)/$}) {
3958: my $cdom = $1;
3959: my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
3960: my $namespace = 'rolelog';
3961: my %storehash = (
3962: role => $trole,
3963: start => $tstart,
3964: end => $tend,
3965: context => $context,
3966: );
1.1188 raeburn 3967: &write_log('domain',$namespace,\%storehash,$delflag,$username,
3968: $domain,$domconfiguser,$cdom);
1.1184 raeburn 3969: }
3970: return;
3971:
3972: }
3973:
3974: sub coauthorrolelog {
3975: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
3976: if ($area =~ m{^/($match_domain)/($match_username)$}) {
3977: my $audom = $1;
3978: my $auname = $2;
3979: my $namespace = 'rolelog';
3980: my %storehash = (
3981: role => $trole,
3982: start => $tstart,
3983: end => $tend,
3984: context => $context,
3985: );
1.1188 raeburn 3986: &write_log('author',$namespace,\%storehash,$delflag,$username,
3987: $domain,$auname,$audom);
1.1184 raeburn 3988: }
3989: return;
3990: }
3991:
1.351 www 3992: sub get_course_adv_roles {
1.948 raeburn 3993: my ($cid,$codes) = @_;
1.620 albertel 3994: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 3995: my %coursehash=&coursedescription($cid);
1.988 raeburn 3996: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 3997: my %nothide=();
1.800 albertel 3998: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 3999: if ($user !~ /:/) {
4000: $nothide{join(':',split(/[\@]/,$user))}=1;
4001: } else {
4002: $nothide{$user}=1;
4003: }
1.470 www 4004: }
1.1219 raeburn 4005: my @possdoms = ($coursehash{'domain'});
4006: if ($coursehash{'checkforpriv'}) {
4007: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
4008: }
1.351 www 4009: my %returnhash=();
4010: my %dumphash=
4011: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
4012: my $now=time;
1.997 raeburn 4013: my %privileged;
1.1000 raeburn 4014: foreach my $entry (keys(%dumphash)) {
1.800 albertel 4015: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 4016: if (($tstart) && ($tstart<0)) { next; }
4017: if (($tend) && ($tend<$now)) { next; }
4018: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 4019: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 4020: if ($username eq '' || $domain eq '') { next; }
1.1219 raeburn 4021: if ((&privileged($username,$domain,\@possdoms)) &&
1.997 raeburn 4022: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 4023: if ($role eq 'cr') { next; }
1.948 raeburn 4024: if ($codes) {
4025: if ($section) { $role .= ':'.$section; }
4026: if ($returnhash{$role}) {
4027: $returnhash{$role}.=','.$username.':'.$domain;
4028: } else {
4029: $returnhash{$role}=$username.':'.$domain;
4030: }
1.351 www 4031: } else {
1.988 raeburn 4032: my $key=&plaintext($role,$crstype);
1.973 bisitz 4033: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 4034: if ($returnhash{$key}) {
4035: $returnhash{$key}.=','.$username.':'.$domain;
4036: } else {
4037: $returnhash{$key}=$username.':'.$domain;
4038: }
1.351 www 4039: }
1.948 raeburn 4040: }
1.400 www 4041: return %returnhash;
4042: }
4043:
4044: sub get_my_roles {
1.937 raeburn 4045: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 4046: unless (defined($uname)) { $uname=$env{'user.name'}; }
4047: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 4048: my (%dumphash,%nothide);
1.1086 raeburn 4049: if ($context eq 'userroles') {
1.1166 raeburn 4050: %dumphash = &dump('roles',$udom,$uname);
1.858 raeburn 4051: } else {
1.1219 raeburn 4052: %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 4053: if ($hidepriv) {
4054: my %coursehash=&coursedescription($udom.'_'.$uname);
4055: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
4056: if ($user !~ /:/) {
4057: $nothide{join(':',split(/[\@]/,$user))} = 1;
4058: } else {
4059: $nothide{$user} = 1;
4060: }
4061: }
4062: }
1.858 raeburn 4063: }
1.400 www 4064: my %returnhash=();
4065: my $now=time;
1.999 raeburn 4066: my %privileged;
1.800 albertel 4067: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 4068: my ($role,$tend,$tstart);
4069: if ($context eq 'userroles') {
1.1149 raeburn 4070: next if ($entry =~ /^rolesdef/);
1.867 raeburn 4071: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
4072: } else {
4073: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
4074: }
1.400 www 4075: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 4076: my $status = 'active';
1.939 raeburn 4077: if (($tend) && ($tend<=$now)) {
1.832 raeburn 4078: $status = 'previous';
4079: }
4080: if (($tstart) && ($now<$tstart)) {
4081: $status = 'future';
4082: }
4083: if (ref($types) eq 'ARRAY') {
4084: if (!grep(/^\Q$status\E$/,@{$types})) {
4085: next;
4086: }
4087: } else {
4088: if ($status ne 'active') {
4089: next;
4090: }
4091: }
1.867 raeburn 4092: my ($rolecode,$username,$domain,$section,$area);
4093: if ($context eq 'userroles') {
1.1186 raeburn 4094: ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867 raeburn 4095: (undef,$domain,$username,$section) = split(/\//,$area);
4096: } else {
4097: ($role,$username,$domain,$section) = split(/\:/,$entry);
4098: }
1.832 raeburn 4099: if (ref($roledoms) eq 'ARRAY') {
4100: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
4101: next;
4102: }
4103: }
4104: if (ref($roles) eq 'ARRAY') {
4105: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 4106: if ($role =~ /^cr\//) {
4107: if (!grep(/^cr$/,@{$roles})) {
4108: next;
4109: }
1.1104 raeburn 4110: } elsif ($role =~ /^gr\//) {
4111: if (!grep(/^gr$/,@{$roles})) {
4112: next;
4113: }
1.922 raeburn 4114: } else {
4115: next;
4116: }
1.832 raeburn 4117: }
1.867 raeburn 4118: }
1.937 raeburn 4119: if ($hidepriv) {
1.1219 raeburn 4120: my @privroles = ('dc','su');
1.999 raeburn 4121: if ($context eq 'userroles') {
1.1219 raeburn 4122: next if (grep(/^\Q$role\E$/,@privroles));
1.999 raeburn 4123: } else {
1.1219 raeburn 4124: my $possdoms = [$domain];
4125: if (ref($roledoms) eq 'ARRAY') {
4126: push(@{$possdoms},@{$roledoms});
1.999 raeburn 4127: }
1.1219 raeburn 4128: if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999 raeburn 4129: if (!$nothide{$username.':'.$domain}) {
4130: next;
4131: }
4132: }
1.937 raeburn 4133: }
4134: }
1.933 raeburn 4135: if ($withsec) {
4136: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
4137: $tstart.':'.$tend;
4138: } else {
4139: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
4140: }
1.832 raeburn 4141: }
1.373 www 4142: return %returnhash;
1.399 www 4143: }
4144:
4145: # ----------------------------------------------------- Frontpage Announcements
4146: #
4147: #
4148:
4149: sub postannounce {
4150: my ($server,$text)=@_;
1.844 albertel 4151: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 4152: unless ($text=~/\w/) { $text=''; }
4153: return &reply('setannounce:'.&escape($text),$server);
4154: }
4155:
4156: sub getannounce {
1.448 albertel 4157:
4158: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 4159: my $announcement='';
1.800 albertel 4160: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 4161: close($fh);
1.399 www 4162: if ($announcement=~/\w/) {
4163: return
4164: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 4165: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 4166: } else {
4167: return '';
4168: }
4169: } else {
4170: return '';
4171: }
1.351 www 4172: }
1.353 www 4173:
4174: # ---------------------------------------------------------- Course ID routines
4175: # Deal with domain's nohist_courseid.db files
4176: #
4177:
4178: sub courseidput {
1.921 raeburn 4179: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 4180: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 4181: my $outcome;
4182: if ($caller eq 'timeonly') {
4183: my $cids = '';
4184: foreach my $item (keys(%$storehash)) {
4185: $cids.=&escape($item).'&';
4186: }
4187: $cids=~s/\&$//;
4188: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
4189: $coursehome);
4190: } else {
4191: my $items = '';
4192: foreach my $item (keys(%$storehash)) {
4193: $items.= &escape($item).'='.
4194: &freeze_escape($$storehash{$item}).'&';
4195: }
4196: $items=~s/\&$//;
4197: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
4198: $coursehome);
1.918 raeburn 4199: }
4200: if ($outcome eq 'unknown_cmd') {
4201: my $what;
4202: foreach my $cid (keys(%$storehash)) {
4203: $what .= &escape($cid).'=';
1.921 raeburn 4204: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 4205: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 4206: }
4207: $what =~ s/\:$/&/;
4208: }
4209: $what =~ s/\&$//;
4210: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
4211: } else {
4212: return $outcome;
4213: }
1.353 www 4214: }
4215:
4216: sub courseiddump {
1.921 raeburn 4217: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 4218: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 4219: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1247 raeburn 4220: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
4221: $hasuniquecode)=@_;
1.918 raeburn 4222: my $as_hash = 1;
4223: my %returnhash;
4224: if (!$domfilter) { $domfilter=''; }
1.845 albertel 4225: my %libserv = &all_library();
4226: foreach my $tryserver (keys(%libserv)) {
4227: if ( ( $hostidflag == 1
4228: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
4229: || (!defined($hostidflag)) ) {
4230:
1.918 raeburn 4231: if (($domfilter eq '') ||
4232: (&host_domain($tryserver) eq $domfilter)) {
1.1180 droeschl 4233: my $rep;
4234: if (grep { $_ eq $tryserver } current_machine_ids()) {
4235: $rep = LONCAPA::Lond::dump_course_id_handler(
4236: join(":", (&host_domain($tryserver), $sincefilter,
4237: &escape($descfilter), &escape($instcodefilter),
4238: &escape($ownerfilter), &escape($coursefilter),
4239: &escape($typefilter), &escape($regexp_ok),
4240: $as_hash, &escape($selfenrollonly),
4241: &escape($catfilter), $showhidden, $caller,
4242: &escape($cloner), &escape($cc_clone), $cloneonly,
4243: &escape($createdbefore), &escape($createdafter),
1.1247 raeburn 4244: &escape($creationcontext), $domcloner, $hasuniquecode)));
1.1180 droeschl 4245: } else {
4246: $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
4247: $sincefilter.':'.&escape($descfilter).':'.
4248: &escape($instcodefilter).':'.&escape($ownerfilter).
4249: ':'.&escape($coursefilter).':'.&escape($typefilter).
4250: ':'.&escape($regexp_ok).':'.$as_hash.':'.
4251: &escape($selfenrollonly).':'.&escape($catfilter).':'.
4252: $showhidden.':'.$caller.':'.&escape($cloner).':'.
4253: &escape($cc_clone).':'.$cloneonly.':'.
4254: &escape($createdbefore).':'.&escape($createdafter).':'.
1.1247 raeburn 4255: &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode,
1.1180 droeschl 4256: $tryserver);
4257: }
4258:
1.918 raeburn 4259: my @pairs=split(/\&/,$rep);
4260: foreach my $item (@pairs) {
4261: my ($key,$value)=split(/\=/,$item,2);
4262: $key = &unescape($key);
4263: next if ($key =~ /^error: 2 /);
4264: my $result = &thaw_unescape($value);
4265: if (ref($result) eq 'HASH') {
4266: $returnhash{$key}=$result;
4267: } else {
1.921 raeburn 4268: my @responses = split(/:/,$value);
4269: my @items = ('description','inst_code','owner','type');
1.918 raeburn 4270: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 4271: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 4272: }
1.1008 raeburn 4273: }
1.353 www 4274: }
4275: }
4276: }
4277: }
4278: return %returnhash;
4279: }
4280:
1.1055 raeburn 4281: sub courselastaccess {
4282: my ($cdom,$cnum,$hostidref) = @_;
4283: my %returnhash;
4284: if ($cdom && $cnum) {
4285: my $chome = &homeserver($cnum,$cdom);
4286: if ($chome ne 'no_host') {
4287: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
4288: &extract_lastaccess(\%returnhash,$rep);
4289: }
4290: } else {
4291: if (!$cdom) { $cdom=''; }
4292: my %libserv = &all_library();
4293: foreach my $tryserver (keys(%libserv)) {
4294: if (ref($hostidref) eq 'ARRAY') {
4295: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
4296: }
4297: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
4298: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
4299: &extract_lastaccess(\%returnhash,$rep);
4300: }
4301: }
4302: }
4303: return %returnhash;
4304: }
4305:
4306: sub extract_lastaccess {
4307: my ($returnhash,$rep) = @_;
4308: if (ref($returnhash) eq 'HASH') {
4309: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
4310: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
4311: $rep eq '') {
4312: my @pairs=split(/\&/,$rep);
4313: foreach my $item (@pairs) {
4314: my ($key,$value)=split(/\=/,$item,2);
4315: $key = &unescape($key);
4316: next if ($key =~ /^error: 2 /);
4317: $returnhash->{$key} = &thaw_unescape($value);
4318: }
4319: }
4320: }
4321: return;
4322: }
4323:
1.658 raeburn 4324: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 4325:
4326: sub dcmailput {
1.685 raeburn 4327: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 4328: my $status = &Apache::lonnet::critical(
1.740 www 4329: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
4330: &escape($message),$server);
1.662 raeburn 4331: return $status;
4332: }
4333:
1.658 raeburn 4334: sub dcmaildump {
4335: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 4336: my %returnhash=();
1.846 albertel 4337:
4338: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 4339: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
4340: &escape($enddate).':';
4341: my @esc_senders=map { &escape($_)} @$senders;
4342: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 4343: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 4344: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 4345: if (($key) && ($value)) {
4346: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 4347: }
4348: }
4349: }
4350: return %returnhash;
4351: }
1.662 raeburn 4352: # ---------------------------------------------------------- Domain roles
4353:
4354: sub get_domain_roles {
4355: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 4356: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 4357: $startdate = '.';
4358: }
1.1018 raeburn 4359: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 4360: $enddate = '.';
4361: }
1.922 raeburn 4362: my $rolelist;
4363: if (ref($roles) eq 'ARRAY') {
1.1219 raeburn 4364: $rolelist = join('&',@{$roles});
1.922 raeburn 4365: }
1.662 raeburn 4366: my %personnel = ();
1.841 albertel 4367:
4368: my %servers = &get_servers($dom,'library');
4369: foreach my $tryserver (keys(%servers)) {
4370: %{$personnel{$tryserver}}=();
4371: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
4372: &escape($startdate).':'.
4373: &escape($enddate).':'.
4374: &escape($rolelist), $tryserver))) {
4375: my ($key,$value) = split(/\=/,$line,2);
4376: if (($key) && ($value)) {
4377: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
4378: }
4379: }
1.662 raeburn 4380: }
4381: return %personnel;
4382: }
1.658 raeburn 4383:
1.1057 www 4384: # ----------------------------------------------------------- Interval timing
1.149 www 4385:
1.1153 www 4386: {
4387: # Caches needed for speedup of navmaps
4388: # We don't want to cache this for very long at all (5 seconds at most)
4389: #
4390: # The user for whom we cache
4391: my $cachedkey='';
4392: # The cached times for this user
4393: my %cachedtimes=();
4394: # When this was last done
4395: my $cachedtime=();
4396:
4397: sub load_all_first_access {
1.1154 raeburn 4398: my ($uname,$udom)=@_;
1.1156 www 4399: if (($cachedkey eq $uname.':'.$udom) &&
1.1174 raeburn 4400: (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154 raeburn 4401: return;
4402: }
4403: $cachedtime=time;
4404: $cachedkey=$uname.':'.$udom;
4405: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153 www 4406: }
4407:
1.504 albertel 4408: sub get_first_access {
1.1162 raeburn 4409: my ($type,$argsymb,$argmap)=@_;
1.790 albertel 4410: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4411: if ($argsymb) { $symb=$argsymb; }
4412: my ($map,$id,$res)=&decode_symb($symb);
1.1162 raeburn 4413: if ($argmap) { $map = $argmap; }
1.926 albertel 4414: if ($type eq 'course') {
4415: $res='course';
4416: } elsif ($type eq 'map') {
1.588 albertel 4417: $res=&symbread($map);
4418: } else {
4419: $res=$symb;
4420: }
1.1153 www 4421: &load_all_first_access($uname,$udom);
4422: return $cachedtimes{"$courseid\0$res"};
1.504 albertel 4423: }
4424:
4425: sub set_first_access {
1.1162 raeburn 4426: my ($type,$interval)=@_;
1.790 albertel 4427: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4428: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 4429: if ($type eq 'course') {
4430: $res='course';
4431: } elsif ($type eq 'map') {
1.588 albertel 4432: $res=&symbread($map);
4433: } else {
4434: $res=$symb;
4435: }
1.1153 www 4436: $cachedkey='';
1.1162 raeburn 4437: my $firstaccess=&get_first_access($type,$symb,$map);
1.505 albertel 4438: if (!$firstaccess) {
1.1162 raeburn 4439: my $start = time;
4440: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
4441: $udom,$uname);
4442: if ($putres eq 'ok') {
4443: &put('timerinterval',{"$courseid\0$res"=>$interval},
4444: $udom,$uname);
4445: &appenv(
4446: {
4447: 'course.'.$courseid.'.firstaccess.'.$res => $start,
4448: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
4449: }
4450: );
4451: }
4452: return $putres;
1.505 albertel 4453: }
4454: return 'already_set';
1.504 albertel 4455: }
1.1153 www 4456: }
1.110 www 4457: # --------------------------------------------- Set Expire Date for Spreadsheet
4458:
4459: sub expirespread {
4460: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 4461: my $cid=$env{'request.course.id'};
1.110 www 4462: if ($cid) {
4463: my $now=time;
4464: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 4465: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
4466: $env{'course.'.$cid.'.num'}.
1.110 www 4467: ':nohist_expirationdates:'.
4468: &escape($key).'='.$now,
1.620 albertel 4469: $env{'course.'.$cid.'.home'})
1.110 www 4470: }
4471: return 'ok';
1.14 www 4472: }
4473:
1.109 www 4474: # ----------------------------------------------------- Devalidate Spreadsheets
4475:
4476: sub devalidate {
1.325 www 4477: my ($symb,$uname,$udom)=@_;
1.620 albertel 4478: my $cid=$env{'request.course.id'};
1.109 www 4479: if ($cid) {
1.391 matthew 4480: # delete the stored spreadsheets for
4481: # - the student level sheet of this user in course's homespace
4482: # - the assessment level sheet for this resource
4483: # for this user in user's homespace
1.553 albertel 4484: # - current conditional state info
1.325 www 4485: my $key=$uname.':'.$udom.':';
1.109 www 4486: my $status=
1.299 matthew 4487: &del('nohist_calculatedsheets',
1.391 matthew 4488: [$key.'studentcalc:'],
1.620 albertel 4489: $env{'course.'.$cid.'.domain'},
4490: $env{'course.'.$cid.'.num'})
1.133 albertel 4491: .' '.
4492: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 4493: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 4494: unless ($status eq 'ok ok') {
4495: &logthis('Could not devalidate spreadsheet '.
1.325 www 4496: $uname.' at '.$udom.' for '.
1.109 www 4497: $symb.': '.$status);
1.133 albertel 4498: }
1.553 albertel 4499: &delenv('user.state.'.$cid);
1.109 www 4500: }
4501: }
4502:
1.265 albertel 4503: sub get_scalar {
4504: my ($string,$end) = @_;
4505: my $value;
4506: if ($$string =~ s/^([^&]*?)($end)/$2/) {
4507: $value = $1;
4508: } elsif ($$string =~ s/^([^&]*?)&//) {
4509: $value = $1;
4510: }
4511: return &unescape($value);
4512: }
4513:
4514: sub array2str {
4515: my (@array) = @_;
4516: my $result=&arrayref2str(\@array);
4517: $result=~s/^__ARRAY_REF__//;
4518: $result=~s/__END_ARRAY_REF__$//;
4519: return $result;
4520: }
4521:
1.204 albertel 4522: sub arrayref2str {
4523: my ($arrayref) = @_;
1.265 albertel 4524: my $result='__ARRAY_REF__';
1.204 albertel 4525: foreach my $elem (@$arrayref) {
1.265 albertel 4526: if(ref($elem) eq 'ARRAY') {
4527: $result.=&arrayref2str($elem).'&';
4528: } elsif(ref($elem) eq 'HASH') {
4529: $result.=&hashref2str($elem).'&';
4530: } elsif(ref($elem)) {
4531: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 4532: } else {
4533: $result.=&escape($elem).'&';
4534: }
4535: }
4536: $result=~s/\&$//;
1.265 albertel 4537: $result .= '__END_ARRAY_REF__';
1.204 albertel 4538: return $result;
4539: }
4540:
1.168 albertel 4541: sub hash2str {
1.204 albertel 4542: my (%hash) = @_;
4543: my $result=&hashref2str(\%hash);
1.265 albertel 4544: $result=~s/^__HASH_REF__//;
4545: $result=~s/__END_HASH_REF__$//;
1.204 albertel 4546: return $result;
4547: }
4548:
4549: sub hashref2str {
4550: my ($hashref)=@_;
1.265 albertel 4551: my $result='__HASH_REF__';
1.800 albertel 4552: foreach my $key (sort(keys(%$hashref))) {
4553: if (ref($key) eq 'ARRAY') {
4554: $result.=&arrayref2str($key).'=';
4555: } elsif (ref($key) eq 'HASH') {
4556: $result.=&hashref2str($key).'=';
4557: } elsif (ref($key)) {
1.265 albertel 4558: $result.='=';
1.800 albertel 4559: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 4560: } else {
1.1132 raeburn 4561: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 4562: }
4563:
1.800 albertel 4564: if(ref($hashref->{$key}) eq 'ARRAY') {
4565: $result.=&arrayref2str($hashref->{$key}).'&';
4566: } elsif(ref($hashref->{$key}) eq 'HASH') {
4567: $result.=&hashref2str($hashref->{$key}).'&';
4568: } elsif(ref($hashref->{$key})) {
1.265 albertel 4569: $result.='&';
1.800 albertel 4570: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 4571: } else {
1.800 albertel 4572: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 4573: }
4574: }
1.168 albertel 4575: $result=~s/\&$//;
1.265 albertel 4576: $result .= '__END_HASH_REF__';
1.168 albertel 4577: return $result;
4578: }
4579:
4580: sub str2hash {
1.265 albertel 4581: my ($string)=@_;
4582: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
4583: return %$hash;
4584: }
4585:
4586: sub str2hashref {
1.168 albertel 4587: my ($string) = @_;
1.265 albertel 4588:
4589: my %hash;
4590:
4591: if($string !~ /^__HASH_REF__/) {
4592: if (! ($string eq '' || !defined($string))) {
4593: $hash{'error'}='Not hash reference';
4594: }
4595: return (\%hash, $string);
4596: }
4597:
4598: $string =~ s/^__HASH_REF__//;
4599:
4600: while($string !~ /^__END_HASH_REF__/) {
4601: #key
4602: my $key='';
4603: if($string =~ /^__HASH_REF__/) {
4604: ($key, $string)=&str2hashref($string);
4605: if(defined($key->{'error'})) {
4606: $hash{'error'}='Bad data';
4607: return (\%hash, $string);
4608: }
4609: } elsif($string =~ /^__ARRAY_REF__/) {
4610: ($key, $string)=&str2arrayref($string);
4611: if($key->[0] eq 'Array reference error') {
4612: $hash{'error'}='Bad data';
4613: return (\%hash, $string);
4614: }
4615: } else {
4616: $string =~ s/^(.*?)=//;
1.267 albertel 4617: $key=&unescape($1);
1.265 albertel 4618: }
4619: $string =~ s/^=//;
4620:
4621: #value
4622: my $value='';
4623: if($string =~ /^__HASH_REF__/) {
4624: ($value, $string)=&str2hashref($string);
4625: if(defined($value->{'error'})) {
4626: $hash{'error'}='Bad data';
4627: return (\%hash, $string);
4628: }
4629: } elsif($string =~ /^__ARRAY_REF__/) {
4630: ($value, $string)=&str2arrayref($string);
4631: if($value->[0] eq 'Array reference error') {
4632: $hash{'error'}='Bad data';
4633: return (\%hash, $string);
4634: }
4635: } else {
4636: $value=&get_scalar(\$string,'__END_HASH_REF__');
4637: }
4638: $string =~ s/^&//;
4639:
4640: $hash{$key}=$value;
1.204 albertel 4641: }
1.265 albertel 4642:
4643: $string =~ s/^__END_HASH_REF__//;
4644:
4645: return (\%hash, $string);
1.204 albertel 4646: }
4647:
4648: sub str2array {
1.265 albertel 4649: my ($string)=@_;
4650: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
4651: return @$array;
4652: }
4653:
4654: sub str2arrayref {
1.204 albertel 4655: my ($string) = @_;
1.265 albertel 4656: my @array;
4657:
4658: if($string !~ /^__ARRAY_REF__/) {
4659: if (! ($string eq '' || !defined($string))) {
4660: $array[0]='Array reference error';
4661: }
4662: return (\@array, $string);
4663: }
4664:
4665: $string =~ s/^__ARRAY_REF__//;
4666:
4667: while($string !~ /^__END_ARRAY_REF__/) {
4668: my $value='';
4669: if($string =~ /^__HASH_REF__/) {
4670: ($value, $string)=&str2hashref($string);
4671: if(defined($value->{'error'})) {
4672: $array[0] ='Array reference error';
4673: return (\@array, $string);
4674: }
4675: } elsif($string =~ /^__ARRAY_REF__/) {
4676: ($value, $string)=&str2arrayref($string);
4677: if($value->[0] eq 'Array reference error') {
4678: $array[0] ='Array reference error';
4679: return (\@array, $string);
4680: }
4681: } else {
4682: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
4683: }
4684: $string =~ s/^&//;
4685:
4686: push(@array, $value);
1.191 harris41 4687: }
1.265 albertel 4688:
4689: $string =~ s/^__END_ARRAY_REF__//;
4690:
4691: return (\@array, $string);
1.168 albertel 4692: }
4693:
1.167 albertel 4694: # -------------------------------------------------------------------Temp Store
4695:
1.168 albertel 4696: sub tmpreset {
4697: my ($symb,$namespace,$domain,$stuname) = @_;
4698: if (!$symb) {
4699: $symb=&symbread();
1.620 albertel 4700: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4701: }
4702: $symb=escape($symb);
4703:
1.620 albertel 4704: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 4705: $namespace=~s/\//\_/g;
4706: $namespace=~s/\W//g;
4707:
1.620 albertel 4708: if (!$domain) { $domain=$env{'user.domain'}; }
4709: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4710: if ($domain eq 'public' && $stuname eq 'public') {
4711: $stuname=$ENV{'REMOTE_ADDR'};
4712: }
1.1117 foxr 4713: my $path=LONCAPA::tempdir();
1.168 albertel 4714: my %hash;
4715: if (tie(%hash,'GDBM_File',
4716: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4717: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 4718: foreach my $key (keys(%hash)) {
1.180 albertel 4719: if ($key=~ /:$symb/) {
1.168 albertel 4720: delete($hash{$key});
4721: }
4722: }
4723: }
4724: }
4725:
1.167 albertel 4726: sub tmpstore {
1.168 albertel 4727: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4728:
4729: if (!$symb) {
4730: $symb=&symbread();
1.620 albertel 4731: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4732: }
4733: $symb=escape($symb);
4734:
4735: if (!$namespace) {
4736: # I don't think we would ever want to store this for a course.
4737: # it seems this will only be used if we don't have a course.
1.620 albertel 4738: #$namespace=$env{'request.course.id'};
1.168 albertel 4739: #if (!$namespace) {
1.620 albertel 4740: $namespace=$env{'request.state'};
1.168 albertel 4741: #}
4742: }
4743: $namespace=~s/\//\_/g;
4744: $namespace=~s/\W//g;
1.620 albertel 4745: if (!$domain) { $domain=$env{'user.domain'}; }
4746: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4747: if ($domain eq 'public' && $stuname eq 'public') {
4748: $stuname=$ENV{'REMOTE_ADDR'};
4749: }
1.168 albertel 4750: my $now=time;
4751: my %hash;
1.1117 foxr 4752: my $path=LONCAPA::tempdir();
1.168 albertel 4753: if (tie(%hash,'GDBM_File',
4754: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4755: &GDBM_WRCREAT(),0640)) {
1.168 albertel 4756: $hash{"version:$symb"}++;
4757: my $version=$hash{"version:$symb"};
4758: my $allkeys='';
4759: foreach my $key (keys(%$storehash)) {
4760: $allkeys.=$key.':';
1.591 albertel 4761: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 4762: }
4763: $hash{"$version:$symb:timestamp"}=$now;
4764: $allkeys.='timestamp';
4765: $hash{"$version:keys:$symb"}=$allkeys;
4766: if (untie(%hash)) {
4767: return 'ok';
4768: } else {
4769: return "error:$!";
4770: }
4771: } else {
4772: return "error:$!";
4773: }
4774: }
1.167 albertel 4775:
1.168 albertel 4776: # -----------------------------------------------------------------Temp Restore
1.167 albertel 4777:
1.168 albertel 4778: sub tmprestore {
4779: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 4780:
1.168 albertel 4781: if (!$symb) {
4782: $symb=&symbread();
1.620 albertel 4783: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4784: }
4785: $symb=escape($symb);
4786:
1.620 albertel 4787: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 4788:
1.620 albertel 4789: if (!$domain) { $domain=$env{'user.domain'}; }
4790: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4791: if ($domain eq 'public' && $stuname eq 'public') {
4792: $stuname=$ENV{'REMOTE_ADDR'};
4793: }
1.168 albertel 4794: my %returnhash;
4795: $namespace=~s/\//\_/g;
4796: $namespace=~s/\W//g;
4797: my %hash;
1.1117 foxr 4798: my $path=LONCAPA::tempdir();
1.168 albertel 4799: if (tie(%hash,'GDBM_File',
4800: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4801: &GDBM_READER(),0640)) {
1.168 albertel 4802: my $version=$hash{"version:$symb"};
4803: $returnhash{'version'}=$version;
4804: my $scope;
4805: for ($scope=1;$scope<=$version;$scope++) {
4806: my $vkeys=$hash{"$scope:keys:$symb"};
4807: my @keys=split(/:/,$vkeys);
4808: my $key;
4809: $returnhash{"$scope:keys"}=$vkeys;
4810: foreach $key (@keys) {
1.591 albertel 4811: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
4812: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 4813: }
4814: }
1.168 albertel 4815: if (!(untie(%hash))) {
4816: return "error:$!";
4817: }
4818: } else {
4819: return "error:$!";
4820: }
4821: return %returnhash;
1.167 albertel 4822: }
4823:
1.9 www 4824: # ----------------------------------------------------------------------- Store
4825:
4826: sub store {
1.124 www 4827: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4828: my $home='';
4829:
1.168 albertel 4830: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4831:
1.213 www 4832: $symb=&symbclean($symb);
1.122 albertel 4833: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 4834:
1.620 albertel 4835: if (!$domain) { $domain=$env{'user.domain'}; }
4836: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 4837:
4838: &devalidate($symb,$stuname,$domain);
1.109 www 4839:
4840: $symb=escape($symb);
1.187 www 4841: if (!$namespace) {
1.620 albertel 4842: unless ($namespace=$env{'request.course.id'}) {
1.187 www 4843: return '';
4844: }
4845: }
1.620 albertel 4846: if (!$home) { $home=$env{'user.home'}; }
1.447 www 4847:
4848: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4849: $$storehash{'host'}=$perlvar{'lonHostID'};
4850:
1.12 www 4851: my $namevalue='';
1.800 albertel 4852: foreach my $key (keys(%$storehash)) {
4853: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 4854: }
1.12 www 4855: $namevalue=~s/\&$//;
1.187 www 4856: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124 www 4857: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9 www 4858: }
4859:
1.47 www 4860: # -------------------------------------------------------------- Critical Store
4861:
4862: sub cstore {
1.124 www 4863: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4864: my $home='';
4865:
1.168 albertel 4866: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4867:
1.213 www 4868: $symb=&symbclean($symb);
1.122 albertel 4869: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 4870:
1.620 albertel 4871: if (!$domain) { $domain=$env{'user.domain'}; }
4872: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 4873:
4874: &devalidate($symb,$stuname,$domain);
1.109 www 4875:
4876: $symb=escape($symb);
1.187 www 4877: if (!$namespace) {
1.620 albertel 4878: unless ($namespace=$env{'request.course.id'}) {
1.187 www 4879: return '';
4880: }
4881: }
1.620 albertel 4882: if (!$home) { $home=$env{'user.home'}; }
1.447 www 4883:
4884: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4885: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 4886:
1.47 www 4887: my $namevalue='';
1.800 albertel 4888: foreach my $key (keys(%$storehash)) {
4889: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 4890: }
1.47 www 4891: $namevalue=~s/\&$//;
1.187 www 4892: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 4893: return critical
4894: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47 www 4895: }
4896:
1.9 www 4897: # --------------------------------------------------------------------- Restore
4898:
4899: sub restore {
1.124 www 4900: my ($symb,$namespace,$domain,$stuname) = @_;
4901: my $home='';
4902:
1.168 albertel 4903: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4904:
1.122 albertel 4905: if (!$symb) {
1.1224 raeburn 4906: return if ($namespace eq 'courserequests');
4907: unless ($symb=escape(&symbread())) { return ''; }
1.122 albertel 4908: } else {
1.1224 raeburn 4909: unless ($namespace eq 'courserequests') {
4910: $symb=&escape(&symbclean($symb));
4911: }
1.122 albertel 4912: }
1.188 www 4913: if (!$namespace) {
1.620 albertel 4914: unless ($namespace=$env{'request.course.id'}) {
1.188 www 4915: return '';
4916: }
4917: }
1.620 albertel 4918: if (!$domain) { $domain=$env{'user.domain'}; }
4919: if (!$stuname) { $stuname=$env{'user.name'}; }
4920: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 4921: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
4922:
1.12 www 4923: my %returnhash=();
1.800 albertel 4924: foreach my $line (split(/\&/,$answer)) {
4925: my ($name,$value)=split(/\=/,$line);
1.591 albertel 4926: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 4927: }
1.75 www 4928: my $version;
4929: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 4930: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
4931: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 4932: }
1.75 www 4933: }
1.13 www 4934: return %returnhash;
1.34 www 4935: }
4936:
4937: # ---------------------------------------------------------- Course Description
1.1118 foxr 4938: #
4939: #
1.34 www 4940:
4941: sub coursedescription {
1.731 albertel 4942: my ($courseid,$args)=@_;
1.34 www 4943: $courseid=~s/^\///;
1.49 www 4944: $courseid=~s/\_/\//g;
1.34 www 4945: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 4946: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 4947: my $normalid=$cdomain.'_'.$cnum;
4948: # need to always cache even if we get errors otherwise we keep
4949: # trying and trying and trying to get the course description.
4950: my %envhash=();
4951: my %returnhash=();
1.731 albertel 4952:
4953: my $expiretime=600;
4954: if ($env{'request.course.id'} eq $normalid) {
4955: $expiretime=120;
4956: }
4957:
4958: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
4959: if (!$args->{'freshen_cache'}
4960: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
4961: foreach my $key (keys(%env)) {
4962: next if ($key !~ /^\Q$prefix\E(.*)/);
4963: my ($setting) = $1;
4964: $returnhash{$setting} = $env{$key};
4965: }
4966: return %returnhash;
4967: }
4968:
1.1118 foxr 4969: # get the data again
4970:
1.731 albertel 4971: if (!$args->{'one_time'}) {
4972: $envhash{'course.'.$normalid.'.last_cache'}=time;
4973: }
1.811 albertel 4974:
1.34 www 4975: if ($chome ne 'no_host') {
1.302 albertel 4976: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 4977: if (!exists($returnhash{'con_lost'})) {
1.1118 foxr 4978: my $username = $env{'user.name'}; # Defult username
4979: if(defined $args->{'user'}) {
4980: $username = $args->{'user'};
4981: }
1.129 albertel 4982: $returnhash{'home'}= $chome;
4983: $returnhash{'domain'} = $cdomain;
4984: $returnhash{'num'} = $cnum;
1.741 raeburn 4985: if (!defined($returnhash{'type'})) {
4986: $returnhash{'type'} = 'Course';
4987: }
1.130 albertel 4988: while (my ($name,$value) = each %returnhash) {
1.53 www 4989: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 4990: }
1.270 www 4991: $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117 foxr 4992: $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118 foxr 4993: $username.'_'.$cdomain.'_'.$cnum;
1.60 www 4994: $envhash{'course.'.$normalid.'.home'}=$chome;
4995: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
4996: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 4997: }
4998: }
1.731 albertel 4999: if (!$args->{'one_time'}) {
1.949 raeburn 5000: &appenv(\%envhash);
1.731 albertel 5001: }
1.302 albertel 5002: return %returnhash;
1.461 www 5003: }
5004:
1.1080 raeburn 5005: sub update_released_required {
5006: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
5007: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
5008: $cid = $env{'request.course.id'};
5009: $cdom = $env{'course.'.$cid.'.domain'};
5010: $cnum = $env{'course.'.$cid.'.num'};
5011: $chome = $env{'course.'.$cid.'.home'};
5012: }
5013: if ($needsrelease) {
5014: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
5015: my $needsupdate;
5016: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
5017: $needsupdate = 1;
5018: } else {
5019: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
5020: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
5021: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
5022: $needsupdate = 1;
5023: }
5024: }
5025: if ($needsupdate) {
5026: my %needshash = (
5027: 'internal.releaserequired' => $needsrelease,
5028: );
5029: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
5030: if ($putresult eq 'ok') {
5031: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
5032: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
5033: if (ref($crsinfo{$cid}) eq 'HASH') {
5034: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
5035: &courseidput($cdom,\%crsinfo,$chome,'notime');
5036: }
5037: }
5038: }
5039: }
5040: return;
5041: }
5042:
1.461 www 5043: # -------------------------------------------------See if a user is privileged
5044:
5045: sub privileged {
1.1219 raeburn 5046: my ($username,$domain,$possdomains,$possroles)=@_;
1.1170 droeschl 5047: my $now = time;
1.1219 raeburn 5048: my $roles;
5049: if (ref($possroles) eq 'ARRAY') {
5050: $roles = $possroles;
5051: } else {
5052: $roles = ['dc','su'];
5053: }
5054: if (ref($possdomains) eq 'ARRAY') {
5055: my %privileged = &privileged_by_domain($possdomains,$roles);
5056: foreach my $dom (@{$possdomains}) {
5057: if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
5058: (ref($privileged{$dom}) eq 'HASH')) {
5059: foreach my $role (@{$roles}) {
5060: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5061: if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
5062: my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
5063: return 1 unless (($end && $end < $now) ||
5064: ($start && $start > $now));
5065: }
5066: }
5067: }
5068: }
5069: }
5070: } else {
5071: my %rolesdump = &dump("roles", $domain, $username) or return 0;
5072: my $now = time;
1.1170 droeschl 5073:
1.1219 raeburn 5074: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys %rolesdump}) {
1.1170 droeschl 5075: my ($trole, $tend, $tstart) = split(/_/, $role);
1.1219 raeburn 5076: if (grep(/^\Q$trole\E$/,@{$roles})) {
1.1170 droeschl 5077: return 1 unless ($tend && $tend < $now)
1.1219 raeburn 5078: or ($tstart && $tstart > $now);
1.1170 droeschl 5079: }
1.1219 raeburn 5080: }
5081: }
5082: return 0;
5083: }
1.1170 droeschl 5084:
1.1219 raeburn 5085: sub privileged_by_domain {
5086: my ($domains,$roles) = @_;
5087: my %privileged = ();
5088: my $cachetime = 60*60*24;
5089: my $now = time;
5090: unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
5091: return %privileged;
5092: }
5093: foreach my $dom (@{$domains}) {
5094: next if (ref($privileged{$dom}) eq 'HASH');
5095: my $needroles;
5096: foreach my $role (@{$roles}) {
5097: my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
5098: if (defined($cached)) {
5099: if (ref($result) eq 'HASH') {
5100: $privileged{$dom}{$role} = $result;
5101: }
5102: } else {
5103: $needroles = 1;
5104: }
5105: }
5106: if ($needroles) {
5107: my %dompersonnel = &get_domain_roles($dom,$roles);
5108: $privileged{$dom} = {};
5109: foreach my $server (keys(%dompersonnel)) {
5110: if (ref($dompersonnel{$server}) eq 'HASH') {
5111: foreach my $item (keys(%{$dompersonnel{$server}})) {
5112: my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
5113: my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
5114: next if ($end && $end < $now);
5115: $privileged{$dom}{$trole}{$uname.':'.$udom} =
5116: $dompersonnel{$server}{$item};
5117: }
5118: }
5119: }
5120: if (ref($privileged{$dom}) eq 'HASH') {
5121: foreach my $role (@{$roles}) {
5122: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5123: &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
5124: } else {
5125: my %hash = ();
5126: &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
5127: }
5128: }
5129: }
5130: }
5131: }
5132: return %privileged;
1.9 www 5133: }
1.1 albertel 5134:
1.103 harris41 5135: # -------------------------------------------------------- Get user privileges
1.11 www 5136:
5137: sub rolesinit {
1.1169 droeschl 5138: my ($domain, $username) = @_;
5139: my %userroles = ('user.login.time' => time);
5140: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
5141:
5142: # firstaccess and timerinterval are related to timed maps/resources.
5143: # also, blocking can be triggered by an activating timer
5144: # it's saved in the user's %env.
5145: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
5146: my %timerinterval = &dump('timerinterval', $domain, $username);
5147: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
5148: %timerintchk, %timerintenv);
5149:
1.1162 raeburn 5150: foreach my $key (keys(%firstaccess)) {
1.1169 droeschl 5151: my ($cid, $rest) = split(/\0/, $key);
1.1162 raeburn 5152: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
5153: }
1.1169 droeschl 5154:
1.1162 raeburn 5155: foreach my $key (keys(%timerinterval)) {
5156: my ($cid,$rest) = split(/\0/,$key);
5157: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
5158: }
1.1169 droeschl 5159:
1.11 www 5160: my %allroles=();
1.1162 raeburn 5161: my %allgroups=();
1.11 www 5162:
1.1169 droeschl 5163: for my $area (grep { ! /^rolesdef_/ } keys %rolesdump) {
5164: my $role = $rolesdump{$area};
5165: $area =~ s/\_\w\w$//;
5166:
5167: my ($trole, $tend, $tstart, $group_privs);
5168:
5169: if ($role =~ /^cr/) {
5170: # Custom role, defined by a user
5171: # e.g., user.role.cr/msu/smith/mynewrole
5172: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
5173: $trole = $1;
5174: ($tend, $tstart) = split('_', $2);
5175: } else {
5176: $trole = $role;
5177: }
5178: } elsif ($role =~ m|^gr/|) {
5179: # Role of member in a group, defined within a course/community
5180: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
5181: ($trole, $tend, $tstart) = split(/_/, $role);
5182: next if $tstart eq '-1';
5183: ($trole, $group_privs) = split(/\//, $trole);
5184: $group_privs = &unescape($group_privs);
5185: } else {
5186: # Just a normal role, defined in roles.tab
5187: ($trole, $tend, $tstart) = split(/_/,$role);
5188: }
5189:
5190: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
5191: $username);
5192: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
5193:
5194: # role expired or not available yet?
5195: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
5196: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
5197:
5198: next if $area eq '' or $trole eq '';
5199:
5200: my $spec = "$trole.$area";
5201: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
5202:
5203: if ($trole =~ /^cr\//) {
5204: # Custom role, defined by a user
5205: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5206: } elsif ($trole eq 'gr') {
5207: # Role of a member in a group, defined within a course/community
5208: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
5209: next;
5210: } else {
5211: # Normal role, defined in roles.tab
5212: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5213: }
5214:
5215: my $cid = $tdomain.'_'.$trest;
5216: unless ($firstaccchk{$cid}) {
5217: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
5218: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
5219: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
5220: $coursetimerstarts{$cid}{$item};
5221: }
5222: }
5223: $firstaccchk{$cid} = 1;
5224: }
5225: unless ($timerintchk{$cid}) {
5226: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
5227: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
5228: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
5229: $coursetimerintervals{$cid}{$item};
1.1162 raeburn 5230: }
1.12 www 5231: }
1.1169 droeschl 5232: $timerintchk{$cid} = 1;
1.191 harris41 5233: }
1.11 www 5234: }
1.1169 droeschl 5235:
5236: @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
5237: \%allroles, \%allgroups);
5238: $env{'user.adv'} = $userroles{'user.adv'};
5239:
1.1162 raeburn 5240: return (\%userroles,\%firstaccenv,\%timerintenv);
1.11 www 5241: }
5242:
1.567 raeburn 5243: sub set_arearole {
1.1215 raeburn 5244: my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
5245: unless ($nolog) {
1.567 raeburn 5246: # log the associated role with the area
1.1215 raeburn 5247: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
5248: }
1.743 albertel 5249: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 5250: }
5251:
5252: sub custom_roleprivs {
5253: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
5254: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1250 raeburn 5255: my $homsvr = &homeserver($rauthor,$rdomain);
1.838 albertel 5256: if (&hostname($homsvr) ne '') {
1.567 raeburn 5257: my ($rdummy,$roledef)=
5258: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
5259: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
5260: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
5261: if (defined($syspriv)) {
1.1043 raeburn 5262: if ($trest =~ /^$match_community$/) {
5263: $syspriv =~ s/bre\&S//;
5264: }
1.567 raeburn 5265: $$allroles{'cm./'}.=':'.$syspriv;
5266: $$allroles{$spec.'./'}.=':'.$syspriv;
5267: }
5268: if ($tdomain ne '') {
5269: if (defined($dompriv)) {
5270: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
5271: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
5272: }
5273: if (($trest ne '') && (defined($coursepriv))) {
5274: $$allroles{'cm.'.$area}.=':'.$coursepriv;
5275: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
5276: }
5277: }
5278: }
5279: }
5280: }
5281:
1.678 raeburn 5282: sub group_roleprivs {
5283: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
5284: my $access = 1;
5285: my $now = time;
5286: if (($tend!=0) && ($tend<$now)) { $access = 0; }
5287: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
5288: if ($access) {
1.811 albertel 5289: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 5290: $$allgroups{$course}{$group} .=':'.$group_privs;
5291: }
5292: }
1.567 raeburn 5293:
5294: sub standard_roleprivs {
5295: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
5296: if (defined($pr{$trole.':s'})) {
5297: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
5298: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
5299: }
5300: if ($tdomain ne '') {
5301: if (defined($pr{$trole.':d'})) {
5302: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5303: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5304: }
5305: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
5306: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
5307: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
5308: }
5309: }
5310: }
5311:
5312: sub set_userprivs {
1.1064 raeburn 5313: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 5314: my $author=0;
5315: my $adv=0;
1.678 raeburn 5316: my %grouproles = ();
5317: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 5318: my @groupkeys;
1.1000 raeburn 5319: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 5320: push(@groupkeys,$role);
5321: }
5322: if (ref($groups_roles) eq 'HASH') {
5323: foreach my $key (keys(%{$groups_roles})) {
5324: unless (grep(/^\Q$key\E$/,@groupkeys)) {
5325: push(@groupkeys,$key);
5326: }
5327: }
5328: }
5329: if (@groupkeys > 0) {
5330: foreach my $role (@groupkeys) {
5331: my ($trole,$area,$sec,$extendedarea);
5332: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
5333: $trole = $1;
5334: $area = $2;
5335: $sec = $3;
5336: $extendedarea = $area.$sec;
5337: if (exists($$allgroups{$area})) {
5338: foreach my $group (keys(%{$$allgroups{$area}})) {
5339: my $spec = $trole.'.'.$extendedarea;
5340: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 5341: $$allgroups{$area}{$group};
1.1064 raeburn 5342: }
1.678 raeburn 5343: }
5344: }
5345: }
5346: }
5347: }
1.800 albertel 5348: foreach my $group (keys(%grouproles)) {
5349: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 5350: }
1.800 albertel 5351: foreach my $role (keys(%{$allroles})) {
5352: my %thesepriv;
1.941 raeburn 5353: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 5354: foreach my $item (split(/:/,$$allroles{$role})) {
5355: if ($item ne '') {
5356: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 5357: if ($restrictions eq '') {
5358: $thesepriv{$privilege}='F';
5359: } elsif ($thesepriv{$privilege} ne 'F') {
5360: $thesepriv{$privilege}.=$restrictions;
5361: }
5362: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
5363: }
5364: }
5365: my $thesestr='';
1.1104 raeburn 5366: foreach my $priv (sort(keys(%thesepriv))) {
1.800 albertel 5367: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
5368: }
5369: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 5370: }
5371: return ($author,$adv);
5372: }
5373:
1.994 raeburn 5374: sub role_status {
1.1104 raeburn 5375: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 5376: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1250 raeburn 5377: my ($one,$two) = split(m{\./},$rolekey,2);
5378: (undef,undef,$$role) = split(/\./,$one,3);
1.994 raeburn 5379: unless (!defined($$role) || $$role eq '') {
1.1251 raeburn 5380: $$where = '/'.$two;
1.994 raeburn 5381: $$trolecode=$$role.'.'.$$where;
5382: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
5383: $$tstatus='is';
1.1104 raeburn 5384: if ($$tstart && $$tstart>$update) {
1.994 raeburn 5385: $$tstatus='future';
1.1034 raeburn 5386: if ($$tstart<$now) {
5387: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 5388: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 5389: my (%allroles,%allgroups,$group_privs,
5390: %groups_roles,@rolecodes);
1.1002 raeburn 5391: my %userroles = (
5392: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
5393: );
1.1064 raeburn 5394: @rolecodes = ('cm');
1.1002 raeburn 5395: my $spec=$$role.'.'.$$where;
5396: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
5397: if ($$role =~ /^cr\//) {
5398: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 5399: push(@rolecodes,'cr');
1.1002 raeburn 5400: } elsif ($$role eq 'gr') {
1.1064 raeburn 5401: push(@rolecodes,$$role);
1.1002 raeburn 5402: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
5403: $env{'user.name'});
1.1064 raeburn 5404: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 5405: (undef,my $group_privs) = split(/\//,$trole);
5406: $group_privs = &unescape($group_privs);
5407: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 5408: 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 5409: &get_groups_roles($tdomain,$trest,
5410: \%course_roles,\@rolecodes,
5411: \%groups_roles);
1.1002 raeburn 5412: } else {
1.1064 raeburn 5413: push(@rolecodes,$$role);
1.1002 raeburn 5414: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
5415: }
1.1064 raeburn 5416: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
5417: &appenv(\%userroles,\@rolecodes);
1.1002 raeburn 5418: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
5419: }
5420: }
1.1034 raeburn 5421: $$tstatus = 'is';
1.1002 raeburn 5422: }
1.994 raeburn 5423: }
5424: if ($$tend) {
1.1104 raeburn 5425: if ($$tend<$update) {
1.994 raeburn 5426: $$tstatus='expired';
5427: } elsif ($$tend<$now) {
5428: $$tstatus='will_not';
5429: }
5430: }
5431: }
5432: }
5433: }
5434:
1.1104 raeburn 5435: sub get_groups_roles {
5436: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
5437: return unless((ref($cdom_courseroles) eq 'HASH') &&
5438: (ref($rolecodes) eq 'ARRAY') &&
5439: (ref($groups_roles) eq 'HASH'));
5440: if (keys(%{$cdom_courseroles}) > 0) {
5441: my ($cnum) = ($rest =~ /^($match_courseid)/);
5442: if ($cdom ne '' && $cnum ne '') {
5443: foreach my $key (keys(%{$cdom_courseroles})) {
5444: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
5445: my $crsrole = $1;
5446: my $crssec = $2;
5447: if ($crsrole =~ /^cr/) {
5448: unless (grep(/^cr$/,@{$rolecodes})) {
5449: push(@{$rolecodes},'cr');
5450: }
5451: } else {
5452: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
5453: push(@{$rolecodes},$crsrole);
5454: }
5455: }
5456: my $rolekey = "$crsrole./$cdom/$cnum";
5457: if ($crssec ne '') {
5458: $rolekey .= "/$crssec";
5459: }
5460: $rolekey .= './';
5461: $groups_roles->{$rolekey} = $rolecodes;
5462: }
5463: }
5464: }
5465: }
5466: return;
5467: }
5468:
5469: sub delete_env_groupprivs {
5470: my ($where,$courseroles,$possroles) = @_;
5471: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
5472: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
5473: unless (ref($courseroles->{$udom}) eq 'HASH') {
5474: %{$courseroles->{$udom}} =
5475: &get_my_roles('','','userroles',['active'],
5476: $possroles,[$udom],1);
5477: }
5478: if (ref($courseroles->{$udom}) eq 'HASH') {
5479: foreach my $item (keys(%{$courseroles->{$udom}})) {
5480: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
5481: my $area = '/'.$cdom.'/'.$cnum;
5482: my $privkey = "user.priv.$crsrole.$area";
5483: if ($crssec ne '') {
5484: $privkey .= '/'.$crssec;
5485: }
5486: $privkey .= ".$area/$group";
5487: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
5488: }
5489: }
5490: return;
5491: }
5492:
1.994 raeburn 5493: sub check_adhoc_privs {
1.1104 raeburn 5494: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994 raeburn 5495: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1185 raeburn 5496: my $setprivs;
1.994 raeburn 5497: if ($env{$cckey}) {
5498: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104 raeburn 5499: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 5500: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088 raeburn 5501: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185 raeburn 5502: $setprivs = 1;
1.994 raeburn 5503: }
5504: } else {
1.1088 raeburn 5505: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185 raeburn 5506: $setprivs = 1;
1.994 raeburn 5507: }
1.1185 raeburn 5508: return $setprivs;
1.994 raeburn 5509: }
5510:
5511: sub set_adhoc_privileges {
5512: # role can be cc or ca
1.1088 raeburn 5513: my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994 raeburn 5514: my $area = '/'.$dcdom.'/'.$pickedcourse;
5515: my $spec = $role.'.'.$area;
5516: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1215 raeburn 5517: $env{'user.name'},1);
1.994 raeburn 5518: my %ccrole = ();
5519: &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
5520: my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
5521: &appenv(\%userroles,[$role,'cm']);
5522: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088 raeburn 5523: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
5524: &appenv( {'request.role' => $spec,
5525: 'request.role.domain' => $dcdom,
5526: 'request.course.sec' => ''
5527: }
5528: );
5529: my $tadv=0;
5530: if (&allowed('adv') eq 'F') { $tadv=1; }
5531: &appenv({'request.role.adv' => $tadv});
5532: }
1.994 raeburn 5533: }
5534:
1.12 www 5535: # --------------------------------------------------------------- get interface
5536:
5537: sub get {
1.131 albertel 5538: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 5539: my $items='';
1.800 albertel 5540: foreach my $item (@$storearr) {
5541: $items.=&escape($item).'&';
1.191 harris41 5542: }
1.12 www 5543: $items=~s/\&$//;
1.620 albertel 5544: if (!$udomain) { $udomain=$env{'user.domain'}; }
5545: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 5546: my $uhome=&homeserver($uname,$udomain);
5547:
1.133 albertel 5548: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 5549: my @pairs=split(/\&/,$rep);
1.273 albertel 5550: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
5551: return @pairs;
5552: }
1.15 www 5553: my %returnhash=();
1.42 www 5554: my $i=0;
1.800 albertel 5555: foreach my $item (@$storearr) {
5556: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 5557: $i++;
1.191 harris41 5558: }
1.15 www 5559: return %returnhash;
1.27 www 5560: }
5561:
5562: # --------------------------------------------------------------- del interface
5563:
5564: sub del {
1.133 albertel 5565: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 5566: my $items='';
1.800 albertel 5567: foreach my $item (@$storearr) {
5568: $items.=&escape($item).'&';
1.191 harris41 5569: }
1.984 neumanie 5570:
1.27 www 5571: $items=~s/\&$//;
1.620 albertel 5572: if (!$udomain) { $udomain=$env{'user.domain'}; }
5573: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 5574: my $uhome=&homeserver($uname,$udomain);
5575: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 5576: }
5577:
5578: # -------------------------------------------------------------- dump interface
5579:
1.1180 droeschl 5580: sub unserialize {
5581: my ($rep, $escapedkeys) = @_;
5582:
5583: return {} if $rep =~ /^error/;
5584:
5585: my %returnhash=();
1.1252 raeburn 5586: foreach my $item (split(/\&/,$rep)) {
1.1180 droeschl 5587: my ($key, $value) = split(/=/, $item, 2);
5588: $key = unescape($key) unless $escapedkeys;
5589: next if $key =~ /^error: 2 /;
1.1252 raeburn 5590: $returnhash{$key} = &thaw_unescape($value);
1.1180 droeschl 5591: }
5592: #return %returnhash;
5593: return \%returnhash;
5594: }
5595:
5596: # see Lond::dump_with_regexp
5597: # if $escapedkeys hash keys won't get unescaped.
1.15 www 5598: sub dump {
1.1180 droeschl 5599: my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755 albertel 5600: if (!$udomain) { $udomain=$env{'user.domain'}; }
5601: if (!$uname) { $uname=$env{'user.name'}; }
5602: my $uhome=&homeserver($uname,$udomain);
1.1167 droeschl 5603:
1.1180 droeschl 5604: my $reply;
5605: if (grep { $_ eq $uhome } current_machine_ids()) {
5606: # user is hosted on this machine
5607: $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
1.1226 raeburn 5608: $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1180 droeschl 5609: return %{unserialize($reply, $escapedkeys)};
5610: }
1.755 albertel 5611: if ($regexp) {
5612: $regexp=&escape($regexp);
5613: } else {
5614: $regexp='.';
5615: }
1.1166 raeburn 5616: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755 albertel 5617: my @pairs=split(/\&/,$rep);
5618: my %returnhash=();
1.1098 foxr 5619: if (!($rep =~ /^error/ )) {
5620: foreach my $item (@pairs) {
5621: my ($key,$value)=split(/=/,$item,2);
1.1180 droeschl 5622: $key = unescape($key) unless $escapedkeys;
5623: #$key = &unescape($key);
1.1098 foxr 5624: next if ($key =~ /^error: 2 /);
5625: $returnhash{$key}=&thaw_unescape($value);
5626: }
1.755 albertel 5627: }
5628: return %returnhash;
1.407 www 5629: }
5630:
1.1098 foxr 5631:
1.717 albertel 5632: # --------------------------------------------------------- dumpstore interface
5633:
5634: sub dumpstore {
5635: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180 droeschl 5636: # same as dump but keys must be escaped. They may contain colon separated
5637: # lists of values that may themself contain colons (e.g. symbs).
5638: return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717 albertel 5639: }
5640:
1.407 www 5641: # -------------------------------------------------------------- keys interface
5642:
5643: sub getkeys {
5644: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 5645: if (!$udomain) { $udomain=$env{'user.domain'}; }
5646: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 5647: my $uhome=&homeserver($uname,$udomain);
5648: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
5649: my @keyarray=();
1.800 albertel 5650: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 5651: next if ($key =~ /^error: 2 /);
1.800 albertel 5652: push(@keyarray,&unescape($key));
1.407 www 5653: }
5654: return @keyarray;
1.318 matthew 5655: }
5656:
1.319 matthew 5657: # --------------------------------------------------------------- currentdump
5658: sub currentdump {
1.328 matthew 5659: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 5660: $courseid = $env{'request.course.id'} if (! defined($courseid));
5661: $sdom = $env{'user.domain'} if (! defined($sdom));
5662: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 5663: my $uhome = &homeserver($sname,$sdom);
1.1180 droeschl 5664: my $rep;
5665:
5666: if (grep { $_ eq $uhome } current_machine_ids()) {
5667: $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
5668: $courseid)));
5669: } else {
5670: $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
5671: }
5672:
1.318 matthew 5673: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 5674: #
1.318 matthew 5675: my %returnhash=();
1.319 matthew 5676: #
5677: if ($rep eq "unknown_cmd") {
5678: # an old lond will not know currentdump
5679: # Do a dump and make it look like a currentdump
1.822 albertel 5680: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 5681: return if ($tmp[0] =~ /^(error:|no_such_host)/);
5682: my %hash = @tmp;
5683: @tmp=();
1.424 matthew 5684: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 5685: } else {
5686: my @pairs=split(/\&/,$rep);
1.800 albertel 5687: foreach my $pair (@pairs) {
5688: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 5689: my ($symb,$param) = split(/:/,$key);
5690: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 5691: &thaw_unescape($value);
1.319 matthew 5692: }
1.191 harris41 5693: }
1.12 www 5694: return %returnhash;
1.424 matthew 5695: }
5696:
5697: sub convert_dump_to_currentdump{
5698: my %hash = %{shift()};
5699: my %returnhash;
5700: # Code ripped from lond, essentially. The only difference
5701: # here is the unescaping done by lonnet::dump(). Conceivably
5702: # we might run in to problems with parameter names =~ /^v\./
5703: while (my ($key,$value) = each(%hash)) {
5704: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 5705: $symb = &unescape($symb);
5706: $param = &unescape($param);
1.424 matthew 5707: next if ($v eq 'version' || $symb eq 'keys');
5708: next if (exists($returnhash{$symb}) &&
5709: exists($returnhash{$symb}->{$param}) &&
5710: $returnhash{$symb}->{'v.'.$param} > $v);
5711: $returnhash{$symb}->{$param}=$value;
5712: $returnhash{$symb}->{'v.'.$param}=$v;
5713: }
5714: #
5715: # Remove all of the keys in the hashes which keep track of
5716: # the version of the parameter.
5717: while (my ($symb,$param_hash) = each(%returnhash)) {
5718: # use a foreach because we are going to delete from the hash.
5719: foreach my $key (keys(%$param_hash)) {
5720: delete($param_hash->{$key}) if ($key =~ /^v\./);
5721: }
5722: }
5723: return \%returnhash;
1.12 www 5724: }
5725:
1.627 albertel 5726: # ------------------------------------------------------ critical inc interface
5727:
5728: sub cinc {
5729: return &inc(@_,'critical');
5730: }
5731:
1.449 matthew 5732: # --------------------------------------------------------------- inc interface
5733:
5734: sub inc {
1.627 albertel 5735: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 5736: if (!$udomain) { $udomain=$env{'user.domain'}; }
5737: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 5738: my $uhome=&homeserver($uname,$udomain);
5739: my $items='';
5740: if (! ref($store)) {
5741: # got a single value, so use that instead
5742: $items = &escape($store).'=&';
5743: } elsif (ref($store) eq 'SCALAR') {
5744: $items = &escape($$store).'=&';
5745: } elsif (ref($store) eq 'ARRAY') {
5746: $items = join('=&',map {&escape($_);} @{$store});
5747: } elsif (ref($store) eq 'HASH') {
5748: while (my($key,$value) = each(%{$store})) {
5749: $items.= &escape($key).'='.&escape($value).'&';
5750: }
5751: }
5752: $items=~s/\&$//;
1.627 albertel 5753: if ($critical) {
5754: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
5755: } else {
5756: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
5757: }
1.449 matthew 5758: }
5759:
1.12 www 5760: # --------------------------------------------------------------- put interface
5761:
5762: sub put {
1.134 albertel 5763: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 5764: if (!$udomain) { $udomain=$env{'user.domain'}; }
5765: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 5766: my $uhome=&homeserver($uname,$udomain);
1.12 www 5767: my $items='';
1.800 albertel 5768: foreach my $item (keys(%$storehash)) {
5769: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 5770: }
1.12 www 5771: $items=~s/\&$//;
1.134 albertel 5772: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 5773: }
5774:
1.631 albertel 5775: # ------------------------------------------------------------ newput interface
5776:
5777: sub newput {
5778: my ($namespace,$storehash,$udomain,$uname)=@_;
5779: if (!$udomain) { $udomain=$env{'user.domain'}; }
5780: if (!$uname) { $uname=$env{'user.name'}; }
5781: my $uhome=&homeserver($uname,$udomain);
5782: my $items='';
5783: foreach my $key (keys(%$storehash)) {
5784: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
5785: }
5786: $items=~s/\&$//;
5787: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
5788: }
5789:
5790: # --------------------------------------------------------- putstore interface
5791:
1.524 raeburn 5792: sub putstore {
1.715 albertel 5793: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620 albertel 5794: if (!$udomain) { $udomain=$env{'user.domain'}; }
5795: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 5796: my $uhome=&homeserver($uname,$udomain);
5797: my $items='';
1.715 albertel 5798: foreach my $key (keys(%$storehash)) {
5799: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 5800: }
1.715 albertel 5801: $items=~s/\&$//;
1.716 albertel 5802: my $esc_symb=&escape($symb);
5803: my $esc_v=&escape($version);
1.715 albertel 5804: my $reply =
1.716 albertel 5805: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 5806: $uhome);
5807: if ($reply eq 'unknown_cmd') {
1.716 albertel 5808: # gfall back to way things use to be done
1.715 albertel 5809: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
5810: $uname);
1.524 raeburn 5811: }
1.715 albertel 5812: return $reply;
5813: }
5814:
5815: sub old_putstore {
1.716 albertel 5816: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
5817: if (!$udomain) { $udomain=$env{'user.domain'}; }
5818: if (!$uname) { $uname=$env{'user.name'}; }
5819: my $uhome=&homeserver($uname,$udomain);
5820: my %newstorehash;
1.800 albertel 5821: foreach my $item (keys(%$storehash)) {
5822: my $key = $version.':'.&escape($symb).':'.$item;
5823: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 5824: }
5825: my $items='';
5826: my %allitems = ();
1.800 albertel 5827: foreach my $item (keys(%newstorehash)) {
5828: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 5829: my $key = $1.':keys:'.$2;
5830: $allitems{$key} .= $3.':';
5831: }
1.800 albertel 5832: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 5833: }
1.800 albertel 5834: foreach my $item (keys(%allitems)) {
5835: $allitems{$item} =~ s/\:$//;
5836: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 5837: }
5838: $items=~s/\&$//;
5839: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 5840: }
5841:
1.47 www 5842: # ------------------------------------------------------ critical put interface
5843:
5844: sub cput {
1.134 albertel 5845: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 5846: if (!$udomain) { $udomain=$env{'user.domain'}; }
5847: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 5848: my $uhome=&homeserver($uname,$udomain);
1.47 www 5849: my $items='';
1.800 albertel 5850: foreach my $item (keys(%$storehash)) {
5851: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 5852: }
1.47 www 5853: $items=~s/\&$//;
1.134 albertel 5854: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 5855: }
5856:
5857: # -------------------------------------------------------------- eget interface
5858:
5859: sub eget {
1.133 albertel 5860: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 5861: my $items='';
1.800 albertel 5862: foreach my $item (@$storearr) {
5863: $items.=&escape($item).'&';
1.191 harris41 5864: }
1.12 www 5865: $items=~s/\&$//;
1.620 albertel 5866: if (!$udomain) { $udomain=$env{'user.domain'}; }
5867: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 5868: my $uhome=&homeserver($uname,$udomain);
5869: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 5870: my @pairs=split(/\&/,$rep);
5871: my %returnhash=();
1.42 www 5872: my $i=0;
1.800 albertel 5873: foreach my $item (@$storearr) {
5874: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 5875: $i++;
1.191 harris41 5876: }
1.12 www 5877: return %returnhash;
5878: }
5879:
1.667 albertel 5880: # ------------------------------------------------------------ tmpput interface
5881: sub tmpput {
1.802 raeburn 5882: my ($storehash,$server,$context)=@_;
1.667 albertel 5883: my $items='';
1.800 albertel 5884: foreach my $item (keys(%$storehash)) {
5885: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 5886: }
5887: $items=~s/\&$//;
1.802 raeburn 5888: if (defined($context)) {
5889: $items .= ':'.&escape($context);
5890: }
1.667 albertel 5891: return &reply("tmpput:$items",$server);
5892: }
5893:
5894: # ------------------------------------------------------------ tmpget interface
5895: sub tmpget {
1.688 albertel 5896: my ($token,$server)=@_;
5897: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5898: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 5899: my %returnhash;
5900: foreach my $item (split(/\&/,$rep)) {
5901: my ($key,$value)=split(/=/,$item);
1.951 raeburn 5902: next if ($key =~ /^error: 2 /);
1.667 albertel 5903: $returnhash{&unescape($key)}=&thaw_unescape($value);
5904: }
5905: return %returnhash;
5906: }
5907:
1.1113 raeburn 5908: # ------------------------------------------------------------ tmpdel interface
1.688 albertel 5909: sub tmpdel {
5910: my ($token,$server)=@_;
5911: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5912: return &reply("tmpdel:$token",$server);
5913: }
5914:
1.1198 raeburn 5915: # ------------------------------------------------------------ get_timebased_id
5916:
5917: sub get_timebased_id {
5918: my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
5919: $maxtries) = @_;
5920: my ($newid,$error,$dellock);
5921: unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
5922: return ('','ok','invalid call to get suffix');
5923: }
5924:
5925: # set defaults for any optional args for which values were not supplied
5926: if ($who eq '') {
5927: $who = $env{'user.name'}.':'.$env{'user.domain'};
5928: }
5929: if (!$locktries) {
5930: $locktries = 3;
5931: }
5932: if (!$maxtries) {
5933: $maxtries = 10;
5934: }
5935:
5936: if (($cdom eq '') || ($cnum eq '')) {
5937: if ($env{'request.course.id'}) {
5938: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
5939: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
5940: }
5941: if (($cdom eq '') || ($cnum eq '')) {
5942: return ('','ok','call to get suffix not in course context');
5943: }
5944: }
5945:
5946: # construct locking item
5947: my $lockhash = {
5948: $prefix."\0".'locked_'.$keyid => $who,
5949: };
5950: my $tries = 0;
5951:
5952: # attempt to get lock on nohist_$namespace file
5953: my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
5954: while (($gotlock ne 'ok') && $tries <$locktries) {
5955: $tries ++;
5956: sleep 1;
5957: $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
5958: }
5959:
5960: # attempt to get unique identifier, based on current timestamp
5961: if ($gotlock eq 'ok') {
5962: my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
5963: my $id = time;
5964: $newid = $id;
5965: my $idtries = 0;
5966: while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
5967: if ($idtype eq 'concat') {
5968: $newid = $id.$idtries;
5969: } else {
5970: $newid ++;
5971: }
5972: $idtries ++;
5973: }
5974: if (!exists($inuse{$prefix."\0".$newid})) {
5975: my %new_item = (
5976: $prefix."\0".$newid => $who,
5977: );
5978: my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
5979: $cdom,$cnum);
5980: if ($putresult ne 'ok') {
5981: undef($newid);
5982: $error = 'error saving new item: '.$putresult;
5983: }
5984: } else {
5985: $error = ('error: no unique suffix available for the new item ');
5986: }
5987: # remove lock
5988: my @del_lock = ($prefix."\0".'locked_'.$keyid);
5989: $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
5990: } else {
5991: $error = "error: could not obtain lockfile\n";
5992: $dellock = 'ok';
5993: }
5994: return ($newid,$dellock,$error);
5995: }
5996:
1.765 albertel 5997: # -------------------------------------------------- portfolio access checking
5998:
5999: sub portfolio_access {
1.766 albertel 6000: my ($requrl) = @_;
1.765 albertel 6001: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
6002: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814 raeburn 6003: if ($result) {
6004: my %setters;
6005: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6006: my ($startblock,$endblock) =
6007: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
6008: if ($startblock && $endblock) {
6009: return 'B';
6010: }
6011: } else {
6012: my ($startblock,$endblock) =
6013: &Apache::loncommon::blockcheck(\%setters,'port');
6014: if ($startblock && $endblock) {
6015: return 'B';
6016: }
6017: }
6018: }
1.765 albertel 6019: if ($result eq 'ok') {
1.766 albertel 6020: return 'F';
1.765 albertel 6021: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 6022: return 'A';
1.765 albertel 6023: }
1.766 albertel 6024: return '';
1.765 albertel 6025: }
6026:
6027: sub get_portfolio_access {
1.767 albertel 6028: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
6029:
6030: if (!ref($access_hash)) {
6031: my $current_perms = &get_portfile_permissions($udom,$unum);
6032: my %access_controls = &get_access_controls($current_perms,$group,
6033: $file_name);
6034: $access_hash = $access_controls{$file_name};
6035: }
6036:
1.765 albertel 6037: my ($public,$guest,@domains,@users,@courses,@groups);
6038: my $now = time;
6039: if (ref($access_hash) eq 'HASH') {
6040: foreach my $key (keys(%{$access_hash})) {
6041: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
6042: if ($start > $now) {
6043: next;
6044: }
6045: if ($end && $end<$now) {
6046: next;
6047: }
6048: if ($scope eq 'public') {
6049: $public = $key;
6050: last;
6051: } elsif ($scope eq 'guest') {
6052: $guest = $key;
6053: } elsif ($scope eq 'domains') {
6054: push(@domains,$key);
6055: } elsif ($scope eq 'users') {
6056: push(@users,$key);
6057: } elsif ($scope eq 'course') {
6058: push(@courses,$key);
6059: } elsif ($scope eq 'group') {
6060: push(@groups,$key);
6061: }
6062: }
6063: if ($public) {
6064: return 'ok';
6065: }
6066: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6067: if ($guest) {
6068: return $guest;
6069: }
6070: } else {
6071: if (@domains > 0) {
6072: foreach my $domkey (@domains) {
6073: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
6074: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
6075: return 'ok';
6076: }
6077: }
6078: }
6079: }
6080: if (@users > 0) {
6081: foreach my $userkey (@users) {
1.865 raeburn 6082: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
6083: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
6084: if (ref($item) eq 'HASH') {
6085: if (($item->{'uname'} eq $env{'user.name'}) &&
6086: ($item->{'udom'} eq $env{'user.domain'})) {
6087: return 'ok';
6088: }
6089: }
6090: }
6091: }
1.765 albertel 6092: }
6093: }
6094: my %roleshash;
6095: my @courses_and_groups = @courses;
6096: push(@courses_and_groups,@groups);
6097: if (@courses_and_groups > 0) {
6098: my (%allgroups,%allroles);
6099: my ($start,$end,$role,$sec,$group);
6100: foreach my $envkey (%env) {
1.1060 raeburn 6101: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6102: my $cid = $2.'_'.$3;
6103: if ($1 eq 'gr') {
6104: $group = $4;
6105: $allgroups{$cid}{$group} = $env{$envkey};
6106: } else {
6107: if ($4 eq '') {
6108: $sec = 'none';
6109: } else {
6110: $sec = $4;
6111: }
6112: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6113: }
1.811 albertel 6114: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6115: my $cid = $2.'_'.$3;
6116: if ($4 eq '') {
6117: $sec = 'none';
6118: } else {
6119: $sec = $4;
6120: }
6121: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6122: }
6123: }
6124: if (keys(%allroles) == 0) {
6125: return;
6126: }
6127: foreach my $key (@courses_and_groups) {
6128: my %content = %{$$access_hash{$key}};
6129: my $cnum = $content{'number'};
6130: my $cdom = $content{'domain'};
6131: my $cid = $cdom.'_'.$cnum;
6132: if (!exists($allroles{$cid})) {
6133: next;
6134: }
6135: foreach my $role_id (keys(%{$content{'roles'}})) {
6136: my @sections = @{$content{'roles'}{$role_id}{'section'}};
6137: my @groups = @{$content{'roles'}{$role_id}{'group'}};
6138: my @status = @{$content{'roles'}{$role_id}{'access'}};
6139: my @roles = @{$content{'roles'}{$role_id}{'role'}};
6140: foreach my $role (keys(%{$allroles{$cid}})) {
6141: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
6142: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
6143: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
6144: if (grep/^all$/,@sections) {
6145: return 'ok';
6146: } else {
6147: if (grep/^$sec$/,@sections) {
6148: return 'ok';
6149: }
6150: }
6151: }
6152: }
6153: if (keys(%{$allgroups{$cid}}) == 0) {
6154: if (grep/^none$/,@groups) {
6155: return 'ok';
6156: }
6157: } else {
6158: if (grep/^all$/,@groups) {
6159: return 'ok';
6160: }
6161: foreach my $group (keys(%{$allgroups{$cid}})) {
6162: if (grep/^$group$/,@groups) {
6163: return 'ok';
6164: }
6165: }
6166: }
6167: }
6168: }
6169: }
6170: }
6171: }
6172: if ($guest) {
6173: return $guest;
6174: }
6175: }
6176: }
6177: return;
6178: }
6179:
6180: sub course_group_datechecker {
6181: my ($dates,$now,$status) = @_;
6182: my ($start,$end) = split(/\./,$dates);
6183: if (!$start && !$end) {
6184: return 'ok';
6185: }
6186: if (grep/^active$/,@{$status}) {
6187: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
6188: return 'ok';
6189: }
6190: }
6191: if (grep/^previous$/,@{$status}) {
6192: if ($end > $now ) {
6193: return 'ok';
6194: }
6195: }
6196: if (grep/^future$/,@{$status}) {
6197: if ($start > $now) {
6198: return 'ok';
6199: }
6200: }
6201: return;
6202: }
6203:
6204: sub parse_portfolio_url {
6205: my ($url) = @_;
6206:
6207: my ($type,$udom,$unum,$group,$file_name);
6208:
1.823 albertel 6209: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 6210: $type = 1;
6211: $udom = $1;
6212: $unum = $2;
6213: $file_name = $3;
1.823 albertel 6214: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 6215: $type = 2;
6216: $udom = $1;
6217: $unum = $2;
6218: $group = $3;
6219: $file_name = $3.'/'.$4;
6220: }
6221: if (wantarray) {
6222: return ($type,$udom,$unum,$file_name,$group);
6223: }
6224: return $type;
6225: }
6226:
6227: sub is_portfolio_url {
6228: my ($url) = @_;
6229: return scalar(&parse_portfolio_url($url));
6230: }
6231:
1.798 raeburn 6232: sub is_portfolio_file {
6233: my ($file) = @_;
1.820 raeburn 6234: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 6235: return 1;
6236: }
6237: return;
6238: }
6239:
1.976 raeburn 6240: sub usertools_access {
1.1084 raeburn 6241: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 6242: my ($access,%tools);
6243: if ($context eq '') {
6244: $context = 'tools';
6245: }
6246: if ($context eq 'requestcourses') {
6247: %tools = (
6248: official => 1,
6249: unofficial => 1,
1.1006 raeburn 6250: community => 1,
1.1246 raeburn 6251: textbook => 1,
1.985 raeburn 6252: );
1.1183 raeburn 6253: } elsif ($context eq 'requestauthor') {
6254: %tools = (
6255: requestauthor => 1,
6256: );
1.985 raeburn 6257: } else {
6258: %tools = (
6259: aboutme => 1,
6260: blog => 1,
1.1177 raeburn 6261: webdav => 1,
1.985 raeburn 6262: portfolio => 1,
6263: );
6264: }
1.976 raeburn 6265: return if (!defined($tools{$tool}));
6266:
1.1242 raeburn 6267: if (($udom eq '') || ($uname eq '')) {
1.976 raeburn 6268: $udom = $env{'user.domain'};
6269: $uname = $env{'user.name'};
6270: }
6271:
1.978 raeburn 6272: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
6273: if ($action ne 'reload') {
1.985 raeburn 6274: if ($context eq 'requestcourses') {
6275: return $env{'environment.canrequest.'.$tool};
1.1183 raeburn 6276: } elsif ($context eq 'requestauthor') {
6277: return $env{'environment.canrequest.author'};
1.985 raeburn 6278: } else {
6279: return $env{'environment.availabletools.'.$tool};
6280: }
6281: }
1.976 raeburn 6282: }
6283:
1.1183 raeburn 6284: my ($toolstatus,$inststatus,$envkey);
6285: if ($context eq 'requestauthor') {
6286: $envkey = $context;
6287: } else {
6288: $envkey = $context.'.'.$tool;
6289: }
1.976 raeburn 6290:
1.985 raeburn 6291: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
6292: ($action ne 'reload')) {
1.1183 raeburn 6293: $toolstatus = $env{'environment.'.$envkey};
1.976 raeburn 6294: $inststatus = $env{'environment.inststatus'};
6295: } else {
1.1084 raeburn 6296: if (ref($userenvref) eq 'HASH') {
1.1183 raeburn 6297: $toolstatus = $userenvref->{$envkey};
1.1084 raeburn 6298: $inststatus = $userenvref->{'inststatus'};
6299: } else {
1.1183 raeburn 6300: my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
6301: $toolstatus = $userenv{$envkey};
1.1084 raeburn 6302: $inststatus = $userenv{'inststatus'};
6303: }
1.976 raeburn 6304: }
6305:
6306: if ($toolstatus ne '') {
6307: if ($toolstatus) {
6308: $access = 1;
6309: } else {
6310: $access = 0;
6311: }
6312: return $access;
6313: }
6314:
1.1084 raeburn 6315: my ($is_adv,%domdef);
6316: if (ref($is_advref) eq 'HASH') {
6317: $is_adv = $is_advref->{'is_adv'};
6318: } else {
6319: $is_adv = &is_advanced_user($udom,$uname);
6320: }
6321: if (ref($domdefref) eq 'HASH') {
6322: %domdef = %{$domdefref};
6323: } else {
6324: %domdef = &get_domain_defaults($udom);
6325: }
1.976 raeburn 6326: if (ref($domdef{$tool}) eq 'HASH') {
6327: if ($is_adv) {
6328: if ($domdef{$tool}{'_LC_adv'} ne '') {
6329: if ($domdef{$tool}{'_LC_adv'}) {
6330: $access = 1;
6331: } else {
6332: $access = 0;
6333: }
6334: return $access;
6335: }
6336: }
6337: if ($inststatus ne '') {
6338: my ($hasaccess,$hasnoaccess);
6339: foreach my $affiliation (split(/:/,$inststatus)) {
6340: if ($domdef{$tool}{$affiliation} ne '') {
6341: if ($domdef{$tool}{$affiliation}) {
6342: $hasaccess = 1;
6343: } else {
6344: $hasnoaccess = 1;
6345: }
6346: }
6347: }
6348: if ($hasaccess || $hasnoaccess) {
6349: if ($hasaccess) {
6350: $access = 1;
6351: } elsif ($hasnoaccess) {
6352: $access = 0;
6353: }
6354: return $access;
6355: }
6356: } else {
6357: if ($domdef{$tool}{'default'} ne '') {
6358: if ($domdef{$tool}{'default'}) {
6359: $access = 1;
6360: } elsif ($domdef{$tool}{'default'} == 0) {
6361: $access = 0;
6362: }
6363: return $access;
6364: }
6365: }
6366: } else {
1.1177 raeburn 6367: if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985 raeburn 6368: $access = 1;
6369: } else {
6370: $access = 0;
6371: }
1.976 raeburn 6372: return $access;
6373: }
6374: }
6375:
1.1050 raeburn 6376: sub is_course_owner {
6377: my ($cdom,$cnum,$udom,$uname) = @_;
6378: if (($udom eq '') || ($uname eq '')) {
6379: $udom = $env{'user.domain'};
6380: $uname = $env{'user.name'};
6381: }
6382: unless (($udom eq '') || ($uname eq '')) {
6383: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
6384: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
6385: return 1;
6386: } else {
6387: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
6388: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
6389: return 1;
6390: }
6391: }
6392: }
6393: }
6394: return;
6395: }
6396:
1.976 raeburn 6397: sub is_advanced_user {
6398: my ($udom,$uname) = @_;
1.1085 raeburn 6399: if ($udom ne '' && $uname ne '') {
6400: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128 raeburn 6401: if (wantarray) {
6402: return ($env{'user.adv'},$env{'user.author'});
6403: } else {
6404: return $env{'user.adv'};
6405: }
1.1085 raeburn 6406: }
6407: }
1.976 raeburn 6408: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
6409: my %allroles;
1.1128 raeburn 6410: my ($is_adv,$is_author);
1.976 raeburn 6411: foreach my $role (keys(%roleshash)) {
6412: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
6413: my $area = '/'.$tdomain.'/'.$trest;
6414: if ($sec ne '') {
6415: $area .= '/'.$sec;
6416: }
6417: if (($area ne '') && ($trole ne '')) {
6418: my $spec=$trole.'.'.$area;
6419: if ($trole =~ /^cr\//) {
6420: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
6421: } elsif ($trole ne 'gr') {
6422: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
6423: }
1.1128 raeburn 6424: if ($trole eq 'au') {
6425: $is_author = 1;
6426: }
1.976 raeburn 6427: }
6428: }
6429: foreach my $role (keys(%allroles)) {
6430: last if ($is_adv);
6431: foreach my $item (split(/:/,$allroles{$role})) {
6432: if ($item ne '') {
6433: my ($privilege,$restrictions)=split(/&/,$item);
6434: if ($privilege eq 'adv') {
6435: $is_adv = 1;
6436: last;
6437: }
6438: }
6439: }
6440: }
1.1128 raeburn 6441: if (wantarray) {
6442: return ($is_adv,$is_author);
6443: }
1.976 raeburn 6444: return $is_adv;
6445: }
1.798 raeburn 6446:
1.1035 raeburn 6447: sub check_can_request {
1.1036 raeburn 6448: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 6449: my $canreq = 0;
6450: my ($types,$typename) = &Apache::loncommon::course_types();
6451: my @options = ('approval','validate','autolimit');
6452: my $optregex = join('|',@options);
6453: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
6454: foreach my $type (@{$types}) {
6455: if (&usertools_access($env{'user.name'},
6456: $env{'user.domain'},
6457: $type,undef,'requestcourses')) {
6458: $canreq ++;
1.1036 raeburn 6459: if (ref($request_domains) eq 'HASH') {
6460: push(@{$request_domains->{$type}},$env{'user.domain'});
6461: }
1.1035 raeburn 6462: if ($dom eq $env{'user.domain'}) {
6463: $can_request->{$type} = 1;
6464: }
6465: }
6466: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
6467: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
6468: if (@curr > 0) {
1.1036 raeburn 6469: foreach my $item (@curr) {
6470: if (ref($request_domains) eq 'HASH') {
6471: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
6472: if ($otherdom ne '') {
6473: if (ref($request_domains->{$type}) eq 'ARRAY') {
6474: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
6475: push(@{$request_domains->{$type}},$otherdom);
6476: }
6477: } else {
6478: push(@{$request_domains->{$type}},$otherdom);
6479: }
6480: }
6481: }
6482: }
6483: unless($dom eq $env{'user.domain'}) {
6484: $canreq ++;
1.1035 raeburn 6485: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
6486: $can_request->{$type} = 1;
6487: }
6488: }
6489: }
6490: }
6491: }
6492: }
6493: return $canreq;
6494: }
6495:
1.341 www 6496: # ---------------------------------------------- Custom access rule evaluation
6497:
6498: sub customaccess {
6499: my ($priv,$uri)=@_;
1.807 albertel 6500: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 6501: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 6502: $udom = &LONCAPA::clean_domain($udom);
6503: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 6504: my $access=0;
1.800 albertel 6505: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 6506: my ($effect,$realm,$role,$type)=split(/\:/,$right);
6507: if ($type eq 'user') {
6508: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 6509: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 6510: if ($tdom) {
6511: if ($tdom ne $env{'user.domain'}) { next; }
6512: }
1.896 albertel 6513: if ($tuname) {
6514: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 6515: }
6516: $access=($effect eq 'allow');
6517: last;
6518: }
6519: } else {
6520: if ($role) {
6521: if ($role ne $urole) { next; }
6522: }
6523: foreach my $scope (split(/\s*\,\s*/,$realm)) {
6524: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
6525: if ($tdom) {
6526: if ($tdom ne $udom) { next; }
6527: }
6528: if ($tcrs) {
6529: if ($tcrs ne $ucrs) { next; }
6530: }
6531: if ($tsec) {
6532: if ($tsec ne $usec) { next; }
6533: }
6534: $access=($effect eq 'allow');
6535: last;
6536: }
6537: if ($realm eq '' && $role eq '') {
6538: $access=($effect eq 'allow');
6539: }
1.402 bowersj2 6540: }
1.341 www 6541: }
6542: return $access;
6543: }
6544:
1.103 harris41 6545: # ------------------------------------------------- Check for a user privilege
1.12 www 6546:
6547: sub allowed {
1.810 raeburn 6548: my ($priv,$uri,$symb,$role)=@_;
1.705 albertel 6549: my $ver_orguri=$uri;
1.439 www 6550: $uri=&deversion($uri);
1.152 www 6551: my $orguri=$uri;
1.52 www 6552: $uri=&declutter($uri);
1.809 raeburn 6553:
1.810 raeburn 6554: if ($priv eq 'evb') {
6555: # Evade communication block restrictions for specified role in a course
6556: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
6557: return $1;
6558: } else {
6559: return;
6560: }
6561: }
6562:
1.620 albertel 6563: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 6564: # Free bre access to adm and meta resources
1.775 albertel 6565: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 6566: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
6567: && ($priv eq 'bre')) {
1.14 www 6568: return 'F';
1.159 www 6569: }
6570:
1.545 banghart 6571: # Free bre access to user's own portfolio contents
1.714 raeburn 6572: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 6573: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 6574: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 6575: my %setters;
6576: my ($startblock,$endblock) =
6577: &Apache::loncommon::blockcheck(\%setters,'port');
6578: if ($startblock && $endblock) {
6579: return 'B';
6580: } else {
6581: return 'F';
6582: }
1.545 banghart 6583: }
6584:
1.762 raeburn 6585: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 6586: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
6587: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
6588: if (exists($env{'request.course.id'})) {
6589: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6590: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6591: if (($domain eq $cdom) && ($name eq $cnum)) {
6592: my $courseprivid=$env{'request.course.id'};
6593: $courseprivid=~s/\_/\//;
6594: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
6595: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
6596: return $1;
1.762 raeburn 6597: } else {
6598: if ($env{'request.course.sec'}) {
6599: $courseprivid.='/'.$env{'request.course.sec'};
6600: }
6601: if ($env{'user.priv.'.$env{'request.role'}.'./'.
6602: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
6603: return $2;
6604: }
1.714 raeburn 6605: }
6606: }
6607: }
6608: }
6609:
1.159 www 6610: # Free bre to public access
6611:
6612: if ($priv eq 'bre') {
1.238 www 6613: my $copyright=&metadata($uri,'copyright');
1.620 albertel 6614: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 6615: return 'F';
6616: }
1.238 www 6617: if ($copyright eq 'priv') {
6618: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 6619: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 6620: return '';
6621: }
6622: }
6623: if ($copyright eq 'domain') {
6624: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 6625: unless (($env{'user.domain'} eq $1) ||
6626: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 6627: return '';
6628: }
1.262 matthew 6629: }
1.620 albertel 6630: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 6631: # Library role, so allow browsing of resources in this domain.
6632: return 'F';
1.238 www 6633: }
1.341 www 6634: if ($copyright eq 'custom') {
6635: unless (&customaccess($priv,$uri)) { return ''; }
6636: }
1.14 www 6637: }
1.264 matthew 6638: # Domain coordinator is trying to create a course
1.620 albertel 6639: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 6640: # uri is the requested domain in this case.
6641: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 6642: # a role of dc for the domain in question.
1.620 albertel 6643: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 6644: }
1.29 www 6645:
1.52 www 6646: my $thisallowed='';
6647: my $statecond=0;
6648: my $courseprivid='';
6649:
1.1039 raeburn 6650: my $ownaccess;
1.1043 raeburn 6651: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 6652: if (($priv eq 'bro') && ($env{'user.author'})) {
6653: if ($uri eq '') {
6654: $ownaccess = 1;
6655: } else {
6656: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
6657: my $udom = $env{'user.domain'};
6658: my $uname = $env{'user.name'};
6659: if ($uri =~ m{^\Q$udom\E/?$}) {
6660: $ownaccess = 1;
1.1040 raeburn 6661: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 6662: unless ($uri =~ m{\.\./}) {
6663: $ownaccess = 1;
6664: }
6665: } elsif (($udom ne 'public') && ($uname ne 'public')) {
6666: my $now = time;
6667: if ($uri =~ m{^([^/]+)/?$}) {
6668: my $adom = $1;
6669: foreach my $key (keys(%env)) {
1.1042 raeburn 6670: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 6671: my ($start,$end) = split('.',$env{$key});
6672: if (($now >= $start) && (!$end || $end < $now)) {
6673: $ownaccess = 1;
6674: last;
6675: }
6676: }
6677: }
6678: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
6679: my $adom = $1;
6680: my $aname = $2;
1.1042 raeburn 6681: foreach my $role ('ca','aa') {
6682: if ($env{"user.role.$role./$adom/$aname"}) {
6683: my ($start,$end) =
6684: split('.',$env{"user.role.$role./$adom/$aname"});
6685: if (($now >= $start) && (!$end || $end < $now)) {
6686: $ownaccess = 1;
6687: last;
6688: }
1.1039 raeburn 6689: }
6690: }
6691: }
6692: }
6693: }
6694: }
6695: }
6696:
1.52 www 6697: # Course
6698:
1.620 albertel 6699: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6700: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6701: $thisallowed.=$1;
6702: }
1.52 www 6703: }
1.29 www 6704:
1.52 www 6705: # Domain
6706:
1.620 albertel 6707: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 6708: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6709: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6710: $thisallowed.=$1;
6711: }
1.12 www 6712: }
1.52 www 6713:
1.1141 raeburn 6714: # User who is not author or co-author might still be able to edit
6715: # resource of an author in the domain (e.g., if Domain Coordinator).
6716: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
6717: (&allowed('mdc',$env{'request.course.id'}))) {
6718: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
6719: $thisallowed.=$1;
6720: }
6721: }
6722:
1.52 www 6723: # Course: uri itself is a course
1.66 www 6724: my $courseuri=$uri;
6725: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 6726: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 6727:
1.620 albertel 6728: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 6729: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6730: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6731: $thisallowed.=$1;
6732: }
1.12 www 6733: }
1.29 www 6734:
1.665 albertel 6735: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 6736: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 6737: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 6738: $thisallowed='';
1.671 raeburn 6739: my ($match)=&is_on_map($uri);
6740: if ($match) {
6741: if ($env{'user.priv.'.$env{'request.role'}.'./'}
6742: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6743: my @blockers = &has_comm_blocking($priv,$symb,$uri);
6744: if (@blockers > 0) {
6745: $thisallowed = 'B';
6746: } else {
6747: $thisallowed.=$1;
6748: }
1.671 raeburn 6749: }
6750: } else {
1.705 albertel 6751: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 6752: if ($refuri) {
6753: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 6754: $thisallowed='F';
1.671 raeburn 6755: } else {
6756: $refuri=&declutter($refuri);
6757: my ($match) = &is_on_map($refuri);
6758: if ($match) {
1.1162 raeburn 6759: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
6760: if (@blockers > 0) {
6761: $thisallowed = 'B';
6762: } else {
6763: $thisallowed='F';
6764: }
1.671 raeburn 6765: }
1.669 raeburn 6766: }
1.671 raeburn 6767: }
6768: }
1.314 www 6769: }
1.492 albertel 6770:
1.766 albertel 6771: if ($priv eq 'bre'
6772: && $thisallowed ne 'F'
6773: && $thisallowed ne '2'
6774: && &is_portfolio_url($uri)) {
6775: $thisallowed = &portfolio_access($uri);
6776: }
1.1250 raeburn 6777:
1.52 www 6778: # Full access at system, domain or course-wide level? Exit.
1.29 www 6779: if ($thisallowed=~/F/) {
6780: return 'F';
6781: }
6782:
1.52 www 6783: # If this is generating or modifying users, exit with special codes
1.29 www 6784:
1.643 www 6785: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
6786: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 6787: my ($audom,$auname)=split('/',$uri);
1.643 www 6788: # no author name given, so this just checks on the general right to make a co-author in this domain
6789: unless ($auname) { return $thisallowed; }
6790: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 6791: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
6792: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
6793: ($audom ne $env{'request.role.domain'}))) { return ''; }
6794: }
1.52 www 6795: return $thisallowed;
6796: }
6797: #
1.103 harris41 6798: # Gathered so far: system, domain and course wide privileges
1.52 www 6799: #
6800: # Course: See if uri or referer is an individual resource that is part of
6801: # the course
6802:
1.620 albertel 6803: if ($env{'request.course.id'}) {
1.232 www 6804:
1.620 albertel 6805: $courseprivid=$env{'request.course.id'};
6806: if ($env{'request.course.sec'}) {
6807: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 6808: }
6809: $courseprivid=~s/\_/\//;
6810: my $checkreferer=1;
1.232 www 6811: my ($match,$cond)=&is_on_map($uri);
6812: if ($match) {
6813: $statecond=$cond;
1.620 albertel 6814: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 6815: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6816: my $value = $1;
6817: if ($priv eq 'bre') {
6818: my @blockers = &has_comm_blocking($priv,$symb,$uri);
6819: if (@blockers > 0) {
6820: $thisallowed = 'B';
6821: } else {
6822: $thisallowed.=$value;
6823: }
6824: } else {
6825: $thisallowed.=$value;
6826: }
1.52 www 6827: $checkreferer=0;
6828: }
1.29 www 6829: }
1.83 www 6830:
1.148 www 6831: if ($checkreferer) {
1.620 albertel 6832: my $refuri=$env{'httpref.'.$orguri};
1.148 www 6833: unless ($refuri) {
1.800 albertel 6834: foreach my $key (keys(%env)) {
6835: if ($key=~/^httpref\..*\*/) {
6836: my $pattern=$key;
1.156 www 6837: $pattern=~s/^httpref\.\/res\///;
1.148 www 6838: $pattern=~s/\*/\[\^\/\]\+/g;
6839: $pattern=~s/\//\\\//g;
1.152 www 6840: if ($orguri=~/$pattern/) {
1.800 albertel 6841: $refuri=$env{$key};
1.148 www 6842: }
6843: }
1.191 harris41 6844: }
1.148 www 6845: }
1.232 www 6846:
1.148 www 6847: if ($refuri) {
1.152 www 6848: $refuri=&declutter($refuri);
1.232 www 6849: my ($match,$cond)=&is_on_map($refuri);
6850: if ($match) {
6851: my $refstatecond=$cond;
1.620 albertel 6852: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 6853: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6854: my $value = $1;
6855: if ($priv eq 'bre') {
6856: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
6857: if (@blockers > 0) {
6858: $thisallowed = 'B';
6859: } else {
6860: $thisallowed.=$value;
6861: }
6862: } else {
6863: $thisallowed.=$value;
6864: }
1.53 www 6865: $uri=$refuri;
6866: $statecond=$refstatecond;
1.52 www 6867: }
6868: }
1.148 www 6869: }
1.29 www 6870: }
1.52 www 6871: }
1.29 www 6872:
1.52 www 6873: #
1.103 harris41 6874: # Gathered now: all privileges that could apply, and condition number
1.52 www 6875: #
6876: #
6877: # Full or no access?
6878: #
1.29 www 6879:
1.52 www 6880: if ($thisallowed=~/F/) {
6881: return 'F';
6882: }
1.29 www 6883:
1.52 www 6884: unless ($thisallowed) {
6885: return '';
6886: }
1.29 www 6887:
1.52 www 6888: # Restrictions exist, deal with them
6889: #
6890: # C:according to course preferences
6891: # R:according to resource settings
6892: # L:unless locked
6893: # X:according to user session state
6894: #
6895:
6896: # Possibly locked functionality, check all courses
1.54 www 6897: # Locks might take effect only after 10 minutes cache expiration for other
6898: # courses, and 2 minutes for current course
1.52 www 6899:
6900: my $envkey;
6901: if ($thisallowed=~/L/) {
1.1000 raeburn 6902: foreach $envkey (keys(%env)) {
1.54 www 6903: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
6904: my $courseid=$2;
6905: my $roleid=$1.'.'.$2;
1.92 www 6906: $courseid=~s/^\///;
1.54 www 6907: my $expiretime=600;
1.620 albertel 6908: if ($env{'request.role'} eq $roleid) {
1.54 www 6909: $expiretime=120;
6910: }
6911: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
6912: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 6913: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 6914: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 6915: }
1.620 albertel 6916: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
6917: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
6918: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
6919: &log($env{'user.domain'},$env{'user.name'},
6920: $env{'user.home'},
1.57 www 6921: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 6922: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 6923: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 6924: return '';
6925: }
6926: }
1.620 albertel 6927: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
6928: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
6929: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
6930: &log($env{'user.domain'},$env{'user.name'},
6931: $env{'user.home'},
1.57 www 6932: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 6933: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 6934: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 6935: return '';
6936: }
6937: }
6938: }
1.29 www 6939: }
1.52 www 6940: }
6941:
6942: #
6943: # Rest of the restrictions depend on selected course
6944: #
6945:
1.620 albertel 6946: unless ($env{'request.course.id'}) {
1.766 albertel 6947: if ($thisallowed eq 'A') {
6948: return 'A';
1.814 raeburn 6949: } elsif ($thisallowed eq 'B') {
6950: return 'B';
1.766 albertel 6951: } else {
6952: return '1';
6953: }
1.52 www 6954: }
1.29 www 6955:
1.52 www 6956: #
6957: # Now user is definitely in a course
6958: #
1.53 www 6959:
6960:
6961: # Course preferences
6962:
6963: if ($thisallowed=~/C/) {
1.620 albertel 6964: my $rolecode=(split(/\./,$env{'request.role'}))[0];
6965: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
6966: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 6967: =~/\Q$rolecode\E/) {
1.1103 raeburn 6968: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 6969: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
6970: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
6971: $env{'request.course.id'});
6972: }
1.237 www 6973: return '';
6974: }
6975:
1.620 albertel 6976: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 6977: =~/\Q$unamedom\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 user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
6981: $env{'request.course.id'});
6982: }
1.54 www 6983: return '';
6984: }
1.53 www 6985: }
6986:
6987: # Resource preferences
6988:
6989: if ($thisallowed=~/R/) {
1.620 albertel 6990: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 6991: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103 raeburn 6992: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 6993: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
6994: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
6995: }
6996: return '';
1.54 www 6997: }
1.53 www 6998: }
1.30 www 6999:
1.246 www 7000: # Restricted by state or randomout?
1.30 www 7001:
1.52 www 7002: if ($thisallowed=~/X/) {
1.620 albertel 7003: if ($env{'acc.randomout'}) {
1.579 albertel 7004: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 7005: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 7006: return '';
7007: }
1.247 www 7008: }
7009: if (&condval($statecond)) {
1.52 www 7010: return '2';
7011: } else {
7012: return '';
7013: }
7014: }
1.30 www 7015:
1.766 albertel 7016: if ($thisallowed eq 'A') {
7017: return 'A';
1.814 raeburn 7018: } elsif ($thisallowed eq 'B') {
7019: return 'B';
1.766 albertel 7020: }
1.52 www 7021: return 'F';
1.232 www 7022: }
1.1162 raeburn 7023:
1.1192 raeburn 7024: # ------------------------------------------- Check construction space access
7025:
7026: sub constructaccess {
7027: my ($url,$setpriv)=@_;
7028:
7029: # We do not allow editing of previous versions of files
7030: if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
7031:
7032: # Get username and domain from URL
7033: my ($ownername,$ownerdomain,$ownerhome);
7034:
7035: ($ownerdomain,$ownername) =
7036: ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
7037:
7038: # The URL does not really point to any authorspace, forget it
7039: unless (($ownername) && ($ownerdomain)) { return ''; }
7040:
7041: # Now we need to see if the user has access to the authorspace of
7042: # $ownername at $ownerdomain
7043:
7044: if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
7045: # Real author for this?
7046: $ownerhome = $env{'user.home'};
7047: if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
7048: return ($ownername,$ownerdomain,$ownerhome);
7049: }
7050: } else {
7051: # Co-author for this?
7052: if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
7053: exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
7054: $ownerhome = &homeserver($ownername,$ownerdomain);
7055: return ($ownername,$ownerdomain,$ownerhome);
7056: }
7057: }
7058:
7059: # We don't have any access right now. If we are not possibly going to do anything about this,
7060: # we might as well leave
7061: unless ($setpriv) { return ''; }
7062:
7063: # Backdoor access?
7064: my $allowed=&allowed('eco',$ownerdomain);
7065: # Nope
7066: unless ($allowed) { return ''; }
7067: # Looks like we may have access, but could be locked by the owner of the construction space
7068: if ($allowed eq 'U') {
7069: my %blocked=&get('environment',['domcoord.author'],
7070: $ownerdomain,$ownername);
7071: # Is blocked by owner
7072: if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
7073: }
7074: if (($allowed eq 'F') || ($allowed eq 'U')) {
7075: # Grant temporary access
7076: my $then=$env{'user.login.time'};
1.1209 raeburn 7077: my $update=$env{'user.update.time'};
1.1192 raeburn 7078: if (!$update) { $update = $then; }
7079: my $refresh=$env{'user.refresh.time'};
7080: if (!$refresh) { $refresh = $update; }
7081: my $now = time;
7082: &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
7083: $now,'ca','constructaccess');
7084: $ownerhome = &homeserver($ownername,$ownerdomain);
7085: return($ownername,$ownerdomain,$ownerhome);
7086: }
7087: # No business here
7088: return '';
7089: }
7090:
1.1162 raeburn 7091: sub get_comm_blocks {
7092: my ($cdom,$cnum) = @_;
7093: if ($cdom eq '' || $cnum eq '') {
7094: return unless ($env{'request.course.id'});
7095: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7096: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7097: }
7098: my %commblocks;
7099: my $hashid=$cdom.'_'.$cnum;
7100: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
7101: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
7102: %commblocks = %{$blocksref};
7103: } else {
7104: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
7105: my $cachetime = 600;
7106: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
7107: }
7108: return %commblocks;
7109: }
7110:
7111: sub has_comm_blocking {
7112: my ($priv,$symb,$uri,$blocks) = @_;
7113: return unless ($env{'request.course.id'});
7114: return unless ($priv eq 'bre');
7115: return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
7116: my %commblocks;
7117: if (ref($blocks) eq 'HASH') {
7118: %commblocks = %{$blocks};
7119: } else {
7120: %commblocks = &get_comm_blocks();
7121: }
7122: return unless (keys(%commblocks) > 0);
7123: if (!$symb) { $symb=&symbread($uri,1); }
7124: my ($map,$resid,undef)=&decode_symb($symb);
7125: my %tocheck = (
7126: maps => $map,
7127: resources => $symb,
7128: );
7129: my @blockers;
7130: my $now = time;
1.1163 raeburn 7131: my $navmap = Apache::lonnavmaps::navmap->new();
1.1162 raeburn 7132: foreach my $block (keys(%commblocks)) {
7133: if ($block =~ /^(\d+)____(\d+)$/) {
7134: my ($start,$end) = ($1,$2);
7135: if ($start <= $now && $end >= $now) {
7136: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7137: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
7138: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
7139: if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
7140: unless (grep(/^\Q$block\E$/,@blockers)) {
7141: push(@blockers,$block);
7142: }
7143: }
7144: }
7145: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
7146: if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
7147: unless (grep(/^\Q$block\E$/,@blockers)) {
7148: push(@blockers,$block);
7149: }
7150: }
7151: }
7152: }
7153: }
7154: }
7155: } elsif ($block =~ /^firstaccess____(.+)$/) {
7156: my $item = $1;
1.1163 raeburn 7157: my @to_test;
1.1162 raeburn 7158: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7159: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
7160: my $check_interval;
7161: if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
7162: my @interval;
7163: my $type = 'map';
7164: if ($item eq 'course') {
7165: $type = 'course';
7166: @interval=&EXT("resource.0.interval");
7167: } else {
7168: if ($item =~ /___\d+___/) {
7169: $type = 'resource';
7170: @interval=&EXT("resource.0.interval",$item);
1.1163 raeburn 7171: if (ref($navmap)) {
7172: my $res = $navmap->getBySymb($item);
7173: push(@to_test,$res);
7174: }
1.1162 raeburn 7175: } else {
7176: my $mapsymb = &symbread($item,1);
7177: if ($mapsymb) {
7178: if (ref($navmap)) {
7179: my $mapres = $navmap->getBySymb($mapsymb);
1.1163 raeburn 7180: @to_test = $mapres->retrieveResources($mapres,undef,0,1);
7181: foreach my $res (@to_test) {
1.1162 raeburn 7182: my $symb = $res->symb();
7183: next if ($symb eq $mapsymb);
7184: if ($symb ne '') {
7185: @interval=&EXT("resource.0.interval",$symb);
7186: last;
7187: }
7188: }
7189: }
7190: }
7191: }
7192: }
7193: if ($interval[0] =~ /\d+/) {
7194: my $first_access;
7195: if ($type eq 'resource') {
7196: $first_access=&get_first_access($interval[1],$item);
7197: } elsif ($type eq 'map') {
7198: $first_access=&get_first_access($interval[1],undef,$item);
7199: } else {
7200: $first_access=&get_first_access($interval[1]);
7201: }
7202: if ($first_access) {
7203: my $timesup = $first_access+$interval[0];
7204: if ($timesup > $now) {
1.1163 raeburn 7205: foreach my $res (@to_test) {
7206: if ($res->is_problem()) {
7207: if ($res->completable()) {
7208: unless (grep(/^\Q$block\E$/,@blockers)) {
7209: push(@blockers,$block);
7210: }
7211: last;
7212: }
7213: }
1.1162 raeburn 7214: }
7215: }
7216: }
7217: }
7218: }
7219: }
7220: }
7221: }
7222: }
7223: return @blockers;
7224: }
7225:
7226: sub check_docs_block {
7227: my ($docsblock,$tocheck) =@_;
7228: if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
7229: return;
7230: }
7231: if (ref($docsblock->{'maps'}) eq 'HASH') {
7232: if ($tocheck->{'maps'}) {
7233: if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
7234: return 1;
7235: }
7236: }
7237: }
7238: if (ref($docsblock->{'resources'}) eq 'HASH') {
7239: if ($tocheck->{'resources'}) {
7240: if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
7241: return 1;
7242: }
7243: }
7244: }
7245: return;
7246: }
7247:
1.1133 foxr 7248: #
7249: # Removes the versino from a URI and
7250: # splits it in to its filename and path to the filename.
7251: # Seems like File::Basename could have done this more clearly.
7252: # Parameters:
7253: # $uri - input URI
7254: # Returns:
7255: # Two element list consisting of
7256: # $pathname - the URI up to and excluding the trailing /
7257: # $filename - The part of the URI following the last /
7258: # NOTE:
7259: # Another realization of this is simply:
7260: # use File::Basename;
7261: # ...
7262: # $uri = shift;
7263: # $filename = basename($uri);
7264: # $path = dirname($uri);
7265: # return ($filename, $path);
7266: #
7267: # The implementation below is probably faster however.
7268: #
1.710 albertel 7269: sub split_uri_for_cond {
7270: my $uri=&deversion(&declutter(shift));
7271: my @uriparts=split(/\//,$uri);
7272: my $filename=pop(@uriparts);
7273: my $pathname=join('/',@uriparts);
7274: return ($pathname,$filename);
7275: }
1.232 www 7276: # --------------------------------------------------- Is a resource on the map?
7277:
7278: sub is_on_map {
1.710 albertel 7279: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 7280: #Trying to find the conditional for the file
1.620 albertel 7281: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 7282: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 7283: if ($match) {
1.289 bowersj2 7284: return (1,$1);
7285: } else {
1.434 www 7286: return (0,0);
1.289 bowersj2 7287: }
1.12 www 7288: }
7289:
1.427 www 7290: # --------------------------------------------------------- Get symb from alias
7291:
7292: sub get_symb_from_alias {
7293: my $symb=shift;
7294: my ($map,$resid,$url)=&decode_symb($symb);
7295: # Already is a symb
7296: if ($url) { return $symb; }
7297: # Must be an alias
7298: my $aliassymb='';
7299: my %bighash;
1.620 albertel 7300: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 7301: &GDBM_READER(),0640)) {
7302: my $rid=$bighash{'mapalias_'.$symb};
7303: if ($rid) {
7304: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 7305: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
7306: $resid,$bighash{'src_'.$rid});
1.427 www 7307: }
7308: untie %bighash;
7309: }
7310: return $aliassymb;
7311: }
7312:
1.12 www 7313: # ----------------------------------------------------------------- Define Role
7314:
7315: sub definerole {
7316: if (allowed('mcr','/')) {
7317: my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800 albertel 7318: foreach my $role (split(':',$sysrole)) {
7319: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7320: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
7321: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
7322: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 7323: return "refused:s:$crole&$cqual";
7324: }
7325: }
1.191 harris41 7326: }
1.800 albertel 7327: foreach my $role (split(':',$domrole)) {
7328: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7329: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
7330: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
7331: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 7332: return "refused:d:$crole&$cqual";
7333: }
7334: }
1.191 harris41 7335: }
1.800 albertel 7336: foreach my $role (split(':',$courole)) {
7337: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7338: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
7339: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
7340: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 7341: return "refused:c:$crole&$cqual";
7342: }
7343: }
1.191 harris41 7344: }
1.620 albertel 7345: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
7346: "$env{'user.domain'}:$env{'user.name'}:".
1.21 www 7347: "rolesdef_$rolename=".
7348: escape($sysrole.'_'.$domrole.'_'.$courole);
1.620 albertel 7349: return reply($command,$env{'user.home'});
1.12 www 7350: } else {
7351: return 'refused';
7352: }
1.105 harris41 7353: }
7354:
7355: # ---------------- Make a metadata query against the network of library servers
7356:
7357: sub metadata_query {
1.1237 raeburn 7358: my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120 harris41 7359: my %rhash;
1.845 albertel 7360: my %libserv = &all_library();
1.244 matthew 7361: my @server_list = (defined($server_array) ? @$server_array
7362: : keys(%libserv) );
7363: for my $server (@server_list) {
1.1237 raeburn 7364: my $domains = '';
7365: if (ref($domains_hash) eq 'HASH') {
7366: $domains = $domains_hash->{$server};
7367: }
1.118 harris41 7368: unless ($custom or $customshow) {
1.1237 raeburn 7369: my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118 harris41 7370: $rhash{$server}=$reply;
7371: }
7372: else {
7373: my $reply=&reply("querysend:".&escape($query).':'.
1.1237 raeburn 7374: &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118 harris41 7375: $server);
7376: $rhash{$server}=$reply;
7377: }
1.112 harris41 7378: }
1.118 harris41 7379: return \%rhash;
1.240 www 7380: }
7381:
7382: # ----------------------------------------- Send log queries and wait for reply
7383:
7384: sub log_query {
7385: my ($uname,$udom,$query,%filters)=@_;
7386: my $uhome=&homeserver($uname,$udom);
7387: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 7388: my $uhost=&hostname($uhome);
1.800 albertel 7389: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 7390: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
7391: $uhome);
1.479 albertel 7392: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 7393: return get_query_reply($queryid);
7394: }
7395:
1.818 raeburn 7396: # -------------------------- Update MySQL table for portfolio file
7397:
7398: sub update_portfolio_table {
1.821 raeburn 7399: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 7400: if ($group ne '') {
7401: $file_name =~s /^\Q$group\E//;
7402: }
1.818 raeburn 7403: my $homeserver = &homeserver($uname,$udom);
7404: my $queryid=
1.821 raeburn 7405: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
7406: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 7407: my $reply = &get_query_reply($queryid);
7408: return $reply;
7409: }
7410:
1.899 raeburn 7411: # -------------------------- Update MySQL allusers table
7412:
7413: sub update_allusers_table {
7414: my ($uname,$udom,$names) = @_;
7415: my $homeserver = &homeserver($uname,$udom);
7416: my $queryid=
7417: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
7418: 'lastname='.&escape($names->{'lastname'}).'%%'.
7419: 'firstname='.&escape($names->{'firstname'}).'%%'.
7420: 'middlename='.&escape($names->{'middlename'}).'%%'.
7421: 'generation='.&escape($names->{'generation'}).'%%'.
7422: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
7423: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 7424: return;
1.899 raeburn 7425: }
7426:
1.508 raeburn 7427: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 7428:
7429: sub fetch_enrollment_query {
1.511 raeburn 7430: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508 raeburn 7431: my $homeserver;
1.547 raeburn 7432: my $maxtries = 1;
1.508 raeburn 7433: if ($context eq 'automated') {
7434: $homeserver = $perlvar{'lonHostID'};
1.547 raeburn 7435: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 7436: } else {
7437: $homeserver = &homeserver($cnum,$dom);
7438: }
1.838 albertel 7439: my $host=&hostname($homeserver);
1.506 raeburn 7440: my $cmd = '';
1.1000 raeburn 7441: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 7442: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 7443: }
7444: $cmd =~ s/%%$//;
7445: $cmd = &escape($cmd);
7446: my $query = 'fetchenrollment';
1.620 albertel 7447: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 7448: unless ($queryid=~/^\Q$host\E\_/) {
7449: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
7450: return 'error: '.$queryid;
7451: }
1.506 raeburn 7452: my $reply = &get_query_reply($queryid);
1.547 raeburn 7453: my $tries = 1;
7454: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
7455: $reply = &get_query_reply($queryid);
7456: $tries ++;
7457: }
1.526 raeburn 7458: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 7459: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 7460: } else {
1.901 albertel 7461: my @responses = split(/:/,$reply);
1.515 raeburn 7462: if ($homeserver eq $perlvar{'lonHostID'}) {
1.800 albertel 7463: foreach my $line (@responses) {
7464: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 7465: $$replyref{$key} = $value;
7466: }
7467: } else {
1.1117 foxr 7468: my $pathname = LONCAPA::tempdir();
1.800 albertel 7469: foreach my $line (@responses) {
7470: my ($key,$value) = split(/=/,$line);
1.506 raeburn 7471: $$replyref{$key} = $value;
7472: if ($value > 0) {
1.800 albertel 7473: foreach my $item (@{$$affiliatesref{$key}}) {
7474: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 7475: my $destname = $pathname.'/'.$filename;
7476: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 7477: if ($xml_classlist =~ /^error/) {
7478: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
7479: } else {
1.506 raeburn 7480: if ( open(FILE,">$destname") ) {
7481: print FILE &unescape($xml_classlist);
7482: close(FILE);
1.526 raeburn 7483: } else {
7484: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 7485: }
7486: }
7487: }
7488: }
7489: }
7490: }
7491: return 'ok';
7492: }
7493: return 'error';
7494: }
7495:
1.242 www 7496: sub get_query_reply {
7497: my $queryid=shift;
1.1117 foxr 7498: my $replyfile=LONCAPA::tempdir().$queryid;
1.240 www 7499: my $reply='';
7500: for (1..100) {
7501: sleep 2;
7502: if (-e $replyfile.'.end') {
1.448 albertel 7503: if (open(my $fh,$replyfile)) {
1.904 albertel 7504: $reply = join('',<$fh>);
7505: close($fh);
1.240 www 7506: } else { return 'error: reply_file_error'; }
1.242 www 7507: return &unescape($reply);
7508: }
1.240 www 7509: }
1.242 www 7510: return 'timeout:'.$queryid;
1.240 www 7511: }
7512:
7513: sub courselog_query {
1.241 www 7514: #
7515: # possible filters:
7516: # url: url or symb
7517: # username
7518: # domain
7519: # action: view, submit, grade
7520: # start: timestamp
7521: # end: timestamp
7522: #
1.240 www 7523: my (%filters)=@_;
1.620 albertel 7524: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 7525: if ($filters{'url'}) {
7526: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
7527: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
7528: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
7529: }
1.620 albertel 7530: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
7531: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 7532: return &log_query($cname,$cdom,'courselog',%filters);
7533: }
7534:
7535: sub userlog_query {
1.858 raeburn 7536: #
7537: # possible filters:
7538: # action: log check role
7539: # start: timestamp
7540: # end: timestamp
7541: #
1.240 www 7542: my ($uname,$udom,%filters)=@_;
7543: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 7544: }
7545:
1.506 raeburn 7546: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
7547:
7548: sub auto_run {
1.508 raeburn 7549: my ($cnum,$cdom) = @_;
1.876 raeburn 7550: my $response = 0;
7551: my $settings;
7552: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
7553: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
7554: $settings = $domconfig{'autoenroll'};
7555: if ($settings->{'run'} eq '1') {
7556: $response = 1;
7557: }
7558: } else {
1.934 raeburn 7559: my $homeserver;
7560: if (&is_course($cdom,$cnum)) {
7561: $homeserver = &homeserver($cnum,$cdom);
7562: } else {
7563: $homeserver = &domain($cdom,'primary');
7564: }
7565: if ($homeserver ne 'no_host') {
7566: $response = &reply('autorun:'.$cdom,$homeserver);
7567: }
1.876 raeburn 7568: }
1.506 raeburn 7569: return $response;
7570: }
1.776 albertel 7571:
1.506 raeburn 7572: sub auto_get_sections {
1.508 raeburn 7573: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 7574: my $homeserver;
7575: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7576: $homeserver = &homeserver($cnum,$cdom);
7577: }
7578: if (!defined($homeserver)) {
7579: if ($cdom =~ /^$match_domain$/) {
7580: $homeserver = &domain($cdom,'primary');
7581: }
7582: }
7583: my @secs;
7584: if (defined($homeserver)) {
7585: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
7586: unless ($response eq 'refused') {
7587: @secs = split(/:/,$response);
7588: }
1.506 raeburn 7589: }
7590: return @secs;
7591: }
1.776 albertel 7592:
1.506 raeburn 7593: sub auto_new_course {
1.1099 raeburn 7594: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 7595: my $homeserver = &homeserver($cnum,$cdom);
1.1099 raeburn 7596: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 7597: return $response;
7598: }
1.776 albertel 7599:
1.506 raeburn 7600: sub auto_validate_courseID {
1.508 raeburn 7601: my ($cnum,$cdom,$inst_course_id) = @_;
7602: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 7603: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 7604: return $response;
7605: }
1.776 albertel 7606:
1.1007 raeburn 7607: sub auto_validate_instcode {
1.1020 raeburn 7608: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 7609: my ($homeserver,$response);
7610: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7611: $homeserver = &homeserver($cnum,$cdom);
7612: }
7613: if (!defined($homeserver)) {
7614: if ($cdom =~ /^$match_domain$/) {
7615: $homeserver = &domain($cdom,'primary');
7616: }
7617: }
1.1065 raeburn 7618: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
7619: &escape($instcode).':'.&escape($owner),$homeserver));
1.1216 raeburn 7620: my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
7621: return ($outcome,$description,$defaultcredits);
1.1007 raeburn 7622: }
7623:
1.506 raeburn 7624: sub auto_create_password {
1.873 raeburn 7625: my ($cnum,$cdom,$authparam,$udom) = @_;
7626: my ($homeserver,$response);
1.506 raeburn 7627: my $create_passwd = 0;
7628: my $authchk = '';
1.873 raeburn 7629: if ($udom =~ /^$match_domain$/) {
7630: $homeserver = &domain($udom,'primary');
7631: }
7632: if ($homeserver eq '') {
7633: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7634: $homeserver = &homeserver($cnum,$cdom);
7635: }
7636: }
7637: if ($homeserver eq '') {
7638: $authchk = 'nodomain';
1.506 raeburn 7639: } else {
1.873 raeburn 7640: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
7641: if ($response eq 'refused') {
7642: $authchk = 'refused';
7643: } else {
1.901 albertel 7644: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 7645: }
1.506 raeburn 7646: }
7647: return ($authparam,$create_passwd,$authchk);
7648: }
7649:
1.706 raeburn 7650: sub auto_photo_permission {
7651: my ($cnum,$cdom,$students) = @_;
7652: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 7653: my ($outcome,$perm_reqd,$conditions) =
7654: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 7655: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7656: return (undef,undef);
7657: }
1.706 raeburn 7658: return ($outcome,$perm_reqd,$conditions);
7659: }
7660:
7661: sub auto_checkphotos {
7662: my ($uname,$udom,$pid) = @_;
7663: my $homeserver = &homeserver($uname,$udom);
7664: my ($result,$resulttype);
7665: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 7666: &escape($uname).':'.&escape($pid),
7667: $homeserver));
1.709 albertel 7668: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7669: return (undef,undef);
7670: }
1.706 raeburn 7671: if ($outcome) {
7672: ($result,$resulttype) = split(/:/,$outcome);
7673: }
7674: return ($result,$resulttype);
7675: }
7676:
7677: sub auto_photochoice {
7678: my ($cnum,$cdom) = @_;
7679: my $homeserver = &homeserver($cnum,$cdom);
7680: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 7681: &escape($cdom),
7682: $homeserver)));
1.709 albertel 7683: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7684: return (undef,undef);
7685: }
1.706 raeburn 7686: return ($update,$comment);
7687: }
7688:
7689: sub auto_photoupdate {
7690: my ($affiliatesref,$dom,$cnum,$photo) = @_;
7691: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 7692: my $host=&hostname($homeserver);
1.706 raeburn 7693: my $cmd = '';
7694: my $maxtries = 1;
1.800 albertel 7695: foreach my $affiliate (keys(%{$affiliatesref})) {
7696: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 7697: }
7698: $cmd =~ s/%%$//;
7699: $cmd = &escape($cmd);
7700: my $query = 'institutionalphotos';
7701: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
7702: unless ($queryid=~/^\Q$host\E\_/) {
7703: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
7704: return 'error: '.$queryid;
7705: }
7706: my $reply = &get_query_reply($queryid);
7707: my $tries = 1;
7708: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
7709: $reply = &get_query_reply($queryid);
7710: $tries ++;
7711: }
7712: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
7713: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
7714: } else {
7715: my @responses = split(/:/,$reply);
7716: my $outcome = shift(@responses);
7717: foreach my $item (@responses) {
7718: my ($key,$value) = split(/=/,$item);
7719: $$photo{$key} = $value;
7720: }
7721: return $outcome;
7722: }
7723: return 'error';
7724: }
7725:
1.521 raeburn 7726: sub auto_instcode_format {
1.793 albertel 7727: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
7728: $cat_order) = @_;
1.521 raeburn 7729: my $courses = '';
1.772 raeburn 7730: my @homeservers;
1.521 raeburn 7731: if ($caller eq 'global') {
1.841 albertel 7732: my %servers = &get_servers($codedom,'library');
7733: foreach my $tryserver (keys(%servers)) {
7734: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7735: push(@homeservers,$tryserver);
7736: }
1.584 raeburn 7737: }
1.1022 raeburn 7738: } elsif ($caller eq 'requests') {
7739: if ($codedom =~ /^$match_domain$/) {
7740: my $chome = &domain($codedom,'primary');
7741: unless ($chome eq 'no_host') {
7742: push(@homeservers,$chome);
7743: }
7744: }
1.521 raeburn 7745: } else {
1.772 raeburn 7746: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 7747: }
1.793 albertel 7748: foreach my $code (keys(%{$instcodes})) {
7749: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 7750: }
7751: chop($courses);
1.772 raeburn 7752: my $ok_response = 0;
7753: my $response;
7754: while (@homeservers > 0 && $ok_response == 0) {
7755: my $server = shift(@homeservers);
7756: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
7757: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
7758: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 7759: split(/:/,$response);
1.772 raeburn 7760: %{$codes} = (%{$codes},&str2hash($codes_str));
7761: push(@{$codetitles},&str2array($codetitles_str));
7762: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
7763: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
7764: $ok_response = 1;
7765: }
7766: }
7767: if ($ok_response) {
1.521 raeburn 7768: return 'ok';
1.772 raeburn 7769: } else {
7770: return $response;
1.521 raeburn 7771: }
7772: }
7773:
1.792 raeburn 7774: sub auto_instcode_defaults {
7775: my ($domain,$returnhash,$code_order) = @_;
7776: my @homeservers;
1.841 albertel 7777:
7778: my %servers = &get_servers($domain,'library');
7779: foreach my $tryserver (keys(%servers)) {
7780: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7781: push(@homeservers,$tryserver);
7782: }
1.792 raeburn 7783: }
1.841 albertel 7784:
1.792 raeburn 7785: my $response;
1.841 albertel 7786: foreach my $server (@homeservers) {
1.792 raeburn 7787: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 7788: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
7789:
7790: foreach my $pair (split(/\&/,$response)) {
7791: my ($name,$value)=split(/\=/,$pair);
7792: if ($name eq 'code_order') {
7793: @{$code_order} = split(/\&/,&unescape($value));
7794: } else {
7795: $returnhash->{&unescape($name)}=&unescape($value);
7796: }
7797: }
7798: return 'ok';
1.792 raeburn 7799: }
1.841 albertel 7800:
7801: return $response;
1.1003 raeburn 7802: }
7803:
7804: sub auto_possible_instcodes {
1.1007 raeburn 7805: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
7806: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
7807: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
7808: return;
7809: }
1.1003 raeburn 7810: my (@homeservers,$uhome);
7811: if (defined(&domain($domain,'primary'))) {
7812: $uhome=&domain($domain,'primary');
7813: push(@homeservers,&domain($domain,'primary'));
7814: } else {
7815: my %servers = &get_servers($domain,'library');
7816: foreach my $tryserver (keys(%servers)) {
7817: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7818: push(@homeservers,$tryserver);
7819: }
7820: }
7821: }
7822: my $response;
7823: foreach my $server (@homeservers) {
7824: $response=&reply('autopossibleinstcodes:'.$domain,$server);
7825: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 7826: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
7827: split(':',$response);
7828: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
7829: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 7830: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 7831: my ($name,$value)=split('=',$item);
7832: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 7833: }
7834: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 7835: my ($name,$value)=split('=',$item);
7836: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 7837: }
7838: return 'ok';
7839: }
7840: return $response;
7841: }
1.792 raeburn 7842:
1.1010 raeburn 7843: sub auto_courserequest_checks {
7844: my ($dom) = @_;
1.1020 raeburn 7845: my ($homeserver,%validations);
7846: if ($dom =~ /^$match_domain$/) {
7847: $homeserver = &domain($dom,'primary');
7848: }
7849: unless ($homeserver eq 'no_host') {
7850: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
7851: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
7852: my @items = split(/&/,$response);
7853: foreach my $item (@items) {
7854: my ($key,$value) = split('=',$item);
7855: $validations{&unescape($key)} = &thaw_unescape($value);
7856: }
7857: }
7858: }
1.1010 raeburn 7859: return %validations;
7860: }
7861:
1.1020 raeburn 7862: sub auto_courserequest_validation {
1.1255 ! raeburn 7863: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020 raeburn 7864: my ($homeserver,$response);
7865: if ($dom =~ /^$match_domain$/) {
7866: $homeserver = &domain($dom,'primary');
7867: }
1.1255 ! raeburn 7868: unless ($homeserver eq 'no_host') {
! 7869: my $customdata;
! 7870: if (ref($custominfo) eq 'HASH') {
! 7871: $customdata = &freeze_escape($custominfo);
! 7872: }
1.1020 raeburn 7873: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 7874: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1255 ! raeburn 7875: ':'.&escape($instcode).':'.&escape($instseclist).':'.
! 7876: $customdata,$homeserver));
1.1020 raeburn 7877: }
7878: return $response;
7879: }
7880:
1.777 albertel 7881: sub auto_validate_class_sec {
1.918 raeburn 7882: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 7883: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 7884: my $ownerlist;
7885: if (ref($owners) eq 'ARRAY') {
7886: $ownerlist = join(',',@{$owners});
7887: } else {
7888: $ownerlist = $owners;
7889: }
1.773 raeburn 7890: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 7891: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 7892: return $response;
7893: }
7894:
1.1248 raeburn 7895: sub auto_crsreq_update {
7896: my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
7897: $code,$inbound) = @_;
7898: my ($homeserver,%crsreqresponse);
7899: if ($cdom =~ /^$match_domain$/) {
7900: $homeserver = &domain($cdom,'primary');
7901: }
7902: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
7903: my $info;
7904: if (ref($inbound) eq 'HASH') {
7905: $info = &freeze_escape($inbound);
7906: }
7907: my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
7908: ':'.&escape($action).':'.&escape($ownername).':'.
7909: &escape($ownerdomain).':'.&escape($fullname).':'.
7910: &escape($title).':'.&escape($code).':'.$info,$homeserver);
7911: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
7912: my @items = split(/&/,$response);
7913: foreach my $item (@items) {
7914: my ($key,$value) = split('=',$item);
7915: $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
7916: }
7917: }
7918: }
7919: return \%crsreqresponse;
7920: }
7921:
1.679 raeburn 7922: # ------------------------------------------------------- Course Group routines
7923:
7924: sub get_coursegroups {
1.809 raeburn 7925: my ($cdom,$cnum,$group,$namespace) = @_;
7926: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 7927: }
7928:
1.679 raeburn 7929: sub modify_coursegroup {
7930: my ($cdom,$cnum,$groupsettings) = @_;
7931: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
7932: }
7933:
1.809 raeburn 7934: sub toggle_coursegroup_status {
7935: my ($cdom,$cnum,$group,$action) = @_;
7936: my ($from_namespace,$to_namespace);
7937: if ($action eq 'delete') {
7938: $from_namespace = 'coursegroups';
7939: $to_namespace = 'deleted_groups';
7940: } else {
7941: $from_namespace = 'deleted_groups';
7942: $to_namespace = 'coursegroups';
7943: }
7944: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 7945: if (my $tmp = &error(%curr_group)) {
7946: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
7947: return ('read error',$tmp);
7948: } else {
7949: my %savedsettings = %curr_group;
1.809 raeburn 7950: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 7951: my $deloutcome;
7952: if ($result eq 'ok') {
1.809 raeburn 7953: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 7954: } else {
7955: return ('write error',$result);
7956: }
7957: if ($deloutcome eq 'ok') {
7958: return 'ok';
7959: } else {
7960: return ('delete error',$deloutcome);
7961: }
7962: }
7963: }
7964:
1.679 raeburn 7965: sub modify_group_roles {
1.957 raeburn 7966: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 7967: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
7968: my $role = 'gr/'.&escape($userprivs);
7969: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 7970: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 7971: if ($result eq 'ok') {
7972: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
7973: }
1.679 raeburn 7974: return $result;
7975: }
7976:
7977: sub modify_coursegroup_membership {
7978: my ($cdom,$cnum,$membership) = @_;
7979: my $result = &put('groupmembership',$membership,$cdom,$cnum);
7980: return $result;
7981: }
7982:
1.682 raeburn 7983: sub get_active_groups {
7984: my ($udom,$uname,$cdom,$cnum) = @_;
7985: my $now = time;
7986: my %groups = ();
7987: foreach my $key (keys(%env)) {
1.811 albertel 7988: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 7989: my ($start,$end) = split(/\./,$env{$key});
7990: if (($end!=0) && ($end<$now)) { next; }
7991: if (($start!=0) && ($start>$now)) { next; }
7992: if ($1 eq $cdom && $2 eq $cnum) {
7993: $groups{$3} = $env{$key} ;
7994: }
7995: }
7996: }
7997: return %groups;
7998: }
7999:
1.683 raeburn 8000: sub get_group_membership {
8001: my ($cdom,$cnum,$group) = @_;
8002: return(&dump('groupmembership',$cdom,$cnum,$group));
8003: }
8004:
8005: sub get_users_groups {
8006: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 8007: my @usersgroups;
1.683 raeburn 8008: my $cachetime=1800;
8009:
8010: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 8011: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
8012: if (defined($cached)) {
1.734 albertel 8013: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 8014: } else {
8015: $grouplist = '';
1.816 raeburn 8016: my $courseurl = &courseid_to_courseurl($courseid);
1.1166 raeburn 8017: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 8018: my $access_end = $env{'course.'.$courseid.
8019: '.default_enrollment_end_date'};
8020: my $now = time;
8021: foreach my $key (keys(%roleshash)) {
8022: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
8023: my $group = $1;
8024: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
8025: my $start = $2;
8026: my $end = $1;
8027: if ($start == -1) { next; } # deleted from group
8028: if (($start!=0) && ($start>$now)) { next; }
8029: if (($end!=0) && ($end<$now)) {
8030: if ($access_end && $access_end < $now) {
8031: if ($access_end - $end < 86400) {
8032: push(@usersgroups,$group);
1.733 raeburn 8033: }
8034: }
1.817 raeburn 8035: next;
1.733 raeburn 8036: }
1.817 raeburn 8037: push(@usersgroups,$group);
1.683 raeburn 8038: }
8039: }
8040: }
1.817 raeburn 8041: @usersgroups = &sort_course_groups($courseid,@usersgroups);
8042: $grouplist = join(':',@usersgroups);
8043: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 8044: }
1.733 raeburn 8045: return @usersgroups;
1.683 raeburn 8046: }
8047:
8048: sub devalidate_getgroups_cache {
8049: my ($udom,$uname,$cdom,$cnum)=@_;
8050: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 8051:
1.683 raeburn 8052: my $hashid="$udom:$uname:$courseid";
8053: &devalidate_cache_new('getgroups',$hashid);
8054: }
8055:
1.12 www 8056: # ------------------------------------------------------------------ Plain Text
8057:
8058: sub plaintext {
1.988 raeburn 8059: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 8060: if ($short =~ m{^cr/}) {
1.758 albertel 8061: return (split('/',$short))[-1];
8062: }
1.742 raeburn 8063: if (!defined($cid)) {
8064: $cid = $env{'request.course.id'};
8065: }
8066: my %rolenames = (
1.1008 raeburn 8067: Course => 'std',
8068: Community => 'alt1',
1.742 raeburn 8069: );
1.1037 raeburn 8070: if ($cid ne '') {
8071: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
8072: unless ($forcedefault) {
8073: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
8074: &Apache::lonlocal::mt_escape(\$roletext);
8075: return &Apache::lonlocal::mt($roletext);
8076: }
8077: }
8078: }
8079: if ((defined($type)) && (defined($rolenames{$type})) &&
8080: (defined($rolenames{$type})) &&
8081: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 8082: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 8083: } elsif ($cid ne '') {
8084: my $crstype = $env{'course.'.$cid.'.type'};
8085: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
8086: (defined($prp{$short}{$rolenames{$crstype}}))) {
8087: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
8088: }
1.742 raeburn 8089: }
1.1037 raeburn 8090: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 8091: }
8092:
8093: # ----------------------------------------------------------------- Assign Role
8094:
8095: sub assignrole {
1.957 raeburn 8096: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
8097: $context)=@_;
1.21 www 8098: my $mrole;
8099: if ($role =~ /^cr\//) {
1.393 www 8100: my $cwosec=$url;
1.811 albertel 8101: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 8102: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 8103: my $refused = 1;
8104: if ($context eq 'requestcourses') {
8105: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
8106: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
8107: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
8108: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8109: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8110: if ($crsenv{'internal.courseowner'} eq
8111: $env{'user.name'}.':'.$env{'user.domain'}) {
8112: $refused = '';
8113: }
8114: }
8115: }
8116: }
8117: }
8118: if ($refused) {
8119: &logthis('Refused custom assignrole: '.
8120: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
8121: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
8122: return 'refused';
8123: }
1.104 www 8124: }
1.21 www 8125: $mrole='cr';
1.678 raeburn 8126: } elsif ($role =~ /^gr\//) {
8127: my $cwogrp=$url;
1.811 albertel 8128: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 8129: unless (&allowed('mdg',$cwogrp)) {
8130: &logthis('Refused group assignrole: '.
8131: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
8132: $env{'user.name'}.' at '.$env{'user.domain'});
8133: return 'refused';
8134: }
8135: $mrole='gr';
1.21 www 8136: } else {
1.82 www 8137: my $cwosec=$url;
1.811 albertel 8138: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 8139: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
8140: my $refused;
8141: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
8142: if (!(&allowed('c'.$role,$url))) {
8143: $refused = 1;
8144: }
8145: } else {
8146: $refused = 1;
8147: }
1.947 raeburn 8148: if ($refused) {
1.1045 raeburn 8149: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8150: if (!$selfenroll && $context eq 'course') {
8151: my %crsenv;
8152: if ($role eq 'cc' || $role eq 'co') {
8153: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8154: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
8155: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
8156: if ($crsenv{'internal.courseowner'} eq
8157: $env{'user.name'}.':'.$env{'user.domain'}) {
8158: $refused = '';
8159: }
8160: }
8161: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
8162: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
8163: if ($crsenv{'internal.courseowner'} eq
8164: $env{'user.name'}.':'.$env{'user.domain'}) {
8165: $refused = '';
8166: }
8167: }
8168: }
8169: }
8170: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 8171: $refused = '';
1.1017 raeburn 8172: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 8173: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 8174: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 8175: my $wrongcc;
8176: if ($cnum =~ /^$match_community$/) {
8177: $wrongcc = 1 if ($role eq 'cc');
8178: } else {
8179: $wrongcc = 1 if ($role eq 'co');
8180: }
8181: unless ($wrongcc) {
8182: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8183: if ($crsenv{'internal.courseowner'} eq
8184: $env{'user.name'}.':'.$env{'user.domain'}) {
8185: $refused = '';
8186: }
1.1017 raeburn 8187: }
8188: }
1.1183 raeburn 8189: } elsif ($context eq 'requestauthor') {
8190: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
8191: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
8192: if ($env{'environment.requestauthor'} eq 'automatic') {
8193: $refused = '';
8194: } else {
8195: my %domdefaults = &get_domain_defaults($udom);
8196: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
8197: my $checkbystatus;
8198: if ($env{'user.adv'}) {
8199: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
8200: if ($disposition eq 'automatic') {
8201: $refused = '';
8202: } elsif ($disposition eq '') {
8203: $checkbystatus = 1;
8204: }
8205: } else {
8206: $checkbystatus = 1;
8207: }
8208: if ($checkbystatus) {
8209: if ($env{'environment.inststatus'}) {
8210: my @inststatuses = split(/,/,$env{'environment.inststatus'});
8211: foreach my $type (@inststatuses) {
8212: if (($type ne '') &&
8213: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
8214: $refused = '';
8215: }
8216: }
8217: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
8218: $refused = '';
8219: }
8220: }
8221: }
8222: }
8223: }
1.1017 raeburn 8224: }
8225: if ($refused) {
1.947 raeburn 8226: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
8227: ' '.$role.' '.$end.' '.$start.' by '.
8228: $env{'user.name'}.' at '.$env{'user.domain'});
8229: return 'refused';
8230: }
1.932 raeburn 8231: }
1.1131 raeburn 8232: } elsif ($role eq 'au') {
8233: if ($url ne '/'.$udom.'/') {
8234: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
8235: ' to assign author role for '.$uname.':'.$udom.
8236: ' in domain: '.$url.' refused (wrong domain).');
8237: return 'refused';
8238: }
1.104 www 8239: }
1.21 www 8240: $mrole=$role;
8241: }
1.620 albertel 8242: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 8243: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 8244: if ($end) { $command.='_'.$end; }
1.21 www 8245: if ($start) {
8246: if ($end) {
1.81 www 8247: $command.='_'.$start;
1.21 www 8248: } else {
1.81 www 8249: $command.='_0_'.$start;
1.21 www 8250: }
8251: }
1.739 raeburn 8252: my $origstart = $start;
8253: my $origend = $end;
1.957 raeburn 8254: my $delflag;
1.357 www 8255: # actually delete
8256: if ($deleteflag) {
1.373 www 8257: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 8258: # modify command to delete the role
1.620 albertel 8259: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 8260: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 8261: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 8262: # set start and finish to negative values for userrolelog
8263: $start=-1;
8264: $end=-1;
1.957 raeburn 8265: $delflag = 1;
1.357 www 8266: }
8267: }
8268: # send command
1.349 www 8269: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 8270: # log new user role if status is ok
1.349 www 8271: if ($answer eq 'ok') {
1.663 raeburn 8272: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.1184 raeburn 8273: if (($role eq 'cc') || ($role eq 'in') ||
8274: ($role eq 'ep') || ($role eq 'ad') ||
8275: ($role eq 'ta') || ($role eq 'st') ||
8276: ($role=~/^cr/) || ($role eq 'gr') ||
8277: ($role eq 'co')) {
1.1200 raeburn 8278: # for course roles, perform group memberships changes triggered by role change.
8279: unless ($role =~ /^gr/) {
8280: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
8281: $origstart,$selfenroll,$context);
8282: }
1.1184 raeburn 8283: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8284: $selfenroll,$context);
8285: } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
8286: ($role eq 'au') || ($role eq 'dc')) {
8287: &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8288: $context);
8289: } elsif (($role eq 'ca') || ($role eq 'aa')) {
8290: &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8291: $context);
8292: }
1.1053 raeburn 8293: if ($role eq 'cc') {
8294: &autoupdate_coowners($url,$end,$start,$uname,$udom);
8295: }
1.349 www 8296: }
8297: return $answer;
1.169 harris41 8298: }
8299:
1.1053 raeburn 8300: sub autoupdate_coowners {
8301: my ($url,$end,$start,$uname,$udom) = @_;
8302: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
8303: if (($cdom ne '') && ($cnum ne '')) {
8304: my $now = time;
8305: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
8306: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
8307: my %coursehash = &coursedescription($cdom.'_'.$cnum);
8308: my $instcode = $coursehash{'internal.coursecode'};
8309: if ($instcode ne '') {
1.1056 raeburn 8310: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
8311: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 8312: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 8313: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
8314: if ($result eq 'valid') {
8315: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 8316: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
8317: push(@newcoowners,$coowner);
8318: }
8319: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
8320: push(@newcoowners,$uname.':'.$udom);
8321: }
8322: @newcoowners = sort(@newcoowners);
8323: } else {
8324: push(@newcoowners,$uname.':'.$udom);
8325: }
8326: } else {
8327: if ($coursehash{'internal.co-owners'}) {
8328: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
8329: unless ($coowner eq $uname.':'.$udom) {
8330: push(@newcoowners,$coowner);
8331: }
8332: }
8333: unless (@newcoowners > 0) {
8334: $delcoowners = 1;
8335: $coowners = '';
8336: }
8337: }
8338: }
8339: if (@newcoowners || $delcoowners) {
8340: &store_coowners($cdom,$cnum,$coursehash{'home'},
8341: $delcoowners,@newcoowners);
8342: }
8343: }
8344: }
8345: }
8346: }
8347: }
8348: }
8349:
8350: sub store_coowners {
8351: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
8352: my $cid = $cdom.'_'.$cnum;
8353: my ($coowners,$delresult,$putresult);
8354: if (@newcoowners) {
8355: $coowners = join(',',@newcoowners);
8356: my %coownershash = (
8357: 'internal.co-owners' => $coowners,
8358: );
8359: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
8360: if ($putresult eq 'ok') {
8361: if ($env{'course.'.$cid.'.num'} eq $cnum) {
8362: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
8363: }
8364: }
8365: }
8366: if ($delcoowners) {
8367: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
8368: if ($delresult eq 'ok') {
8369: if ($env{'course.'.$cid.'.internal.co-owners'}) {
8370: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
8371: }
8372: }
8373: }
8374: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
8375: my %crsinfo =
8376: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
8377: if (ref($crsinfo{$cid}) eq 'HASH') {
8378: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
8379: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
8380: }
8381: }
8382: }
8383:
1.169 harris41 8384: # -------------------------------------------------- Modify user authentication
1.197 www 8385: # Overrides without validation
8386:
1.169 harris41 8387: sub modifyuserauth {
8388: my ($udom,$uname,$umode,$upass)=@_;
8389: my $uhome=&homeserver($uname,$udom);
1.197 www 8390: unless (&allowed('mau',$udom)) { return 'refused'; }
8391: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 8392: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
8393: ' in domain '.$env{'request.role.domain'});
1.169 harris41 8394: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
8395: &escape($upass),$uhome);
1.620 albertel 8396: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 8397: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
8398: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
8399: &log($udom,,$uname,$uhome,
1.620 albertel 8400: 'Authentication changed by '.$env{'user.domain'}.', '.
8401: $env{'user.name'}.', '.$umode.
1.197 www 8402: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 8403: unless ($reply eq 'ok') {
1.197 www 8404: &logthis('Authentication mode error: '.$reply);
1.169 harris41 8405: return 'error: '.$reply;
8406: }
1.170 harris41 8407: return 'ok';
1.80 www 8408: }
8409:
1.81 www 8410: # --------------------------------------------------------------- Modify a user
1.80 www 8411:
1.81 www 8412: sub modifyuser {
1.206 matthew 8413: my ($udom, $uname, $uid,
8414: $umode, $upass, $first,
8415: $middle, $last, $gene,
1.1058 raeburn 8416: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 8417: $udom= &LONCAPA::clean_domain($udom);
8418: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 8419: my $showcandelete = 'none';
8420: if (ref($candelete) eq 'ARRAY') {
8421: if (@{$candelete} > 0) {
8422: $showcandelete = join(', ',@{$candelete});
8423: }
8424: }
1.81 www 8425: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 8426: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 8427: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 8428: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
8429: ' desiredhome not specified').
1.620 albertel 8430: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
8431: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 8432: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 8433: my $newuser;
8434: if ($uhome eq 'no_host') {
8435: $newuser = 1;
8436: }
1.80 www 8437: # ----------------------------------------------------------------- Create User
1.406 albertel 8438: if (($uhome eq 'no_host') &&
8439: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 8440: my $unhome='';
1.844 albertel 8441: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 8442: $unhome = $desiredhome;
1.620 albertel 8443: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
8444: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 8445: } else { # load balancing routine for determining $unhome
1.81 www 8446: my $loadm=10000000;
1.841 albertel 8447: my %servers = &get_servers($udom,'library');
8448: foreach my $tryserver (keys(%servers)) {
8449: my $answer=reply('load',$tryserver);
8450: if (($answer=~/\d+/) && ($answer<$loadm)) {
8451: $loadm=$answer;
8452: $unhome=$tryserver;
8453: }
1.80 www 8454: }
8455: }
8456: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 8457: return 'error: unable to find a home server for '.$uname.
8458: ' in domain '.$udom;
1.80 www 8459: }
8460: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
8461: &escape($upass),$unhome);
8462: unless ($reply eq 'ok') {
8463: return 'error: '.$reply;
8464: }
1.230 stredwic 8465: $uhome=&homeserver($uname,$udom,'true');
1.80 www 8466: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 8467: return 'error: unable verify users home machine.';
1.80 www 8468: }
1.209 matthew 8469: } # End of creation of new user
1.80 www 8470: # ---------------------------------------------------------------------- Add ID
8471: if ($uid) {
8472: $uid=~tr/A-Z/a-z/;
8473: my %uidhash=&idrget($udom,$uname);
1.196 www 8474: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
8475: && (!$forceid)) {
1.80 www 8476: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 8477: return 'error: user id "'.$uid.'" does not match '.
8478: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 8479: }
8480: } else {
8481: &idput($udom,($uname => $uid));
8482: }
8483: }
8484: # -------------------------------------------------------------- Add names, etc
1.313 matthew 8485: my @tmp=&get('environment',
1.899 raeburn 8486: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 8487: 'permanentemail','inststatus'],
1.134 albertel 8488: $udom,$uname);
1.1075 raeburn 8489: my (%names,%oldnames);
1.313 matthew 8490: if ($tmp[0] =~ m/^error:.*/) {
8491: %names=();
8492: } else {
8493: %names = @tmp;
1.1075 raeburn 8494: %oldnames = %names;
1.313 matthew 8495: }
1.388 www 8496: #
1.1058 raeburn 8497: # If name, email and/or uid are blank (e.g., because an uploaded file
8498: # of users did not contain them), do not overwrite existing values
8499: # unless field is in $candelete array ref.
8500: #
8501:
8502: my @fields = ('firstname','middlename','lastname','generation',
8503: 'permanentemail','id');
8504: my %newvalues;
8505: if (ref($candelete) eq 'ARRAY') {
8506: foreach my $field (@fields) {
8507: if (grep(/^\Q$field\E$/,@{$candelete})) {
8508: if ($field eq 'firstname') {
8509: $names{$field} = $first;
8510: } elsif ($field eq 'middlename') {
8511: $names{$field} = $middle;
8512: } elsif ($field eq 'lastname') {
8513: $names{$field} = $last;
8514: } elsif ($field eq 'generation') {
8515: $names{$field} = $gene;
8516: } elsif ($field eq 'permanentemail') {
8517: $names{$field} = $email;
8518: } elsif ($field eq 'id') {
8519: $names{$field} = $uid;
8520: }
8521: }
8522: }
8523: }
1.388 www 8524: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 8525: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 8526: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 8527: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 8528: if ($email) {
8529: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 8530: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 8531: }
1.899 raeburn 8532: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 8533: if (defined($inststatus)) {
8534: $names{'inststatus'} = '';
8535: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
8536: if (ref($usertypes) eq 'HASH') {
8537: my @okstatuses;
8538: foreach my $item (split(/:/,$inststatus)) {
8539: if (defined($usertypes->{$item})) {
8540: push(@okstatuses,$item);
8541: }
8542: }
8543: if (@okstatuses) {
8544: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
8545: }
8546: }
8547: }
1.1075 raeburn 8548: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 8549: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 8550: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 8551: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
8552: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
8553: } else {
8554: $logmsg .= ' during self creation';
8555: }
1.1075 raeburn 8556: my $changed;
8557: if ($newuser) {
8558: $changed = 1;
8559: } else {
8560: foreach my $field (@fields) {
8561: if ($names{$field} ne $oldnames{$field}) {
8562: $changed = 1;
8563: last;
8564: }
8565: }
8566: }
8567: unless ($changed) {
8568: $logmsg = 'No changes in user information needed for: '.$logmsg;
8569: &logthis($logmsg);
8570: return 'ok';
8571: }
8572: my $reply = &put('environment', \%names, $udom,$uname);
8573: if ($reply ne 'ok') {
8574: return 'error: '.$reply;
8575: }
1.1087 raeburn 8576: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
8577: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
8578: }
1.1075 raeburn 8579: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
8580: &devalidate_cache_new('namescache',$uname.':'.$udom);
8581: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 8582: &logthis($logmsg);
1.134 albertel 8583: return 'ok';
1.80 www 8584: }
8585:
1.81 www 8586: # -------------------------------------------------------------- Modify student
1.80 www 8587:
1.81 www 8588: sub modifystudent {
8589: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 8590: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1216 raeburn 8591: $selfenroll,$context,$inststatus,$credits)=@_;
1.455 albertel 8592: if (!$cid) {
1.620 albertel 8593: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 8594: return 'not_in_class';
8595: }
1.80 www 8596: }
8597: # --------------------------------------------------------------- Make the user
1.81 www 8598: my $reply=&modifyuser
1.209 matthew 8599: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 8600: $desiredhome,$email,$inststatus);
1.80 www 8601: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 8602: # This will cause &modify_student_enrollment to get the uid from the
1.1235 raeburn 8603: # student's environment
1.297 matthew 8604: $uid = undef if (!$forceid);
1.455 albertel 8605: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1216 raeburn 8606: $gene,$usec,$end,$start,$type,$locktype,
8607: $cid,$selfenroll,$context,$credits);
1.297 matthew 8608: return $reply;
8609: }
8610:
8611: sub modify_student_enrollment {
1.1216 raeburn 8612: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
8613: $locktype,$cid,$selfenroll,$context,$credits) = @_;
1.455 albertel 8614: my ($cdom,$cnum,$chome);
8615: if (!$cid) {
1.620 albertel 8616: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 8617: return 'not_in_class';
8618: }
1.620 albertel 8619: $cdom=$env{'course.'.$cid.'.domain'};
8620: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 8621: } else {
8622: ($cdom,$cnum)=split(/_/,$cid);
8623: }
1.620 albertel 8624: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 8625: if (!$chome) {
1.457 raeburn 8626: $chome=&homeserver($cnum,$cdom);
1.297 matthew 8627: }
1.455 albertel 8628: if (!$chome) { return 'unknown_course'; }
1.297 matthew 8629: # Make sure the user exists
1.81 www 8630: my $uhome=&homeserver($uname,$udom);
8631: if (($uhome eq '') || ($uhome eq 'no_host')) {
8632: return 'error: no such user';
8633: }
1.297 matthew 8634: # Get student data if we were not given enough information
8635: if (!defined($first) || $first eq '' ||
8636: !defined($last) || $last eq '' ||
8637: !defined($uid) || $uid eq '' ||
8638: !defined($middle) || $middle eq '' ||
8639: !defined($gene) || $gene eq '') {
1.294 matthew 8640: # They did not supply us with enough data to enroll the student, so
8641: # we need to pick up more information.
1.297 matthew 8642: my %tmp = &get('environment',
1.294 matthew 8643: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 8644: ,$udom,$uname);
8645:
1.800 albertel 8646: #foreach my $key (keys(%tmp)) {
8647: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 8648: #}
1.294 matthew 8649: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
8650: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
8651: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 8652: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 8653: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
8654: }
1.556 albertel 8655: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148 raeburn 8656: my $user = "$uname:$udom";
8657: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487 albertel 8658: my $reply=cput('classlist',
1.1148 raeburn 8659: {$user =>
1.1216 raeburn 8660: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits) },
1.487 albertel 8661: $cdom,$cnum);
1.1148 raeburn 8662: if (($reply eq 'ok') || ($reply eq 'delayed')) {
8663: &devalidate_getsection_cache($udom,$uname,$cid);
8664: } else {
1.81 www 8665: return 'error: '.$reply;
8666: }
1.297 matthew 8667: # Add student role to user
1.83 www 8668: my $uurl='/'.$cid;
1.81 www 8669: $uurl=~s/\_/\//g;
8670: if ($usec) {
8671: $uurl.='/'.$usec;
8672: }
1.1148 raeburn 8673: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
8674: $selfenroll,$context);
8675: if ($result ne 'ok') {
8676: if ($old_entry{$user} ne '') {
8677: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
8678: } else {
8679: $reply = &del('classlist',[$user],$cdom,$cnum);
8680: }
8681: }
8682: return $result;
1.21 www 8683: }
8684:
1.556 albertel 8685: sub format_name {
8686: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
8687: my $name;
8688: if ($first ne 'lastname') {
8689: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
8690: } else {
8691: if ($lastname=~/\S/) {
8692: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
8693: $name=~s/\s+,/,/;
8694: } else {
8695: $name.= $firstname.' '.$middlename.' '.$generation;
8696: }
8697: }
8698: $name=~s/^\s+//;
8699: $name=~s/\s+$//;
8700: $name=~s/\s+/ /g;
8701: return $name;
8702: }
8703:
1.84 www 8704: # ------------------------------------------------- Write to course preferences
8705:
8706: sub writecoursepref {
8707: my ($courseid,%prefs)=@_;
8708: $courseid=~s/^\///;
8709: $courseid=~s/\_/\//g;
8710: my ($cdomain,$cnum)=split(/\//,$courseid);
8711: my $chome=homeserver($cnum,$cdomain);
8712: if (($chome eq '') || ($chome eq 'no_host')) {
8713: return 'error: no such course';
8714: }
8715: my $cstring='';
1.800 albertel 8716: foreach my $pref (keys(%prefs)) {
8717: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 8718: }
1.84 www 8719: $cstring=~s/\&$//;
8720: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
8721: }
8722:
8723: # ---------------------------------------------------------- Make/modify course
8724:
8725: sub createcourse {
1.741 raeburn 8726: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 8727: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 8728: $url=&declutter($url);
8729: my $cid='';
1.1028 raeburn 8730: if ($context eq 'requestcourses') {
8731: my $can_create = 0;
8732: my ($ownername,$ownerdom) = split(':',$course_owner);
8733: if ($udom eq $ownerdom) {
8734: if (&usertools_access($ownername,$ownerdom,$category,undef,
8735: $context)) {
8736: $can_create = 1;
8737: }
8738: } else {
8739: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
8740: $category);
8741: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
8742: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
8743: if (@curr > 0) {
8744: my @options = qw(approval validate autolimit);
8745: my $optregex = join('|',@options);
8746: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
8747: $can_create = 1;
8748: }
8749: }
8750: }
8751: }
8752: if ($can_create) {
8753: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
8754: unless (&allowed('ccc',$udom)) {
8755: return 'refused';
8756: }
1.1017 raeburn 8757: }
8758: } else {
8759: return 'refused';
8760: }
1.1028 raeburn 8761: } elsif (!&allowed('ccc',$udom)) {
8762: return 'refused';
1.84 www 8763: }
1.1011 raeburn 8764: # --------------------------------------------------------------- Get Unique ID
8765: my $uname;
8766: if ($cnum =~ /^$match_courseid$/) {
8767: my $chome=&homeserver($cnum,$udom,'true');
8768: if (($chome eq '') || ($chome eq 'no_host')) {
8769: $uname = $cnum;
8770: } else {
1.1038 raeburn 8771: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 8772: }
8773: } else {
1.1038 raeburn 8774: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 8775: }
8776: return $uname if ($uname =~ /^error/);
8777: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 8778: if (!defined($course_server)) {
8779: if (defined(&domain($udom,'primary'))) {
8780: $course_server = &domain($udom,'primary');
8781: } else {
8782: $course_server = $env{'user.home'};
8783: }
8784: }
8785: my %host_servers =
8786: &Apache::lonnet::get_servers($udom,'library');
8787: unless ($host_servers{$course_server}) {
8788: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 8789: }
1.84 www 8790: # ------------------------------------------------------------- Make the course
8791: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 8792: $course_server);
1.84 www 8793: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 8794: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 8795: if (($uhome eq '') || ($uhome eq 'no_host')) {
8796: return 'error: no such course';
8797: }
1.271 www 8798: # ----------------------------------------------------------------- Course made
1.516 raeburn 8799: # log existence
1.1029 raeburn 8800: my $now = time;
1.918 raeburn 8801: my $newcourse = {
8802: $udom.'_'.$uname => {
1.921 raeburn 8803: description => $description,
8804: inst_code => $inst_code,
8805: owner => $course_owner,
8806: type => $crstype,
1.1029 raeburn 8807: creator => $env{'user.name'}.':'.
8808: $env{'user.domain'},
8809: created => $now,
8810: context => $context,
1.918 raeburn 8811: },
8812: };
1.921 raeburn 8813: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 8814: # set toplevel url
1.271 www 8815: my $topurl=$url;
8816: unless ($nonstandard) {
8817: # ------------------------------------------ For standard courses, make top url
8818: my $mapurl=&clutter($url);
1.278 www 8819: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 8820: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 8821: <map>
8822: <resource id="1" type="start"></resource>
8823: <resource id="2" src="$mapurl"></resource>
8824: <resource id="3" type="finish"></resource>
8825: <link index="1" from="1" to="2"></link>
8826: <link index="2" from="2" to="3"></link>
8827: </map>
8828: ENDINITMAP
8829: $topurl=&declutter(
1.638 albertel 8830: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 8831: );
8832: }
8833: # ----------------------------------------------------------- Write preferences
1.84 www 8834: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 8835: ('description' => $description,
8836: 'url' => $topurl,
8837: 'internal.creator' => $env{'user.name'}.':'.
8838: $env{'user.domain'},
8839: 'internal.created' => $now,
8840: 'internal.creationcontext' => $context)
8841: );
1.84 www 8842: return '/'.$udom.'/'.$uname;
8843: }
8844:
1.1011 raeburn 8845: # ------------------------------------------------------------------- Create ID
8846: sub generate_coursenum {
1.1038 raeburn 8847: my ($udom,$crstype) = @_;
1.1011 raeburn 8848: my $domdesc = &domain($udom);
8849: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 8850: my $first;
8851: if ($crstype eq 'Community') {
8852: $first = '0';
8853: } else {
8854: $first = int(1+rand(9));
8855: }
8856: my $uname=$first.
1.1011 raeburn 8857: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
8858: substr($$.time,0,5).unpack("H8",pack("I32",time)).
8859: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
8860: # ----------------------------------------------- Make sure that does not exist
8861: my $uhome=&homeserver($uname,$udom,'true');
8862: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 8863: if ($crstype eq 'Community') {
8864: $first = '0';
8865: } else {
8866: $first = int(1+rand(9));
8867: }
8868: $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: $uhome=&homeserver($uname,$udom,'true');
8873: unless (($uhome eq '') || ($uhome eq 'no_host')) {
8874: return 'error: unable to generate unique course-ID';
8875: }
8876: }
8877: return $uname;
8878: }
8879:
1.813 albertel 8880: sub is_course {
1.1167 droeschl 8881: my ($cdom, $cnum) = scalar(@_) == 1 ?
8882: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
8883:
8884: return unless $cdom and $cnum;
8885:
8886: my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
8887: '.');
8888:
1.1219 raeburn 8889: return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167 droeschl 8890: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813 albertel 8891: }
8892:
1.1015 raeburn 8893: sub store_userdata {
8894: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 8895: my $result;
1.1016 raeburn 8896: if ($datakey ne '') {
1.1013 raeburn 8897: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 8898: if ($udom eq '' || $uname eq '') {
8899: $udom = $env{'user.domain'};
8900: $uname = $env{'user.name'};
8901: }
8902: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 8903: if (($uhome eq '') || ($uhome eq 'no_host')) {
8904: $result = 'error: no_host';
8905: } else {
8906: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
8907: $storehash->{'host'} = $perlvar{'lonHostID'};
8908:
8909: my $namevalue='';
8910: foreach my $key (keys(%{$storehash})) {
8911: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
8912: }
8913: $namevalue=~s/\&$//;
1.1224 raeburn 8914: unless ($namespace eq 'courserequests') {
8915: $datakey = &escape($datakey);
8916: }
1.1105 raeburn 8917: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
8918: $namevalue,$uhome);
1.1013 raeburn 8919: }
8920: } else {
8921: $result = 'error: data to store was not a hash reference';
8922: }
8923: } else {
8924: $result= 'error: invalid requestkey';
8925: }
8926: return $result;
8927: }
8928:
1.21 www 8929: # ---------------------------------------------------------- Assign Custom Role
8930:
8931: sub assigncustomrole {
1.957 raeburn 8932: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 8933: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 8934: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 8935: }
8936:
8937: # ----------------------------------------------------------------- Revoke Role
8938:
8939: sub revokerole {
1.957 raeburn 8940: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 8941: my $now=time;
1.965 raeburn 8942: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 8943: }
8944:
8945: # ---------------------------------------------------------- Revoke Custom Role
8946:
8947: sub revokecustomrole {
1.957 raeburn 8948: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 8949: my $now=time;
1.357 www 8950: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 8951: $deleteflag,$selfenroll,$context);
1.17 www 8952: }
8953:
1.533 banghart 8954: # ------------------------------------------------------------ Disk usage
1.535 albertel 8955: sub diskusage {
1.955 raeburn 8956: my ($udom,$uname,$directorypath,$getpropath)=@_;
8957: $directorypath =~ s/\/$//;
8958: my $listing=&reply('du2:'.&escape($directorypath).':'
8959: .&escape($getpropath).':'.&escape($uname).':'
8960: .&escape($udom),homeserver($uname,$udom));
8961: if ($listing eq 'unknown_cmd') {
8962: if ($getpropath) {
8963: $directorypath = &propath($udom,$uname).'/'.$directorypath;
8964: }
8965: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
8966: }
1.514 albertel 8967: return $listing;
1.512 banghart 8968: }
8969:
1.566 banghart 8970: sub is_locked {
1.1096 raeburn 8971: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 8972: my @check;
8973: my $is_locked;
1.1093 raeburn 8974: push (@check,$file_name);
1.613 albertel 8975: my %locked = &get('file_permissions',\@check,
1.620 albertel 8976: $env{'user.domain'},$env{'user.name'});
1.615 albertel 8977: my ($tmp)=keys(%locked);
8978: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 8979:
1.566 banghart 8980: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 8981: $is_locked = 'false';
8982: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 8983: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 8984: $is_locked = 'true';
1.1096 raeburn 8985: if (ref($which) eq 'ARRAY') {
8986: push(@{$which},$entry);
8987: } else {
8988: last;
8989: }
1.745 raeburn 8990: }
8991: }
1.566 banghart 8992: } else {
8993: $is_locked = 'false';
8994: }
1.1093 raeburn 8995: return $is_locked;
1.566 banghart 8996: }
8997:
1.759 albertel 8998: sub declutter_portfile {
8999: my ($file) = @_;
1.833 albertel 9000: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 9001: return $file;
9002: }
9003:
1.559 banghart 9004: # ------------------------------------------------------------- Mark as Read Only
9005:
9006: sub mark_as_readonly {
9007: my ($domain,$user,$files,$what) = @_;
1.613 albertel 9008: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 9009: my ($tmp)=keys(%current_permissions);
9010: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 9011: foreach my $file (@{$files}) {
1.759 albertel 9012: $file = &declutter_portfile($file);
1.561 banghart 9013: push(@{$current_permissions{$file}},$what);
1.559 banghart 9014: }
1.613 albertel 9015: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 9016: return;
9017: }
9018:
1.572 banghart 9019: # ------------------------------------------------------------Save Selected Files
9020:
9021: sub save_selected_files {
9022: my ($user, $path, @files) = @_;
9023: my $filename = $user."savedfiles";
1.573 banghart 9024: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 9025: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 9026: foreach my $file (@files) {
1.620 albertel 9027: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 9028: }
9029: foreach my $file (@other_files) {
1.574 banghart 9030: print (OUT $file."\n");
1.572 banghart 9031: }
1.574 banghart 9032: close (OUT);
1.572 banghart 9033: return 'ok';
9034: }
9035:
1.574 banghart 9036: sub clear_selected_files {
9037: my ($user) = @_;
9038: my $filename = $user."savedfiles";
1.1117 foxr 9039: open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574 banghart 9040: print (OUT undef);
9041: close (OUT);
9042: return ("ok");
9043: }
9044:
1.572 banghart 9045: sub files_in_path {
9046: my ($user, $path) = @_;
9047: my $filename = $user."savedfiles";
9048: my %return_files;
1.1117 foxr 9049: open (IN, '<'.LONCAPA::tempdir().$filename);
1.573 banghart 9050: while (my $line_in = <IN>) {
1.574 banghart 9051: chomp ($line_in);
9052: my @paths_and_file = split (m!/!, $line_in);
9053: my $file_part = pop (@paths_and_file);
9054: my $path_part = join ('/', @paths_and_file);
1.573 banghart 9055: $path_part.='/';
9056: my $path_and_file = $path_part.$file_part;
9057: if ($path_part eq $path) {
9058: $return_files{$file_part}= 'selected';
9059: }
9060: }
1.574 banghart 9061: close (IN);
9062: return (\%return_files);
1.572 banghart 9063: }
9064:
9065: # called in portfolio select mode, to show files selected NOT in current directory
9066: sub files_not_in_path {
9067: my ($user, $path) = @_;
9068: my $filename = $user."savedfiles";
9069: my @return_files;
9070: my $path_part;
1.1117 foxr 9071: open(IN, '<'.LONCAPA::.$filename);
1.800 albertel 9072: while (my $line = <IN>) {
1.572 banghart 9073: #ok, I know it's clunky, but I want it to work
1.800 albertel 9074: my @paths_and_file = split(m|/|, $line);
9075: my $file_part = pop(@paths_and_file);
9076: chomp($file_part);
9077: my $path_part = join('/', @paths_and_file);
1.572 banghart 9078: $path_part .= '/';
9079: my $path_and_file = $path_part.$file_part;
9080: if ($path_part ne $path) {
1.800 albertel 9081: push(@return_files, ($path_and_file));
1.572 banghart 9082: }
9083: }
1.800 albertel 9084: close(OUT);
1.574 banghart 9085: return (@return_files);
1.572 banghart 9086: }
9087:
1.745 raeburn 9088: #----------------------------------------------Get portfolio file permissions
1.629 banghart 9089:
1.745 raeburn 9090: sub get_portfile_permissions {
9091: my ($domain,$user) = @_;
1.613 albertel 9092: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 9093: my ($tmp)=keys(%current_permissions);
9094: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 9095: return \%current_permissions;
9096: }
9097:
9098: #---------------------------------------------Get portfolio file access controls
9099:
1.749 raeburn 9100: sub get_access_controls {
1.745 raeburn 9101: my ($current_permissions,$group,$file) = @_;
1.769 albertel 9102: my %access;
9103: my $real_file = $file;
9104: $file =~ s/\.meta$//;
1.745 raeburn 9105: if (defined($file)) {
1.749 raeburn 9106: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
9107: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 9108: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 9109: }
9110: }
1.745 raeburn 9111: } else {
1.749 raeburn 9112: foreach my $key (keys(%{$current_permissions})) {
9113: if ($key =~ /\0accesscontrol$/) {
9114: if (defined($group)) {
9115: if ($key !~ m-^\Q$group\E/-) {
9116: next;
9117: }
9118: }
9119: my ($fullpath) = split(/\0/,$key);
9120: if (ref($$current_permissions{$key}) eq 'HASH') {
9121: foreach my $control (keys(%{$$current_permissions{$key}})) {
9122: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
9123: }
9124: }
9125: }
9126: }
9127: }
9128: return %access;
9129: }
9130:
9131: sub modify_access_controls {
9132: my ($file_name,$changes,$domain,$user)=@_;
9133: my ($outcome,$deloutcome);
9134: my %store_permissions;
9135: my %new_values;
9136: my %new_control;
9137: my %translation;
9138: my @deletions = ();
9139: my $now = time;
9140: if (exists($$changes{'activate'})) {
9141: if (ref($$changes{'activate'}) eq 'HASH') {
9142: my @newitems = sort(keys(%{$$changes{'activate'}}));
9143: my $numnew = scalar(@newitems);
9144: for (my $i=0; $i<$numnew; $i++) {
9145: my $newkey = $newitems[$i];
9146: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 9147: if ($newkey =~ /^\d+:/) {
9148: $newkey =~ s/^(\d+)/$newid/;
9149: $translation{$1} = $newid;
9150: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
9151: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
9152: $translation{$1} = $newid;
9153: }
1.749 raeburn 9154: $new_values{$file_name."\0".$newkey} =
9155: $$changes{'activate'}{$newitems[$i]};
9156: $new_control{$newkey} = $now;
9157: }
9158: }
9159: }
9160: my %todelete;
9161: my %changed_items;
9162: foreach my $action ('delete','update') {
9163: if (exists($$changes{$action})) {
9164: if (ref($$changes{$action}) eq 'HASH') {
9165: foreach my $key (keys(%{$$changes{$action}})) {
9166: my ($itemnum) = ($key =~ /^([^:]+):/);
9167: if ($action eq 'delete') {
9168: $todelete{$itemnum} = 1;
9169: } else {
9170: $changed_items{$itemnum} = $key;
9171: }
9172: }
1.745 raeburn 9173: }
9174: }
1.749 raeburn 9175: }
9176: # get lock on access controls for file.
9177: my $lockhash = {
9178: $file_name."\0".'locked_access_records' => $env{'user.name'}.
9179: ':'.$env{'user.domain'},
9180: };
9181: my $tries = 0;
9182: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9183:
9184: while (($gotlock ne 'ok') && $tries <3) {
9185: $tries ++;
9186: sleep 1;
9187: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9188: }
9189: if ($gotlock eq 'ok') {
9190: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
9191: my ($tmp)=keys(%curr_permissions);
9192: if ($tmp=~/^error:/) { undef(%curr_permissions); }
9193: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
9194: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
9195: if (ref($curr_controls) eq 'HASH') {
9196: foreach my $control_item (keys(%{$curr_controls})) {
9197: my ($itemnum) = ($control_item =~ /^([^:]+):/);
9198: if (defined($todelete{$itemnum})) {
9199: push(@deletions,$file_name."\0".$control_item);
9200: } else {
9201: if (defined($changed_items{$itemnum})) {
9202: $new_control{$changed_items{$itemnum}} = $now;
9203: push(@deletions,$file_name."\0".$control_item);
9204: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
9205: } else {
9206: $new_control{$control_item} = $$curr_controls{$control_item};
9207: }
9208: }
1.745 raeburn 9209: }
9210: }
9211: }
1.970 raeburn 9212: my ($group);
9213: if (&is_course($domain,$user)) {
9214: ($group,my $file) = split(/\//,$file_name,2);
9215: }
1.749 raeburn 9216: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
9217: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
9218: $outcome = &put('file_permissions',\%new_values,$domain,$user);
9219: # remove lock
9220: my @del_lock = ($file_name."\0".'locked_access_records');
9221: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 9222: my $sqlresult =
1.970 raeburn 9223: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 9224: $group);
1.749 raeburn 9225: } else {
9226: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 9227: }
1.749 raeburn 9228: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 9229: }
9230:
1.827 raeburn 9231: sub make_public_indefinitely {
9232: my ($requrl) = @_;
9233: my $now = time;
9234: my $action = 'activate';
9235: my $aclnum = 0;
9236: if (&is_portfolio_url($requrl)) {
9237: my (undef,$udom,$unum,$file_name,$group) =
9238: &parse_portfolio_url($requrl);
9239: my $current_perms = &get_portfile_permissions($udom,$unum);
9240: my %access_controls = &get_access_controls($current_perms,
9241: $group,$file_name);
9242: foreach my $key (keys(%{$access_controls{$file_name}})) {
9243: my ($num,$scope,$end,$start) =
9244: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
9245: if ($scope eq 'public') {
9246: if ($start <= $now && $end == 0) {
9247: $action = 'none';
9248: } else {
9249: $action = 'update';
9250: $aclnum = $num;
9251: }
9252: last;
9253: }
9254: }
9255: if ($action eq 'none') {
9256: return 'ok';
9257: } else {
9258: my %changes;
9259: my $newend = 0;
9260: my $newstart = $now;
9261: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
9262: $changes{$action}{$newkey} = {
9263: type => 'public',
9264: time => {
9265: start => $newstart,
9266: end => $newend,
9267: },
9268: };
9269: my ($outcome,$deloutcome,$new_values,$translation) =
9270: &modify_access_controls($file_name,\%changes,$udom,$unum);
9271: return $outcome;
9272: }
9273: } else {
9274: return 'invalid';
9275: }
9276: }
9277:
1.745 raeburn 9278: #------------------------------------------------------Get Marked as Read Only
9279:
9280: sub get_marked_as_readonly {
9281: my ($domain,$user,$what,$group) = @_;
9282: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 9283: my @readonly_files;
1.629 banghart 9284: my $cmp1=$what;
9285: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 9286: while (my ($file_name,$value) = each(%{$current_permissions})) {
9287: if (defined($group)) {
9288: if ($file_name !~ m-^\Q$group\E/-) {
9289: next;
9290: }
9291: }
1.561 banghart 9292: if (ref($value) eq "ARRAY"){
9293: foreach my $stored_what (@{$value}) {
1.629 banghart 9294: my $cmp2=$stored_what;
1.759 albertel 9295: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 9296: $cmp2=join('',@{$stored_what});
1.745 raeburn 9297: }
1.629 banghart 9298: if ($cmp1 eq $cmp2) {
1.561 banghart 9299: push(@readonly_files, $file_name);
1.745 raeburn 9300: last;
1.563 banghart 9301: } elsif (!defined($what)) {
9302: push(@readonly_files, $file_name);
1.745 raeburn 9303: last;
1.561 banghart 9304: }
9305: }
1.745 raeburn 9306: }
1.561 banghart 9307: }
9308: return @readonly_files;
9309: }
1.577 banghart 9310: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 9311:
1.577 banghart 9312: sub get_marked_as_readonly_hash {
1.745 raeburn 9313: my ($current_permissions,$group,$what) = @_;
1.577 banghart 9314: my %readonly_files;
1.745 raeburn 9315: while (my ($file_name,$value) = each(%{$current_permissions})) {
9316: if (defined($group)) {
9317: if ($file_name !~ m-^\Q$group\E/-) {
9318: next;
9319: }
9320: }
1.577 banghart 9321: if (ref($value) eq "ARRAY"){
9322: foreach my $stored_what (@{$value}) {
1.745 raeburn 9323: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 9324: foreach my $lock_descriptor(@{$stored_what}) {
9325: if ($lock_descriptor eq 'graded') {
9326: $readonly_files{$file_name} = 'graded';
9327: } elsif ($lock_descriptor eq 'handback') {
9328: $readonly_files{$file_name} = 'handback';
9329: } else {
9330: if (!exists($readonly_files{$file_name})) {
9331: $readonly_files{$file_name} = 'locked';
9332: }
9333: }
1.745 raeburn 9334: }
1.750 banghart 9335: }
1.577 banghart 9336: }
9337: }
9338: }
9339: return %readonly_files;
9340: }
1.559 banghart 9341: # ------------------------------------------------------------ Unmark as Read Only
9342:
9343: sub unmark_as_readonly {
1.629 banghart 9344: # unmarks $file_name (if $file_name is defined), or all files locked by $what
9345: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 9346: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 9347: $file_name = &declutter_portfile($file_name);
1.634 albertel 9348: my $symb_crs = $what;
9349: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 9350: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 9351: my ($tmp)=keys(%current_permissions);
9352: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 9353: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 9354: foreach my $file (@readonly_files) {
1.759 albertel 9355: my $clean_file = &declutter_portfile($file);
9356: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 9357: my $current_locks = $current_permissions{$file};
1.563 banghart 9358: my @new_locks;
9359: my @del_keys;
9360: if (ref($current_locks) eq "ARRAY"){
9361: foreach my $locker (@{$current_locks}) {
1.632 albertel 9362: my $compare=$locker;
1.749 raeburn 9363: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 9364: $compare=join('',@{$locker});
1.746 raeburn 9365: if ($compare ne $symb_crs) {
9366: push(@new_locks, $locker);
9367: }
1.563 banghart 9368: }
9369: }
1.650 albertel 9370: if (scalar(@new_locks) > 0) {
1.563 banghart 9371: $current_permissions{$file} = \@new_locks;
9372: } else {
9373: push(@del_keys, $file);
1.613 albertel 9374: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 9375: delete($current_permissions{$file});
1.563 banghart 9376: }
9377: }
1.561 banghart 9378: }
1.613 albertel 9379: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 9380: return;
9381: }
1.512 banghart 9382:
1.17 www 9383: # ------------------------------------------------------------ Directory lister
9384:
9385: sub dirlist {
1.955 raeburn 9386: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 9387: $uri=~s/^\///;
9388: $uri=~s/\/$//;
1.253 stredwic 9389: my ($udom, $uname);
1.955 raeburn 9390: if ($getuserdir) {
1.253 stredwic 9391: $udom = $userdomain;
9392: $uname = $username;
1.955 raeburn 9393: } else {
9394: (undef,$udom,$uname)=split(/\//,$uri);
9395: if(defined($userdomain)) {
9396: $udom = $userdomain;
9397: }
9398: if(defined($username)) {
9399: $uname = $username;
9400: }
1.253 stredwic 9401: }
1.955 raeburn 9402: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 9403:
1.955 raeburn 9404: $dirRoot = $perlvar{'lonDocRoot'};
9405: if (defined($getpropath)) {
9406: $dirRoot = &propath($udom,$uname);
1.253 stredwic 9407: $dirRoot =~ s/\/$//;
1.955 raeburn 9408: } elsif (defined($getuserdir)) {
9409: my $subdir=$uname.'__';
9410: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
9411: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
9412: ."/$udom/$subdir/$uname";
9413: } elsif (defined($alternateRoot)) {
9414: $dirRoot = $alternateRoot;
1.751 banghart 9415: }
1.253 stredwic 9416:
9417: if($udom) {
9418: if($uname) {
1.1135 raeburn 9419: my $uhome = &homeserver($uname,$udom);
1.1136 raeburn 9420: if ($uhome eq 'no_host') {
9421: return ([],'no_host');
9422: }
1.955 raeburn 9423: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 9424: .$getuserdir.':'.&escape($dirRoot)
1.1135 raeburn 9425: .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955 raeburn 9426: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 9427: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955 raeburn 9428: } else {
9429: @listing_results = map { &unescape($_); } split(/:/,$listing);
9430: }
1.605 matthew 9431: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 9432: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605 matthew 9433: @listing_results = split(/:/,$listing);
9434: } else {
9435: @listing_results = map { &unescape($_); } split(/:/,$listing);
9436: }
1.1135 raeburn 9437: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
1.1136 raeburn 9438: ($listing eq 'rejected') || ($listing eq 'refused') ||
9439: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
9440: return ([],$listing);
9441: } else {
9442: return (\@listing_results);
1.1135 raeburn 9443: }
1.955 raeburn 9444: } elsif(!$alternateRoot) {
1.1136 raeburn 9445: my (%allusers,%listerror);
1.841 albertel 9446: my %servers = &get_servers($udom,'library');
1.955 raeburn 9447: foreach my $tryserver (keys(%servers)) {
9448: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
9449: &escape($udom),$tryserver);
9450: if ($listing eq 'unknown_cmd') {
9451: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
9452: $udom, $tryserver);
9453: } else {
9454: @listing_results = map { &unescape($_); } split(/:/,$listing);
9455: }
1.841 albertel 9456: if ($listing eq 'unknown_cmd') {
9457: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
9458: $udom, $tryserver);
9459: @listing_results = split(/:/,$listing);
9460: } else {
9461: @listing_results =
9462: map { &unescape($_); } split(/:/,$listing);
9463: }
1.1136 raeburn 9464: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
9465: ($listing eq 'rejected') || ($listing eq 'refused') ||
9466: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
9467: $listerror{$tryserver} = $listing;
9468: } else {
1.841 albertel 9469: foreach my $line (@listing_results) {
9470: my ($entry) = split(/&/,$line,2);
9471: $allusers{$entry} = 1;
9472: }
9473: }
1.253 stredwic 9474: }
1.1136 raeburn 9475: my @alluserslist=();
1.800 albertel 9476: foreach my $user (sort(keys(%allusers))) {
1.1136 raeburn 9477: push(@alluserslist,$user.'&user');
1.253 stredwic 9478: }
1.1136 raeburn 9479: return (\@alluserslist);
1.253 stredwic 9480: } else {
1.1136 raeburn 9481: return ([],'missing username');
1.253 stredwic 9482: }
1.955 raeburn 9483: } elsif(!defined($getpropath)) {
1.1136 raeburn 9484: my $path = $perlvar{'lonDocRoot'}.'/res/';
9485: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
9486: return (\@all_domains);
1.955 raeburn 9487: } else {
1.1136 raeburn 9488: return ([],'missing domain');
1.275 stredwic 9489: }
9490: }
9491:
9492: # --------------------------------------------- GetFileTimestamp
9493: # This function utilizes dirlist and returns the date stamp for
9494: # when it was last modified. It will also return an error of -1
9495: # if an error occurs
9496:
9497: sub GetFileTimestamp {
1.955 raeburn 9498: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 9499: $studentDomain = &LONCAPA::clean_domain($studentDomain);
9500: $studentName = &LONCAPA::clean_username($studentName);
1.1136 raeburn 9501: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
9502: undef,$getuserdir);
9503: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
9504: return -1;
9505: }
9506: if (ref($fileref) eq 'ARRAY') {
9507: my @stats = split('&',$fileref->[0]);
1.375 matthew 9508: # @stats contains first the filename, then the stat output
9509: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 9510: } else {
9511: return -1;
1.253 stredwic 9512: }
1.26 www 9513: }
9514:
1.712 albertel 9515: sub stat_file {
9516: my ($uri) = @_;
1.787 albertel 9517: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 9518:
1.955 raeburn 9519: my ($udom,$uname,$file);
1.712 albertel 9520: if ($uri =~ m-^/(uploaded|editupload)/-) {
9521: ($udom,$uname,$file) =
1.811 albertel 9522: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 9523: $file = 'userfiles/'.$file;
9524: }
9525: if ($uri =~ m-^/res/-) {
9526: ($udom,$uname) =
1.807 albertel 9527: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 9528: $file = $uri;
9529: }
9530:
9531: if (!$udom || !$uname || !$file) {
9532: # unable to handle the uri
9533: return ();
9534: }
1.956 raeburn 9535: my $getpropath;
9536: if ($file =~ /^userfiles\//) {
9537: $getpropath = 1;
9538: }
1.1136 raeburn 9539: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
9540: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
9541: return ();
9542: } else {
9543: if (ref($listref) eq 'ARRAY') {
9544: my @stats = split('&',$listref->[0]);
9545: shift(@stats); #filename is first
9546: return @stats;
9547: }
1.712 albertel 9548: }
9549: return ();
9550: }
9551:
1.26 www 9552: # -------------------------------------------------------- Value of a Condition
9553:
1.713 albertel 9554: # gets the value of a specific preevaluated condition
9555: # stored in the string $env{user.state.<cid>}
9556: # or looks up a condition reference in the bighash and if if hasn't
9557: # already been evaluated recurses into docondval to get the value of
9558: # the condition, then memoizing it to
9559: # $env{user.state.<cid>.<condition>}
1.40 www 9560: sub directcondval {
9561: my $number=shift;
1.620 albertel 9562: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 9563: &Apache::lonuserstate::evalstate();
9564: }
1.713 albertel 9565: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
9566: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
9567: } elsif ($number =~ /^_/) {
9568: my $sub_condition;
9569: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
9570: &GDBM_READER(),0640)) {
9571: $sub_condition=$bighash{'conditions'.$number};
9572: untie(%bighash);
9573: }
9574: my $value = &docondval($sub_condition);
1.949 raeburn 9575: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 9576: return $value;
9577: }
1.620 albertel 9578: if ($env{'user.state.'.$env{'request.course.id'}}) {
9579: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 9580: } else {
9581: return 2;
9582: }
9583: }
9584:
1.713 albertel 9585: # get the collection of conditions for this resource
1.26 www 9586: sub condval {
9587: my $condidx=shift;
1.54 www 9588: my $allpathcond='';
1.713 albertel 9589: foreach my $cond (split(/\|/,$condidx)) {
9590: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
9591: $allpathcond.=
9592: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
9593: }
1.191 harris41 9594: }
1.54 www 9595: $allpathcond=~s/\|$//;
1.713 albertel 9596: return &docondval($allpathcond);
9597: }
9598:
9599: #evaluates an expression of conditions
9600: sub docondval {
9601: my ($allpathcond) = @_;
9602: my $result=0;
9603: if ($env{'request.course.id'}
9604: && defined($allpathcond)) {
9605: my $operand='|';
9606: my @stack;
9607: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
9608: if ($chunk eq '(') {
9609: push @stack,($operand,$result);
9610: } elsif ($chunk eq ')') {
9611: my $before=pop @stack;
9612: if (pop @stack eq '&') {
9613: $result=$result>$before?$before:$result;
9614: } else {
9615: $result=$result>$before?$result:$before;
9616: }
9617: } elsif (($chunk eq '&') || ($chunk eq '|')) {
9618: $operand=$chunk;
9619: } else {
9620: my $new=directcondval($chunk);
9621: if ($operand eq '&') {
9622: $result=$result>$new?$new:$result;
9623: } else {
9624: $result=$result>$new?$result:$new;
9625: }
9626: }
9627: }
1.26 www 9628: }
9629: return $result;
1.421 albertel 9630: }
9631:
9632: # ---------------------------------------------------- Devalidate courseresdata
9633:
9634: sub devalidatecourseresdata {
9635: my ($coursenum,$coursedomain)=@_;
9636: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 9637: &devalidate_cache_new('courseres',$hashid);
1.28 www 9638: }
9639:
1.763 www 9640:
1.200 www 9641: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 9642: #
9643: # Parameters:
9644: # $coursenum - Number of the course.
9645: # $coursedomain - Domain at which the course was created.
9646: # Returns:
9647: # A hash of the course parameters along (I think) with timestamps
9648: # and version info.
1.877 foxr 9649:
1.624 albertel 9650: sub get_courseresdata {
9651: my ($coursenum,$coursedomain)=@_;
1.200 www 9652: my $coursehom=&homeserver($coursenum,$coursedomain);
9653: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 9654: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 9655: my %dumpreply;
1.417 albertel 9656: unless (defined($cached)) {
1.624 albertel 9657: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 9658: $result=\%dumpreply;
1.251 albertel 9659: my ($tmp) = keys(%dumpreply);
9660: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 9661: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 9662: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
9663: return $tmp;
1.416 albertel 9664: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 9665: $result=undef;
1.599 albertel 9666: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 9667: }
9668: }
1.624 albertel 9669: return $result;
9670: }
9671:
1.633 albertel 9672: sub devalidateuserresdata {
9673: my ($uname,$udom)=@_;
9674: my $hashid="$udom:$uname";
9675: &devalidate_cache_new('userres',$hashid);
9676: }
9677:
1.624 albertel 9678: sub get_userresdata {
9679: my ($uname,$udom)=@_;
9680: #most student don\'t have any data set, check if there is some data
9681: if (&EXT_cache_status($udom,$uname)) { return undef; }
9682:
9683: my $hashid="$udom:$uname";
9684: my ($result,$cached)=&is_cached_new('userres',$hashid);
9685: if (!defined($cached)) {
9686: my %resourcedata=&dump('resourcedata',$udom,$uname);
9687: $result=\%resourcedata;
9688: &do_cache_new('userres',$hashid,$result,600);
9689: }
9690: my ($tmp)=keys(%$result);
9691: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
9692: return $result;
9693: }
9694: #error 2 occurs when the .db doesn't exist
9695: if ($tmp!~/error: 2 /) {
1.672 albertel 9696: &logthis("<font color=\"blue\">WARNING:".
1.624 albertel 9697: " Trying to get resource data for ".
9698: $uname." at ".$udom.": ".
9699: $tmp."</font>");
9700: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 9701: #&EXT_cache_set($udom,$uname);
9702: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 9703: undef($tmp); # not really an error so don't send it back
1.624 albertel 9704: }
9705: return $tmp;
9706: }
1.879 foxr 9707: #----------------------------------------------- resdata - return resource data
9708: # Purpose:
9709: # Return resource data for either users or for a course.
9710: # Parameters:
9711: # $name - Course/user name.
9712: # $domain - Name of the domain the user/course is registered on.
9713: # $type - Type of thing $name is (must be 'course' or 'user'
9714: # @which - Array of names of resources desired.
9715: # Returns:
9716: # The value of the first reasource in @which that is found in the
9717: # resource hash.
9718: # Exceptional Conditions:
9719: # If the $type passed in is not valid (not the string 'course' or
9720: # 'user', an undefined reference is returned.
9721: # If none of the resources are found, an undef is returned
1.624 albertel 9722: sub resdata {
9723: my ($name,$domain,$type,@which)=@_;
9724: my $result;
9725: if ($type eq 'course') {
9726: $result=&get_courseresdata($name,$domain);
9727: } elsif ($type eq 'user') {
9728: $result=&get_userresdata($name,$domain);
9729: }
9730: if (!ref($result)) { return $result; }
1.251 albertel 9731: foreach my $item (@which) {
1.927 albertel 9732: if (defined($result->{$item->[0]})) {
9733: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 9734: }
1.250 albertel 9735: }
1.291 albertel 9736: return undef;
1.200 www 9737: }
9738:
1.1236 raeburn 9739: sub get_numsuppfiles {
9740: my ($cnum,$cdom,$ignorecache)=@_;
9741: my $hashid=$cnum.':'.$cdom;
9742: my ($suppcount,$cached);
9743: unless ($ignorecache) {
9744: ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
9745: }
9746: unless (defined($cached)) {
9747: my $chome=&homeserver($cnum,$cdom);
9748: unless ($chome eq 'no_host') {
9749: ($suppcount,my $errors) = (0,0);
9750: my $suppmap = 'supplemental.sequence';
9751: ($suppcount,$errors) =
9752: &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
9753: }
9754: &do_cache_new('suppcount',$hashid,$suppcount,600);
9755: }
9756: return $suppcount;
9757: }
9758:
1.379 matthew 9759: #
9760: # EXT resource caching routines
9761: #
9762:
9763: sub clear_EXT_cache_status {
1.383 albertel 9764: &delenv('cache.EXT.');
1.379 matthew 9765: }
9766:
9767: sub EXT_cache_status {
9768: my ($target_domain,$target_user) = @_;
1.383 albertel 9769: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 9770: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 9771: # We know already the user has no data
9772: return 1;
9773: } else {
9774: return 0;
9775: }
9776: }
9777:
9778: sub EXT_cache_set {
9779: my ($target_domain,$target_user) = @_;
1.383 albertel 9780: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 9781: #&appenv({$cachename => time});
1.379 matthew 9782: }
9783:
1.28 www 9784: # --------------------------------------------------------- Value of a Variable
1.58 www 9785: sub EXT {
1.715 albertel 9786:
1.1228 raeburn 9787: my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68 www 9788: unless ($varname) { return ''; }
1.218 albertel 9789: #get real user name/domain, courseid and symb
9790: my $courseid;
1.359 albertel 9791: my $publicuser;
1.427 www 9792: if ($symbparm) {
9793: $symbparm=&get_symb_from_alias($symbparm);
9794: }
1.218 albertel 9795: if (!($uname && $udom)) {
1.790 albertel 9796: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 9797: if (!$symbparm) { $symbparm=$cursymb; }
9798: } else {
1.620 albertel 9799: $courseid=$env{'request.course.id'};
1.218 albertel 9800: }
1.48 www 9801: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
9802: my $rest;
1.320 albertel 9803: if (defined($therest[0])) {
1.48 www 9804: $rest=join('.',@therest);
9805: } else {
9806: $rest='';
9807: }
1.320 albertel 9808:
1.57 www 9809: my $qualifierrest=$qualifier;
9810: if ($rest) { $qualifierrest.='.'.$rest; }
9811: my $spacequalifierrest=$space;
9812: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 9813: if ($realm eq 'user') {
1.48 www 9814: # --------------------------------------------------------------- user.resource
9815: if ($space eq 'resource') {
1.651 albertel 9816: if ( (defined($Apache::lonhomework::parsing_a_problem)
9817: || defined($Apache::lonhomework::parsing_a_task))
9818: &&
1.744 albertel 9819: ($symbparm eq &symbread()) ) {
9820: # if we are in the middle of processing the resource the
9821: # get the value we are planning on committing
9822: if (defined($Apache::lonhomework::results{$qualifierrest})) {
9823: return $Apache::lonhomework::results{$qualifierrest};
9824: } else {
9825: return $Apache::lonhomework::history{$qualifierrest};
9826: }
1.335 albertel 9827: } else {
1.359 albertel 9828: my %restored;
1.620 albertel 9829: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 9830: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
9831: } else {
9832: %restored=&restore($symbparm,$courseid,$udom,$uname);
9833: }
1.335 albertel 9834: return $restored{$qualifierrest};
9835: }
1.48 www 9836: # ----------------------------------------------------------------- user.access
9837: } elsif ($space eq 'access') {
1.218 albertel 9838: # FIXME - not supporting calls for a specific user
1.48 www 9839: return &allowed($qualifier,$rest);
9840: # ------------------------------------------ user.preferences, user.environment
9841: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 9842: if (($uname eq $env{'user.name'}) &&
9843: ($udom eq $env{'user.domain'})) {
9844: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 9845: } else {
1.359 albertel 9846: my %returnhash;
9847: if (!$publicuser) {
9848: %returnhash=&userenvironment($udom,$uname,
9849: $qualifierrest);
9850: }
1.218 albertel 9851: return $returnhash{$qualifierrest};
9852: }
1.48 www 9853: # ----------------------------------------------------------------- user.course
9854: } elsif ($space eq 'course') {
1.218 albertel 9855: # FIXME - not supporting calls for a specific user
1.620 albertel 9856: return $env{join('.',('request.course',$qualifier))};
1.48 www 9857: # ------------------------------------------------------------------- user.role
9858: } elsif ($space eq 'role') {
1.218 albertel 9859: # FIXME - not supporting calls for a specific user
1.620 albertel 9860: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 9861: if ($qualifier eq 'value') {
9862: return $role;
9863: } elsif ($qualifier eq 'extent') {
9864: return $where;
9865: }
9866: # ----------------------------------------------------------------- user.domain
9867: } elsif ($space eq 'domain') {
1.218 albertel 9868: return $udom;
1.48 www 9869: # ------------------------------------------------------------------- user.name
9870: } elsif ($space eq 'name') {
1.218 albertel 9871: return $uname;
1.48 www 9872: # ---------------------------------------------------- Any other user namespace
1.29 www 9873: } else {
1.359 albertel 9874: my %reply;
9875: if (!$publicuser) {
9876: %reply=&get($space,[$qualifierrest],$udom,$uname);
9877: }
9878: return $reply{$qualifierrest};
1.48 www 9879: }
1.236 www 9880: } elsif ($realm eq 'query') {
9881: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 9882: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
9883: [$spacequalifierrest]);
1.620 albertel 9884: return $env{'form.'.$spacequalifierrest};
1.236 www 9885: } elsif ($realm eq 'request') {
1.48 www 9886: # ------------------------------------------------------------- request.browser
9887: if ($space eq 'browser') {
1.1145 bisitz 9888: return $env{'browser.'.$qualifier};
1.57 www 9889: # ------------------------------------------------------------ request.filename
9890: } else {
1.620 albertel 9891: return $env{'request.'.$spacequalifierrest};
1.29 www 9892: }
1.28 www 9893: } elsif ($realm eq 'course') {
1.48 www 9894: # ---------------------------------------------------------- course.description
1.620 albertel 9895: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 9896: } elsif ($realm eq 'resource') {
1.165 www 9897:
1.620 albertel 9898: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 9899: if (!$symbparm) { $symbparm=&symbread(); }
9900: }
1.693 albertel 9901:
1.1232 raeburn 9902: if ($qualifier eq '') {
9903: if ($space eq 'title') {
9904: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
9905: return &gettitle($symbparm);
9906: }
1.693 albertel 9907:
1.1232 raeburn 9908: if ($space eq 'map') {
9909: my ($map) = &decode_symb($symbparm);
9910: return &symbread($map);
9911: }
9912: if ($space eq 'maptitle') {
9913: my ($map) = &decode_symb($symbparm);
9914: return &gettitle($map);
9915: }
9916: if ($space eq 'filename') {
9917: if ($symbparm) {
9918: return &clutter((&decode_symb($symbparm))[2]);
9919: }
9920: return &hreflocation('',$env{'request.filename'});
1.905 albertel 9921: }
1.1232 raeburn 9922:
1.1233 raeburn 9923: if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
9924: if ($space eq 'visibleparts') {
9925: my $navmap = Apache::lonnavmaps::navmap->new();
9926: my $item;
9927: if (ref($navmap)) {
9928: my $res = $navmap->getBySymb($symbparm);
9929: my $parts = $res->parts();
9930: if (ref($parts) eq 'ARRAY') {
9931: $item = join(',',@{$parts});
9932: }
9933: undef($navmap);
1.1232 raeburn 9934: }
1.1233 raeburn 9935: return $item;
1.1232 raeburn 9936: }
9937: }
9938: }
1.693 albertel 9939:
9940: my ($section, $group, @groups);
1.593 albertel 9941: my ($courselevelm,$courselevel);
1.1228 raeburn 9942: if (($courseid eq '') && ($cid)) {
9943: $courseid = $cid;
9944: }
9945: if (($symbparm && $courseid) &&
9946: (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165 www 9947:
1.218 albertel 9948: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 9949:
1.60 www 9950: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 9951: my $symbp=$symbparm;
1.735 albertel 9952: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 9953:
9954: my $symbparm=$symbp.'.'.$spacequalifierrest;
9955: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
9956:
1.620 albertel 9957: if (($env{'user.name'} eq $uname) &&
9958: ($env{'user.domain'} eq $udom)) {
9959: $section=$env{'request.course.sec'};
1.733 raeburn 9960: @groups = split(/:/,$env{'request.course.groups'});
9961: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 9962: } else {
1.539 albertel 9963: if (! defined($usection)) {
1.551 albertel 9964: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 9965: } else {
9966: $section = $usection;
9967: }
1.733 raeburn 9968: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 9969: }
9970:
9971: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
9972: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
9973: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
9974:
1.593 albertel 9975: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 9976: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 9977: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 9978:
1.60 www 9979: # ----------------------------------------------------------- first, check user
1.624 albertel 9980:
9981: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 9982: ([$courselevelr,'resource'],
9983: [$courselevelm,'map' ],
9984: [$courselevel, 'course' ]));
1.931 albertel 9985: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 9986:
1.594 albertel 9987: # ------------------------------------------------ second, check some of course
1.684 raeburn 9988: my $coursereply;
1.691 raeburn 9989: if (@groups > 0) {
9990: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
9991: $mapparm,$spacequalifierrest);
1.927 albertel 9992: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 9993: }
1.96 www 9994:
1.684 raeburn 9995: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 9996: $env{'course.'.$courseid.'.domain'},
9997: 'course',
9998: ([$seclevelr, 'resource'],
9999: [$seclevelm, 'map' ],
10000: [$seclevel, 'course' ],
10001: [$courselevelr,'resource']));
10002: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 10003:
1.60 www 10004: # ------------------------------------------------------ third, check map parms
1.218 albertel 10005: my %parmhash=();
10006: my $thisparm='';
10007: if (tie(%parmhash,'GDBM_File',
1.620 albertel 10008: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 10009: &GDBM_READER(),0640)) {
1.218 albertel 10010: $thisparm=$parmhash{$symbparm};
10011: untie(%parmhash);
10012: }
1.927 albertel 10013: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 10014: }
1.594 albertel 10015: # ------------------------------------------ fourth, look in resource metadata
1.71 www 10016:
1.218 albertel 10017: $spacequalifierrest=~s/\./\_/;
1.282 albertel 10018: my $filename;
10019: if (!$symbparm) { $symbparm=&symbread(); }
10020: if ($symbparm) {
1.409 www 10021: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 10022: } else {
1.620 albertel 10023: $filename=$env{'request.filename'};
1.282 albertel 10024: }
10025: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 10026: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 10027: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 10028: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 10029:
1.927 albertel 10030: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 10031: if ($symbparm && defined($courseid) &&
1.620 albertel 10032: $courseid eq $env{'request.course.id'}) {
1.624 albertel 10033: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
10034: $env{'course.'.$courseid.'.domain'},
10035: 'course',
1.927 albertel 10036: ([$courselevelm,'map' ],
10037: [$courselevel, 'course']));
10038: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 10039: }
1.145 www 10040: # ------------------------------------------------------------------ Cascade up
1.218 albertel 10041: unless ($space eq '0') {
1.336 albertel 10042: my @parts=split(/_/,$space);
10043: my $id=pop(@parts);
10044: my $part=join('_',@parts);
10045: if ($part eq '') { $part='0'; }
1.927 albertel 10046: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 10047: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 10048: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 10049: }
1.395 albertel 10050: if ($recurse) { return undef; }
10051: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 10052: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 10053: # ---------------------------------------------------- Any other user namespace
10054: } elsif ($realm eq 'environment') {
10055: # ----------------------------------------------------------------- environment
1.620 albertel 10056: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
10057: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 10058: } else {
1.770 albertel 10059: if ($uname eq 'anonymous' && $udom eq '') {
10060: return '';
10061: }
1.219 albertel 10062: my %returnhash=&userenvironment($udom,$uname,
10063: $spacequalifierrest);
10064: return $returnhash{$spacequalifierrest};
10065: }
1.28 www 10066: } elsif ($realm eq 'system') {
1.48 www 10067: # ----------------------------------------------------------------- system.time
10068: if ($space eq 'time') {
10069: return time;
10070: }
1.696 albertel 10071: } elsif ($realm eq 'server') {
10072: # ----------------------------------------------------------------- system.time
10073: if ($space eq 'name') {
10074: return $ENV{'SERVER_NAME'};
10075: }
1.28 www 10076: }
1.48 www 10077: return '';
1.61 www 10078: }
10079:
1.927 albertel 10080: sub get_reply {
10081: my ($reply_value) = @_;
1.940 raeburn 10082: if (ref($reply_value) eq 'ARRAY') {
10083: if (wantarray) {
10084: return @$reply_value;
10085: }
10086: return $reply_value->[0];
10087: } else {
10088: return $reply_value;
1.927 albertel 10089: }
10090: }
10091:
1.691 raeburn 10092: sub check_group_parms {
10093: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
10094: my @groupitems = ();
10095: my $resultitem;
1.927 albertel 10096: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 10097: foreach my $group (@{$groups}) {
10098: foreach my $level (@levels) {
1.927 albertel 10099: my $item = $courseid.'.['.$group.'].'.$level->[0];
10100: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 10101: }
10102: }
10103: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
10104: $env{'course.'.$courseid.'.domain'},
10105: 'course',@groupitems);
10106: return $coursereply;
10107: }
10108:
10109: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 10110: my ($courseid,@groups) = @_;
10111: @groups = sort(@groups);
1.691 raeburn 10112: return @groups;
10113: }
10114:
1.395 albertel 10115: sub packages_tab_default {
10116: my ($uri,$varname)=@_;
10117: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 10118:
10119: my (@extension,@specifics,$do_default);
10120: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 10121: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 10122: if ($pack_type eq 'default') {
10123: $do_default=1;
10124: } elsif ($pack_type eq 'extension') {
10125: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 10126: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 10127: # only look at packages defaults for packages that this id is
1.738 albertel 10128: push(@specifics,[$package,$pack_type,$pack_part]);
10129: }
10130: }
10131: # first look for a package that matches the requested part id
10132: foreach my $package (@specifics) {
10133: my (undef,$pack_type,$pack_part)=@{$package};
10134: next if ($pack_part ne $part);
10135: if (defined($packagetab{"$pack_type&$name&default"})) {
10136: return $packagetab{"$pack_type&$name&default"};
10137: }
10138: }
10139: # look for any possible matching non extension_ package
10140: foreach my $package (@specifics) {
10141: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 10142: if (defined($packagetab{"$pack_type&$name&default"})) {
10143: return $packagetab{"$pack_type&$name&default"};
10144: }
1.585 albertel 10145: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 10146: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
10147: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 10148: }
10149: }
1.738 albertel 10150: # look for any posible extension_ match
10151: foreach my $package (@extension) {
10152: my ($package,$pack_type)=@{$package};
10153: if (defined($packagetab{"$pack_type&$name&default"})) {
10154: return $packagetab{"$pack_type&$name&default"};
10155: }
10156: if (defined($packagetab{$package."&$name&default"})) {
10157: return $packagetab{$package."&$name&default"};
10158: }
10159: }
10160: # look for a global default setting
10161: if ($do_default && defined($packagetab{"default&$name&default"})) {
10162: return $packagetab{"default&$name&default"};
10163: }
1.395 albertel 10164: return undef;
10165: }
10166:
1.334 albertel 10167: sub add_prefix_and_part {
10168: my ($prefix,$part)=@_;
10169: my $keyroot;
10170: if (defined($prefix) && $prefix !~ /^__/) {
10171: # prefix that has a part already
10172: $keyroot=$prefix;
10173: } elsif (defined($prefix)) {
10174: # prefix that is missing a part
10175: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
10176: } else {
10177: # no prefix at all
10178: if (defined($part)) { $keyroot='_'.$part; }
10179: }
10180: return $keyroot;
10181: }
10182:
1.71 www 10183: # ---------------------------------------------------------------- Get metadata
10184:
1.599 albertel 10185: my %metaentry;
1.1070 www 10186: my %importedpartids;
1.71 www 10187: sub metadata {
1.176 www 10188: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 10189: $uri=&declutter($uri);
1.288 albertel 10190: # if it is a non metadata possible uri return quickly
1.529 albertel 10191: if (($uri eq '') ||
10192: (($uri =~ m|^/*adm/|) &&
1.1217 raeburn 10193: ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108 raeburn 10194: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 10195: return undef;
10196: }
1.1140 www 10197: if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/)
1.924 albertel 10198: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 10199: return undef;
1.288 albertel 10200: }
1.73 www 10201: my $filename=$uri;
10202: $uri=~s/\.meta$//;
1.172 www 10203: #
10204: # Is the metadata already cached?
1.177 www 10205: # Look at timestamp of caching
1.172 www 10206: # Everything is cached by the main uri, libraries are never directly cached
10207: #
1.428 albertel 10208: if (!defined($liburi)) {
1.599 albertel 10209: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 10210: if (defined($cached)) { return $result->{':'.$what}; }
10211: }
10212: {
1.1069 www 10213: # Imported parts would go here
1.1070 www 10214: my %importedids=();
10215: my @origfileimportpartids=();
1.1069 www 10216: my $importedparts=0;
1.172 www 10217: #
10218: # Is this a recursive call for a library?
10219: #
1.599 albertel 10220: # if (! exists($metacache{$uri})) {
10221: # $metacache{$uri}={};
10222: # }
1.924 albertel 10223: my $cachetime = 60*60;
1.171 www 10224: if ($liburi) {
10225: $liburi=&declutter($liburi);
10226: $filename=$liburi;
1.401 bowersj2 10227: } else {
1.599 albertel 10228: &devalidate_cache_new('meta',$uri);
10229: undef(%metaentry);
1.401 bowersj2 10230: }
1.140 www 10231: my %metathesekeys=();
1.73 www 10232: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 10233: my $metastring;
1.1140 www 10234: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929 albertel 10235: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 10236: $metastring =
1.929 albertel 10237: &Apache::lonnet::ssi_body($which,
1.924 albertel 10238: ('grade_target' => 'meta'));
10239: $cachetime = 1; # only want this cached in the child not long term
1.1108 raeburn 10240: } elsif (($uri !~ m -^(editupload)/-) &&
10241: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 10242: my $file=&filelocation('',&clutter($filename));
1.599 albertel 10243: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 10244: $metastring=&getfile($file);
1.489 albertel 10245: }
1.208 albertel 10246: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 10247: my $token;
1.140 www 10248: undef %metathesekeys;
1.71 www 10249: while ($token=$parser->get_token) {
1.339 albertel 10250: if ($token->[0] eq 'S') {
10251: if (defined($token->[2]->{'package'})) {
1.172 www 10252: #
10253: # This is a package - get package info
10254: #
1.339 albertel 10255: my $package=$token->[2]->{'package'};
10256: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10257: if (defined($token->[2]->{'id'})) {
10258: $keyroot.='_'.$token->[2]->{'id'};
10259: }
1.599 albertel 10260: if ($metaentry{':packages'}) {
10261: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 10262: } else {
1.599 albertel 10263: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 10264: }
1.736 albertel 10265: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 10266: my $part=$keyroot;
10267: $part=~s/^\_//;
1.736 albertel 10268: if ($pack_entry=~/^\Q$package\E\&/ ||
10269: $pack_entry=~/^\Q$package\E_0\&/) {
10270: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 10271: # ignore package.tab specified default values
10272: # here &package_tab_default() will fetch those
10273: if ($subp eq 'default') { next; }
1.736 albertel 10274: my $value=$packagetab{$pack_entry};
1.432 albertel 10275: my $unikey;
10276: if ($pack =~ /_0$/) {
10277: $unikey='parameter_0_'.$name;
10278: $part=0;
10279: } else {
10280: $unikey='parameter'.$keyroot.'_'.$name;
10281: }
1.339 albertel 10282: if ($subp eq 'display') {
10283: $value.=' [Part: '.$part.']';
10284: }
1.599 albertel 10285: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 10286: $metathesekeys{$unikey}=1;
1.599 albertel 10287: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10288: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 10289: }
1.599 albertel 10290: if (defined($metaentry{':'.$unikey.'.default'})) {
10291: $metaentry{':'.$unikey}=
10292: $metaentry{':'.$unikey.'.default'};
1.356 albertel 10293: }
1.339 albertel 10294: }
10295: }
10296: } else {
1.172 www 10297: #
10298: # This is not a package - some other kind of start tag
1.339 albertel 10299: #
10300: my $entry=$token->[1];
1.1068 www 10301: my $unikey='';
1.175 www 10302:
1.339 albertel 10303: if ($entry eq 'import') {
1.175 www 10304: #
10305: # Importing a library here
1.339 albertel 10306: #
1.1067 www 10307: my $location=$parser->get_text('/import');
10308: my $dir=$filename;
10309: $dir=~s|[^/]*$||;
10310: $location=&filelocation($dir,$location);
1.1069 www 10311:
1.1068 www 10312: my $importmode=$token->[2]->{'importmode'};
10313: if ($importmode eq 'problem') {
1.1069 www 10314: # Import as problem/response
1.1068 www 10315: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10316: } elsif ($importmode eq 'part') {
10317: # Import as part(s)
1.1069 www 10318: $importedparts=1;
10319: # We need to get the original file and the imported file to get the part order correct
10320: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
10321: # Load and inspect original file
1.1070 www 10322: if ($#origfileimportpartids<0) {
10323: undef(%importedpartids);
10324: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
10325: my $origfile=&getfile($origfilelocation);
10326: @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10327: }
10328:
1.1069 www 10329: # Load and inspect imported file
10330: my $impfile=&getfile($location);
10331: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10332: if ($#impfilepartids>=0) {
10333: # This problem had parts
1.1070 www 10334: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 10335: } else {
10336: # Importing by turning a single problem into a problem part
10337: # It gets the import-tags ID as part-ID
10338: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 10339: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 10340: }
1.1068 www 10341: } else {
10342: # Normal import
10343: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10344: if (defined($token->[2]->{'id'})) {
10345: $unikey.='_'.$token->[2]->{'id'};
10346: }
1.1067 www 10347: }
10348:
1.339 albertel 10349: if ($depthcount<20) {
1.736 albertel 10350: my $metadata =
10351: &metadata($uri,'keys', $location,$unikey,
10352: $depthcount+1);
10353: foreach my $meta (split(',',$metadata)) {
10354: $metaentry{':'.$meta}=$metaentry{':'.$meta};
10355: $metathesekeys{$meta}=1;
1.339 albertel 10356: }
1.1068 www 10357:
10358: }
1.1067 www 10359: } else {
10360: #
10361: # Not importing, some other kind of non-package, non-library start tag
10362: #
10363: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
10364: if (defined($token->[2]->{'id'})) {
10365: $unikey.='_'.$token->[2]->{'id'};
10366: }
1.339 albertel 10367: if (defined($token->[2]->{'name'})) {
10368: $unikey.='_'.$token->[2]->{'name'};
10369: }
10370: $metathesekeys{$unikey}=1;
1.736 albertel 10371: foreach my $param (@{$token->[3]}) {
10372: $metaentry{':'.$unikey.'.'.$param} =
10373: $token->[2]->{$param};
1.339 albertel 10374: }
10375: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 10376: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 10377: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
10378: # only ws inside the tag, and not in default, so use default
10379: # as value
1.599 albertel 10380: $metaentry{':'.$unikey}=$default;
1.908 albertel 10381: } elsif ( $internaltext =~ /\S/ ) {
10382: # something interesting inside the tag
10383: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 10384: } else {
1.908 albertel 10385: # no interesting values, don't set a default
1.339 albertel 10386: }
1.172 www 10387: # end of not-a-package not-a-library import
1.339 albertel 10388: }
1.172 www 10389: # end of not-a-package start tag
1.339 albertel 10390: }
1.172 www 10391: # the next is the end of "start tag"
1.339 albertel 10392: }
10393: }
1.483 albertel 10394: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 10395: $extension = lc($extension);
10396: if ($extension eq 'htm') { $extension='html'; }
10397:
1.737 albertel 10398: foreach my $key (keys(%packagetab)) {
1.483 albertel 10399: #no specific packages #how's our extension
10400: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 10401: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 10402: \%metathesekeys);
10403: }
1.883 albertel 10404:
10405: if (!exists($metaentry{':packages'})
10406: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 10407: foreach my $key (keys(%packagetab)) {
1.483 albertel 10408: #no specific packages well let's get default then
10409: if ($key!~/^default&/) { next; }
1.488 albertel 10410: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 10411: \%metathesekeys);
10412: }
10413: }
1.338 www 10414: # are there custom rights to evaluate
1.599 albertel 10415: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 10416:
1.338 www 10417: #
10418: # Importing a rights file here
1.339 albertel 10419: #
10420: unless ($depthcount) {
1.599 albertel 10421: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 10422: my $dir=$filename;
10423: $dir=~s|[^/]*$||;
10424: $location=&filelocation($dir,$location);
1.736 albertel 10425: my $rights_metadata =
10426: &metadata($uri,'keys',$location,'_rights',
10427: $depthcount+1);
10428: foreach my $rights (split(',',$rights_metadata)) {
10429: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
10430: $metathesekeys{$rights}=1;
1.339 albertel 10431: }
10432: }
10433: }
1.737 albertel 10434: # uniqifiy package listing
10435: my %seen;
10436: my @uniq_packages =
10437: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
10438: $metaentry{':packages'} = join(',',@uniq_packages);
10439:
1.1070 www 10440: if ($importedparts) {
10441: # We had imported parts and need to rebuild partorder
10442: $metaentry{':partorder'}='';
10443: $metathesekeys{'partorder'}=1;
10444: for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
10445: if ($origfileimportpartids[$index] eq 'part') {
10446: # original part, part of the problem
10447: $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
10448: } else {
10449: # we have imported parts at this position
10450: $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
10451: }
10452: }
10453: $metaentry{':partorder'}=~s/^\,//;
10454: }
10455:
1.737 albertel 10456: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 10457: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
10458: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924 albertel 10459: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 10460: # this is the end of "was not already recently cached
1.71 www 10461: }
1.599 albertel 10462: return $metaentry{':'.$what};
1.261 albertel 10463: }
10464:
1.488 albertel 10465: sub metadata_create_package_def {
1.483 albertel 10466: my ($uri,$key,$package,$metathesekeys)=@_;
10467: my ($pack,$name,$subp)=split(/\&/,$key);
10468: if ($subp eq 'default') { next; }
10469:
1.599 albertel 10470: if (defined($metaentry{':packages'})) {
10471: $metaentry{':packages'}.=','.$package;
1.483 albertel 10472: } else {
1.599 albertel 10473: $metaentry{':packages'}=$package;
1.483 albertel 10474: }
10475: my $value=$packagetab{$key};
10476: my $unikey;
10477: $unikey='parameter_0_'.$name;
1.599 albertel 10478: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 10479: $$metathesekeys{$unikey}=1;
1.599 albertel 10480: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10481: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 10482: }
1.599 albertel 10483: if (defined($metaentry{':'.$unikey.'.default'})) {
10484: $metaentry{':'.$unikey}=
10485: $metaentry{':'.$unikey.'.default'};
1.483 albertel 10486: }
10487: }
10488:
1.261 albertel 10489: sub metadata_generate_part0 {
10490: my ($metadata,$metacache,$uri) = @_;
10491: my %allnames;
1.737 albertel 10492: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 10493: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 10494: my $part=$$metacache{':'.$metakey.'.part'};
10495: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 10496: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 10497: $allnames{$name}=$part;
10498: }
10499: }
10500: }
10501: foreach my $name (keys(%allnames)) {
10502: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 10503: my $key=":parameter_0_$name";
1.261 albertel 10504: $$metacache{"$key.part"}='0';
10505: $$metacache{"$key.name"}=$name;
1.428 albertel 10506: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 10507: $allnames{$name}.'_'.$name.
10508: '.type'};
1.428 albertel 10509: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 10510: '.display'};
1.644 www 10511: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 10512: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 10513: $$metacache{"$key.display"}=$olddis;
10514: }
1.71 www 10515: }
10516:
1.764 albertel 10517: # ------------------------------------------------------ Devalidate title cache
10518:
10519: sub devalidate_title_cache {
10520: my ($url)=@_;
10521: if (!$env{'request.course.id'}) { return; }
10522: my $symb=&symbread($url);
10523: if (!$symb) { return; }
10524: my $key=$env{'request.course.id'}."\0".$symb;
10525: &devalidate_cache_new('title',$key);
10526: }
10527:
1.1014 droeschl 10528: # ------------------------------------------------- Get the title of a course
10529:
10530: sub current_course_title {
10531: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
10532: }
1.301 www 10533: # ------------------------------------------------- Get the title of a resource
10534:
10535: sub gettitle {
10536: my $urlsymb=shift;
10537: my $symb=&symbread($urlsymb);
1.534 albertel 10538: if ($symb) {
1.620 albertel 10539: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 10540: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 10541: if (defined($cached)) {
10542: return $result;
10543: }
1.534 albertel 10544: my ($map,$resid,$url)=&decode_symb($symb);
10545: my $title='';
1.907 albertel 10546: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
10547: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
10548: } else {
10549: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10550: &GDBM_READER(),0640)) {
10551: my $mapid=$bighash{'map_pc_'.&clutter($map)};
10552: $title=$bighash{'title_'.$mapid.'.'.$resid};
10553: untie(%bighash);
10554: }
1.534 albertel 10555: }
10556: $title=~s/\&colon\;/\:/gs;
10557: if ($title) {
1.1159 www 10558: # Remember both $symb and $title for dynamic metadata
10559: $accesshash{$symb.'___crstitle'}=$title;
1.1161 www 10560: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159 www 10561: # Cache this title and then return it
1.599 albertel 10562: return &do_cache_new('title',$key,$title,600);
1.534 albertel 10563: }
10564: $urlsymb=$url;
10565: }
10566: my $title=&metadata($urlsymb,'title');
10567: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
10568: return $title;
1.301 www 10569: }
1.613 albertel 10570:
1.614 albertel 10571: sub get_slot {
10572: my ($which,$cnum,$cdom)=@_;
10573: if (!$cnum || !$cdom) {
1.790 albertel 10574: (undef,my $courseid)=&whichuser();
1.620 albertel 10575: $cdom=$env{'course.'.$courseid.'.domain'};
10576: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 10577: }
1.703 albertel 10578: my $key=join("\0",'slots',$cdom,$cnum,$which);
10579: my %slotinfo;
10580: if (exists($remembered{$key})) {
10581: $slotinfo{$which} = $remembered{$key};
10582: } else {
10583: %slotinfo=&get('slots',[$which],$cdom,$cnum);
10584: &Apache::lonhomework::showhash(%slotinfo);
10585: my ($tmp)=keys(%slotinfo);
10586: if ($tmp=~/^error:/) { return (); }
10587: $remembered{$key} = $slotinfo{$which};
10588: }
1.616 albertel 10589: if (ref($slotinfo{$which}) eq 'HASH') {
10590: return %{$slotinfo{$which}};
10591: }
10592: return $slotinfo{$which};
1.614 albertel 10593: }
1.1150 raeburn 10594:
10595: sub get_reservable_slots {
10596: my ($cnum,$cdom,$uname,$udom) = @_;
10597: my $now = time;
10598: my $reservable_info;
10599: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
10600: if (exists($remembered{$key})) {
10601: $reservable_info = $remembered{$key};
10602: } else {
10603: my %resv;
10604: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
10605: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
10606: $reservable_info = \%resv;
10607: $remembered{$key} = $reservable_info;
10608: }
10609: return $reservable_info;
10610: }
10611:
10612: sub get_course_slots {
10613: my ($cnum,$cdom) = @_;
10614: my $hashid=$cnum.':'.$cdom;
10615: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
10616: if (defined($cached)) {
10617: if (ref($result) eq 'HASH') {
10618: return %{$result};
10619: }
10620: } else {
10621: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
10622: my ($tmp) = keys(%slots);
10623: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1219 raeburn 10624: &do_cache_new('allslots',$hashid,\%slots,600);
1.1150 raeburn 10625: return %slots;
10626: }
10627: }
10628: return;
10629: }
10630:
10631: sub devalidate_slots_cache {
10632: my ($cnum,$cdom)=@_;
10633: my $hashid=$cnum.':'.$cdom;
10634: &devalidate_cache_new('allslots',$hashid);
10635: }
10636:
1.1181 raeburn 10637: sub get_coursechange {
10638: my ($cdom,$cnum) = @_;
10639: if ($cdom eq '' || $cnum eq '') {
10640: return unless ($env{'request.course.id'});
10641: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10642: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10643: }
10644: my $hashid=$cdom.'_'.$cnum;
10645: my ($change,$cached)=&is_cached_new('crschange',$hashid);
10646: if ((defined($cached)) && ($change ne '')) {
10647: return $change;
10648: } else {
10649: my %crshash;
10650: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
10651: if ($crshash{'internal.contentchange'} eq '') {
10652: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
10653: if ($change eq '') {
10654: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
10655: $change = $crshash{'internal.created'};
10656: }
10657: } else {
10658: $change = $crshash{'internal.contentchange'};
10659: }
10660: my $cachetime = 600;
10661: &do_cache_new('crschange',$hashid,$change,$cachetime);
10662: }
10663: return $change;
10664: }
10665:
10666: sub devalidate_coursechange_cache {
10667: my ($cnum,$cdom)=@_;
10668: my $hashid=$cnum.':'.$cdom;
10669: &devalidate_cache_new('crschange',$hashid);
10670: }
10671:
1.31 www 10672: # ------------------------------------------------- Update symbolic store links
10673:
10674: sub symblist {
10675: my ($mapname,%newhash)=@_;
1.438 www 10676: $mapname=&deversion(&declutter($mapname));
1.31 www 10677: my %hash;
1.620 albertel 10678: if (($env{'request.course.fn'}) && (%newhash)) {
10679: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 10680: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 10681: foreach my $url (keys(%newhash)) {
1.711 albertel 10682: next if ($url eq 'last_known'
10683: && $env{'form.no_update_last_known'});
10684: $hash{declutter($url)}=&encode_symb($mapname,
10685: $newhash{$url}->[1],
10686: $newhash{$url}->[0]);
1.191 harris41 10687: }
1.31 www 10688: if (untie(%hash)) {
10689: return 'ok';
10690: }
10691: }
10692: }
10693: return 'error';
1.212 www 10694: }
10695:
10696: # --------------------------------------------------------------- Verify a symb
10697:
10698: sub symbverify {
1.1190 raeburn 10699: my ($symb,$thisurl,$encstate)=@_;
1.510 www 10700: my $thisfn=$thisurl;
1.439 www 10701: $thisfn=&declutter($thisfn);
1.215 www 10702: # direct jump to resource in page or to a sequence - will construct own symbs
10703: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
10704: # check URL part
1.409 www 10705: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 10706:
1.431 www 10707: unless ($url eq $thisfn) { return 0; }
1.213 www 10708:
1.216 www 10709: $symb=&symbclean($symb);
1.510 www 10710: $thisurl=&deversion($thisurl);
1.439 www 10711: $thisfn=&deversion($thisfn);
1.213 www 10712:
10713: my %bighash;
10714: my $okay=0;
1.431 www 10715:
1.620 albertel 10716: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 10717: &GDBM_READER(),0640)) {
1.1204 raeburn 10718: my $noclutter;
1.1032 raeburn 10719: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
10720: $thisurl =~ s/\?.+$//;
1.1204 raeburn 10721: if ($map =~ m{^uploaded/.+\.page$}) {
10722: $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
10723: $thisurl =~ s{^\Qhttp://https://\E}{https://};
10724: $noclutter = 1;
10725: }
10726: }
10727: my $ids;
10728: if ($noclutter) {
10729: $ids=$bighash{'ids_'.$thisurl};
10730: } else {
10731: $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032 raeburn 10732: }
1.1102 raeburn 10733: unless ($ids) {
10734: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
10735: $ids=$bighash{$idkey};
1.216 www 10736: }
10737: if ($ids) {
10738: # ------------------------------------------------------------------- Has ID(s)
1.1202 raeburn 10739: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
1.1203 raeburn 10740: $symb =~ s/\?.+$//;
1.1202 raeburn 10741: }
1.800 albertel 10742: foreach my $id (split(/\,/,$ids)) {
10743: my ($mapid,$resid)=split(/\./,$id);
1.216 www 10744: if (
10745: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190 raeburn 10746: eq $symb) {
10747: if (ref($encstate)) {
10748: $$encstate = $bighash{'encrypted_'.$id};
10749: }
1.620 albertel 10750: if (($env{'request.role.adv'}) ||
1.1101 raeburn 10751: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
10752: ($thisurl eq '/adm/navmaps')) {
1.1190 raeburn 10753: $okay=1;
1.1202 raeburn 10754: last;
1.582 albertel 10755: }
10756: }
1.216 www 10757: }
10758: }
1.213 www 10759: untie(%bighash);
10760: }
10761: return $okay;
1.31 www 10762: }
10763:
1.210 www 10764: # --------------------------------------------------------------- Clean-up symb
10765:
10766: sub symbclean {
10767: my $symb=shift;
1.568 albertel 10768: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 10769: # remove version from map
10770: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 10771:
1.210 www 10772: # remove version from URL
10773: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 10774:
1.507 www 10775: # remove wrapper
10776:
1.510 www 10777: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 10778: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 10779: return $symb;
1.409 www 10780: }
10781:
10782: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 10783:
10784: sub encode_symb {
10785: my ($map,$resid,$url)=@_;
10786: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
10787: }
1.409 www 10788:
10789: sub decode_symb {
1.568 albertel 10790: my $symb=shift;
10791: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
10792: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 10793: return (&fixversion($map),$resid,&fixversion($url));
10794: }
10795:
10796: sub fixversion {
10797: my $fn=shift;
1.609 banghart 10798: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 10799: my %bighash;
10800: my $uri=&clutter($fn);
1.620 albertel 10801: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 10802: # is this cached?
1.599 albertel 10803: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 10804: if (defined($cached)) { return $result; }
10805: # unfortunately not cached, or expired
1.620 albertel 10806: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 10807: &GDBM_READER(),0640)) {
10808: if ($bighash{'version_'.$uri}) {
10809: my $version=$bighash{'version_'.$uri};
1.444 www 10810: unless (($version eq 'mostrecent') ||
10811: ($version==&getversion($uri))) {
1.440 www 10812: $uri=~s/\.(\w+)$/\.$version\.$1/;
10813: }
10814: }
10815: untie %bighash;
1.413 www 10816: }
1.599 albertel 10817: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 10818: }
10819:
10820: sub deversion {
10821: my $url=shift;
10822: $url=~s/\.\d+\.(\w+)$/\.$1/;
10823: return $url;
1.210 www 10824: }
10825:
1.31 www 10826: # ------------------------------------------------------ Return symb list entry
10827:
10828: sub symbread {
1.249 www 10829: my ($thisfn,$donotrecurse)=@_;
1.1206 raeburn 10830: my $cache_str;
10831: if ($thisfn ne '') {
10832: $cache_str='request.symbread.cached.'.$thisfn;
10833: if ($env{$cache_str} ne '') {
1.1179 raeburn 10834: return $env{$cache_str};
10835: }
1.1206 raeburn 10836: } else {
1.242 www 10837: # no filename provided? try from environment
1.620 albertel 10838: if ($env{'request.symb'}) {
10839: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 10840: }
1.620 albertel 10841: $thisfn=$env{'request.filename'};
1.44 www 10842: }
1.569 albertel 10843: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 10844: # is that filename actually a symb? Verify, clean, and return
10845: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 10846: if (&symbverify($thisfn,$1)) {
1.620 albertel 10847: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 10848: }
1.242 www 10849: }
1.44 www 10850: $thisfn=declutter($thisfn);
1.31 www 10851: my %hash;
1.37 www 10852: my %bighash;
10853: my $syval='';
1.620 albertel 10854: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 10855: my $targetfn = $thisfn;
1.609 banghart 10856: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 10857: $targetfn = 'adm/wrapper/'.$thisfn;
10858: }
1.687 albertel 10859: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
10860: $targetfn=$1;
10861: }
1.620 albertel 10862: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 10863: &GDBM_READER(),0640)) {
1.481 raeburn 10864: $syval=$hash{$targetfn};
1.37 www 10865: untie(%hash);
10866: }
10867: # ---------------------------------------------------------- There was an entry
10868: if ($syval) {
1.601 albertel 10869: #unless ($syval=~/\_\d+$/) {
1.620 albertel 10870: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 10871: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 10872: #return $env{$cache_str}='';
1.601 albertel 10873: #}
10874: #$syval.=$1;
10875: #}
1.37 www 10876: } else {
10877: # ------------------------------------------------------- Was not in symb table
1.620 albertel 10878: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 10879: &GDBM_READER(),0640)) {
1.37 www 10880: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 10881: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 10882: unless ($ids) {
10883: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 10884: }
10885: unless ($ids) {
10886: # alias?
10887: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 10888: }
1.37 www 10889: if ($ids) {
10890: # ------------------------------------------------------------------- Has ID(s)
10891: my @possibilities=split(/\,/,$ids);
1.39 www 10892: if ($#possibilities==0) {
10893: # ----------------------------------------------- There is only one possibility
1.37 www 10894: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 10895: $syval=&encode_symb($bighash{'map_id_'.$mapid},
10896: $resid,$thisfn);
1.249 www 10897: } elsif (!$donotrecurse) {
1.39 www 10898: # ------------------------------------------ There is more than one possibility
10899: my $realpossible=0;
1.800 albertel 10900: foreach my $id (@possibilities) {
10901: my $file=$bighash{'src_'.$id};
1.39 www 10902: if (&allowed('bre',$file)) {
1.800 albertel 10903: my ($mapid,$resid)=split(/\./,$id);
1.39 www 10904: if ($bighash{'map_type_'.$mapid} ne 'page') {
10905: $realpossible++;
1.626 albertel 10906: $syval=&encode_symb($bighash{'map_id_'.$mapid},
10907: $resid,$thisfn);
1.39 www 10908: }
10909: }
1.191 harris41 10910: }
1.39 www 10911: if ($realpossible!=1) { $syval=''; }
1.249 www 10912: } else {
10913: $syval='';
1.37 www 10914: }
10915: }
10916: untie(%bighash)
1.481 raeburn 10917: }
1.31 www 10918: }
1.62 www 10919: if ($syval) {
1.620 albertel 10920: return $env{$cache_str}=$syval;
1.62 www 10921: }
1.31 www 10922: }
1.949 raeburn 10923: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 10924: return $env{$cache_str}='';
1.31 www 10925: }
10926:
10927: # ---------------------------------------------------------- Return random seed
10928:
1.32 www 10929: sub numval {
10930: my $txt=shift;
10931: $txt=~tr/A-J/0-9/;
10932: $txt=~tr/a-j/0-9/;
10933: $txt=~tr/K-T/0-9/;
10934: $txt=~tr/k-t/0-9/;
10935: $txt=~tr/U-Z/0-5/;
10936: $txt=~tr/u-z/0-5/;
10937: $txt=~s/\D//g;
1.564 albertel 10938: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 10939: return int($txt);
1.368 albertel 10940: }
10941:
1.484 albertel 10942: sub numval2 {
10943: my $txt=shift;
10944: $txt=~tr/A-J/0-9/;
10945: $txt=~tr/a-j/0-9/;
10946: $txt=~tr/K-T/0-9/;
10947: $txt=~tr/k-t/0-9/;
10948: $txt=~tr/U-Z/0-5/;
10949: $txt=~tr/u-z/0-5/;
10950: $txt=~s/\D//g;
10951: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10952: my $total;
10953: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 10954: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 10955: return int($total);
10956: }
10957:
1.575 albertel 10958: sub numval3 {
10959: use integer;
10960: my $txt=shift;
10961: $txt=~tr/A-J/0-9/;
10962: $txt=~tr/a-j/0-9/;
10963: $txt=~tr/K-T/0-9/;
10964: $txt=~tr/k-t/0-9/;
10965: $txt=~tr/U-Z/0-5/;
10966: $txt=~tr/u-z/0-5/;
10967: $txt=~s/\D//g;
10968: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10969: my $total;
10970: foreach my $val (@txts) { $total+=$val; }
10971: if ($_64bit) { $total=(($total<<32)>>32); }
10972: return $total;
10973: }
10974:
1.675 albertel 10975: sub digest {
10976: my ($data)=@_;
10977: my $digest=&Digest::MD5::md5($data);
10978: my ($a,$b,$c,$d)=unpack("iiii",$digest);
10979: my ($e,$f);
10980: {
10981: use integer;
10982: $e=($a+$b);
10983: $f=($c+$d);
10984: if ($_64bit) {
10985: $e=(($e<<32)>>32);
10986: $f=(($f<<32)>>32);
10987: }
10988: }
10989: if (wantarray) {
10990: return ($e,$f);
10991: } else {
10992: my $g;
10993: {
10994: use integer;
10995: $g=($e+$f);
10996: if ($_64bit) {
10997: $g=(($g<<32)>>32);
10998: }
10999: }
11000: return $g;
11001: }
11002: }
11003:
1.368 albertel 11004: sub latest_rnd_algorithm_id {
1.675 albertel 11005: return '64bit5';
1.366 albertel 11006: }
1.32 www 11007:
1.503 albertel 11008: sub get_rand_alg {
11009: my ($courseid)=@_;
1.790 albertel 11010: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 11011: if ($courseid) {
1.620 albertel 11012: return $env{"course.$courseid.rndseed"};
1.503 albertel 11013: }
11014: return &latest_rnd_algorithm_id();
11015: }
11016:
1.562 albertel 11017: sub validCODE {
11018: my ($CODE)=@_;
11019: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
11020: return 0;
11021: }
11022:
1.491 albertel 11023: sub getCODE {
1.620 albertel 11024: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 11025: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
11026: defined($Apache::lonhomework::parsing_a_task) ) &&
11027: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 11028: return $Apache::lonhomework::history{'resource.CODE'};
11029: }
11030: return undef;
11031: }
1.1133 foxr 11032: #
11033: # Determines the random seed for a specific context:
11034: #
11035: # parameters:
11036: # symb - in course context the symb for the seed.
11037: # course_id - The course id of the form domain_coursenum.
11038: # domain - Domain for the user.
11039: # course - Course for the user.
11040: # cenv - environment of the course.
11041: #
11042: # NOTE:
11043: # All parameters are picked out of the environment if missing
11044: # or not defined.
11045: # If a symb cannot be determined the current time is used instead.
11046: #
11047: # For a given well defined symb, courside, domain, username,
11048: # and course environment, the seed is reproducible.
11049: #
1.31 www 11050: sub rndseed {
1.1133 foxr 11051: my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790 albertel 11052: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 11053: if (!defined($symb)) {
1.366 albertel 11054: unless ($symb=$wsymb) { return time; }
11055: }
1.1146 foxr 11056: if (!defined $courseid) {
11057: $courseid=$wcourseid;
11058: }
11059: if (!defined $domain) { $domain=$wdomain; }
11060: if (!defined $username) { $username=$wusername }
1.1133 foxr 11061:
11062: my $which;
11063: if (defined($cenv->{'rndseed'})) {
11064: $which = $cenv->{'rndseed'};
11065: } else {
11066: $which =&get_rand_alg($courseid);
11067: }
1.491 albertel 11068: if (defined(&getCODE())) {
1.1133 foxr 11069:
1.675 albertel 11070: if ($which eq '64bit5') {
11071: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
11072: } elsif ($which eq '64bit4') {
1.575 albertel 11073: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
11074: } else {
11075: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
11076: }
1.675 albertel 11077: } elsif ($which eq '64bit5') {
11078: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 11079: } elsif ($which eq '64bit4') {
11080: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 11081: } elsif ($which eq '64bit3') {
11082: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 11083: } elsif ($which eq '64bit2') {
11084: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 11085: } elsif ($which eq '64bit') {
11086: return &rndseed_64bit($symb,$courseid,$domain,$username);
11087: }
11088: return &rndseed_32bit($symb,$courseid,$domain,$username);
11089: }
11090:
11091: sub rndseed_32bit {
11092: my ($symb,$courseid,$domain,$username)=@_;
11093: {
11094: use integer;
11095: my $symbchck=unpack("%32C*",$symb) << 27;
11096: my $symbseed=numval($symb) << 22;
11097: my $namechck=unpack("%32C*",$username) << 17;
11098: my $nameseed=numval($username) << 12;
11099: my $domainseed=unpack("%32C*",$domain) << 7;
11100: my $courseseed=unpack("%32C*",$courseid);
11101: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 11102: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11103: #&logthis("rndseed :$num:$symb");
1.564 albertel 11104: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 11105: return $num;
11106: }
11107: }
11108:
11109: sub rndseed_64bit {
11110: my ($symb,$courseid,$domain,$username)=@_;
11111: {
11112: use integer;
11113: my $symbchck=unpack("%32S*",$symb) << 21;
11114: my $symbseed=numval($symb) << 10;
11115: my $namechck=unpack("%32S*",$username);
11116:
11117: my $nameseed=numval($username) << 21;
11118: my $domainseed=unpack("%32S*",$domain) << 10;
11119: my $courseseed=unpack("%32S*",$courseid);
11120:
11121: my $num1=$symbchck+$symbseed+$namechck;
11122: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11123: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11124: #&logthis("rndseed :$num:$symb");
1.564 albertel 11125: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 11126: return "$num1,$num2";
1.155 albertel 11127: }
1.366 albertel 11128: }
11129:
1.443 albertel 11130: sub rndseed_64bit2 {
11131: my ($symb,$courseid,$domain,$username)=@_;
11132: {
11133: use integer;
11134: # strings need to be an even # of cahracters long, it it is odd the
11135: # last characters gets thrown away
11136: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11137: my $symbseed=numval($symb) << 10;
11138: my $namechck=unpack("%32S*",$username.' ');
11139:
11140: my $nameseed=numval($username) << 21;
1.501 albertel 11141: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11142: my $courseseed=unpack("%32S*",$courseid.' ');
11143:
11144: my $num1=$symbchck+$symbseed+$namechck;
11145: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11146: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11147: #&logthis("rndseed :$num:$symb");
1.803 albertel 11148: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 11149: return "$num1,$num2";
11150: }
11151: }
11152:
11153: sub rndseed_64bit3 {
11154: my ($symb,$courseid,$domain,$username)=@_;
11155: {
11156: use integer;
11157: # strings need to be an even # of cahracters long, it it is odd the
11158: # last characters gets thrown away
11159: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11160: my $symbseed=numval2($symb) << 10;
11161: my $namechck=unpack("%32S*",$username.' ');
11162:
11163: my $nameseed=numval2($username) << 21;
1.443 albertel 11164: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11165: my $courseseed=unpack("%32S*",$courseid.' ');
11166:
11167: my $num1=$symbchck+$symbseed+$namechck;
11168: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11169: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11170: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 11171: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 11172:
1.503 albertel 11173: return "$num1:$num2";
1.443 albertel 11174: }
11175: }
11176:
1.575 albertel 11177: sub rndseed_64bit4 {
11178: my ($symb,$courseid,$domain,$username)=@_;
11179: {
11180: use integer;
11181: # strings need to be an even # of cahracters long, it it is odd the
11182: # last characters gets thrown away
11183: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11184: my $symbseed=numval3($symb) << 10;
11185: my $namechck=unpack("%32S*",$username.' ');
11186:
11187: my $nameseed=numval3($username) << 21;
11188: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11189: my $courseseed=unpack("%32S*",$courseid.' ');
11190:
11191: my $num1=$symbchck+$symbseed+$namechck;
11192: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11193: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11194: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 11195: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 11196:
1.575 albertel 11197: return "$num1:$num2";
11198: }
11199: }
11200:
1.675 albertel 11201: sub rndseed_64bit5 {
11202: my ($symb,$courseid,$domain,$username)=@_;
11203: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
11204: return "$num1:$num2";
11205: }
11206:
1.366 albertel 11207: sub rndseed_CODE_64bit {
11208: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 11209: {
1.366 albertel 11210: use integer;
1.443 albertel 11211: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 11212: my $symbseed=numval2($symb);
1.491 albertel 11213: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11214: my $CODEseed=numval(&getCODE());
1.443 albertel 11215: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 11216: my $num1=$symbseed+$CODEchck;
11217: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 11218: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11219: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 11220: if ($_64bit) { $num1=(($num1<<32)>>32); }
11221: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 11222: return "$num1:$num2";
1.366 albertel 11223: }
11224: }
11225:
1.575 albertel 11226: sub rndseed_CODE_64bit4 {
11227: my ($symb,$courseid,$domain,$username)=@_;
11228: {
11229: use integer;
11230: my $symbchck=unpack("%32S*",$symb.' ') << 16;
11231: my $symbseed=numval3($symb);
11232: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11233: my $CODEseed=numval3(&getCODE());
11234: my $courseseed=unpack("%32S*",$courseid.' ');
11235: my $num1=$symbseed+$CODEchck;
11236: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 11237: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11238: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 11239: if ($_64bit) { $num1=(($num1<<32)>>32); }
11240: if ($_64bit) { $num2=(($num2<<32)>>32); }
11241: return "$num1:$num2";
11242: }
11243: }
11244:
1.675 albertel 11245: sub rndseed_CODE_64bit5 {
11246: my ($symb,$courseid,$domain,$username)=@_;
11247: my $code = &getCODE();
11248: my ($num1,$num2)=&digest("$symb,$courseid,$code");
11249: return "$num1:$num2";
11250: }
11251:
1.366 albertel 11252: sub setup_random_from_rndseed {
11253: my ($rndseed)=@_;
1.503 albertel 11254: if ($rndseed =~/([,:])/) {
11255: my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366 albertel 11256: &Math::Random::random_set_seed(abs($num1),abs($num2));
11257: } else {
11258: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 11259: }
1.36 albertel 11260: }
11261:
1.474 albertel 11262: sub latest_receipt_algorithm_id {
1.835 albertel 11263: return 'receipt3';
1.474 albertel 11264: }
11265:
1.480 www 11266: sub recunique {
11267: my $fucourseid=shift;
11268: my $unique;
1.835 albertel 11269: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
11270: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 11271: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 11272: } else {
11273: $unique=$perlvar{'lonReceipt'};
11274: }
11275: return unpack("%32C*",$unique);
11276: }
11277:
11278: sub recprefix {
11279: my $fucourseid=shift;
11280: my $prefix;
1.835 albertel 11281: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
11282: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 11283: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 11284: } else {
11285: $prefix=$perlvar{'lonHostID'};
11286: }
11287: return unpack("%32C*",$prefix);
11288: }
11289:
1.76 www 11290: sub ireceipt {
1.474 albertel 11291: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 11292:
11293: my $return =&recprefix($fucourseid).'-';
11294:
11295: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
11296: $env{'request.state'} eq 'construct') {
11297: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
11298: return $return;
11299: }
11300:
1.76 www 11301: my $cuname=unpack("%32C*",$funame);
11302: my $cudom=unpack("%32C*",$fudom);
11303: my $cucourseid=unpack("%32C*",$fucourseid);
11304: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 11305: my $cunique=&recunique($fucourseid);
1.474 albertel 11306: my $cpart=unpack("%32S*",$part);
1.835 albertel 11307: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
11308:
1.790 albertel 11309: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 11310:
11311: $return.= ($cunique%$cuname+
11312: $cunique%$cudom+
11313: $cusymb%$cuname+
11314: $cusymb%$cudom+
11315: $cucourseid%$cuname+
11316: $cucourseid%$cudom+
11317: $cpart%$cuname+
11318: $cpart%$cudom);
11319: } else {
11320: $return.= ($cunique%$cuname+
11321: $cunique%$cudom+
11322: $cusymb%$cuname+
11323: $cusymb%$cudom+
11324: $cucourseid%$cuname+
11325: $cucourseid%$cudom);
11326: }
11327: return $return;
1.76 www 11328: }
11329:
11330: sub receipt {
1.474 albertel 11331: my ($part)=@_;
1.790 albertel 11332: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 11333: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 11334: }
1.260 ng 11335:
1.790 albertel 11336: sub whichuser {
11337: my ($passedsymb)=@_;
11338: my ($symb,$courseid,$domain,$name,$publicuser);
11339: if (defined($env{'form.grade_symb'})) {
11340: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
11341: my $allowed=&allowed('vgr',$tmp_courseid);
11342: if (!$allowed &&
11343: exists($env{'request.course.sec'}) &&
11344: $env{'request.course.sec'} !~ /^\s*$/) {
11345: $allowed=&allowed('vgr',$tmp_courseid.
11346: '/'.$env{'request.course.sec'});
11347: }
11348: if ($allowed) {
11349: ($symb)=&get_env_multiple('form.grade_symb');
11350: $courseid=$tmp_courseid;
11351: ($domain)=&get_env_multiple('form.grade_domain');
11352: ($name)=&get_env_multiple('form.grade_username');
11353: return ($symb,$courseid,$domain,$name,$publicuser);
11354: }
11355: }
11356: if (!$passedsymb) {
11357: $symb=&symbread();
11358: } else {
11359: $symb=$passedsymb;
11360: }
11361: $courseid=$env{'request.course.id'};
11362: $domain=$env{'user.domain'};
11363: $name=$env{'user.name'};
11364: if ($name eq 'public' && $domain eq 'public') {
11365: if (!defined($env{'form.username'})) {
11366: $env{'form.username'}.=time.rand(10000000);
11367: }
11368: $name.=$env{'form.username'};
11369: }
11370: return ($symb,$courseid,$domain,$name,$publicuser);
11371:
11372: }
11373:
1.36 albertel 11374: # ------------------------------------------------------------ Serves up a file
1.472 albertel 11375: # returns either the contents of the file or
11376: # -1 if the file doesn't exist
1.481 raeburn 11377: #
11378: # if the target is a file that was uploaded via DOCS,
11379: # a check will be made to see if a current copy exists on the local server,
11380: # if it does this will be served, otherwise a copy will be retrieved from
11381: # the home server for the course and stored in /home/httpd/html/userfiles on
11382: # the local server.
1.472 albertel 11383:
1.36 albertel 11384: sub getfile {
1.538 albertel 11385: my ($file) = @_;
1.609 banghart 11386: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 11387: &repcopy($file);
11388: return &readfile($file);
11389: }
11390:
11391: sub repcopy_userfile {
11392: my ($file)=@_;
1.1142 raeburn 11393: my $londocroot = $perlvar{'lonDocRoot'};
11394: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164 raeburn 11395: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538 albertel 11396: my ($cdom,$cnum,$filename) =
1.811 albertel 11397: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 11398: my $uri="/uploaded/$cdom/$cnum/$filename";
11399: if (-e "$file") {
1.828 www 11400: # we already have a local copy, check it out
1.538 albertel 11401: my @fileinfo = stat($file);
1.828 www 11402: my $rtncode;
11403: my $info;
1.538 albertel 11404: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 11405: if ($lwpresp ne 'ok') {
1.828 www 11406: # there is no such file anymore, even though we had a local copy
1.482 albertel 11407: if ($rtncode eq '404') {
1.538 albertel 11408: unlink($file);
1.482 albertel 11409: }
11410: return -1;
11411: }
11412: if ($info < $fileinfo[9]) {
1.828 www 11413: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 11414: return 'ok';
1.828 www 11415: } else {
11416: # the file is outdated, get rid of it
11417: unlink($file);
1.482 albertel 11418: }
1.828 www 11419: }
11420: # one way or the other, at this point, we don't have the file
11421: # construct the correct path for the file
11422: my @parts = ($cdom,$cnum);
11423: if ($filename =~ m|^(.+)/[^/]+$|) {
11424: push @parts, split(/\//,$1);
11425: }
11426: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
11427: foreach my $part (@parts) {
11428: $path .= '/'.$part;
11429: if (!-e $path) {
11430: mkdir($path,0770);
1.482 albertel 11431: }
11432: }
1.828 www 11433: # now the path exists for sure
11434: # get a user agent
11435: my $ua=new LWP::UserAgent;
11436: my $transferfile=$file.'.in.transfer';
11437: # FIXME: this should flock
11438: if (-e $transferfile) { return 'ok'; }
11439: my $request;
11440: $uri=~s/^\///;
1.980 raeburn 11441: my $homeserver = &homeserver($cnum,$cdom);
11442: my $protocol = $protocol{$homeserver};
11443: $protocol = 'http' if ($protocol ne 'https');
11444: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 11445: my $response=$ua->request($request,$transferfile);
11446: # did it work?
11447: if ($response->is_error()) {
11448: unlink($transferfile);
11449: &logthis("Userfile repcopy failed for $uri");
11450: return -1;
11451: }
11452: # worked, rename the transfer file
11453: rename($transferfile,$file);
1.607 raeburn 11454: return 'ok';
1.481 raeburn 11455: }
11456:
1.517 albertel 11457: sub tokenwrapper {
11458: my $uri=shift;
1.980 raeburn 11459: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 11460: $uri=~s|^/||;
1.620 albertel 11461: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 11462: my $token=$1;
1.552 albertel 11463: my (undef,$udom,$uname,$file)=split('/',$uri,4);
11464: if ($udom && $uname && $file) {
11465: $file=~s|(\?\.*)*$||;
1.949 raeburn 11466: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 11467: my $homeserver = &homeserver($uname,$udom);
11468: my $protocol = $protocol{$homeserver};
11469: $protocol = 'http' if ($protocol ne 'https');
11470: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 11471: (($uri=~/\?/)?'&':'?').'token='.$token.
11472: '&tokenissued='.$perlvar{'lonHostID'};
11473: } else {
11474: return '/adm/notfound.html';
11475: }
11476: }
11477:
1.828 www 11478: # call with reqtype HEAD: get last modification time
11479: # call with reqtype GET: get the file contents
11480: # Do not call this with reqtype GET for large files! It loads everything into memory
11481: #
1.481 raeburn 11482: sub getuploaded {
11483: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
11484: $uri=~s/^\///;
1.980 raeburn 11485: my $homeserver = &homeserver($cnum,$cdom);
11486: my $protocol = $protocol{$homeserver};
11487: $protocol = 'http' if ($protocol ne 'https');
11488: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 11489: my $ua=new LWP::UserAgent;
11490: my $request=new HTTP::Request($reqtype,$uri);
11491: my $response=$ua->request($request);
11492: $$rtncode = $response->code;
1.482 albertel 11493: if (! $response->is_success()) {
11494: return 'failed';
11495: }
11496: if ($reqtype eq 'HEAD') {
1.486 www 11497: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 11498: } elsif ($reqtype eq 'GET') {
11499: $$info = $response->content;
1.472 albertel 11500: }
1.482 albertel 11501: return 'ok';
1.36 albertel 11502: }
11503:
1.481 raeburn 11504: sub readfile {
11505: my $file = shift;
11506: if ( (! -e $file ) || ($file eq '') ) { return -1; };
11507: my $fh;
11508: open($fh,"<$file");
11509: my $a='';
1.800 albertel 11510: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 11511: return $a;
11512: }
11513:
1.36 albertel 11514: sub filelocation {
1.590 banghart 11515: my ($dir,$file) = @_;
11516: my $location;
11517: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 11518:
11519: if ($file =~ m-^/adm/-) {
11520: $file=~s-^/adm/wrapper/-/-;
11521: $file=~s-^/adm/coursedocs/showdoc/-/-;
11522: }
1.882 albertel 11523:
1.1139 www 11524: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956 raeburn 11525: $location = $file;
1.609 banghart 11526: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 11527: my ($udom,$uname,$filename)=
1.811 albertel 11528: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 11529: my $home=&homeserver($uname,$udom);
11530: my $is_me=0;
11531: my @ids=¤t_machine_ids();
11532: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
11533: if ($is_me) {
1.1117 foxr 11534: $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 11535: } else {
11536: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
11537: $udom.'/'.$uname.'/'.$filename;
11538: }
1.882 albertel 11539: } elsif ($file =~ m-^/adm/-) {
11540: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 11541: } else {
11542: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139 www 11543: $file=~s:^/(res|priv)/:/:;
11544: my $space=$1;
1.590 banghart 11545: if ( !( $file =~ m:^/:) ) {
11546: $location = $dir. '/'.$file;
11547: } else {
1.1142 raeburn 11548: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590 banghart 11549: }
1.59 albertel 11550: }
1.590 banghart 11551: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 11552: while ($location=~m{/\.\./}) {
11553: if ($location =~ m{/[^/]+/\.\./}) {
11554: $location=~ s{/[^/]+/\.\./}{/}g;
11555: } else {
11556: $location=~ s{/\.\./}{/}g;
11557: }
11558: } #remove dir/..
1.590 banghart 11559: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
11560: return $location;
1.46 www 11561: }
1.36 albertel 11562:
1.46 www 11563: sub hreflocation {
11564: my ($dir,$file)=@_;
1.980 raeburn 11565: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 11566: $file=filelocation($dir,$file);
1.700 albertel 11567: } elsif ($file=~m-^/adm/-) {
11568: $file=~s-^/adm/wrapper/-/-;
11569: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 11570: }
11571: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
11572: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
11573: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143 raeburn 11574: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
11575: {/uploaded/$1/$2/}x;
1.46 www 11576: }
1.913 albertel 11577: if ($file=~ m{^/userfiles/}) {
11578: $file =~ s{^/userfiles/}{/uploaded/};
11579: }
1.462 albertel 11580: return $file;
1.465 albertel 11581: }
11582:
1.1139 www 11583:
11584:
11585:
11586:
1.465 albertel 11587: sub current_machine_domains {
1.853 albertel 11588: return &machine_domains(&hostname($perlvar{'lonHostID'}));
11589: }
11590:
11591: sub machine_domains {
11592: my ($hostname) = @_;
1.465 albertel 11593: my @domains;
1.838 albertel 11594: my %hostname = &all_hostnames();
1.465 albertel 11595: while( my($id, $name) = each(%hostname)) {
1.467 matthew 11596: # &logthis("-$id-$name-$hostname-");
1.465 albertel 11597: if ($hostname eq $name) {
1.844 albertel 11598: push(@domains,&host_domain($id));
1.465 albertel 11599: }
11600: }
11601: return @domains;
11602: }
11603:
11604: sub current_machine_ids {
1.853 albertel 11605: return &machine_ids(&hostname($perlvar{'lonHostID'}));
11606: }
11607:
11608: sub machine_ids {
11609: my ($hostname) = @_;
11610: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 11611: my @ids;
1.888 albertel 11612: my %name_to_host = &all_names();
1.889 albertel 11613: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
11614: return @{ $name_to_host{$hostname} };
11615: }
11616: return;
1.31 www 11617: }
11618:
1.824 raeburn 11619: sub additional_machine_domains {
11620: my @domains;
11621: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
11622: while( my $line = <$fh>) {
11623: $line =~ s/\s//g;
11624: push(@domains,$line);
11625: }
11626: return @domains;
11627: }
11628:
11629: sub default_login_domain {
11630: my $domain = $perlvar{'lonDefDomain'};
11631: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
11632: foreach my $posdom (¤t_machine_domains(),
11633: &additional_machine_domains()) {
11634: if (lc($posdom) eq lc($testdomain)) {
11635: $domain=$posdom;
11636: last;
11637: }
11638: }
11639: return $domain;
11640: }
11641:
1.31 www 11642: # ------------------------------------------------------------- Declutters URLs
11643:
11644: sub declutter {
11645: my $thisfn=shift;
1.569 albertel 11646: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479 albertel 11647: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31 www 11648: $thisfn=~s/^\///;
1.697 albertel 11649: $thisfn=~s|^adm/wrapper/||;
11650: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 11651: $thisfn=~s/^res\///;
1.1172 bisitz 11652: $thisfn=~s/^priv\///;
1.1032 raeburn 11653: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
11654: $thisfn=~s/\?.+$//;
11655: }
1.268 www 11656: return $thisfn;
11657: }
11658:
11659: # ------------------------------------------------------------- Clutter up URLs
11660:
11661: sub clutter {
11662: my $thisfn='/'.&declutter(shift);
1.887 albertel 11663: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 11664: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 11665: $thisfn='/res'.$thisfn;
11666: }
1.1031 raeburn 11667: if ($thisfn !~m|^/adm|) {
11668: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 11669: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 11670: } else {
11671: my ($ext) = ($thisfn =~ /\.(\w+)$/);
11672: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 11673: if ($embstyle eq 'ssi'
11674: || ($embstyle eq 'hdn')
11675: || ($embstyle eq 'rat')
11676: || ($embstyle eq 'prv')
11677: || ($embstyle eq 'ign')) {
11678: #do nothing with these
11679: } elsif (($embstyle eq 'img')
1.695 albertel 11680: || ($embstyle eq 'emb')
11681: || ($embstyle eq 'wrp')) {
11682: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 11683: } elsif ($embstyle eq 'unk'
11684: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 11685: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 11686: } else {
1.718 www 11687: # &logthis("Got a blank emb style");
1.695 albertel 11688: }
1.694 albertel 11689: }
11690: }
1.31 www 11691: return $thisfn;
1.12 www 11692: }
11693:
1.787 albertel 11694: sub clutter_with_no_wrapper {
11695: my $uri = &clutter(shift);
11696: if ($uri =~ m-^/adm/-) {
11697: $uri =~ s-^/adm/wrapper/-/-;
11698: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
11699: }
11700: return $uri;
11701: }
11702:
1.557 albertel 11703: sub freeze_escape {
11704: my ($value)=@_;
11705: if (ref($value)) {
11706: $value=&nfreeze($value);
11707: return '__FROZEN__'.&escape($value);
11708: }
11709: return &escape($value);
11710: }
11711:
1.11 www 11712:
1.557 albertel 11713: sub thaw_unescape {
11714: my ($value)=@_;
11715: if ($value =~ /^__FROZEN__/) {
11716: substr($value,0,10,undef);
11717: $value=&unescape($value);
11718: return &thaw($value);
11719: }
11720: return &unescape($value);
11721: }
11722:
1.436 albertel 11723: sub correct_line_ends {
11724: my ($result)=@_;
11725: $$result =~s/\r\n/\n/mg;
11726: $$result =~s/\r/\n/mg;
1.415 albertel 11727: }
1.1 albertel 11728: # ================================================================ Main Program
11729:
1.184 www 11730: sub goodbye {
1.204 albertel 11731: &logthis("Starting Shut down");
1.443 albertel 11732: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 11733: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 11734: #converted
1.599 albertel 11735: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 11736: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
11737: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
11738: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 11739: #1.1 only
1.870 albertel 11740: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
11741: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
11742: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
11743: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
11744: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 11745: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
11746: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 11747: &flushcourselogs();
11748: &logthis("Shutting down");
11749: }
11750:
1.852 albertel 11751: sub get_dns {
1.1210 raeburn 11752: my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869 albertel 11753: if (!$ignore_cache) {
11754: my ($content,$cached)=
11755: &Apache::lonnet::is_cached_new('dns',$url);
11756: if ($cached) {
1.1210 raeburn 11757: &$func($content,$hashref);
1.869 albertel 11758: return;
11759: }
11760: }
11761:
11762: my %alldns;
1.852 albertel 11763: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11764: foreach my $dns (<$config>) {
11765: next if ($dns !~ /^\^(\S*)/x);
1.979 raeburn 11766: my $line = $1;
11767: my ($host,$protocol) = split(/:/,$line);
11768: if ($protocol ne 'https') {
11769: $protocol = 'http';
11770: }
11771: $alldns{$host} = $protocol;
1.869 albertel 11772: }
11773: while (%alldns) {
11774: my ($dns) = keys(%alldns);
1.852 albertel 11775: my $ua=new LWP::UserAgent;
1.1134 raeburn 11776: $ua->timeout(30);
1.979 raeburn 11777: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 11778: my $response=$ua->request($request);
1.979 raeburn 11779: delete($alldns{$dns});
1.852 albertel 11780: next if ($response->is_error());
11781: my @content = split("\n",$response->content);
1.1210 raeburn 11782: unless ($nocache) {
1.1219 raeburn 11783: &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1210 raeburn 11784: }
11785: &$func(\@content,$hashref);
1.869 albertel 11786: return;
1.852 albertel 11787: }
11788: close($config);
1.871 albertel 11789: my $which = (split('/',$url))[3];
11790: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
11791: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 11792: my @content = <$config>;
1.1210 raeburn 11793: &$func(\@content,$hashref);
11794: return;
11795: }
11796:
11797: # ------------------------------------------------------Get DNS checksums file
1.1211 raeburn 11798: sub parse_dns_checksums_tab {
1.1210 raeburn 11799: my ($lines,$hashref) = @_;
11800: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
11801: my $loncaparev = &get_server_loncaparev($machine_dom);
11802: my ($release,$timestamp) = split(/\-/,$loncaparev);
11803: my (%chksum,%revnum);
11804: if (ref($lines) eq 'ARRAY') {
11805: chomp(@{$lines});
1.1238 raeburn 11806: my $version = shift(@{$lines});
11807: if ($version eq $release) {
1.1210 raeburn 11808: foreach my $line (@{$lines}) {
1.1238 raeburn 11809: my ($file,$version,$shasum) = split(/,/,$line);
11810: $chksum{$file} = $shasum;
11811: $revnum{$file} = $version;
1.1210 raeburn 11812: }
11813: if (ref($hashref) eq 'HASH') {
11814: %{$hashref} = (
11815: sums => \%chksum,
11816: versions => \%revnum,
11817: );
11818: }
11819: }
11820: }
1.869 albertel 11821: return;
1.852 albertel 11822: }
1.1210 raeburn 11823:
11824: sub fetch_dns_checksums {
1.1238 raeburn 11825: my %checksums;
11826: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
11827: my $loncaparev = &get_server_loncaparev($machine_dom);
11828: my ($release,$timestamp) = split(/\-/,$loncaparev);
11829: &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1211 raeburn 11830: \%checksums);
1.1210 raeburn 11831: return \%checksums;
11832: }
11833:
1.327 albertel 11834: # ------------------------------------------------------------ Read domain file
11835: {
1.852 albertel 11836: my $loaded;
1.846 albertel 11837: my %domain;
11838:
1.852 albertel 11839: sub parse_domain_tab {
11840: my ($lines) = @_;
11841: foreach my $line (@$lines) {
11842: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 11843:
1.846 albertel 11844: chomp($line);
1.852 albertel 11845: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 11846: my %this_domain;
11847: foreach my $field ('description', 'auth_def', 'auth_arg_def',
11848: 'lang_def', 'city', 'longi', 'lati',
11849: 'primary') {
11850: $this_domain{$field} = shift(@elements);
11851: }
11852: $domain{$name} = \%this_domain;
1.852 albertel 11853: }
11854: }
1.864 albertel 11855:
11856: sub reset_domain_info {
11857: undef($loaded);
11858: undef(%domain);
11859: }
11860:
1.852 albertel 11861: sub load_domain_tab {
1.869 albertel 11862: my ($ignore_cache) = @_;
11863: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852 albertel 11864: my $fh;
11865: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
11866: my @lines = <$fh>;
11867: &parse_domain_tab(\@lines);
1.448 albertel 11868: }
1.852 albertel 11869: close($fh);
11870: $loaded = 1;
1.327 albertel 11871: }
1.846 albertel 11872:
11873: sub domain {
1.852 albertel 11874: &load_domain_tab() if (!$loaded);
11875:
1.846 albertel 11876: my ($name,$what) = @_;
11877: return if ( !exists($domain{$name}) );
11878:
11879: if (!$what) {
11880: return $domain{$name}{'description'};
11881: }
11882: return $domain{$name}{$what};
11883: }
1.974 raeburn 11884:
11885: sub domain_info {
11886: &load_domain_tab() if (!$loaded);
11887: return %domain;
11888: }
11889:
1.327 albertel 11890: }
11891:
11892:
1.1 albertel 11893: # ------------------------------------------------------------- Read hosts file
11894: {
1.838 albertel 11895: my %hostname;
1.844 albertel 11896: my %hostdom;
1.845 albertel 11897: my %libserv;
1.852 albertel 11898: my $loaded;
1.888 albertel 11899: my %name_to_host;
1.1074 raeburn 11900: my %internetdom;
1.1107 raeburn 11901: my %LC_dns_serv;
1.852 albertel 11902:
11903: sub parse_hosts_tab {
11904: my ($file) = @_;
11905: foreach my $configline (@$file) {
11906: next if ($configline =~ /^(\#|\s*$ )/x);
1.1107 raeburn 11907: chomp($configline);
11908: if ($configline =~ /^\^/) {
11909: if ($configline =~ /^\^([\w.\-]+)/) {
11910: $LC_dns_serv{$1} = 1;
11911: }
11912: next;
11913: }
1.1074 raeburn 11914: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 11915: $name=~s/\s//g;
11916: if ($id && $domain && $role && $name) {
11917: $hostname{$id}=$name;
1.888 albertel 11918: push(@{$name_to_host{$name}}, $id);
1.852 albertel 11919: $hostdom{$id}=$domain;
11920: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 11921: if (defined($protocol)) {
11922: if ($protocol eq 'https') {
11923: $protocol{$id} = $protocol;
11924: } else {
11925: $protocol{$id} = 'http';
11926: }
1.968 raeburn 11927: } else {
1.969 raeburn 11928: $protocol{$id} = 'http';
1.968 raeburn 11929: }
1.1074 raeburn 11930: if (defined($intdom)) {
11931: $internetdom{$id} = $intdom;
11932: }
1.852 albertel 11933: }
11934: }
11935: }
1.864 albertel 11936:
11937: sub reset_hosts_info {
1.897 albertel 11938: &purge_remembered();
1.864 albertel 11939: &reset_domain_info();
11940: &reset_hosts_ip_info();
1.892 albertel 11941: undef(%name_to_host);
1.864 albertel 11942: undef(%hostname);
11943: undef(%hostdom);
11944: undef(%libserv);
11945: undef($loaded);
11946: }
1.1 albertel 11947:
1.852 albertel 11948: sub load_hosts_tab {
1.869 albertel 11949: my ($ignore_cache) = @_;
11950: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852 albertel 11951: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11952: my @config = <$config>;
11953: &parse_hosts_tab(\@config);
11954: close($config);
11955: $loaded=1;
1.1 albertel 11956: }
1.852 albertel 11957:
1.838 albertel 11958: sub hostname {
1.852 albertel 11959: &load_hosts_tab() if (!$loaded);
11960:
1.838 albertel 11961: my ($lonid) = @_;
11962: return $hostname{$lonid};
11963: }
1.845 albertel 11964:
1.838 albertel 11965: sub all_hostnames {
1.852 albertel 11966: &load_hosts_tab() if (!$loaded);
11967:
1.838 albertel 11968: return %hostname;
11969: }
1.845 albertel 11970:
1.888 albertel 11971: sub all_names {
11972: &load_hosts_tab() if (!$loaded);
11973:
11974: return %name_to_host;
11975: }
11976:
1.974 raeburn 11977: sub all_host_domain {
11978: &load_hosts_tab() if (!$loaded);
11979: return %hostdom;
11980: }
11981:
1.845 albertel 11982: sub is_library {
1.852 albertel 11983: &load_hosts_tab() if (!$loaded);
11984:
1.845 albertel 11985: return exists($libserv{$_[0]});
11986: }
11987:
11988: sub all_library {
1.852 albertel 11989: &load_hosts_tab() if (!$loaded);
11990:
1.845 albertel 11991: return %libserv;
11992: }
11993:
1.1062 droeschl 11994: sub unique_library {
11995: #2x reverse removes all hostnames that appear more than once
11996: my %unique = reverse &all_library();
11997: return reverse %unique;
11998: }
11999:
1.841 albertel 12000: sub get_servers {
1.852 albertel 12001: &load_hosts_tab() if (!$loaded);
12002:
1.841 albertel 12003: my ($domain,$type) = @_;
12004: my %possible_hosts = ($type eq 'library') ? %libserv
12005: : %hostname;
12006: my %result;
1.842 albertel 12007: if (ref($domain) eq 'ARRAY') {
12008: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 12009: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 12010: $result{$host} = $hostname;
12011: }
12012: }
12013: } else {
12014: while ( my ($host,$hostname) = each(%possible_hosts)) {
12015: if ($hostdom{$host} eq $domain) {
12016: $result{$host} = $hostname;
12017: }
1.841 albertel 12018: }
12019: }
12020: return %result;
12021: }
1.845 albertel 12022:
1.1062 droeschl 12023: sub get_unique_servers {
12024: my %unique = reverse &get_servers(@_);
12025: return reverse %unique;
12026: }
12027:
1.844 albertel 12028: sub host_domain {
1.852 albertel 12029: &load_hosts_tab() if (!$loaded);
12030:
1.844 albertel 12031: my ($lonid) = @_;
12032: return $hostdom{$lonid};
12033: }
12034:
1.841 albertel 12035: sub all_domains {
1.852 albertel 12036: &load_hosts_tab() if (!$loaded);
12037:
1.841 albertel 12038: my %seen;
12039: my @uniq = grep(!$seen{$_}++, values(%hostdom));
12040: return @uniq;
12041: }
1.1074 raeburn 12042:
12043: sub internet_dom {
12044: &load_hosts_tab() if (!$loaded);
12045:
12046: my ($lonid) = @_;
12047: return $internetdom{$lonid};
12048: }
1.1107 raeburn 12049:
12050: sub is_LC_dns {
12051: &load_hosts_tab() if (!$loaded);
12052:
12053: my ($hostname) = @_;
12054: return exists($LC_dns_serv{$hostname});
12055: }
12056:
1.1 albertel 12057: }
12058:
1.847 albertel 12059: {
12060: my %iphost;
1.856 albertel 12061: my %name_to_ip;
12062: my %lonid_to_ip;
1.869 albertel 12063:
1.847 albertel 12064: sub get_hosts_from_ip {
12065: my ($ip) = @_;
12066: my %iphosts = &get_iphost();
12067: if (ref($iphosts{$ip})) {
12068: return @{$iphosts{$ip}};
12069: }
12070: return;
1.839 albertel 12071: }
1.864 albertel 12072:
12073: sub reset_hosts_ip_info {
12074: undef(%iphost);
12075: undef(%name_to_ip);
12076: undef(%lonid_to_ip);
12077: }
1.856 albertel 12078:
12079: sub get_host_ip {
12080: my ($lonid) = @_;
12081: if (exists($lonid_to_ip{$lonid})) {
12082: return $lonid_to_ip{$lonid};
12083: }
12084: my $name=&hostname($lonid);
12085: my $ip = gethostbyname($name);
12086: return if (!$ip || length($ip) ne 4);
12087: $ip=inet_ntoa($ip);
12088: $name_to_ip{$name} = $ip;
12089: $lonid_to_ip{$lonid} = $ip;
12090: return $ip;
12091: }
1.847 albertel 12092:
12093: sub get_iphost {
1.869 albertel 12094: my ($ignore_cache) = @_;
1.894 albertel 12095:
1.869 albertel 12096: if (!$ignore_cache) {
12097: if (%iphost) {
12098: return %iphost;
12099: }
12100: my ($ip_info,$cached)=
12101: &Apache::lonnet::is_cached_new('iphost','iphost');
12102: if ($cached) {
12103: %iphost = %{$ip_info->[0]};
12104: %name_to_ip = %{$ip_info->[1]};
12105: %lonid_to_ip = %{$ip_info->[2]};
12106: return %iphost;
12107: }
12108: }
1.894 albertel 12109:
12110: # get yesterday's info for fallback
12111: my %old_name_to_ip;
12112: my ($ip_info,$cached)=
12113: &Apache::lonnet::is_cached_new('iphost','iphost');
12114: if ($cached) {
12115: %old_name_to_ip = %{$ip_info->[1]};
12116: }
12117:
1.888 albertel 12118: my %name_to_host = &all_names();
12119: foreach my $name (keys(%name_to_host)) {
1.847 albertel 12120: my $ip;
12121: if (!exists($name_to_ip{$name})) {
12122: $ip = gethostbyname($name);
12123: if (!$ip || length($ip) ne 4) {
1.894 albertel 12124: if (defined($old_name_to_ip{$name})) {
12125: $ip = $old_name_to_ip{$name};
12126: &logthis("Can't find $name defaulting to old $ip");
12127: } else {
12128: &logthis("Name $name no IP found");
12129: next;
12130: }
12131: } else {
12132: $ip=inet_ntoa($ip);
1.847 albertel 12133: }
12134: $name_to_ip{$name} = $ip;
12135: } else {
12136: $ip = $name_to_ip{$name};
1.653 albertel 12137: }
1.888 albertel 12138: foreach my $id (@{ $name_to_host{$name} }) {
12139: $lonid_to_ip{$id} = $ip;
12140: }
12141: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 12142: }
1.1219 raeburn 12143: &do_cache_new('iphost','iphost',
12144: [\%iphost,\%name_to_ip,\%lonid_to_ip],
12145: 48*60*60);
1.869 albertel 12146:
1.847 albertel 12147: return %iphost;
1.598 albertel 12148: }
12149:
1.992 raeburn 12150: #
12151: # Given a DNS returns the loncapa host name for that DNS
12152: #
12153: sub host_from_dns {
12154: my ($dns) = @_;
12155: my @hosts;
12156: my $ip;
12157:
1.993 raeburn 12158: if (exists($name_to_ip{$dns})) {
1.992 raeburn 12159: $ip = $name_to_ip{$dns};
12160: }
12161: if (!$ip) {
12162: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
12163: if (length($ip) == 4) {
12164: $ip = &IO::Socket::inet_ntoa($ip);
12165: }
12166: }
12167: if ($ip) {
12168: @hosts = get_hosts_from_ip($ip);
12169: return $hosts[0];
12170: }
12171: return undef;
1.986 foxr 12172: }
1.992 raeburn 12173:
1.1074 raeburn 12174: sub get_internet_names {
12175: my ($lonid) = @_;
12176: return if ($lonid eq '');
12177: my ($idnref,$cached)=
12178: &Apache::lonnet::is_cached_new('internetnames',$lonid);
12179: if ($cached) {
12180: return $idnref;
12181: }
12182: my $ip = &get_host_ip($lonid);
12183: my @hosts = &get_hosts_from_ip($ip);
12184: my %iphost = &get_iphost();
12185: my (@idns,%seen);
12186: foreach my $id (@hosts) {
12187: my $dom = &host_domain($id);
12188: my $prim_id = &domain($dom,'primary');
12189: my $prim_ip = &get_host_ip($prim_id);
12190: next if ($seen{$prim_ip});
12191: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
12192: foreach my $id (@{$iphost{$prim_ip}}) {
12193: my $intdom = &internet_dom($id);
12194: unless (grep(/^\Q$intdom\E$/,@idns)) {
12195: push(@idns,$intdom);
12196: }
12197: }
12198: }
12199: $seen{$prim_ip} = 1;
12200: }
1.1219 raeburn 12201: return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074 raeburn 12202: }
12203:
1.986 foxr 12204: }
12205:
1.1079 raeburn 12206: sub all_loncaparevs {
1.1249 raeburn 12207: 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 12208: }
12209:
1.1227 raeburn 12210: # ---------------------------------------------------------- Read loncaparev table
12211: {
12212: sub load_loncaparevs {
12213: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
12214: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
12215: while (my $configline=<$config>) {
12216: chomp($configline);
12217: my ($hostid,$loncaparev)=split(/:/,$configline);
12218: $loncaparevs{$hostid}=$loncaparev;
12219: }
12220: close($config);
12221: }
12222: }
12223: }
12224: }
12225:
12226: # ---------------------------------------------------------- Read serverhostID table
12227: {
12228: sub load_serverhomeIDs {
12229: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
12230: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
12231: while (my $configline=<$config>) {
12232: chomp($configline);
12233: my ($name,$id)=split(/:/,$configline);
12234: $serverhomeIDs{$name}=$id;
12235: }
12236: close($config);
12237: }
12238: }
12239: }
12240: }
12241:
12242:
1.862 albertel 12243: BEGIN {
12244:
12245: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
12246: unless ($readit) {
12247: {
12248: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
12249: %perlvar = (%perlvar,%{$configvars});
12250: }
12251:
12252:
1.1 albertel 12253: # ------------------------------------------------------ Read spare server file
12254: {
1.448 albertel 12255: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 12256:
12257: while (my $configline=<$config>) {
12258: chomp($configline);
1.284 matthew 12259: if ($configline) {
1.784 albertel 12260: my ($host,$type) = split(':',$configline,2);
1.785 albertel 12261: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 12262: push(@{ $spareid{$type} }, $host);
1.1 albertel 12263: }
12264: }
1.448 albertel 12265: close($config);
1.1 albertel 12266: }
1.11 www 12267: # ------------------------------------------------------------ Read permissions
12268: {
1.448 albertel 12269: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 12270:
12271: while (my $configline=<$config>) {
1.448 albertel 12272: chomp($configline);
12273: if ($configline) {
12274: my ($role,$perm)=split(/ /,$configline);
12275: if ($perm ne '') { $pr{$role}=$perm; }
12276: }
1.11 www 12277: }
1.448 albertel 12278: close($config);
1.11 www 12279: }
12280:
12281: # -------------------------------------------- Read plain texts for permissions
12282: {
1.448 albertel 12283: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 12284:
12285: while (my $configline=<$config>) {
1.448 albertel 12286: chomp($configline);
12287: if ($configline) {
1.742 raeburn 12288: my ($short,@plain)=split(/:/,$configline);
12289: %{$prp{$short}} = ();
12290: if (@plain > 0) {
12291: $prp{$short}{'std'} = $plain[0];
12292: for (my $i=1; $i<@plain; $i++) {
12293: $prp{$short}{'alt'.$i} = $plain[$i];
12294: }
12295: }
1.448 albertel 12296: }
1.135 www 12297: }
1.448 albertel 12298: close($config);
1.135 www 12299: }
12300:
12301: # ---------------------------------------------------------- Read package table
12302: {
1.448 albertel 12303: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 12304:
12305: while (my $configline=<$config>) {
1.483 albertel 12306: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 12307: chomp($configline);
12308: my ($short,$plain)=split(/:/,$configline);
12309: my ($pack,$name)=split(/\&/,$short);
12310: if ($plain ne '') {
12311: $packagetab{$pack.'&'.$name.'&name'}=$name;
12312: $packagetab{$short}=$plain;
12313: }
1.11 www 12314: }
1.448 albertel 12315: close($config);
1.329 matthew 12316: }
12317:
1.1073 raeburn 12318: # ---------------------------------------------------------- Read loncaparev table
1.1227 raeburn 12319:
12320: &load_loncaparevs();
1.1073 raeburn 12321:
1.1074 raeburn 12322: # ---------------------------------------------------------- Read serverhostID table
12323:
1.1227 raeburn 12324: &load_serverhomeIDs();
12325:
12326: # ---------------------------------------------------------- Read releaseslist XML
1.1079 raeburn 12327: {
12328: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
12329: if (-e $file) {
12330: my $parser = HTML::LCParser->new($file);
12331: while (my $token = $parser->get_token()) {
12332: if ($token->[0] eq 'S') {
12333: my $item = $token->[1];
12334: my $name = $token->[2]{'name'};
12335: my $value = $token->[2]{'value'};
12336: if ($item ne '' && $name ne '' && $value ne '') {
12337: my $release = $parser->get_text();
12338: $release =~ s/(^\s*|\s*$ )//gx;
12339: $needsrelease{$item.':'.$name.':'.$value} = $release;
12340: }
12341: }
12342: }
12343: }
1.1073 raeburn 12344: }
12345:
1.1138 raeburn 12346: # ---------------------------------------------------------- Read managers table
12347: {
12348: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
12349: if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
12350: while (my $configline=<$config>) {
12351: chomp($configline);
12352: next if ($configline =~ /^\#/);
12353: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
12354: $managerstab{$configline} = 1;
12355: }
12356: }
12357: close($config);
12358: }
12359: }
12360: }
12361:
1.329 matthew 12362: # ------------- set up temporary directory
12363: {
1.1117 foxr 12364: $tmpdir = LONCAPA::tempdir();
1.329 matthew 12365:
1.11 www 12366: }
12367:
1.794 albertel 12368: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
12369: 'compress_threshold'=> 20_000,
12370: });
1.185 www 12371:
1.281 www 12372: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 12373: $dumpcount=0;
1.958 www 12374: $locknum=0;
1.22 www 12375:
1.163 harris41 12376: &logtouch();
1.672 albertel 12377: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 12378: $readit=1;
1.564 albertel 12379: {
12380: use integer;
12381: my $test=(2**32)+1;
1.568 albertel 12382: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 12383: &logthis(" Detected 64bit platform ($_64bit)");
12384: }
1.195 www 12385: }
1.1 albertel 12386: }
1.179 www 12387:
1.1 albertel 12388: 1;
1.191 harris41 12389: __END__
12390:
1.243 albertel 12391: =pod
12392:
1.191 harris41 12393: =head1 NAME
12394:
1.243 albertel 12395: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 12396:
12397: =head1 SYNOPSIS
12398:
1.243 albertel 12399: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 12400:
12401: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
12402:
1.243 albertel 12403: Common parameters:
12404:
12405: =over 4
12406:
12407: =item *
12408:
12409: $uname : an internal username (if $cname expecting a course Id specifically)
12410:
12411: =item *
12412:
12413: $udom : a domain (if $cdom expecting a course's domain specifically)
12414:
12415: =item *
12416:
12417: $symb : a resource instance identifier
12418:
12419: =item *
12420:
12421: $namespace : the name of a .db file that contains the data needed or
12422: being set.
12423:
12424: =back
12425:
1.394 bowersj2 12426: =head1 OVERVIEW
1.191 harris41 12427:
1.394 bowersj2 12428: lonnet provides subroutines which interact with the
12429: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
12430: about classes, users, and resources.
1.243 albertel 12431:
12432: For many of these objects you can also use this to store data about
12433: them or modify them in various ways.
1.191 harris41 12434:
1.394 bowersj2 12435: =head2 Symbs
1.191 harris41 12436:
1.394 bowersj2 12437: To identify a specific instance of a resource, LON-CAPA uses symbols
12438: or "symbs"X<symb>. These identifiers are built from the URL of the
12439: map, the resource number of the resource in the map, and the URL of
12440: the resource itself. The latter is somewhat redundant, but might help
12441: if maps change.
12442:
12443: An example is
12444:
12445: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
12446:
12447: The respective map entry is
12448:
12449: <resource id="19" src="/res/msu/korte/tests/part12.problem"
12450: title="Problem 2">
12451: </resource>
12452:
12453: Symbs are used by the random number generator, as well as to store and
12454: restore data specific to a certain instance of for example a problem.
12455:
12456: =head2 Storing And Retrieving Data
12457:
12458: X<store()>X<cstore()>X<restore()>Three of the most important functions
12459: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
12460: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
12461: is is the non-critical message twin of cstore. These functions are for
12462: handlers to store a perl hash to a user's permanent data space in an
12463: easy manner, and to retrieve it again on another call. It is expected
12464: that a handler would use this once at the beginning to retrieve data,
12465: and then again once at the end to send only the new data back.
12466:
12467: The data is stored in the user's data directory on the user's
12468: homeserver under the ID of the course.
12469:
12470: The hash that is returned by restore will have all of the previous
12471: value for all of the elements of the hash.
12472:
12473: Example:
12474:
12475: #creating a hash
12476: my %hash;
12477: $hash{'foo'}='bar';
12478:
12479: #storing it
12480: &Apache::lonnet::cstore(\%hash);
12481:
12482: #changing a value
12483: $hash{'foo'}='notbar';
12484:
12485: #adding a new value
12486: $hash{'bar'}='foo';
12487: &Apache::lonnet::cstore(\%hash);
12488:
12489: #retrieving the hash
12490: my %history=&Apache::lonnet::restore();
12491:
12492: #print the hash
12493: foreach my $key (sort(keys(%history))) {
12494: print("\%history{$key} = $history{$key}");
12495: }
12496:
12497: Will print out:
1.191 harris41 12498:
1.394 bowersj2 12499: %history{1:foo} = bar
12500: %history{1:keys} = foo:timestamp
12501: %history{1:timestamp} = 990455579
12502: %history{2:bar} = foo
12503: %history{2:foo} = notbar
12504: %history{2:keys} = foo:bar:timestamp
12505: %history{2:timestamp} = 990455580
12506: %history{bar} = foo
12507: %history{foo} = notbar
12508: %history{timestamp} = 990455580
12509: %history{version} = 2
12510:
12511: Note that the special hash entries C<keys>, C<version> and
12512: C<timestamp> were added to the hash. C<version> will be equal to the
12513: total number of versions of the data that have been stored. The
12514: C<timestamp> attribute will be the UNIX time the hash was
12515: stored. C<keys> is available in every historical section to list which
12516: keys were added or changed at a specific historical revision of a
12517: hash.
12518:
12519: B<Warning>: do not store the hash that restore returns directly. This
12520: will cause a mess since it will restore the historical keys as if the
12521: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 12522:
1.394 bowersj2 12523: Calling convention:
1.191 harris41 12524:
1.1225 raeburn 12525: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
12526: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname);
1.191 harris41 12527:
1.394 bowersj2 12528: For more detailed information, see lonnet specific documentation.
1.191 harris41 12529:
1.394 bowersj2 12530: =head1 RETURN MESSAGES
1.191 harris41 12531:
1.394 bowersj2 12532: =over 4
1.191 harris41 12533:
1.394 bowersj2 12534: =item * B<con_lost>: unable to contact remote host
1.191 harris41 12535:
1.394 bowersj2 12536: =item * B<con_delayed>: unable to contact remote host, message will be delivered
12537: when the connection is brought back up
1.191 harris41 12538:
1.394 bowersj2 12539: =item * B<con_failed>: unable to contact remote host and unable to save message
12540: for later delivery
1.191 harris41 12541:
1.967 bisitz 12542: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 12543:
1.394 bowersj2 12544: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 12545: that was requested
1.191 harris41 12546:
1.243 albertel 12547: =back
1.191 harris41 12548:
1.243 albertel 12549: =head1 PUBLIC SUBROUTINES
1.191 harris41 12550:
1.243 albertel 12551: =head2 Session Environment Functions
1.191 harris41 12552:
1.243 albertel 12553: =over 4
1.191 harris41 12554:
1.394 bowersj2 12555: =item *
12556: X<appenv()>
1.949 raeburn 12557: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 12558: the user envirnoment file, and will be restored for each access this
1.620 albertel 12559: user makes during this session, also modifies the %env for the current
1.949 raeburn 12560: process. Optional rolesarrayref - if defined contains a reference to an array
12561: of roles which are exempt from the restriction on modifying user.role entries
12562: in the user's environment.db and in %env.
1.191 harris41 12563:
12564: =item *
1.394 bowersj2 12565: X<delenv()>
1.987 raeburn 12566: B<delenv($delthis,$regexp)>: removes all items from the session
12567: environment file that begin with $delthis. If the
12568: optional second arg - $regexp - is true, $delthis is treated as a
12569: regular expression, otherwise \Q$delthis\E is used.
12570: The values are also deleted from the current processes %env.
1.191 harris41 12571:
1.795 albertel 12572: =item * get_env_multiple($name)
12573:
12574: gets $name from the %env hash, it seemlessly handles the cases where multiple
12575: values may be defined and end up as an array ref.
12576:
12577: returns an array of values
12578:
1.243 albertel 12579: =back
12580:
12581: =head2 User Information
1.191 harris41 12582:
1.243 albertel 12583: =over 4
1.191 harris41 12584:
12585: =item *
1.394 bowersj2 12586: X<queryauthenticate()>
12587: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 12588: authentication scheme
12589:
12590: =item *
1.394 bowersj2 12591: X<authenticate()>
1.1073 raeburn 12592: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 12593: authenticate user from domain's lib servers (first use the current
12594: one). C<$upass> should be the users password.
1.1073 raeburn 12595: $checkdefauth is optional (value is 1 if a check should be made to
12596: authenticate user using default authentication method, and allow
12597: account creation if username does not have account in the domain).
12598: $clientcancheckhost is optional (value is 1 if checking whether the
12599: server can host will occur on the client side in lonauth.pm).
1.191 harris41 12600:
12601: =item *
1.394 bowersj2 12602: X<homeserver()>
12603: B<homeserver($uname,$udom)>: find the server which has
12604: the user's directory and files (there must be only one), this caches
12605: the answer, and also caches if there is a borken connection.
1.191 harris41 12606:
12607: =item *
1.394 bowersj2 12608: X<idget()>
12609: B<idget($udom,@ids)>: find the usernames behind a list of IDs
12610: (IDs are a unique resource in a domain, there must be only 1 ID per
12611: username, and only 1 username per ID in a specific domain) (returns
12612: hash: id=>name,id=>name)
1.191 harris41 12613:
12614: =item *
1.394 bowersj2 12615: X<idrget()>
12616: B<idrget($udom,@unames)>: find the IDs behind a list of
12617: usernames (returns hash: name=>id,name=>id)
1.191 harris41 12618:
12619: =item *
1.394 bowersj2 12620: X<idput()>
12621: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 12622:
12623: =item *
1.394 bowersj2 12624: X<rolesinit()>
1.1169 droeschl 12625: B<rolesinit($udom,$username)>: get user privileges.
12626: returns user role, first access and timer interval hashes
1.243 albertel 12627:
12628: =item *
1.1171 droeschl 12629: X<privileged()>
12630: B<privileged($username,$domain)>: returns a true if user has a
12631: privileged and active role (i.e. su or dc), false otherwise.
12632:
12633: =item *
1.551 albertel 12634: X<getsection()>
12635: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 12636: course $cname, return section name/number or '' for "not in course"
12637: and '-1' for "no section"
12638:
12639: =item *
1.394 bowersj2 12640: X<userenvironment()>
12641: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 12642: passed in @what from the requested user's environment, returns a hash
12643:
1.858 raeburn 12644: =item *
12645: X<userlog_query()>
1.859 albertel 12646: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
12647: activity.log file. %filters defines filters applied when parsing the
12648: log file. These can be start or end timestamps, or the type of action
12649: - log to look for Login or Logout events, check for Checkin or
12650: Checkout, role for role selection. The response is in the form
12651: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
12652: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 12653:
1.243 albertel 12654: =back
12655:
12656: =head2 User Roles
12657:
12658: =over 4
12659:
12660: =item *
12661:
1.810 raeburn 12662: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243 albertel 12663: F: full access
12664: U,I,K: authentication modes (cxx only)
12665: '': forbidden
12666: 1: user needs to choose course
12667: 2: browse allowed
1.766 albertel 12668: A: passphrase authentication needed
1.243 albertel 12669:
12670: =item *
12671:
1.1192 raeburn 12672: constructaccess($url,$setpriv) : check for access to construction space URL
12673:
12674: See if the owner domain and name in the URL match those in the
12675: expected environment. If so, return three element list
12676: ($ownername,$ownerdomain,$ownerhome).
12677:
12678: Otherwise return the null string.
12679:
12680: If second argument 'setpriv' is true, it assigns the privileges,
12681: and returns the same three element list, unless the owner has
12682: blocked "ad hoc" Domain Coordinator access to the Author Space,
12683: in which case the null string is returned.
12684:
12685: =item *
12686:
1.243 albertel 12687: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
12688: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
12689: and course level
12690:
12691: =item *
12692:
1.988 raeburn 12693: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
12694: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 12695: $type is Course (default) or Community.
1.988 raeburn 12696: If $forcedefault evaluates to true, text returned will be default
12697: text for $type. Otherwise, if this is a course, the text returned
12698: will be a custom name for the role (if defined in the course's
12699: environment). If no custom name is defined the default is returned.
12700:
1.832 raeburn 12701: =item *
12702:
1.1219 raeburn 12703: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858 raeburn 12704: All arguments are optional. Returns a hash of a roles, either for
12705: co-author/assistant author roles for a user's Construction Space
1.906 albertel 12706: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 12707: In the hash, keys are set to colon-separated $uname,$udom,$role, and
12708: (optionally) if $withsec is true, a fourth colon-separated item - $section.
12709: For each key, value is set to colon-separated start and end times for
12710: the role. If no username and domain are specified, will default to
1.934 raeburn 12711: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 12712: of role statuses (active, future or previous), roles
12713: (e.g., cc,in, st etc.) and domains of the roles which can be used
12714: to restrict the list of roles reported. If no array ref is
12715: provided for types, will default to return only active roles.
1.834 albertel 12716:
1.1195 raeburn 12717: =item *
12718:
12719: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196 raeburn 12720: user: $uname:$udom has a role in the course: $cdom_$cnum.
12721:
12722: Additional optional arguments are: $type (if role checking is to be restricted
12723: to certain user status types -- previous (expired roles), active (currently
1.1195 raeburn 12724: available roles) or future (roles available in the future), and
12725: $hideprivileged -- if true will not report course roles for users who
1.1219 raeburn 12726: have active Domain Coordinator role in course's domain or in additional
12727: domains (specified in 'Domains to check for privileged users' in course
12728: environment -- set via: Course Settings -> Classlists and staff listing).
12729:
12730: =item *
12731:
12732: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
12733: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
12734: $possdomains and $possroles are optional array refs -- to domains to check and
12735: roles to check. If $possdomains is not specified, a dump will be done of the
12736: users' roles.db to check for a dc or su role in any domain. This can be
12737: time consuming if &privileged is called repeatedly (e.g., when displaying a
12738: classlist), so in such cases, supplying a $possdomains array is preferred, as
12739: this then allows &privileged_by_domain() to be used, which caches the identity
12740: of privileged users, eliminating the need for repeated calls to &dump().
12741:
12742: =item *
12743:
12744: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
12745: where the outer hash keys are domains specified in the $possdomains array ref,
12746: next inner hash keys are privileged roles specified in the $roles array ref,
12747: and the innermost hash contains key = value pairs for username:domain = end:start
12748: for active or future "privileged" users with that role in that domain. To avoid
12749: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
12750: innerhash are cached using priv_$role and $dom as the identifiers.
1.1195 raeburn 12751:
1.243 albertel 12752: =back
12753:
12754: =head2 User Modification
12755:
12756: =over 4
12757:
12758: =item *
12759:
1.957 raeburn 12760: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 12761: user for the level given by URL. Optional start and end dates (leave empty
12762: string or zero for "no date")
1.191 harris41 12763:
12764: =item *
12765:
1.243 albertel 12766: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
12767: change a users, password, possible return values are: ok,
12768: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
12769: refused
1.191 harris41 12770:
12771: =item *
12772:
1.243 albertel 12773: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 12774:
12775: =item *
12776:
1.1058 raeburn 12777: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
12778: $forceid,$desiredhome,$email,$inststatus,$candelete) :
12779:
12780: will update user information (firstname,middlename,lastname,generation,
12781: permanentemail), and if forceid is true, student/employee ID also.
12782: A user's institutional affiliation(s) can also be updated.
12783: User information fields will not be overwritten with empty entries
12784: unless the field is included in the $candelete array reference.
12785: This array is included when a single user is modified via "Manage Users",
12786: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 12787:
12788: =item *
12789:
1.286 matthew 12790: modifystudent
12791:
1.957 raeburn 12792: modify a student's enrollment and identification information.
1.1235 raeburn 12793: The course id is resolved based on the current user's environment.
12794: This means the invoking user must be a course coordinator or otherwise
1.286 matthew 12795: associated with a course.
12796:
1.297 matthew 12797: This call is essentially a wrapper for lonnet::modifyuser and
12798: lonnet::modify_student_enrollment
1.286 matthew 12799:
12800: Inputs:
12801:
12802: =over 4
12803:
1.957 raeburn 12804: =item B<$udom> Student's loncapa domain
1.286 matthew 12805:
1.957 raeburn 12806: =item B<$uname> Student's loncapa login name
1.286 matthew 12807:
1.964 bisitz 12808: =item B<$uid> Student/Employee ID
1.286 matthew 12809:
1.957 raeburn 12810: =item B<$umode> Student's authentication mode
1.286 matthew 12811:
1.957 raeburn 12812: =item B<$upass> Student's password
1.286 matthew 12813:
1.957 raeburn 12814: =item B<$first> Student's first name
1.286 matthew 12815:
1.957 raeburn 12816: =item B<$middle> Student's middle name
1.286 matthew 12817:
1.957 raeburn 12818: =item B<$last> Student's last name
1.286 matthew 12819:
1.957 raeburn 12820: =item B<$gene> Student's generation
1.286 matthew 12821:
1.957 raeburn 12822: =item B<$usec> Student's section in course
1.286 matthew 12823:
12824: =item B<$end> Unix time of the roles expiration
12825:
12826: =item B<$start> Unix time of the roles start date
12827:
12828: =item B<$forceid> If defined, allow $uid to be changed
12829:
12830: =item B<$desiredhome> server to use as home server for student
12831:
1.957 raeburn 12832: =item B<$email> Student's permanent e-mail address
12833:
12834: =item B<$type> Type of enrollment (auto or manual)
12835:
1.963 raeburn 12836: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
12837:
12838: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 12839:
1.963 raeburn 12840: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 12841:
1.963 raeburn 12842: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 12843:
1.1216 raeburn 12844: =item B<$inststatus> institutional status of user - : separated string of escaped status types
12845:
12846: =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 12847:
1.286 matthew 12848: =back
1.297 matthew 12849:
12850: =item *
12851:
12852: modify_student_enrollment
12853:
1.1235 raeburn 12854: Change a student's enrollment status in a class. The environment variable
1.297 matthew 12855: 'role.request.course' must be defined for this function to proceed.
12856:
12857: Inputs:
12858:
12859: =over 4
12860:
1.1235 raeburn 12861: =item $udom, student's domain
1.297 matthew 12862:
1.1235 raeburn 12863: =item $uname, student's name
1.297 matthew 12864:
1.1235 raeburn 12865: =item $uid, student's user id
1.297 matthew 12866:
1.1235 raeburn 12867: =item $first, student's first name
1.297 matthew 12868:
12869: =item $middle
12870:
12871: =item $last
12872:
12873: =item $gene
12874:
12875: =item $usec
12876:
12877: =item $end
12878:
12879: =item $start
12880:
1.957 raeburn 12881: =item $type
12882:
12883: =item $locktype
12884:
12885: =item $cid
12886:
12887: =item $selfenroll
12888:
12889: =item $context
12890:
1.1216 raeburn 12891: =item $credits, number of credits student will earn from this class
12892:
1.297 matthew 12893: =back
12894:
1.191 harris41 12895:
12896: =item *
12897:
1.243 albertel 12898: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
12899: custom role; give a custom role to a user for the level given by URL. Specify
12900: name and domain of role author, and role name
1.191 harris41 12901:
12902: =item *
12903:
1.243 albertel 12904: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 12905:
12906: =item *
12907:
1.243 albertel 12908: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
12909:
12910: =back
12911:
12912: =head2 Course Infomation
12913:
12914: =over 4
1.191 harris41 12915:
12916: =item *
12917:
1.1118 foxr 12918: coursedescription($courseid,$options) : returns a hash of information about the
1.631 albertel 12919: specified course id, including all environment settings for the
12920: course, the description of the course will be in the hash under the
12921: key 'description'
1.191 harris41 12922:
1.1118 foxr 12923: $options is an optional parameter that if supplied is a hash reference that controls
12924: what how this function works. It has the following key/values:
12925:
12926: =over 4
12927:
12928: =item freshen_cache
12929:
12930: If defined, and the environment cache for the course is valid, it is
12931: returned in the returned hash.
12932:
12933: =item one_time
12934:
12935: If defined, the last cache time is set to _now_
12936:
12937: =item user
12938:
12939: If defined, the supplied username is used instead of the current user.
12940:
12941:
12942: =back
12943:
1.191 harris41 12944: =item *
12945:
1.624 albertel 12946: resdata($name,$domain,$type,@which) : request for current parameter
12947: setting for a specific $type, where $type is either 'course' or 'user',
12948: @what should be a list of parameters to ask about. This routine caches
1.1235 raeburn 12949: answers for 10 minutes.
1.243 albertel 12950:
1.877 foxr 12951: =item *
12952:
12953: get_courseresdata($courseid, $domain) : dump the entire course resource
12954: data base, returning a hash that is keyed by the resource name and has
12955: values that are the resource value. I believe that the timestamps and
12956: versions are also returned.
12957:
1.1236 raeburn 12958: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
12959: supplemental content area. This routine caches the number of files for
12960: 10 minutes.
12961:
1.243 albertel 12962: =back
12963:
12964: =head2 Course Modification
12965:
12966: =over 4
1.191 harris41 12967:
12968: =item *
12969:
1.243 albertel 12970: writecoursepref($courseid,%prefs) : write preferences (environment
12971: database) for a course
1.191 harris41 12972:
12973: =item *
12974:
1.1011 raeburn 12975: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
12976:
12977: =item *
12978:
1.1038 raeburn 12979: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 12980:
1.1167 droeschl 12981: =item *
12982:
12983: is_course($courseid), is_course($cdom, $cnum)
12984:
12985: Accepts either a combined $courseid (in the form of domain_courseid) or the
12986: two component version $cdom, $cnum. It checks if the specified course exists.
12987:
12988: Returns:
12989: undef if the course doesn't exist, otherwise
12990: in scalar context the combined courseid.
12991: in list context the two components of the course identifier, domain and
12992: courseid.
12993:
1.243 albertel 12994: =back
12995:
12996: =head2 Resource Subroutines
12997:
12998: =over 4
1.191 harris41 12999:
13000: =item *
13001:
1.243 albertel 13002: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 13003:
13004: =item *
13005:
1.243 albertel 13006: repcopy($filename) : subscribes to the requested file, and attempts to
13007: replicate from the owning library server, Might return
1.607 raeburn 13008: 'unavailable', 'not_found', 'forbidden', 'ok', or
13009: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 13010: resource. Expects the local filesystem pathname
13011: (/home/httpd/html/res/....)
13012:
13013: =back
13014:
13015: =head2 Resource Information
13016:
13017: =over 4
1.191 harris41 13018:
13019: =item *
13020:
1.1228 raeburn 13021: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates
13022: and returns the value of a variety of different possible values,
13023: $varname should be a request string, and the other parameters can be
13024: used to specify who and what one is asking about. Ordinarily, $cid
13025: does not need to be specified, as it is retrived from
13026: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
13027: within lonuserstate::loadmap() when initializing a course, before
13028: $env{'request.course.id'} has been set, so it needs to be provided
13029: in that one case.
1.243 albertel 13030:
13031: Possible values for $varname are environment.lastname (or other item
13032: from the envirnment hash), user.name (or someother aspect about the
13033: user), resource.0.maxtries (or some other part and parameter of a
13034: resource)
1.204 albertel 13035:
13036: =item *
13037:
1.243 albertel 13038: directcondval($number) : get current value of a condition; reads from a state
13039: string
1.204 albertel 13040:
13041: =item *
13042:
1.243 albertel 13043: condval($condidx) : value of condition index based on state
1.204 albertel 13044:
13045: =item *
13046:
1.243 albertel 13047: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
13048: resource's metadata, $what should be either a specific key, or either
13049: 'keys' (to get a list of possible keys) or 'packages' to get a list of
13050: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
13051:
13052: this function automatically caches all requests
1.191 harris41 13053:
13054: =item *
13055:
1.243 albertel 13056: metadata_query($query,$custom,$customshow) : make a metadata query against the
13057: network of library servers; returns file handle of where SQL and regex results
13058: will be stored for query
1.191 harris41 13059:
13060: =item *
13061:
1.243 albertel 13062: symbread($filename) : return symbolic list entry (filename argument optional);
13063: returns the data handle
1.191 harris41 13064:
13065: =item *
13066:
1.1190 raeburn 13067: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
13068: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582 albertel 13069: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190 raeburn 13070: on failure, user must be in a course, as it assumes the existence of
13071: the course initial hash, and uses $env('request.course.id'}. The third
13072: arg is an optional reference to a scalar. If this arg is passed in the
13073: call to symbverify, it will be set to 1 if the symb has been set to be
13074: encrypted; otherwise it will be null.
1.191 harris41 13075:
13076: =item *
13077:
1.243 albertel 13078: symbclean($symb) : removes versions numbers from a symb, returns the
13079: cleaned symb
1.191 harris41 13080:
13081: =item *
13082:
1.243 albertel 13083: is_on_map($uri) : checks if the $uri is somewhere on the current
13084: course map, user must be in a course for it to work.
1.191 harris41 13085:
13086: =item *
13087:
1.243 albertel 13088: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 13089:
13090: =item *
13091:
1.243 albertel 13092: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
13093: a random seed, all arguments are optional, if they aren't sent it uses the
13094: environment to derive them. Note: if symb isn't sent and it can't get one
13095: from &symbread it will use the current time as its return value
1.191 harris41 13096:
13097: =item *
13098:
1.243 albertel 13099: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
13100: unfakeable, receipt
1.191 harris41 13101:
13102: =item *
13103:
1.620 albertel 13104: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 13105:
13106: =item *
13107:
1.243 albertel 13108: countacc($url) : count the number of accesses to a given URL
1.191 harris41 13109:
13110: =item *
13111:
1.243 albertel 13112: 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 13113:
13114: =item *
13115:
1.243 albertel 13116: 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 13117:
13118: =item *
13119:
1.243 albertel 13120: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 13121:
13122: =item *
13123:
1.243 albertel 13124: devalidate($symb) : devalidate temporary spreadsheet calculations,
13125: forcing spreadsheet to reevaluate the resource scores next time.
13126:
1.1195 raeburn 13127: =item *
13128:
1.1196 raeburn 13129: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
13130: when viewing in course context.
1.1195 raeburn 13131:
1.1196 raeburn 13132: input: six args -- filename (decluttered), course number, course domain,
13133: url, symb (if registered) and group (if this is a
13134: group item -- e.g., bulletin board, group page etc.).
1.1195 raeburn 13135:
1.1196 raeburn 13136: output: array of five scalars --
1.1195 raeburn 13137: $cfile -- url for file editing if editable on current server
13138: $home -- homeserver of resource (i.e., for author if published,
13139: or course if uploaded.).
13140: $switchserver -- 1 if server switch will be needed.
1.1196 raeburn 13141: $forceedit -- 1 if icon/link should be to go to edit mode
13142: $forceview -- 1 if icon/link should be to go to view mode
1.1195 raeburn 13143:
13144: =item *
13145:
13146: is_course_upload($file,$cnum,$cdom)
13147:
13148: Used in course context to determine if current file was uploaded to
13149: the course (i.e., would be found in /userfiles/docs on the course's
13150: homeserver.
13151:
13152: input: 3 args -- filename (decluttered), course number and course domain.
13153: output: boolean -- 1 if file was uploaded.
13154:
1.243 albertel 13155: =back
13156:
13157: =head2 Storing/Retreiving Data
13158:
13159: =over 4
1.191 harris41 13160:
13161: =item *
13162:
1.243 albertel 13163: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
13164: for this url; hashref needs to be given and should be a \%hashname; the
13165: remaining args aren't required and if they aren't passed or are '' they will
1.620 albertel 13166: be derived from the env
1.191 harris41 13167:
13168: =item *
13169:
1.243 albertel 13170: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
13171: uses critical subroutine
1.191 harris41 13172:
13173: =item *
13174:
1.243 albertel 13175: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
13176: all args are optional
1.191 harris41 13177:
13178: =item *
13179:
1.717 albertel 13180: dumpstore($namespace,$udom,$uname,$regexp,$range) :
13181: dumps the complete (or key matching regexp) namespace into a hash
13182: ($udom, $uname, $regexp, $range are optional) for a namespace that is
13183: normally &store()ed into
13184:
13185: $range should be either an integer '100' (give me the first 100
13186: matching records)
13187: or be two integers sperated by a - with no spaces
13188: '30-50' (give me the 30th through the 50th matching
13189: records)
13190:
13191:
13192: =item *
13193:
13194: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
13195: replaces a &store() version of data with a replacement set of data
13196: for a particular resource in a namespace passed in the $storehash hash
13197: reference
13198:
13199: =item *
13200:
1.243 albertel 13201: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
13202: works very similar to store/cstore, but all data is stored in a
13203: temporary location and can be reset using tmpreset, $storehash should
13204: be a hash reference, returns nothing on success
1.191 harris41 13205:
13206: =item *
13207:
1.243 albertel 13208: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
13209: similar to restore, but all data is stored in a temporary location and
13210: can be reset using tmpreset. Returns a hash of values on success,
13211: error string otherwise.
1.191 harris41 13212:
13213: =item *
13214:
1.243 albertel 13215: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
13216: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 13217:
13218: =item *
13219:
1.243 albertel 13220: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13221: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 13222:
13223: =item *
13224:
1.243 albertel 13225: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
13226: namesp ($udom and $uname are optional)
1.191 harris41 13227:
13228: =item *
13229:
1.702 albertel 13230: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 13231: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 13232: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 13233:
1.702 albertel 13234: $range should be either an integer '100' (give me the first 100
13235: matching records)
13236: or be two integers sperated by a - with no spaces
13237: '30-50' (give me the 30th through the 50th matching
13238: records)
1.449 matthew 13239: =item *
13240:
13241: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
13242: $store can be a scalar, an array reference, or if the amount to be
13243: incremented is > 1, a hash reference.
13244:
13245: ($udom and $uname are optional)
1.191 harris41 13246:
13247: =item *
13248:
1.243 albertel 13249: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
13250: ($udom and $uname are optional)
1.191 harris41 13251:
13252: =item *
13253:
1.243 albertel 13254: cput($namespace,$storehash,$udom,$uname) : critical put
13255: ($udom and $uname are optional)
1.191 harris41 13256:
13257: =item *
13258:
1.748 albertel 13259: newput($namespace,$storehash,$udom,$uname) :
13260:
13261: Attempts to store the items in the $storehash, but only if they don't
13262: currently exist, if this succeeds you can be certain that you have
13263: successfully created a new key value pair in the $namespace db.
13264:
13265:
13266: Args:
13267: $namespace: name of database to store values to
13268: $storehash: hashref to store to the db
13269: $udom: (optional) domain of user containing the db
13270: $uname: (optional) name of user caontaining the db
13271:
13272: Returns:
13273: 'ok' -> succeeded in storing all keys of $storehash
13274: 'key_exists: <key>' -> failed to anything out of $storehash, as at
13275: least <key> already existed in the db (other
13276: requested keys may also already exist)
1.967 bisitz 13277: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 13278: 'con_lost' -> unable to contact request server
13279: 'refused' -> action was not allowed by remote machine
13280:
13281:
13282: =item *
13283:
1.243 albertel 13284: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13285: reference filled in from namesp (encrypts the return communication)
13286: ($udom and $uname are optional)
1.191 harris41 13287:
13288: =item *
13289:
1.243 albertel 13290: log($udom,$name,$home,$message) : write to permanent log for user; use
13291: critical subroutine
13292:
1.806 raeburn 13293: =item *
13294:
1.860 raeburn 13295: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
13296: array reference filled in from namespace found in domain level on either
13297: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 13298:
13299: =item *
13300:
1.860 raeburn 13301: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
13302: domain level either on specified domain server ($uhome) or primary domain
13303: server ($udom and $uhome are optional)
1.806 raeburn 13304:
1.943 raeburn 13305: =item *
13306:
1.1240 raeburn 13307: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
13308: for: authentication, language, quotas, timezone, date locale, and portal URL in
13309: the target domain.
13310:
13311: May also include additional key => value pairs for the following groups:
13312:
13313: =over
13314:
13315: =item
13316: disk quotas (MB allocated by default to portfolios and authoring spaces).
13317:
13318: =over
13319:
13320: =item defaultquota, authorquota
13321:
13322: =back
13323:
13324: =item
13325: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
13326: portfolio for users).
13327:
13328: =over
13329:
13330: =item
13331: aboutme, blog, webdav, portfolio
13332:
13333: =back
13334:
13335: =item
13336: requestcourses: ability to request courses, and how requests are processed.
13337:
13338: =over
13339:
13340: =item
1.1246 raeburn 13341: official, unofficial, community, textbook
1.1240 raeburn 13342:
13343: =back
13344:
13345: =item
13346: inststatus: types of institutional affiliation, and order in which they are displayed.
13347:
13348: =over
13349:
13350: =item
13351: inststatustypes, inststatusorder
13352:
13353: =back
13354:
13355: =item
13356: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
13357: for course's uploaded content.
13358:
13359: =over
13360:
13361: =item
1.1246 raeburn 13362: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
13363: communityquota, textbookquota
1.1240 raeburn 13364:
13365: =back
13366:
13367: =item
13368: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
13369: on your servers.
13370:
13371: =over
13372:
13373: =item
13374: remotesessions, hostedsessions
13375:
13376: =back
13377:
13378: =back
13379:
13380: In cases where a domain coordinator has never used the "Set Domain Configuration"
13381: utility to create a configuration.db file on a domain's primary library server
13382: only the following domain defaults: auth_def, auth_arg_def, lang_def
13383: -- corresponding values are authentication type (internal, krb4, krb5,
13384: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
13385: will be available. Values are retrieved from cache (if current), unless the
13386: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
13387: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
13388:
13389: Typical usage:
1.943 raeburn 13390:
1.1240 raeburn 13391: %domdefaults = &get_domain_defaults($target_domain);
1.943 raeburn 13392:
1.243 albertel 13393: =back
13394:
13395: =head2 Network Status Functions
13396:
13397: =over 4
1.191 harris41 13398:
13399: =item *
13400:
1.1137 raeburn 13401: dirlist() : return directory list based on URI (first arg).
13402:
13403: Inputs: 1 required, 5 optional.
13404:
13405: =over
13406:
13407: =item
13408: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
13409:
13410: =item
13411: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
13412:
13413: =item
13414: $username - username of user/course to be listed. Extracted from $uri if absent.
13415:
13416: =item
13417: $getpropath - boolean: 1 if prepend path using &propath().
13418:
13419: =item
13420: $getuserdir - boolean: 1 if prepend path for "userfiles".
13421:
13422: =item
13423: $alternateRoot - path to prepend in place of path from $uri.
13424:
13425: =back
13426:
13427: Returns: Array of up to two items.
13428:
13429: =over
13430:
13431: a reference to an array of files/subdirectories
13432:
13433: =over
13434:
13435: Each element in the array of files/subdirectories is a & separated list of
13436: item name and the result of running stat on the item. If dirlist was requested
13437: for a file instead of a directory, the item name will be ''. For a directory
13438: listing, if the item is a metadata file, the element will end &N&M
13439: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
13440: default copyright set (1).
13441:
13442: =back
13443:
13444: a scalar containing error condition (if encountered).
13445:
13446: =over
13447:
13448: =item
13449: no_host (no homeserver identified for $username:$domain).
13450:
13451: =item
13452: no_such_host (server contacted for listing not identified as valid host).
13453:
13454: =item
13455: con_lost (connection to remote server failed).
13456:
13457: =item
13458: refused (invalid $username:$domain received on lond side).
13459:
13460: =item
13461: no_such_dir (directory at specified path on lond side does not exist).
13462:
13463: =item
13464: empty (directory at specified path on lond side is empty).
13465:
13466: =over
13467:
13468: This is currently not encountered because the &ls3, &ls2,
13469: &ls (_handler) routines on the lond side do not filter out
13470: . and .. from a directory listing.
13471:
13472: =back
13473:
13474: =back
13475:
13476: =back
1.191 harris41 13477:
13478: =item *
13479:
1.243 albertel 13480: spareserver() : find server with least workload from spare.tab
13481:
1.986 foxr 13482:
13483: =item *
13484:
13485: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
13486: if there is no corresponding loncapa host.
13487:
1.243 albertel 13488: =back
13489:
1.986 foxr 13490:
1.243 albertel 13491: =head2 Apache Request
13492:
13493: =over 4
1.191 harris41 13494:
13495: =item *
13496:
1.243 albertel 13497: ssi($url,%hash) : server side include, does a complete request cycle on url to
13498: localhost, posts hash
13499:
13500: =back
13501:
13502: =head2 Data to String to Data
13503:
13504: =over 4
1.191 harris41 13505:
13506: =item *
13507:
1.243 albertel 13508: hash2str(%hash) : convert a hash into a string complete with escaping and '='
13509: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 13510:
13511: =item *
13512:
1.243 albertel 13513: hashref2str($hashref) : convert a hashref into a string complete with
13514: escaping and '=' and '&' separators, supports elements that are
13515: arrayrefs and hashrefs
1.191 harris41 13516:
13517: =item *
13518:
1.243 albertel 13519: arrayref2str($arrayref) : convert an arrayref into a string complete
13520: with escaping and '&' separators, supports elements that are arrayrefs
13521: and hashrefs
1.191 harris41 13522:
13523: =item *
13524:
1.243 albertel 13525: str2hash($string) : convert string to hash using unescaping and
13526: splitting on '=' and '&', supports elements that are arrayrefs and
13527: hashrefs
1.191 harris41 13528:
13529: =item *
13530:
1.243 albertel 13531: str2array($string) : convert string to hash using unescaping and
13532: splitting on '&', supports elements that are arrayrefs and hashrefs
13533:
13534: =back
13535:
13536: =head2 Logging Routines
13537:
13538:
13539: These routines allow one to make log messages in the lonnet.log and
13540: lonnet.perm logfiles.
1.191 harris41 13541:
1.1119 foxr 13542: =over 4
13543:
1.191 harris41 13544: =item *
13545:
1.243 albertel 13546: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 13547:
13548: =item *
13549:
1.243 albertel 13550: logthis() : append message to the normal lonnet.log file, it gets
13551: preiodically rolled over and deleted.
1.191 harris41 13552:
13553: =item *
13554:
1.243 albertel 13555: logperm() : append a permanent message to lonnet.perm.log, this log
13556: file never gets deleted by any automated portion of the system, only
13557: messages of critical importance should go in here.
13558:
1.1119 foxr 13559:
1.243 albertel 13560: =back
13561:
13562: =head2 General File Helper Routines
13563:
13564: =over 4
1.191 harris41 13565:
13566: =item *
13567:
1.481 raeburn 13568: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
13569: (a) files in /uploaded
13570: (i) If a local copy of the file exists -
13571: compares modification date of local copy with last-modified date for
13572: definitive version stored on home server for course. If local copy is
13573: stale, requests a new version from the home server and stores it.
13574: If the original has been removed from the home server, then local copy
13575: is unlinked.
13576: (ii) If local copy does not exist -
13577: requests the file from the home server and stores it.
13578:
13579: If $caller is 'uploadrep':
13580: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
13581: for request for files originally uploaded via DOCS.
13582: - returns 'ok' if fresh local copy now available, -1 otherwise.
13583:
13584: Otherwise:
13585: This indicates a call from the content generation phase of the request.
13586: - returns the entire contents of the file or -1.
13587:
13588: (b) files in /res
13589: - returns the entire contents of a file or -1;
13590: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 13591:
1.712 albertel 13592:
13593: =item *
13594:
13595: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
13596: reference
13597:
13598: returns either a stat() list of data about the file or an empty list
13599: if the file doesn't exist or couldn't find out about it (connection
13600: problems or user unknown)
13601:
1.191 harris41 13602: =item *
13603:
1.243 albertel 13604: filelocation($dir,$file) : returns file system location of a file
13605: based on URI; meant to be "fairly clean" absolute reference, $dir is a
13606: directory that relative $file lookups are to looked in ($dir of /a/dir
13607: and a file of ../bob will become /a/bob)
1.191 harris41 13608:
13609: =item *
13610:
13611: hreflocation($dir,$file) : returns file system location or a URL; same as
13612: filelocation except for hrefs
13613:
13614: =item *
13615:
13616: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
13617:
1.243 albertel 13618: =back
13619:
1.608 albertel 13620: =head2 Usererfile file routines (/uploaded*)
13621:
13622: =over 4
13623:
13624: =item *
13625:
13626: userfileupload(): main rotine for putting a file in a user or course's
13627: filespace, arguments are,
13628:
1.620 albertel 13629: formname - required - this is the name of the element in $env where the
1.608 albertel 13630: filename, and the contents of the file to create/modifed exist
1.620 albertel 13631: the filename is in $env{'form.'.$formname.'.filename'} and the
13632: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 13633: context - if coursedoc, store the file in the course of the active role
13634: of the current user;
13635: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
13636: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 13637: subdir - required - subdirectory to put the file in under ../userfiles/
13638: if undefined, it will be placed in "unknown"
13639:
13640: (This routine calls clean_filename() to remove any dangerous
13641: characters from the filename, and then calls finuserfileupload() to
13642: complete the transaction)
13643:
13644: returns either the url of the uploaded file (/uploaded/....) if successful
13645: and /adm/notfound.html if unsuccessful
13646:
13647: =item *
13648:
13649: clean_filename(): routine for cleaing a filename up for storage in
13650: userfile space, argument is:
13651:
13652: filename - proposed filename
13653:
13654: returns: the new clean filename
13655:
13656: =item *
13657:
1.1090 raeburn 13658: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 13659: userspace, probably shouldn't be called directly
13660:
13661: docuname: username or courseid of destination for the file
13662: docudom: domain of user/course of destination for the file
13663: formname: same as for userfileupload()
1.1090 raeburn 13664: fname: filename (including subdirectories) for the file
13665: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
13666: allfiles: reference to hash used to store objects found by parser
13667: codebase: reference to hash used for codebases of java objects found by parser
13668: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
13669: thumbheight: height (pixels) of thumbnail to be created for uploaded image
13670: resizewidth: width to be used to resize image using resizeImage from ImageMagick
13671: resizeheight: height to be used to resize image using resizeImage from ImageMagick
13672: context: if 'overwrite', will move the uploaded file from its temporary location to
13673: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 13674: mimetype: reference to scalar to accommodate mime type determined
13675: from File::MMagic if $parser = parse.
1.608 albertel 13676:
13677: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 13678: and /adm/notfound.html if unsuccessful (or an error message if context
13679: was 'overwrite').
13680:
1.608 albertel 13681:
13682: =item *
13683:
13684: renameuserfile(): renames an existing userfile to a new name
13685:
13686: Args:
13687: docuname: username or courseid of destination for the file
13688: docudom: domain of user/course of destination for the file
13689: old: current file name (including any subdirs under userfiles)
13690: new: desired file name (including any subdirs under userfiles)
13691:
13692: =item *
13693:
13694: mkdiruserfile(): creates a directory is a userfiles dir
13695:
13696: Args:
13697: docuname: username or courseid of destination for the file
13698: docudom: domain of user/course of destination for the file
13699: dir: dir to create (including any subdirs under userfiles)
13700:
13701: =item *
13702:
13703: removeuserfile(): removes a file that exists in userfiles
13704:
13705: Args:
13706: docuname: username or courseid of destination for the file
13707: docudom: domain of user/course of destination for the file
13708: fname: filname to delete (including any subdirs under userfiles)
13709:
13710: =item *
13711:
13712: removeuploadedurl(): convience function for removeuserfile()
13713:
13714: Args:
13715: url: a full /uploaded/... url to delete
13716:
1.747 albertel 13717: =item *
13718:
13719: get_portfile_permissions():
13720: Args:
13721: domain: domain of user or course contain the portfolio files
13722: user: name of user or num of course contain the portfolio files
13723: Returns:
13724: hashref of a dump of the proper file_permissions.db
13725:
13726:
13727: =item *
13728:
13729: get_access_controls():
13730:
13731: Args:
13732: current_permissions: the hash ref returned from get_portfile_permissions()
13733: group: (optional) the group you want the files associated with
13734: file: (optional) the file you want access info on
13735:
13736: Returns:
1.749 raeburn 13737: a hash (keys are file names) of hashes containing
13738: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
13739: values are XML containing access control settings (see below)
1.747 albertel 13740:
13741: Internal notes:
13742:
1.749 raeburn 13743: access controls are stored in file_permissions.db as key=value pairs.
13744: key -> path to file/file_name\0uniqueID:scope_end_start
13745: where scope -> public,guest,course,group,domains or users.
13746: end -> UNIX time for end of access (0 -> no end date)
13747: start -> UNIX time for start of access
13748:
13749: value -> XML description of access control
13750: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
13751: <start></start>
13752: <end></end>
13753:
13754: <password></password> for scope type = guest
13755:
13756: <domain></domain> for scope type = course or group
13757: <number></number>
13758: <roles id="">
13759: <role></role>
13760: <access></access>
13761: <section></section>
13762: <group></group>
13763: </roles>
13764:
13765: <dom></dom> for scope type = domains
13766:
13767: <users> for scope type = users
13768: <user>
13769: <uname></uname>
13770: <udom></udom>
13771: </user>
13772: </users>
13773: </scope>
13774:
13775: Access data is also aggregated for each file in an additional key=value pair:
13776: key -> path to file/file_name\0accesscontrol
13777: value -> reference to hash
13778: hash contains key = value pairs
13779: where key = uniqueID:scope_end_start
13780: value = UNIX time record was last updated
13781:
13782: Used to improve speed of look-ups of access controls for each file.
13783:
13784: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
13785:
1.1198 raeburn 13786: =item *
13787:
1.749 raeburn 13788: modify_access_controls():
13789:
13790: Modifies access controls for a portfolio file
13791: Args
13792: 1. file name
13793: 2. reference to hash of required changes,
13794: 3. domain
13795: 4. username
13796: where domain,username are the domain of the portfolio owner
13797: (either a user or a course)
13798:
13799: Returns:
13800: 1. result of additions or updates ('ok' or 'error', with error message).
13801: 2. result of deletions ('ok' or 'error', with error message).
13802: 3. reference to hash of any new or updated access controls.
13803: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
13804: key = integer (inbound ID)
1.1198 raeburn 13805: value = uniqueID
13806:
13807: =item *
13808:
13809: get_timebased_id():
13810:
13811: Attempts to get a unique timestamp-based suffix for use with items added to a
13812: course via the Course Editor (e.g., folders, composite pages,
13813: group bulletin boards).
13814:
13815: Args: (first three required; six others optional)
13816:
13817: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
13818: docssequence, or name of group
13819:
13820: 2. keyid (alphanumeric): name of temporary locking key in hash,
13821: e.g., num, boardids
13822:
13823: 3. namespace: name of gdbm file used to store suffixes already assigned;
13824: file will be named nohist_namespace.db
13825:
13826: 4. cdom: domain of course; default is current course domain from %env
13827:
13828: 5. cnum: course number; default is current course number from %env
13829:
13830: 6. idtype: set to concat if an additional digit is to be appended to the
13831: unix timestamp to form the suffix, if the plain timestamp is already
13832: in use. Default is to not do this, but simply increment the unix
13833: timestamp by 1 until a unique key is obtained.
13834:
13835: 7. who: holder of locking key; defaults to user:domain for user.
13836:
13837: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
13838: retrying); default is 3.
13839:
13840: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
13841:
13842: Returns:
13843:
13844: 1. suffix obtained (numeric)
13845:
13846: 2. result of deleting locking key (ok if deleted, or lock never obtained)
13847:
13848: 3. error: contains (localized) error message if an error occurred.
13849:
1.747 albertel 13850:
1.608 albertel 13851: =back
13852:
1.243 albertel 13853: =head2 HTTP Helper Routines
13854:
13855: =over 4
13856:
1.191 harris41 13857: =item *
13858:
13859: escape() : unpack non-word characters into CGI-compatible hex codes
13860:
13861: =item *
13862:
13863: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
13864:
1.243 albertel 13865: =back
13866:
13867: =head1 PRIVATE SUBROUTINES
13868:
13869: =head2 Underlying communication routines (Shouldn't call)
13870:
13871: =over 4
13872:
13873: =item *
13874:
13875: subreply() : tries to pass a message to lonc, returns con_lost if incapable
13876:
13877: =item *
13878:
13879: reply() : uses subreply to send a message to remote machine, logs all failures
13880:
13881: =item *
13882:
13883: critical() : passes a critical message to another server; if cannot
13884: get through then place message in connection buffer directory and
13885: returns con_delayed, if incapable of saving message, returns
13886: con_failed
13887:
13888: =item *
13889:
13890: reconlonc() : tries to reconnect lonc client processes.
13891:
13892: =back
13893:
13894: =head2 Resource Access Logging
13895:
13896: =over 4
13897:
13898: =item *
13899:
13900: flushcourselogs() : flush (save) buffer logs and access logs
13901:
13902: =item *
13903:
13904: courselog($what) : save message for course in hash
13905:
13906: =item *
13907:
13908: courseacclog($what) : save message for course using &courselog(). Perform
13909: special processing for specific resource types (problems, exams, quizzes, etc).
13910:
1.191 harris41 13911: =item *
13912:
13913: goodbye() : flush course logs and log shutting down; it is called in srm.conf
13914: as a PerlChildExitHandler
1.243 albertel 13915:
13916: =back
13917:
13918: =head2 Other
13919:
13920: =over 4
13921:
13922: =item *
13923:
13924: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 13925:
13926: =back
13927:
13928: =cut
1.877 foxr 13929:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>