Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1254
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1254 ! raeburn 4: # $Id: lonnet.pm,v 1.1253 2014/03/25 09:41:08 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 {
7863: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
7864: my ($homeserver,$response);
7865: if ($dom =~ /^$match_domain$/) {
7866: $homeserver = &domain($dom,'primary');
7867: }
7868: unless ($homeserver eq 'no_host') {
1.1021 raeburn 7869:
1.1020 raeburn 7870: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 7871: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020 raeburn 7872: ':'.&escape($instcode).':'.&escape($instseclist),
7873: $homeserver));
7874: }
7875: return $response;
7876: }
7877:
1.777 albertel 7878: sub auto_validate_class_sec {
1.918 raeburn 7879: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 7880: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 7881: my $ownerlist;
7882: if (ref($owners) eq 'ARRAY') {
7883: $ownerlist = join(',',@{$owners});
7884: } else {
7885: $ownerlist = $owners;
7886: }
1.773 raeburn 7887: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 7888: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 7889: return $response;
7890: }
7891:
1.1248 raeburn 7892: sub auto_crsreq_update {
7893: my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
7894: $code,$inbound) = @_;
7895: my ($homeserver,%crsreqresponse);
7896: if ($cdom =~ /^$match_domain$/) {
7897: $homeserver = &domain($cdom,'primary');
7898: }
7899: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
7900: my $info;
7901: if (ref($inbound) eq 'HASH') {
7902: $info = &freeze_escape($inbound);
7903: }
7904: my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
7905: ':'.&escape($action).':'.&escape($ownername).':'.
7906: &escape($ownerdomain).':'.&escape($fullname).':'.
7907: &escape($title).':'.&escape($code).':'.$info,$homeserver);
7908: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
7909: my @items = split(/&/,$response);
7910: foreach my $item (@items) {
7911: my ($key,$value) = split('=',$item);
7912: $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
7913: }
7914: }
7915: }
7916: return \%crsreqresponse;
7917: }
7918:
1.679 raeburn 7919: # ------------------------------------------------------- Course Group routines
7920:
7921: sub get_coursegroups {
1.809 raeburn 7922: my ($cdom,$cnum,$group,$namespace) = @_;
7923: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 7924: }
7925:
1.679 raeburn 7926: sub modify_coursegroup {
7927: my ($cdom,$cnum,$groupsettings) = @_;
7928: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
7929: }
7930:
1.809 raeburn 7931: sub toggle_coursegroup_status {
7932: my ($cdom,$cnum,$group,$action) = @_;
7933: my ($from_namespace,$to_namespace);
7934: if ($action eq 'delete') {
7935: $from_namespace = 'coursegroups';
7936: $to_namespace = 'deleted_groups';
7937: } else {
7938: $from_namespace = 'deleted_groups';
7939: $to_namespace = 'coursegroups';
7940: }
7941: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 7942: if (my $tmp = &error(%curr_group)) {
7943: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
7944: return ('read error',$tmp);
7945: } else {
7946: my %savedsettings = %curr_group;
1.809 raeburn 7947: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 7948: my $deloutcome;
7949: if ($result eq 'ok') {
1.809 raeburn 7950: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 7951: } else {
7952: return ('write error',$result);
7953: }
7954: if ($deloutcome eq 'ok') {
7955: return 'ok';
7956: } else {
7957: return ('delete error',$deloutcome);
7958: }
7959: }
7960: }
7961:
1.679 raeburn 7962: sub modify_group_roles {
1.957 raeburn 7963: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 7964: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
7965: my $role = 'gr/'.&escape($userprivs);
7966: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 7967: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 7968: if ($result eq 'ok') {
7969: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
7970: }
1.679 raeburn 7971: return $result;
7972: }
7973:
7974: sub modify_coursegroup_membership {
7975: my ($cdom,$cnum,$membership) = @_;
7976: my $result = &put('groupmembership',$membership,$cdom,$cnum);
7977: return $result;
7978: }
7979:
1.682 raeburn 7980: sub get_active_groups {
7981: my ($udom,$uname,$cdom,$cnum) = @_;
7982: my $now = time;
7983: my %groups = ();
7984: foreach my $key (keys(%env)) {
1.811 albertel 7985: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 7986: my ($start,$end) = split(/\./,$env{$key});
7987: if (($end!=0) && ($end<$now)) { next; }
7988: if (($start!=0) && ($start>$now)) { next; }
7989: if ($1 eq $cdom && $2 eq $cnum) {
7990: $groups{$3} = $env{$key} ;
7991: }
7992: }
7993: }
7994: return %groups;
7995: }
7996:
1.683 raeburn 7997: sub get_group_membership {
7998: my ($cdom,$cnum,$group) = @_;
7999: return(&dump('groupmembership',$cdom,$cnum,$group));
8000: }
8001:
8002: sub get_users_groups {
8003: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 8004: my @usersgroups;
1.683 raeburn 8005: my $cachetime=1800;
8006:
8007: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 8008: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
8009: if (defined($cached)) {
1.734 albertel 8010: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 8011: } else {
8012: $grouplist = '';
1.816 raeburn 8013: my $courseurl = &courseid_to_courseurl($courseid);
1.1166 raeburn 8014: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 8015: my $access_end = $env{'course.'.$courseid.
8016: '.default_enrollment_end_date'};
8017: my $now = time;
8018: foreach my $key (keys(%roleshash)) {
8019: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
8020: my $group = $1;
8021: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
8022: my $start = $2;
8023: my $end = $1;
8024: if ($start == -1) { next; } # deleted from group
8025: if (($start!=0) && ($start>$now)) { next; }
8026: if (($end!=0) && ($end<$now)) {
8027: if ($access_end && $access_end < $now) {
8028: if ($access_end - $end < 86400) {
8029: push(@usersgroups,$group);
1.733 raeburn 8030: }
8031: }
1.817 raeburn 8032: next;
1.733 raeburn 8033: }
1.817 raeburn 8034: push(@usersgroups,$group);
1.683 raeburn 8035: }
8036: }
8037: }
1.817 raeburn 8038: @usersgroups = &sort_course_groups($courseid,@usersgroups);
8039: $grouplist = join(':',@usersgroups);
8040: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 8041: }
1.733 raeburn 8042: return @usersgroups;
1.683 raeburn 8043: }
8044:
8045: sub devalidate_getgroups_cache {
8046: my ($udom,$uname,$cdom,$cnum)=@_;
8047: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 8048:
1.683 raeburn 8049: my $hashid="$udom:$uname:$courseid";
8050: &devalidate_cache_new('getgroups',$hashid);
8051: }
8052:
1.12 www 8053: # ------------------------------------------------------------------ Plain Text
8054:
8055: sub plaintext {
1.988 raeburn 8056: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 8057: if ($short =~ m{^cr/}) {
1.758 albertel 8058: return (split('/',$short))[-1];
8059: }
1.742 raeburn 8060: if (!defined($cid)) {
8061: $cid = $env{'request.course.id'};
8062: }
8063: my %rolenames = (
1.1008 raeburn 8064: Course => 'std',
8065: Community => 'alt1',
1.742 raeburn 8066: );
1.1037 raeburn 8067: if ($cid ne '') {
8068: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
8069: unless ($forcedefault) {
8070: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
8071: &Apache::lonlocal::mt_escape(\$roletext);
8072: return &Apache::lonlocal::mt($roletext);
8073: }
8074: }
8075: }
8076: if ((defined($type)) && (defined($rolenames{$type})) &&
8077: (defined($rolenames{$type})) &&
8078: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 8079: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 8080: } elsif ($cid ne '') {
8081: my $crstype = $env{'course.'.$cid.'.type'};
8082: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
8083: (defined($prp{$short}{$rolenames{$crstype}}))) {
8084: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
8085: }
1.742 raeburn 8086: }
1.1037 raeburn 8087: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 8088: }
8089:
8090: # ----------------------------------------------------------------- Assign Role
8091:
8092: sub assignrole {
1.957 raeburn 8093: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
8094: $context)=@_;
1.21 www 8095: my $mrole;
8096: if ($role =~ /^cr\//) {
1.393 www 8097: my $cwosec=$url;
1.811 albertel 8098: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 8099: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 8100: my $refused = 1;
8101: if ($context eq 'requestcourses') {
8102: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
8103: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
8104: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
8105: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8106: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8107: if ($crsenv{'internal.courseowner'} eq
8108: $env{'user.name'}.':'.$env{'user.domain'}) {
8109: $refused = '';
8110: }
8111: }
8112: }
8113: }
8114: }
8115: if ($refused) {
8116: &logthis('Refused custom assignrole: '.
8117: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
8118: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
8119: return 'refused';
8120: }
1.104 www 8121: }
1.21 www 8122: $mrole='cr';
1.678 raeburn 8123: } elsif ($role =~ /^gr\//) {
8124: my $cwogrp=$url;
1.811 albertel 8125: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 8126: unless (&allowed('mdg',$cwogrp)) {
8127: &logthis('Refused group assignrole: '.
8128: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
8129: $env{'user.name'}.' at '.$env{'user.domain'});
8130: return 'refused';
8131: }
8132: $mrole='gr';
1.21 www 8133: } else {
1.82 www 8134: my $cwosec=$url;
1.811 albertel 8135: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 8136: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
8137: my $refused;
8138: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
8139: if (!(&allowed('c'.$role,$url))) {
8140: $refused = 1;
8141: }
8142: } else {
8143: $refused = 1;
8144: }
1.947 raeburn 8145: if ($refused) {
1.1045 raeburn 8146: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8147: if (!$selfenroll && $context eq 'course') {
8148: my %crsenv;
8149: if ($role eq 'cc' || $role eq 'co') {
8150: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8151: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
8152: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
8153: if ($crsenv{'internal.courseowner'} eq
8154: $env{'user.name'}.':'.$env{'user.domain'}) {
8155: $refused = '';
8156: }
8157: }
8158: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
8159: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
8160: if ($crsenv{'internal.courseowner'} eq
8161: $env{'user.name'}.':'.$env{'user.domain'}) {
8162: $refused = '';
8163: }
8164: }
8165: }
8166: }
8167: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 8168: $refused = '';
1.1017 raeburn 8169: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 8170: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 8171: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 8172: my $wrongcc;
8173: if ($cnum =~ /^$match_community$/) {
8174: $wrongcc = 1 if ($role eq 'cc');
8175: } else {
8176: $wrongcc = 1 if ($role eq 'co');
8177: }
8178: unless ($wrongcc) {
8179: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8180: if ($crsenv{'internal.courseowner'} eq
8181: $env{'user.name'}.':'.$env{'user.domain'}) {
8182: $refused = '';
8183: }
1.1017 raeburn 8184: }
8185: }
1.1183 raeburn 8186: } elsif ($context eq 'requestauthor') {
8187: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
8188: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
8189: if ($env{'environment.requestauthor'} eq 'automatic') {
8190: $refused = '';
8191: } else {
8192: my %domdefaults = &get_domain_defaults($udom);
8193: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
8194: my $checkbystatus;
8195: if ($env{'user.adv'}) {
8196: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
8197: if ($disposition eq 'automatic') {
8198: $refused = '';
8199: } elsif ($disposition eq '') {
8200: $checkbystatus = 1;
8201: }
8202: } else {
8203: $checkbystatus = 1;
8204: }
8205: if ($checkbystatus) {
8206: if ($env{'environment.inststatus'}) {
8207: my @inststatuses = split(/,/,$env{'environment.inststatus'});
8208: foreach my $type (@inststatuses) {
8209: if (($type ne '') &&
8210: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
8211: $refused = '';
8212: }
8213: }
8214: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
8215: $refused = '';
8216: }
8217: }
8218: }
8219: }
8220: }
1.1017 raeburn 8221: }
8222: if ($refused) {
1.947 raeburn 8223: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
8224: ' '.$role.' '.$end.' '.$start.' by '.
8225: $env{'user.name'}.' at '.$env{'user.domain'});
8226: return 'refused';
8227: }
1.932 raeburn 8228: }
1.1131 raeburn 8229: } elsif ($role eq 'au') {
8230: if ($url ne '/'.$udom.'/') {
8231: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
8232: ' to assign author role for '.$uname.':'.$udom.
8233: ' in domain: '.$url.' refused (wrong domain).');
8234: return 'refused';
8235: }
1.104 www 8236: }
1.21 www 8237: $mrole=$role;
8238: }
1.620 albertel 8239: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 8240: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 8241: if ($end) { $command.='_'.$end; }
1.21 www 8242: if ($start) {
8243: if ($end) {
1.81 www 8244: $command.='_'.$start;
1.21 www 8245: } else {
1.81 www 8246: $command.='_0_'.$start;
1.21 www 8247: }
8248: }
1.739 raeburn 8249: my $origstart = $start;
8250: my $origend = $end;
1.957 raeburn 8251: my $delflag;
1.357 www 8252: # actually delete
8253: if ($deleteflag) {
1.373 www 8254: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 8255: # modify command to delete the role
1.620 albertel 8256: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 8257: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 8258: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 8259: # set start and finish to negative values for userrolelog
8260: $start=-1;
8261: $end=-1;
1.957 raeburn 8262: $delflag = 1;
1.357 www 8263: }
8264: }
8265: # send command
1.349 www 8266: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 8267: # log new user role if status is ok
1.349 www 8268: if ($answer eq 'ok') {
1.663 raeburn 8269: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.1184 raeburn 8270: if (($role eq 'cc') || ($role eq 'in') ||
8271: ($role eq 'ep') || ($role eq 'ad') ||
8272: ($role eq 'ta') || ($role eq 'st') ||
8273: ($role=~/^cr/) || ($role eq 'gr') ||
8274: ($role eq 'co')) {
1.1200 raeburn 8275: # for course roles, perform group memberships changes triggered by role change.
8276: unless ($role =~ /^gr/) {
8277: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
8278: $origstart,$selfenroll,$context);
8279: }
1.1184 raeburn 8280: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8281: $selfenroll,$context);
8282: } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
8283: ($role eq 'au') || ($role eq 'dc')) {
8284: &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8285: $context);
8286: } elsif (($role eq 'ca') || ($role eq 'aa')) {
8287: &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8288: $context);
8289: }
1.1053 raeburn 8290: if ($role eq 'cc') {
8291: &autoupdate_coowners($url,$end,$start,$uname,$udom);
8292: }
1.349 www 8293: }
8294: return $answer;
1.169 harris41 8295: }
8296:
1.1053 raeburn 8297: sub autoupdate_coowners {
8298: my ($url,$end,$start,$uname,$udom) = @_;
8299: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
8300: if (($cdom ne '') && ($cnum ne '')) {
8301: my $now = time;
8302: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
8303: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
8304: my %coursehash = &coursedescription($cdom.'_'.$cnum);
8305: my $instcode = $coursehash{'internal.coursecode'};
8306: if ($instcode ne '') {
1.1056 raeburn 8307: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
8308: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 8309: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 8310: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
8311: if ($result eq 'valid') {
8312: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 8313: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
8314: push(@newcoowners,$coowner);
8315: }
8316: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
8317: push(@newcoowners,$uname.':'.$udom);
8318: }
8319: @newcoowners = sort(@newcoowners);
8320: } else {
8321: push(@newcoowners,$uname.':'.$udom);
8322: }
8323: } else {
8324: if ($coursehash{'internal.co-owners'}) {
8325: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
8326: unless ($coowner eq $uname.':'.$udom) {
8327: push(@newcoowners,$coowner);
8328: }
8329: }
8330: unless (@newcoowners > 0) {
8331: $delcoowners = 1;
8332: $coowners = '';
8333: }
8334: }
8335: }
8336: if (@newcoowners || $delcoowners) {
8337: &store_coowners($cdom,$cnum,$coursehash{'home'},
8338: $delcoowners,@newcoowners);
8339: }
8340: }
8341: }
8342: }
8343: }
8344: }
8345: }
8346:
8347: sub store_coowners {
8348: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
8349: my $cid = $cdom.'_'.$cnum;
8350: my ($coowners,$delresult,$putresult);
8351: if (@newcoowners) {
8352: $coowners = join(',',@newcoowners);
8353: my %coownershash = (
8354: 'internal.co-owners' => $coowners,
8355: );
8356: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
8357: if ($putresult eq 'ok') {
8358: if ($env{'course.'.$cid.'.num'} eq $cnum) {
8359: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
8360: }
8361: }
8362: }
8363: if ($delcoowners) {
8364: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
8365: if ($delresult eq 'ok') {
8366: if ($env{'course.'.$cid.'.internal.co-owners'}) {
8367: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
8368: }
8369: }
8370: }
8371: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
8372: my %crsinfo =
8373: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
8374: if (ref($crsinfo{$cid}) eq 'HASH') {
8375: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
8376: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
8377: }
8378: }
8379: }
8380:
1.169 harris41 8381: # -------------------------------------------------- Modify user authentication
1.197 www 8382: # Overrides without validation
8383:
1.169 harris41 8384: sub modifyuserauth {
8385: my ($udom,$uname,$umode,$upass)=@_;
8386: my $uhome=&homeserver($uname,$udom);
1.197 www 8387: unless (&allowed('mau',$udom)) { return 'refused'; }
8388: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 8389: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
8390: ' in domain '.$env{'request.role.domain'});
1.169 harris41 8391: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
8392: &escape($upass),$uhome);
1.620 albertel 8393: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 8394: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
8395: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
8396: &log($udom,,$uname,$uhome,
1.620 albertel 8397: 'Authentication changed by '.$env{'user.domain'}.', '.
8398: $env{'user.name'}.', '.$umode.
1.197 www 8399: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 8400: unless ($reply eq 'ok') {
1.197 www 8401: &logthis('Authentication mode error: '.$reply);
1.169 harris41 8402: return 'error: '.$reply;
8403: }
1.170 harris41 8404: return 'ok';
1.80 www 8405: }
8406:
1.81 www 8407: # --------------------------------------------------------------- Modify a user
1.80 www 8408:
1.81 www 8409: sub modifyuser {
1.206 matthew 8410: my ($udom, $uname, $uid,
8411: $umode, $upass, $first,
8412: $middle, $last, $gene,
1.1058 raeburn 8413: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 8414: $udom= &LONCAPA::clean_domain($udom);
8415: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 8416: my $showcandelete = 'none';
8417: if (ref($candelete) eq 'ARRAY') {
8418: if (@{$candelete} > 0) {
8419: $showcandelete = join(', ',@{$candelete});
8420: }
8421: }
1.81 www 8422: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 8423: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 8424: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 8425: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
8426: ' desiredhome not specified').
1.620 albertel 8427: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
8428: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 8429: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 8430: my $newuser;
8431: if ($uhome eq 'no_host') {
8432: $newuser = 1;
8433: }
1.80 www 8434: # ----------------------------------------------------------------- Create User
1.406 albertel 8435: if (($uhome eq 'no_host') &&
8436: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 8437: my $unhome='';
1.844 albertel 8438: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 8439: $unhome = $desiredhome;
1.620 albertel 8440: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
8441: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 8442: } else { # load balancing routine for determining $unhome
1.81 www 8443: my $loadm=10000000;
1.841 albertel 8444: my %servers = &get_servers($udom,'library');
8445: foreach my $tryserver (keys(%servers)) {
8446: my $answer=reply('load',$tryserver);
8447: if (($answer=~/\d+/) && ($answer<$loadm)) {
8448: $loadm=$answer;
8449: $unhome=$tryserver;
8450: }
1.80 www 8451: }
8452: }
8453: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 8454: return 'error: unable to find a home server for '.$uname.
8455: ' in domain '.$udom;
1.80 www 8456: }
8457: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
8458: &escape($upass),$unhome);
8459: unless ($reply eq 'ok') {
8460: return 'error: '.$reply;
8461: }
1.230 stredwic 8462: $uhome=&homeserver($uname,$udom,'true');
1.80 www 8463: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 8464: return 'error: unable verify users home machine.';
1.80 www 8465: }
1.209 matthew 8466: } # End of creation of new user
1.80 www 8467: # ---------------------------------------------------------------------- Add ID
8468: if ($uid) {
8469: $uid=~tr/A-Z/a-z/;
8470: my %uidhash=&idrget($udom,$uname);
1.196 www 8471: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
8472: && (!$forceid)) {
1.80 www 8473: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 8474: return 'error: user id "'.$uid.'" does not match '.
8475: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 8476: }
8477: } else {
8478: &idput($udom,($uname => $uid));
8479: }
8480: }
8481: # -------------------------------------------------------------- Add names, etc
1.313 matthew 8482: my @tmp=&get('environment',
1.899 raeburn 8483: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 8484: 'permanentemail','inststatus'],
1.134 albertel 8485: $udom,$uname);
1.1075 raeburn 8486: my (%names,%oldnames);
1.313 matthew 8487: if ($tmp[0] =~ m/^error:.*/) {
8488: %names=();
8489: } else {
8490: %names = @tmp;
1.1075 raeburn 8491: %oldnames = %names;
1.313 matthew 8492: }
1.388 www 8493: #
1.1058 raeburn 8494: # If name, email and/or uid are blank (e.g., because an uploaded file
8495: # of users did not contain them), do not overwrite existing values
8496: # unless field is in $candelete array ref.
8497: #
8498:
8499: my @fields = ('firstname','middlename','lastname','generation',
8500: 'permanentemail','id');
8501: my %newvalues;
8502: if (ref($candelete) eq 'ARRAY') {
8503: foreach my $field (@fields) {
8504: if (grep(/^\Q$field\E$/,@{$candelete})) {
8505: if ($field eq 'firstname') {
8506: $names{$field} = $first;
8507: } elsif ($field eq 'middlename') {
8508: $names{$field} = $middle;
8509: } elsif ($field eq 'lastname') {
8510: $names{$field} = $last;
8511: } elsif ($field eq 'generation') {
8512: $names{$field} = $gene;
8513: } elsif ($field eq 'permanentemail') {
8514: $names{$field} = $email;
8515: } elsif ($field eq 'id') {
8516: $names{$field} = $uid;
8517: }
8518: }
8519: }
8520: }
1.388 www 8521: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 8522: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 8523: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 8524: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 8525: if ($email) {
8526: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 8527: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 8528: }
1.899 raeburn 8529: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 8530: if (defined($inststatus)) {
8531: $names{'inststatus'} = '';
8532: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
8533: if (ref($usertypes) eq 'HASH') {
8534: my @okstatuses;
8535: foreach my $item (split(/:/,$inststatus)) {
8536: if (defined($usertypes->{$item})) {
8537: push(@okstatuses,$item);
8538: }
8539: }
8540: if (@okstatuses) {
8541: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
8542: }
8543: }
8544: }
1.1075 raeburn 8545: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 8546: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 8547: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 8548: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
8549: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
8550: } else {
8551: $logmsg .= ' during self creation';
8552: }
1.1075 raeburn 8553: my $changed;
8554: if ($newuser) {
8555: $changed = 1;
8556: } else {
8557: foreach my $field (@fields) {
8558: if ($names{$field} ne $oldnames{$field}) {
8559: $changed = 1;
8560: last;
8561: }
8562: }
8563: }
8564: unless ($changed) {
8565: $logmsg = 'No changes in user information needed for: '.$logmsg;
8566: &logthis($logmsg);
8567: return 'ok';
8568: }
8569: my $reply = &put('environment', \%names, $udom,$uname);
8570: if ($reply ne 'ok') {
8571: return 'error: '.$reply;
8572: }
1.1087 raeburn 8573: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
8574: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
8575: }
1.1075 raeburn 8576: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
8577: &devalidate_cache_new('namescache',$uname.':'.$udom);
8578: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 8579: &logthis($logmsg);
1.134 albertel 8580: return 'ok';
1.80 www 8581: }
8582:
1.81 www 8583: # -------------------------------------------------------------- Modify student
1.80 www 8584:
1.81 www 8585: sub modifystudent {
8586: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 8587: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1216 raeburn 8588: $selfenroll,$context,$inststatus,$credits)=@_;
1.455 albertel 8589: if (!$cid) {
1.620 albertel 8590: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 8591: return 'not_in_class';
8592: }
1.80 www 8593: }
8594: # --------------------------------------------------------------- Make the user
1.81 www 8595: my $reply=&modifyuser
1.209 matthew 8596: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 8597: $desiredhome,$email,$inststatus);
1.80 www 8598: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 8599: # This will cause &modify_student_enrollment to get the uid from the
1.1235 raeburn 8600: # student's environment
1.297 matthew 8601: $uid = undef if (!$forceid);
1.455 albertel 8602: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1216 raeburn 8603: $gene,$usec,$end,$start,$type,$locktype,
8604: $cid,$selfenroll,$context,$credits);
1.297 matthew 8605: return $reply;
8606: }
8607:
8608: sub modify_student_enrollment {
1.1216 raeburn 8609: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
8610: $locktype,$cid,$selfenroll,$context,$credits) = @_;
1.455 albertel 8611: my ($cdom,$cnum,$chome);
8612: if (!$cid) {
1.620 albertel 8613: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 8614: return 'not_in_class';
8615: }
1.620 albertel 8616: $cdom=$env{'course.'.$cid.'.domain'};
8617: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 8618: } else {
8619: ($cdom,$cnum)=split(/_/,$cid);
8620: }
1.620 albertel 8621: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 8622: if (!$chome) {
1.457 raeburn 8623: $chome=&homeserver($cnum,$cdom);
1.297 matthew 8624: }
1.455 albertel 8625: if (!$chome) { return 'unknown_course'; }
1.297 matthew 8626: # Make sure the user exists
1.81 www 8627: my $uhome=&homeserver($uname,$udom);
8628: if (($uhome eq '') || ($uhome eq 'no_host')) {
8629: return 'error: no such user';
8630: }
1.297 matthew 8631: # Get student data if we were not given enough information
8632: if (!defined($first) || $first eq '' ||
8633: !defined($last) || $last eq '' ||
8634: !defined($uid) || $uid eq '' ||
8635: !defined($middle) || $middle eq '' ||
8636: !defined($gene) || $gene eq '') {
1.294 matthew 8637: # They did not supply us with enough data to enroll the student, so
8638: # we need to pick up more information.
1.297 matthew 8639: my %tmp = &get('environment',
1.294 matthew 8640: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 8641: ,$udom,$uname);
8642:
1.800 albertel 8643: #foreach my $key (keys(%tmp)) {
8644: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 8645: #}
1.294 matthew 8646: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
8647: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
8648: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 8649: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 8650: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
8651: }
1.556 albertel 8652: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148 raeburn 8653: my $user = "$uname:$udom";
8654: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487 albertel 8655: my $reply=cput('classlist',
1.1148 raeburn 8656: {$user =>
1.1216 raeburn 8657: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits) },
1.487 albertel 8658: $cdom,$cnum);
1.1148 raeburn 8659: if (($reply eq 'ok') || ($reply eq 'delayed')) {
8660: &devalidate_getsection_cache($udom,$uname,$cid);
8661: } else {
1.81 www 8662: return 'error: '.$reply;
8663: }
1.297 matthew 8664: # Add student role to user
1.83 www 8665: my $uurl='/'.$cid;
1.81 www 8666: $uurl=~s/\_/\//g;
8667: if ($usec) {
8668: $uurl.='/'.$usec;
8669: }
1.1148 raeburn 8670: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
8671: $selfenroll,$context);
8672: if ($result ne 'ok') {
8673: if ($old_entry{$user} ne '') {
8674: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
8675: } else {
8676: $reply = &del('classlist',[$user],$cdom,$cnum);
8677: }
8678: }
8679: return $result;
1.21 www 8680: }
8681:
1.556 albertel 8682: sub format_name {
8683: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
8684: my $name;
8685: if ($first ne 'lastname') {
8686: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
8687: } else {
8688: if ($lastname=~/\S/) {
8689: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
8690: $name=~s/\s+,/,/;
8691: } else {
8692: $name.= $firstname.' '.$middlename.' '.$generation;
8693: }
8694: }
8695: $name=~s/^\s+//;
8696: $name=~s/\s+$//;
8697: $name=~s/\s+/ /g;
8698: return $name;
8699: }
8700:
1.84 www 8701: # ------------------------------------------------- Write to course preferences
8702:
8703: sub writecoursepref {
8704: my ($courseid,%prefs)=@_;
8705: $courseid=~s/^\///;
8706: $courseid=~s/\_/\//g;
8707: my ($cdomain,$cnum)=split(/\//,$courseid);
8708: my $chome=homeserver($cnum,$cdomain);
8709: if (($chome eq '') || ($chome eq 'no_host')) {
8710: return 'error: no such course';
8711: }
8712: my $cstring='';
1.800 albertel 8713: foreach my $pref (keys(%prefs)) {
8714: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 8715: }
1.84 www 8716: $cstring=~s/\&$//;
8717: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
8718: }
8719:
8720: # ---------------------------------------------------------- Make/modify course
8721:
8722: sub createcourse {
1.741 raeburn 8723: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 8724: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 8725: $url=&declutter($url);
8726: my $cid='';
1.1028 raeburn 8727: if ($context eq 'requestcourses') {
8728: my $can_create = 0;
8729: my ($ownername,$ownerdom) = split(':',$course_owner);
8730: if ($udom eq $ownerdom) {
8731: if (&usertools_access($ownername,$ownerdom,$category,undef,
8732: $context)) {
8733: $can_create = 1;
8734: }
8735: } else {
8736: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
8737: $category);
8738: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
8739: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
8740: if (@curr > 0) {
8741: my @options = qw(approval validate autolimit);
8742: my $optregex = join('|',@options);
8743: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
8744: $can_create = 1;
8745: }
8746: }
8747: }
8748: }
8749: if ($can_create) {
8750: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
8751: unless (&allowed('ccc',$udom)) {
8752: return 'refused';
8753: }
1.1017 raeburn 8754: }
8755: } else {
8756: return 'refused';
8757: }
1.1028 raeburn 8758: } elsif (!&allowed('ccc',$udom)) {
8759: return 'refused';
1.84 www 8760: }
1.1011 raeburn 8761: # --------------------------------------------------------------- Get Unique ID
8762: my $uname;
8763: if ($cnum =~ /^$match_courseid$/) {
8764: my $chome=&homeserver($cnum,$udom,'true');
8765: if (($chome eq '') || ($chome eq 'no_host')) {
8766: $uname = $cnum;
8767: } else {
1.1038 raeburn 8768: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 8769: }
8770: } else {
1.1038 raeburn 8771: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 8772: }
8773: return $uname if ($uname =~ /^error/);
8774: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 8775: if (!defined($course_server)) {
8776: if (defined(&domain($udom,'primary'))) {
8777: $course_server = &domain($udom,'primary');
8778: } else {
8779: $course_server = $env{'user.home'};
8780: }
8781: }
8782: my %host_servers =
8783: &Apache::lonnet::get_servers($udom,'library');
8784: unless ($host_servers{$course_server}) {
8785: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 8786: }
1.84 www 8787: # ------------------------------------------------------------- Make the course
8788: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 8789: $course_server);
1.84 www 8790: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 8791: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 8792: if (($uhome eq '') || ($uhome eq 'no_host')) {
8793: return 'error: no such course';
8794: }
1.271 www 8795: # ----------------------------------------------------------------- Course made
1.516 raeburn 8796: # log existence
1.1029 raeburn 8797: my $now = time;
1.918 raeburn 8798: my $newcourse = {
8799: $udom.'_'.$uname => {
1.921 raeburn 8800: description => $description,
8801: inst_code => $inst_code,
8802: owner => $course_owner,
8803: type => $crstype,
1.1029 raeburn 8804: creator => $env{'user.name'}.':'.
8805: $env{'user.domain'},
8806: created => $now,
8807: context => $context,
1.918 raeburn 8808: },
8809: };
1.921 raeburn 8810: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 8811: # set toplevel url
1.271 www 8812: my $topurl=$url;
8813: unless ($nonstandard) {
8814: # ------------------------------------------ For standard courses, make top url
8815: my $mapurl=&clutter($url);
1.278 www 8816: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 8817: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 8818: <map>
8819: <resource id="1" type="start"></resource>
8820: <resource id="2" src="$mapurl"></resource>
8821: <resource id="3" type="finish"></resource>
8822: <link index="1" from="1" to="2"></link>
8823: <link index="2" from="2" to="3"></link>
8824: </map>
8825: ENDINITMAP
8826: $topurl=&declutter(
1.638 albertel 8827: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 8828: );
8829: }
8830: # ----------------------------------------------------------- Write preferences
1.84 www 8831: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 8832: ('description' => $description,
8833: 'url' => $topurl,
8834: 'internal.creator' => $env{'user.name'}.':'.
8835: $env{'user.domain'},
8836: 'internal.created' => $now,
8837: 'internal.creationcontext' => $context)
8838: );
1.84 www 8839: return '/'.$udom.'/'.$uname;
8840: }
8841:
1.1011 raeburn 8842: # ------------------------------------------------------------------- Create ID
8843: sub generate_coursenum {
1.1038 raeburn 8844: my ($udom,$crstype) = @_;
1.1011 raeburn 8845: my $domdesc = &domain($udom);
8846: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 8847: my $first;
8848: if ($crstype eq 'Community') {
8849: $first = '0';
8850: } else {
8851: $first = int(1+rand(9));
8852: }
8853: my $uname=$first.
1.1011 raeburn 8854: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
8855: substr($$.time,0,5).unpack("H8",pack("I32",time)).
8856: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
8857: # ----------------------------------------------- Make sure that does not exist
8858: my $uhome=&homeserver($uname,$udom,'true');
8859: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 8860: if ($crstype eq 'Community') {
8861: $first = '0';
8862: } else {
8863: $first = int(1+rand(9));
8864: }
8865: $uname=$first.
1.1011 raeburn 8866: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
8867: substr($$.time,0,5).unpack("H8",pack("I32",time)).
8868: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
8869: $uhome=&homeserver($uname,$udom,'true');
8870: unless (($uhome eq '') || ($uhome eq 'no_host')) {
8871: return 'error: unable to generate unique course-ID';
8872: }
8873: }
8874: return $uname;
8875: }
8876:
1.813 albertel 8877: sub is_course {
1.1167 droeschl 8878: my ($cdom, $cnum) = scalar(@_) == 1 ?
8879: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
8880:
8881: return unless $cdom and $cnum;
8882:
8883: my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
8884: '.');
8885:
1.1219 raeburn 8886: return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167 droeschl 8887: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813 albertel 8888: }
8889:
1.1015 raeburn 8890: sub store_userdata {
8891: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 8892: my $result;
1.1016 raeburn 8893: if ($datakey ne '') {
1.1013 raeburn 8894: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 8895: if ($udom eq '' || $uname eq '') {
8896: $udom = $env{'user.domain'};
8897: $uname = $env{'user.name'};
8898: }
8899: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 8900: if (($uhome eq '') || ($uhome eq 'no_host')) {
8901: $result = 'error: no_host';
8902: } else {
8903: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
8904: $storehash->{'host'} = $perlvar{'lonHostID'};
8905:
8906: my $namevalue='';
8907: foreach my $key (keys(%{$storehash})) {
8908: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
8909: }
8910: $namevalue=~s/\&$//;
1.1224 raeburn 8911: unless ($namespace eq 'courserequests') {
8912: $datakey = &escape($datakey);
8913: }
1.1105 raeburn 8914: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
8915: $namevalue,$uhome);
1.1013 raeburn 8916: }
8917: } else {
8918: $result = 'error: data to store was not a hash reference';
8919: }
8920: } else {
8921: $result= 'error: invalid requestkey';
8922: }
8923: return $result;
8924: }
8925:
1.21 www 8926: # ---------------------------------------------------------- Assign Custom Role
8927:
8928: sub assigncustomrole {
1.957 raeburn 8929: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 8930: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 8931: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 8932: }
8933:
8934: # ----------------------------------------------------------------- Revoke Role
8935:
8936: sub revokerole {
1.957 raeburn 8937: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 8938: my $now=time;
1.965 raeburn 8939: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 8940: }
8941:
8942: # ---------------------------------------------------------- Revoke Custom Role
8943:
8944: sub revokecustomrole {
1.957 raeburn 8945: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 8946: my $now=time;
1.357 www 8947: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 8948: $deleteflag,$selfenroll,$context);
1.17 www 8949: }
8950:
1.533 banghart 8951: # ------------------------------------------------------------ Disk usage
1.535 albertel 8952: sub diskusage {
1.955 raeburn 8953: my ($udom,$uname,$directorypath,$getpropath)=@_;
8954: $directorypath =~ s/\/$//;
8955: my $listing=&reply('du2:'.&escape($directorypath).':'
8956: .&escape($getpropath).':'.&escape($uname).':'
8957: .&escape($udom),homeserver($uname,$udom));
8958: if ($listing eq 'unknown_cmd') {
8959: if ($getpropath) {
8960: $directorypath = &propath($udom,$uname).'/'.$directorypath;
8961: }
8962: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
8963: }
1.514 albertel 8964: return $listing;
1.512 banghart 8965: }
8966:
1.566 banghart 8967: sub is_locked {
1.1096 raeburn 8968: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 8969: my @check;
8970: my $is_locked;
1.1093 raeburn 8971: push (@check,$file_name);
1.613 albertel 8972: my %locked = &get('file_permissions',\@check,
1.620 albertel 8973: $env{'user.domain'},$env{'user.name'});
1.615 albertel 8974: my ($tmp)=keys(%locked);
8975: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 8976:
1.566 banghart 8977: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 8978: $is_locked = 'false';
8979: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 8980: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 8981: $is_locked = 'true';
1.1096 raeburn 8982: if (ref($which) eq 'ARRAY') {
8983: push(@{$which},$entry);
8984: } else {
8985: last;
8986: }
1.745 raeburn 8987: }
8988: }
1.566 banghart 8989: } else {
8990: $is_locked = 'false';
8991: }
1.1093 raeburn 8992: return $is_locked;
1.566 banghart 8993: }
8994:
1.759 albertel 8995: sub declutter_portfile {
8996: my ($file) = @_;
1.833 albertel 8997: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 8998: return $file;
8999: }
9000:
1.559 banghart 9001: # ------------------------------------------------------------- Mark as Read Only
9002:
9003: sub mark_as_readonly {
9004: my ($domain,$user,$files,$what) = @_;
1.613 albertel 9005: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 9006: my ($tmp)=keys(%current_permissions);
9007: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 9008: foreach my $file (@{$files}) {
1.759 albertel 9009: $file = &declutter_portfile($file);
1.561 banghart 9010: push(@{$current_permissions{$file}},$what);
1.559 banghart 9011: }
1.613 albertel 9012: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 9013: return;
9014: }
9015:
1.572 banghart 9016: # ------------------------------------------------------------Save Selected Files
9017:
9018: sub save_selected_files {
9019: my ($user, $path, @files) = @_;
9020: my $filename = $user."savedfiles";
1.573 banghart 9021: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 9022: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 9023: foreach my $file (@files) {
1.620 albertel 9024: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 9025: }
9026: foreach my $file (@other_files) {
1.574 banghart 9027: print (OUT $file."\n");
1.572 banghart 9028: }
1.574 banghart 9029: close (OUT);
1.572 banghart 9030: return 'ok';
9031: }
9032:
1.574 banghart 9033: sub clear_selected_files {
9034: my ($user) = @_;
9035: my $filename = $user."savedfiles";
1.1117 foxr 9036: open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574 banghart 9037: print (OUT undef);
9038: close (OUT);
9039: return ("ok");
9040: }
9041:
1.572 banghart 9042: sub files_in_path {
9043: my ($user, $path) = @_;
9044: my $filename = $user."savedfiles";
9045: my %return_files;
1.1117 foxr 9046: open (IN, '<'.LONCAPA::tempdir().$filename);
1.573 banghart 9047: while (my $line_in = <IN>) {
1.574 banghart 9048: chomp ($line_in);
9049: my @paths_and_file = split (m!/!, $line_in);
9050: my $file_part = pop (@paths_and_file);
9051: my $path_part = join ('/', @paths_and_file);
1.573 banghart 9052: $path_part.='/';
9053: my $path_and_file = $path_part.$file_part;
9054: if ($path_part eq $path) {
9055: $return_files{$file_part}= 'selected';
9056: }
9057: }
1.574 banghart 9058: close (IN);
9059: return (\%return_files);
1.572 banghart 9060: }
9061:
9062: # called in portfolio select mode, to show files selected NOT in current directory
9063: sub files_not_in_path {
9064: my ($user, $path) = @_;
9065: my $filename = $user."savedfiles";
9066: my @return_files;
9067: my $path_part;
1.1117 foxr 9068: open(IN, '<'.LONCAPA::.$filename);
1.800 albertel 9069: while (my $line = <IN>) {
1.572 banghart 9070: #ok, I know it's clunky, but I want it to work
1.800 albertel 9071: my @paths_and_file = split(m|/|, $line);
9072: my $file_part = pop(@paths_and_file);
9073: chomp($file_part);
9074: my $path_part = join('/', @paths_and_file);
1.572 banghart 9075: $path_part .= '/';
9076: my $path_and_file = $path_part.$file_part;
9077: if ($path_part ne $path) {
1.800 albertel 9078: push(@return_files, ($path_and_file));
1.572 banghart 9079: }
9080: }
1.800 albertel 9081: close(OUT);
1.574 banghart 9082: return (@return_files);
1.572 banghart 9083: }
9084:
1.745 raeburn 9085: #----------------------------------------------Get portfolio file permissions
1.629 banghart 9086:
1.745 raeburn 9087: sub get_portfile_permissions {
9088: my ($domain,$user) = @_;
1.613 albertel 9089: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 9090: my ($tmp)=keys(%current_permissions);
9091: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 9092: return \%current_permissions;
9093: }
9094:
9095: #---------------------------------------------Get portfolio file access controls
9096:
1.749 raeburn 9097: sub get_access_controls {
1.745 raeburn 9098: my ($current_permissions,$group,$file) = @_;
1.769 albertel 9099: my %access;
9100: my $real_file = $file;
9101: $file =~ s/\.meta$//;
1.745 raeburn 9102: if (defined($file)) {
1.749 raeburn 9103: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
9104: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 9105: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 9106: }
9107: }
1.745 raeburn 9108: } else {
1.749 raeburn 9109: foreach my $key (keys(%{$current_permissions})) {
9110: if ($key =~ /\0accesscontrol$/) {
9111: if (defined($group)) {
9112: if ($key !~ m-^\Q$group\E/-) {
9113: next;
9114: }
9115: }
9116: my ($fullpath) = split(/\0/,$key);
9117: if (ref($$current_permissions{$key}) eq 'HASH') {
9118: foreach my $control (keys(%{$$current_permissions{$key}})) {
9119: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
9120: }
9121: }
9122: }
9123: }
9124: }
9125: return %access;
9126: }
9127:
9128: sub modify_access_controls {
9129: my ($file_name,$changes,$domain,$user)=@_;
9130: my ($outcome,$deloutcome);
9131: my %store_permissions;
9132: my %new_values;
9133: my %new_control;
9134: my %translation;
9135: my @deletions = ();
9136: my $now = time;
9137: if (exists($$changes{'activate'})) {
9138: if (ref($$changes{'activate'}) eq 'HASH') {
9139: my @newitems = sort(keys(%{$$changes{'activate'}}));
9140: my $numnew = scalar(@newitems);
9141: for (my $i=0; $i<$numnew; $i++) {
9142: my $newkey = $newitems[$i];
9143: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 9144: if ($newkey =~ /^\d+:/) {
9145: $newkey =~ s/^(\d+)/$newid/;
9146: $translation{$1} = $newid;
9147: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
9148: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
9149: $translation{$1} = $newid;
9150: }
1.749 raeburn 9151: $new_values{$file_name."\0".$newkey} =
9152: $$changes{'activate'}{$newitems[$i]};
9153: $new_control{$newkey} = $now;
9154: }
9155: }
9156: }
9157: my %todelete;
9158: my %changed_items;
9159: foreach my $action ('delete','update') {
9160: if (exists($$changes{$action})) {
9161: if (ref($$changes{$action}) eq 'HASH') {
9162: foreach my $key (keys(%{$$changes{$action}})) {
9163: my ($itemnum) = ($key =~ /^([^:]+):/);
9164: if ($action eq 'delete') {
9165: $todelete{$itemnum} = 1;
9166: } else {
9167: $changed_items{$itemnum} = $key;
9168: }
9169: }
1.745 raeburn 9170: }
9171: }
1.749 raeburn 9172: }
9173: # get lock on access controls for file.
9174: my $lockhash = {
9175: $file_name."\0".'locked_access_records' => $env{'user.name'}.
9176: ':'.$env{'user.domain'},
9177: };
9178: my $tries = 0;
9179: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9180:
9181: while (($gotlock ne 'ok') && $tries <3) {
9182: $tries ++;
9183: sleep 1;
9184: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9185: }
9186: if ($gotlock eq 'ok') {
9187: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
9188: my ($tmp)=keys(%curr_permissions);
9189: if ($tmp=~/^error:/) { undef(%curr_permissions); }
9190: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
9191: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
9192: if (ref($curr_controls) eq 'HASH') {
9193: foreach my $control_item (keys(%{$curr_controls})) {
9194: my ($itemnum) = ($control_item =~ /^([^:]+):/);
9195: if (defined($todelete{$itemnum})) {
9196: push(@deletions,$file_name."\0".$control_item);
9197: } else {
9198: if (defined($changed_items{$itemnum})) {
9199: $new_control{$changed_items{$itemnum}} = $now;
9200: push(@deletions,$file_name."\0".$control_item);
9201: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
9202: } else {
9203: $new_control{$control_item} = $$curr_controls{$control_item};
9204: }
9205: }
1.745 raeburn 9206: }
9207: }
9208: }
1.970 raeburn 9209: my ($group);
9210: if (&is_course($domain,$user)) {
9211: ($group,my $file) = split(/\//,$file_name,2);
9212: }
1.749 raeburn 9213: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
9214: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
9215: $outcome = &put('file_permissions',\%new_values,$domain,$user);
9216: # remove lock
9217: my @del_lock = ($file_name."\0".'locked_access_records');
9218: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 9219: my $sqlresult =
1.970 raeburn 9220: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 9221: $group);
1.749 raeburn 9222: } else {
9223: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 9224: }
1.749 raeburn 9225: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 9226: }
9227:
1.827 raeburn 9228: sub make_public_indefinitely {
9229: my ($requrl) = @_;
9230: my $now = time;
9231: my $action = 'activate';
9232: my $aclnum = 0;
9233: if (&is_portfolio_url($requrl)) {
9234: my (undef,$udom,$unum,$file_name,$group) =
9235: &parse_portfolio_url($requrl);
9236: my $current_perms = &get_portfile_permissions($udom,$unum);
9237: my %access_controls = &get_access_controls($current_perms,
9238: $group,$file_name);
9239: foreach my $key (keys(%{$access_controls{$file_name}})) {
9240: my ($num,$scope,$end,$start) =
9241: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
9242: if ($scope eq 'public') {
9243: if ($start <= $now && $end == 0) {
9244: $action = 'none';
9245: } else {
9246: $action = 'update';
9247: $aclnum = $num;
9248: }
9249: last;
9250: }
9251: }
9252: if ($action eq 'none') {
9253: return 'ok';
9254: } else {
9255: my %changes;
9256: my $newend = 0;
9257: my $newstart = $now;
9258: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
9259: $changes{$action}{$newkey} = {
9260: type => 'public',
9261: time => {
9262: start => $newstart,
9263: end => $newend,
9264: },
9265: };
9266: my ($outcome,$deloutcome,$new_values,$translation) =
9267: &modify_access_controls($file_name,\%changes,$udom,$unum);
9268: return $outcome;
9269: }
9270: } else {
9271: return 'invalid';
9272: }
9273: }
9274:
1.745 raeburn 9275: #------------------------------------------------------Get Marked as Read Only
9276:
9277: sub get_marked_as_readonly {
9278: my ($domain,$user,$what,$group) = @_;
9279: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 9280: my @readonly_files;
1.629 banghart 9281: my $cmp1=$what;
9282: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 9283: while (my ($file_name,$value) = each(%{$current_permissions})) {
9284: if (defined($group)) {
9285: if ($file_name !~ m-^\Q$group\E/-) {
9286: next;
9287: }
9288: }
1.561 banghart 9289: if (ref($value) eq "ARRAY"){
9290: foreach my $stored_what (@{$value}) {
1.629 banghart 9291: my $cmp2=$stored_what;
1.759 albertel 9292: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 9293: $cmp2=join('',@{$stored_what});
1.745 raeburn 9294: }
1.629 banghart 9295: if ($cmp1 eq $cmp2) {
1.561 banghart 9296: push(@readonly_files, $file_name);
1.745 raeburn 9297: last;
1.563 banghart 9298: } elsif (!defined($what)) {
9299: push(@readonly_files, $file_name);
1.745 raeburn 9300: last;
1.561 banghart 9301: }
9302: }
1.745 raeburn 9303: }
1.561 banghart 9304: }
9305: return @readonly_files;
9306: }
1.577 banghart 9307: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 9308:
1.577 banghart 9309: sub get_marked_as_readonly_hash {
1.745 raeburn 9310: my ($current_permissions,$group,$what) = @_;
1.577 banghart 9311: my %readonly_files;
1.745 raeburn 9312: while (my ($file_name,$value) = each(%{$current_permissions})) {
9313: if (defined($group)) {
9314: if ($file_name !~ m-^\Q$group\E/-) {
9315: next;
9316: }
9317: }
1.577 banghart 9318: if (ref($value) eq "ARRAY"){
9319: foreach my $stored_what (@{$value}) {
1.745 raeburn 9320: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 9321: foreach my $lock_descriptor(@{$stored_what}) {
9322: if ($lock_descriptor eq 'graded') {
9323: $readonly_files{$file_name} = 'graded';
9324: } elsif ($lock_descriptor eq 'handback') {
9325: $readonly_files{$file_name} = 'handback';
9326: } else {
9327: if (!exists($readonly_files{$file_name})) {
9328: $readonly_files{$file_name} = 'locked';
9329: }
9330: }
1.745 raeburn 9331: }
1.750 banghart 9332: }
1.577 banghart 9333: }
9334: }
9335: }
9336: return %readonly_files;
9337: }
1.559 banghart 9338: # ------------------------------------------------------------ Unmark as Read Only
9339:
9340: sub unmark_as_readonly {
1.629 banghart 9341: # unmarks $file_name (if $file_name is defined), or all files locked by $what
9342: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 9343: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 9344: $file_name = &declutter_portfile($file_name);
1.634 albertel 9345: my $symb_crs = $what;
9346: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 9347: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 9348: my ($tmp)=keys(%current_permissions);
9349: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 9350: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 9351: foreach my $file (@readonly_files) {
1.759 albertel 9352: my $clean_file = &declutter_portfile($file);
9353: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 9354: my $current_locks = $current_permissions{$file};
1.563 banghart 9355: my @new_locks;
9356: my @del_keys;
9357: if (ref($current_locks) eq "ARRAY"){
9358: foreach my $locker (@{$current_locks}) {
1.632 albertel 9359: my $compare=$locker;
1.749 raeburn 9360: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 9361: $compare=join('',@{$locker});
1.746 raeburn 9362: if ($compare ne $symb_crs) {
9363: push(@new_locks, $locker);
9364: }
1.563 banghart 9365: }
9366: }
1.650 albertel 9367: if (scalar(@new_locks) > 0) {
1.563 banghart 9368: $current_permissions{$file} = \@new_locks;
9369: } else {
9370: push(@del_keys, $file);
1.613 albertel 9371: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 9372: delete($current_permissions{$file});
1.563 banghart 9373: }
9374: }
1.561 banghart 9375: }
1.613 albertel 9376: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 9377: return;
9378: }
1.512 banghart 9379:
1.17 www 9380: # ------------------------------------------------------------ Directory lister
9381:
9382: sub dirlist {
1.955 raeburn 9383: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 9384: $uri=~s/^\///;
9385: $uri=~s/\/$//;
1.253 stredwic 9386: my ($udom, $uname);
1.955 raeburn 9387: if ($getuserdir) {
1.253 stredwic 9388: $udom = $userdomain;
9389: $uname = $username;
1.955 raeburn 9390: } else {
9391: (undef,$udom,$uname)=split(/\//,$uri);
9392: if(defined($userdomain)) {
9393: $udom = $userdomain;
9394: }
9395: if(defined($username)) {
9396: $uname = $username;
9397: }
1.253 stredwic 9398: }
1.955 raeburn 9399: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 9400:
1.955 raeburn 9401: $dirRoot = $perlvar{'lonDocRoot'};
9402: if (defined($getpropath)) {
9403: $dirRoot = &propath($udom,$uname);
1.253 stredwic 9404: $dirRoot =~ s/\/$//;
1.955 raeburn 9405: } elsif (defined($getuserdir)) {
9406: my $subdir=$uname.'__';
9407: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
9408: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
9409: ."/$udom/$subdir/$uname";
9410: } elsif (defined($alternateRoot)) {
9411: $dirRoot = $alternateRoot;
1.751 banghart 9412: }
1.253 stredwic 9413:
9414: if($udom) {
9415: if($uname) {
1.1135 raeburn 9416: my $uhome = &homeserver($uname,$udom);
1.1136 raeburn 9417: if ($uhome eq 'no_host') {
9418: return ([],'no_host');
9419: }
1.955 raeburn 9420: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 9421: .$getuserdir.':'.&escape($dirRoot)
1.1135 raeburn 9422: .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955 raeburn 9423: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 9424: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955 raeburn 9425: } else {
9426: @listing_results = map { &unescape($_); } split(/:/,$listing);
9427: }
1.605 matthew 9428: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 9429: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605 matthew 9430: @listing_results = split(/:/,$listing);
9431: } else {
9432: @listing_results = map { &unescape($_); } split(/:/,$listing);
9433: }
1.1135 raeburn 9434: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
1.1136 raeburn 9435: ($listing eq 'rejected') || ($listing eq 'refused') ||
9436: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
9437: return ([],$listing);
9438: } else {
9439: return (\@listing_results);
1.1135 raeburn 9440: }
1.955 raeburn 9441: } elsif(!$alternateRoot) {
1.1136 raeburn 9442: my (%allusers,%listerror);
1.841 albertel 9443: my %servers = &get_servers($udom,'library');
1.955 raeburn 9444: foreach my $tryserver (keys(%servers)) {
9445: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
9446: &escape($udom),$tryserver);
9447: if ($listing eq 'unknown_cmd') {
9448: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
9449: $udom, $tryserver);
9450: } else {
9451: @listing_results = map { &unescape($_); } split(/:/,$listing);
9452: }
1.841 albertel 9453: if ($listing eq 'unknown_cmd') {
9454: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
9455: $udom, $tryserver);
9456: @listing_results = split(/:/,$listing);
9457: } else {
9458: @listing_results =
9459: map { &unescape($_); } split(/:/,$listing);
9460: }
1.1136 raeburn 9461: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
9462: ($listing eq 'rejected') || ($listing eq 'refused') ||
9463: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
9464: $listerror{$tryserver} = $listing;
9465: } else {
1.841 albertel 9466: foreach my $line (@listing_results) {
9467: my ($entry) = split(/&/,$line,2);
9468: $allusers{$entry} = 1;
9469: }
9470: }
1.253 stredwic 9471: }
1.1136 raeburn 9472: my @alluserslist=();
1.800 albertel 9473: foreach my $user (sort(keys(%allusers))) {
1.1136 raeburn 9474: push(@alluserslist,$user.'&user');
1.253 stredwic 9475: }
1.1136 raeburn 9476: return (\@alluserslist);
1.253 stredwic 9477: } else {
1.1136 raeburn 9478: return ([],'missing username');
1.253 stredwic 9479: }
1.955 raeburn 9480: } elsif(!defined($getpropath)) {
1.1136 raeburn 9481: my $path = $perlvar{'lonDocRoot'}.'/res/';
9482: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
9483: return (\@all_domains);
1.955 raeburn 9484: } else {
1.1136 raeburn 9485: return ([],'missing domain');
1.275 stredwic 9486: }
9487: }
9488:
9489: # --------------------------------------------- GetFileTimestamp
9490: # This function utilizes dirlist and returns the date stamp for
9491: # when it was last modified. It will also return an error of -1
9492: # if an error occurs
9493:
9494: sub GetFileTimestamp {
1.955 raeburn 9495: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 9496: $studentDomain = &LONCAPA::clean_domain($studentDomain);
9497: $studentName = &LONCAPA::clean_username($studentName);
1.1136 raeburn 9498: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
9499: undef,$getuserdir);
9500: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
9501: return -1;
9502: }
9503: if (ref($fileref) eq 'ARRAY') {
9504: my @stats = split('&',$fileref->[0]);
1.375 matthew 9505: # @stats contains first the filename, then the stat output
9506: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 9507: } else {
9508: return -1;
1.253 stredwic 9509: }
1.26 www 9510: }
9511:
1.712 albertel 9512: sub stat_file {
9513: my ($uri) = @_;
1.787 albertel 9514: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 9515:
1.955 raeburn 9516: my ($udom,$uname,$file);
1.712 albertel 9517: if ($uri =~ m-^/(uploaded|editupload)/-) {
9518: ($udom,$uname,$file) =
1.811 albertel 9519: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 9520: $file = 'userfiles/'.$file;
9521: }
9522: if ($uri =~ m-^/res/-) {
9523: ($udom,$uname) =
1.807 albertel 9524: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 9525: $file = $uri;
9526: }
9527:
9528: if (!$udom || !$uname || !$file) {
9529: # unable to handle the uri
9530: return ();
9531: }
1.956 raeburn 9532: my $getpropath;
9533: if ($file =~ /^userfiles\//) {
9534: $getpropath = 1;
9535: }
1.1136 raeburn 9536: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
9537: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
9538: return ();
9539: } else {
9540: if (ref($listref) eq 'ARRAY') {
9541: my @stats = split('&',$listref->[0]);
9542: shift(@stats); #filename is first
9543: return @stats;
9544: }
1.712 albertel 9545: }
9546: return ();
9547: }
9548:
1.26 www 9549: # -------------------------------------------------------- Value of a Condition
9550:
1.713 albertel 9551: # gets the value of a specific preevaluated condition
9552: # stored in the string $env{user.state.<cid>}
9553: # or looks up a condition reference in the bighash and if if hasn't
9554: # already been evaluated recurses into docondval to get the value of
9555: # the condition, then memoizing it to
9556: # $env{user.state.<cid>.<condition>}
1.40 www 9557: sub directcondval {
9558: my $number=shift;
1.620 albertel 9559: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 9560: &Apache::lonuserstate::evalstate();
9561: }
1.713 albertel 9562: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
9563: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
9564: } elsif ($number =~ /^_/) {
9565: my $sub_condition;
9566: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
9567: &GDBM_READER(),0640)) {
9568: $sub_condition=$bighash{'conditions'.$number};
9569: untie(%bighash);
9570: }
9571: my $value = &docondval($sub_condition);
1.949 raeburn 9572: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 9573: return $value;
9574: }
1.620 albertel 9575: if ($env{'user.state.'.$env{'request.course.id'}}) {
9576: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 9577: } else {
9578: return 2;
9579: }
9580: }
9581:
1.713 albertel 9582: # get the collection of conditions for this resource
1.26 www 9583: sub condval {
9584: my $condidx=shift;
1.54 www 9585: my $allpathcond='';
1.713 albertel 9586: foreach my $cond (split(/\|/,$condidx)) {
9587: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
9588: $allpathcond.=
9589: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
9590: }
1.191 harris41 9591: }
1.54 www 9592: $allpathcond=~s/\|$//;
1.713 albertel 9593: return &docondval($allpathcond);
9594: }
9595:
9596: #evaluates an expression of conditions
9597: sub docondval {
9598: my ($allpathcond) = @_;
9599: my $result=0;
9600: if ($env{'request.course.id'}
9601: && defined($allpathcond)) {
9602: my $operand='|';
9603: my @stack;
9604: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
9605: if ($chunk eq '(') {
9606: push @stack,($operand,$result);
9607: } elsif ($chunk eq ')') {
9608: my $before=pop @stack;
9609: if (pop @stack eq '&') {
9610: $result=$result>$before?$before:$result;
9611: } else {
9612: $result=$result>$before?$result:$before;
9613: }
9614: } elsif (($chunk eq '&') || ($chunk eq '|')) {
9615: $operand=$chunk;
9616: } else {
9617: my $new=directcondval($chunk);
9618: if ($operand eq '&') {
9619: $result=$result>$new?$new:$result;
9620: } else {
9621: $result=$result>$new?$result:$new;
9622: }
9623: }
9624: }
1.26 www 9625: }
9626: return $result;
1.421 albertel 9627: }
9628:
9629: # ---------------------------------------------------- Devalidate courseresdata
9630:
9631: sub devalidatecourseresdata {
9632: my ($coursenum,$coursedomain)=@_;
9633: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 9634: &devalidate_cache_new('courseres',$hashid);
1.28 www 9635: }
9636:
1.763 www 9637:
1.200 www 9638: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 9639: #
9640: # Parameters:
9641: # $coursenum - Number of the course.
9642: # $coursedomain - Domain at which the course was created.
9643: # Returns:
9644: # A hash of the course parameters along (I think) with timestamps
9645: # and version info.
1.877 foxr 9646:
1.624 albertel 9647: sub get_courseresdata {
9648: my ($coursenum,$coursedomain)=@_;
1.200 www 9649: my $coursehom=&homeserver($coursenum,$coursedomain);
9650: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 9651: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 9652: my %dumpreply;
1.417 albertel 9653: unless (defined($cached)) {
1.624 albertel 9654: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 9655: $result=\%dumpreply;
1.251 albertel 9656: my ($tmp) = keys(%dumpreply);
9657: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 9658: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 9659: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
9660: return $tmp;
1.416 albertel 9661: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 9662: $result=undef;
1.599 albertel 9663: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 9664: }
9665: }
1.624 albertel 9666: return $result;
9667: }
9668:
1.633 albertel 9669: sub devalidateuserresdata {
9670: my ($uname,$udom)=@_;
9671: my $hashid="$udom:$uname";
9672: &devalidate_cache_new('userres',$hashid);
9673: }
9674:
1.624 albertel 9675: sub get_userresdata {
9676: my ($uname,$udom)=@_;
9677: #most student don\'t have any data set, check if there is some data
9678: if (&EXT_cache_status($udom,$uname)) { return undef; }
9679:
9680: my $hashid="$udom:$uname";
9681: my ($result,$cached)=&is_cached_new('userres',$hashid);
9682: if (!defined($cached)) {
9683: my %resourcedata=&dump('resourcedata',$udom,$uname);
9684: $result=\%resourcedata;
9685: &do_cache_new('userres',$hashid,$result,600);
9686: }
9687: my ($tmp)=keys(%$result);
9688: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
9689: return $result;
9690: }
9691: #error 2 occurs when the .db doesn't exist
9692: if ($tmp!~/error: 2 /) {
1.672 albertel 9693: &logthis("<font color=\"blue\">WARNING:".
1.624 albertel 9694: " Trying to get resource data for ".
9695: $uname." at ".$udom.": ".
9696: $tmp."</font>");
9697: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 9698: #&EXT_cache_set($udom,$uname);
9699: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 9700: undef($tmp); # not really an error so don't send it back
1.624 albertel 9701: }
9702: return $tmp;
9703: }
1.879 foxr 9704: #----------------------------------------------- resdata - return resource data
9705: # Purpose:
9706: # Return resource data for either users or for a course.
9707: # Parameters:
9708: # $name - Course/user name.
9709: # $domain - Name of the domain the user/course is registered on.
9710: # $type - Type of thing $name is (must be 'course' or 'user'
9711: # @which - Array of names of resources desired.
9712: # Returns:
9713: # The value of the first reasource in @which that is found in the
9714: # resource hash.
9715: # Exceptional Conditions:
9716: # If the $type passed in is not valid (not the string 'course' or
9717: # 'user', an undefined reference is returned.
9718: # If none of the resources are found, an undef is returned
1.624 albertel 9719: sub resdata {
9720: my ($name,$domain,$type,@which)=@_;
9721: my $result;
9722: if ($type eq 'course') {
9723: $result=&get_courseresdata($name,$domain);
9724: } elsif ($type eq 'user') {
9725: $result=&get_userresdata($name,$domain);
9726: }
9727: if (!ref($result)) { return $result; }
1.251 albertel 9728: foreach my $item (@which) {
1.927 albertel 9729: if (defined($result->{$item->[0]})) {
9730: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 9731: }
1.250 albertel 9732: }
1.291 albertel 9733: return undef;
1.200 www 9734: }
9735:
1.1236 raeburn 9736: sub get_numsuppfiles {
9737: my ($cnum,$cdom,$ignorecache)=@_;
9738: my $hashid=$cnum.':'.$cdom;
9739: my ($suppcount,$cached);
9740: unless ($ignorecache) {
9741: ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
9742: }
9743: unless (defined($cached)) {
9744: my $chome=&homeserver($cnum,$cdom);
9745: unless ($chome eq 'no_host') {
9746: ($suppcount,my $errors) = (0,0);
9747: my $suppmap = 'supplemental.sequence';
9748: ($suppcount,$errors) =
9749: &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
9750: }
9751: &do_cache_new('suppcount',$hashid,$suppcount,600);
9752: }
9753: return $suppcount;
9754: }
9755:
1.379 matthew 9756: #
9757: # EXT resource caching routines
9758: #
9759:
9760: sub clear_EXT_cache_status {
1.383 albertel 9761: &delenv('cache.EXT.');
1.379 matthew 9762: }
9763:
9764: sub EXT_cache_status {
9765: my ($target_domain,$target_user) = @_;
1.383 albertel 9766: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 9767: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 9768: # We know already the user has no data
9769: return 1;
9770: } else {
9771: return 0;
9772: }
9773: }
9774:
9775: sub EXT_cache_set {
9776: my ($target_domain,$target_user) = @_;
1.383 albertel 9777: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 9778: #&appenv({$cachename => time});
1.379 matthew 9779: }
9780:
1.28 www 9781: # --------------------------------------------------------- Value of a Variable
1.58 www 9782: sub EXT {
1.715 albertel 9783:
1.1228 raeburn 9784: my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68 www 9785: unless ($varname) { return ''; }
1.218 albertel 9786: #get real user name/domain, courseid and symb
9787: my $courseid;
1.359 albertel 9788: my $publicuser;
1.427 www 9789: if ($symbparm) {
9790: $symbparm=&get_symb_from_alias($symbparm);
9791: }
1.218 albertel 9792: if (!($uname && $udom)) {
1.790 albertel 9793: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 9794: if (!$symbparm) { $symbparm=$cursymb; }
9795: } else {
1.620 albertel 9796: $courseid=$env{'request.course.id'};
1.218 albertel 9797: }
1.48 www 9798: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
9799: my $rest;
1.320 albertel 9800: if (defined($therest[0])) {
1.48 www 9801: $rest=join('.',@therest);
9802: } else {
9803: $rest='';
9804: }
1.320 albertel 9805:
1.57 www 9806: my $qualifierrest=$qualifier;
9807: if ($rest) { $qualifierrest.='.'.$rest; }
9808: my $spacequalifierrest=$space;
9809: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 9810: if ($realm eq 'user') {
1.48 www 9811: # --------------------------------------------------------------- user.resource
9812: if ($space eq 'resource') {
1.651 albertel 9813: if ( (defined($Apache::lonhomework::parsing_a_problem)
9814: || defined($Apache::lonhomework::parsing_a_task))
9815: &&
1.744 albertel 9816: ($symbparm eq &symbread()) ) {
9817: # if we are in the middle of processing the resource the
9818: # get the value we are planning on committing
9819: if (defined($Apache::lonhomework::results{$qualifierrest})) {
9820: return $Apache::lonhomework::results{$qualifierrest};
9821: } else {
9822: return $Apache::lonhomework::history{$qualifierrest};
9823: }
1.335 albertel 9824: } else {
1.359 albertel 9825: my %restored;
1.620 albertel 9826: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 9827: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
9828: } else {
9829: %restored=&restore($symbparm,$courseid,$udom,$uname);
9830: }
1.335 albertel 9831: return $restored{$qualifierrest};
9832: }
1.48 www 9833: # ----------------------------------------------------------------- user.access
9834: } elsif ($space eq 'access') {
1.218 albertel 9835: # FIXME - not supporting calls for a specific user
1.48 www 9836: return &allowed($qualifier,$rest);
9837: # ------------------------------------------ user.preferences, user.environment
9838: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 9839: if (($uname eq $env{'user.name'}) &&
9840: ($udom eq $env{'user.domain'})) {
9841: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 9842: } else {
1.359 albertel 9843: my %returnhash;
9844: if (!$publicuser) {
9845: %returnhash=&userenvironment($udom,$uname,
9846: $qualifierrest);
9847: }
1.218 albertel 9848: return $returnhash{$qualifierrest};
9849: }
1.48 www 9850: # ----------------------------------------------------------------- user.course
9851: } elsif ($space eq 'course') {
1.218 albertel 9852: # FIXME - not supporting calls for a specific user
1.620 albertel 9853: return $env{join('.',('request.course',$qualifier))};
1.48 www 9854: # ------------------------------------------------------------------- user.role
9855: } elsif ($space eq 'role') {
1.218 albertel 9856: # FIXME - not supporting calls for a specific user
1.620 albertel 9857: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 9858: if ($qualifier eq 'value') {
9859: return $role;
9860: } elsif ($qualifier eq 'extent') {
9861: return $where;
9862: }
9863: # ----------------------------------------------------------------- user.domain
9864: } elsif ($space eq 'domain') {
1.218 albertel 9865: return $udom;
1.48 www 9866: # ------------------------------------------------------------------- user.name
9867: } elsif ($space eq 'name') {
1.218 albertel 9868: return $uname;
1.48 www 9869: # ---------------------------------------------------- Any other user namespace
1.29 www 9870: } else {
1.359 albertel 9871: my %reply;
9872: if (!$publicuser) {
9873: %reply=&get($space,[$qualifierrest],$udom,$uname);
9874: }
9875: return $reply{$qualifierrest};
1.48 www 9876: }
1.236 www 9877: } elsif ($realm eq 'query') {
9878: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 9879: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
9880: [$spacequalifierrest]);
1.620 albertel 9881: return $env{'form.'.$spacequalifierrest};
1.236 www 9882: } elsif ($realm eq 'request') {
1.48 www 9883: # ------------------------------------------------------------- request.browser
9884: if ($space eq 'browser') {
1.1145 bisitz 9885: return $env{'browser.'.$qualifier};
1.57 www 9886: # ------------------------------------------------------------ request.filename
9887: } else {
1.620 albertel 9888: return $env{'request.'.$spacequalifierrest};
1.29 www 9889: }
1.28 www 9890: } elsif ($realm eq 'course') {
1.48 www 9891: # ---------------------------------------------------------- course.description
1.620 albertel 9892: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 9893: } elsif ($realm eq 'resource') {
1.165 www 9894:
1.620 albertel 9895: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 9896: if (!$symbparm) { $symbparm=&symbread(); }
9897: }
1.693 albertel 9898:
1.1232 raeburn 9899: if ($qualifier eq '') {
9900: if ($space eq 'title') {
9901: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
9902: return &gettitle($symbparm);
9903: }
1.693 albertel 9904:
1.1232 raeburn 9905: if ($space eq 'map') {
9906: my ($map) = &decode_symb($symbparm);
9907: return &symbread($map);
9908: }
9909: if ($space eq 'maptitle') {
9910: my ($map) = &decode_symb($symbparm);
9911: return &gettitle($map);
9912: }
9913: if ($space eq 'filename') {
9914: if ($symbparm) {
9915: return &clutter((&decode_symb($symbparm))[2]);
9916: }
9917: return &hreflocation('',$env{'request.filename'});
1.905 albertel 9918: }
1.1232 raeburn 9919:
1.1233 raeburn 9920: if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
9921: if ($space eq 'visibleparts') {
9922: my $navmap = Apache::lonnavmaps::navmap->new();
9923: my $item;
9924: if (ref($navmap)) {
9925: my $res = $navmap->getBySymb($symbparm);
9926: my $parts = $res->parts();
9927: if (ref($parts) eq 'ARRAY') {
9928: $item = join(',',@{$parts});
9929: }
9930: undef($navmap);
1.1232 raeburn 9931: }
1.1233 raeburn 9932: return $item;
1.1232 raeburn 9933: }
9934: }
9935: }
1.693 albertel 9936:
9937: my ($section, $group, @groups);
1.593 albertel 9938: my ($courselevelm,$courselevel);
1.1228 raeburn 9939: if (($courseid eq '') && ($cid)) {
9940: $courseid = $cid;
9941: }
9942: if (($symbparm && $courseid) &&
9943: (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165 www 9944:
1.218 albertel 9945: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 9946:
1.60 www 9947: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 9948: my $symbp=$symbparm;
1.735 albertel 9949: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 9950:
9951: my $symbparm=$symbp.'.'.$spacequalifierrest;
9952: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
9953:
1.620 albertel 9954: if (($env{'user.name'} eq $uname) &&
9955: ($env{'user.domain'} eq $udom)) {
9956: $section=$env{'request.course.sec'};
1.733 raeburn 9957: @groups = split(/:/,$env{'request.course.groups'});
9958: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 9959: } else {
1.539 albertel 9960: if (! defined($usection)) {
1.551 albertel 9961: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 9962: } else {
9963: $section = $usection;
9964: }
1.733 raeburn 9965: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 9966: }
9967:
9968: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
9969: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
9970: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
9971:
1.593 albertel 9972: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 9973: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 9974: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 9975:
1.60 www 9976: # ----------------------------------------------------------- first, check user
1.624 albertel 9977:
9978: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 9979: ([$courselevelr,'resource'],
9980: [$courselevelm,'map' ],
9981: [$courselevel, 'course' ]));
1.931 albertel 9982: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 9983:
1.594 albertel 9984: # ------------------------------------------------ second, check some of course
1.684 raeburn 9985: my $coursereply;
1.691 raeburn 9986: if (@groups > 0) {
9987: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
9988: $mapparm,$spacequalifierrest);
1.927 albertel 9989: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 9990: }
1.96 www 9991:
1.684 raeburn 9992: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 9993: $env{'course.'.$courseid.'.domain'},
9994: 'course',
9995: ([$seclevelr, 'resource'],
9996: [$seclevelm, 'map' ],
9997: [$seclevel, 'course' ],
9998: [$courselevelr,'resource']));
9999: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 10000:
1.60 www 10001: # ------------------------------------------------------ third, check map parms
1.218 albertel 10002: my %parmhash=();
10003: my $thisparm='';
10004: if (tie(%parmhash,'GDBM_File',
1.620 albertel 10005: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 10006: &GDBM_READER(),0640)) {
1.218 albertel 10007: $thisparm=$parmhash{$symbparm};
10008: untie(%parmhash);
10009: }
1.927 albertel 10010: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 10011: }
1.594 albertel 10012: # ------------------------------------------ fourth, look in resource metadata
1.71 www 10013:
1.218 albertel 10014: $spacequalifierrest=~s/\./\_/;
1.282 albertel 10015: my $filename;
10016: if (!$symbparm) { $symbparm=&symbread(); }
10017: if ($symbparm) {
1.409 www 10018: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 10019: } else {
1.620 albertel 10020: $filename=$env{'request.filename'};
1.282 albertel 10021: }
10022: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 10023: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 10024: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 10025: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 10026:
1.927 albertel 10027: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 10028: if ($symbparm && defined($courseid) &&
1.620 albertel 10029: $courseid eq $env{'request.course.id'}) {
1.624 albertel 10030: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
10031: $env{'course.'.$courseid.'.domain'},
10032: 'course',
1.927 albertel 10033: ([$courselevelm,'map' ],
10034: [$courselevel, 'course']));
10035: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 10036: }
1.145 www 10037: # ------------------------------------------------------------------ Cascade up
1.218 albertel 10038: unless ($space eq '0') {
1.336 albertel 10039: my @parts=split(/_/,$space);
10040: my $id=pop(@parts);
10041: my $part=join('_',@parts);
10042: if ($part eq '') { $part='0'; }
1.927 albertel 10043: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 10044: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 10045: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 10046: }
1.395 albertel 10047: if ($recurse) { return undef; }
10048: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 10049: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 10050: # ---------------------------------------------------- Any other user namespace
10051: } elsif ($realm eq 'environment') {
10052: # ----------------------------------------------------------------- environment
1.620 albertel 10053: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
10054: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 10055: } else {
1.770 albertel 10056: if ($uname eq 'anonymous' && $udom eq '') {
10057: return '';
10058: }
1.219 albertel 10059: my %returnhash=&userenvironment($udom,$uname,
10060: $spacequalifierrest);
10061: return $returnhash{$spacequalifierrest};
10062: }
1.28 www 10063: } elsif ($realm eq 'system') {
1.48 www 10064: # ----------------------------------------------------------------- system.time
10065: if ($space eq 'time') {
10066: return time;
10067: }
1.696 albertel 10068: } elsif ($realm eq 'server') {
10069: # ----------------------------------------------------------------- system.time
10070: if ($space eq 'name') {
10071: return $ENV{'SERVER_NAME'};
10072: }
1.28 www 10073: }
1.48 www 10074: return '';
1.61 www 10075: }
10076:
1.927 albertel 10077: sub get_reply {
10078: my ($reply_value) = @_;
1.940 raeburn 10079: if (ref($reply_value) eq 'ARRAY') {
10080: if (wantarray) {
10081: return @$reply_value;
10082: }
10083: return $reply_value->[0];
10084: } else {
10085: return $reply_value;
1.927 albertel 10086: }
10087: }
10088:
1.691 raeburn 10089: sub check_group_parms {
10090: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
10091: my @groupitems = ();
10092: my $resultitem;
1.927 albertel 10093: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 10094: foreach my $group (@{$groups}) {
10095: foreach my $level (@levels) {
1.927 albertel 10096: my $item = $courseid.'.['.$group.'].'.$level->[0];
10097: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 10098: }
10099: }
10100: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
10101: $env{'course.'.$courseid.'.domain'},
10102: 'course',@groupitems);
10103: return $coursereply;
10104: }
10105:
10106: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 10107: my ($courseid,@groups) = @_;
10108: @groups = sort(@groups);
1.691 raeburn 10109: return @groups;
10110: }
10111:
1.395 albertel 10112: sub packages_tab_default {
10113: my ($uri,$varname)=@_;
10114: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 10115:
10116: my (@extension,@specifics,$do_default);
10117: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 10118: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 10119: if ($pack_type eq 'default') {
10120: $do_default=1;
10121: } elsif ($pack_type eq 'extension') {
10122: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 10123: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 10124: # only look at packages defaults for packages that this id is
1.738 albertel 10125: push(@specifics,[$package,$pack_type,$pack_part]);
10126: }
10127: }
10128: # first look for a package that matches the requested part id
10129: foreach my $package (@specifics) {
10130: my (undef,$pack_type,$pack_part)=@{$package};
10131: next if ($pack_part ne $part);
10132: if (defined($packagetab{"$pack_type&$name&default"})) {
10133: return $packagetab{"$pack_type&$name&default"};
10134: }
10135: }
10136: # look for any possible matching non extension_ package
10137: foreach my $package (@specifics) {
10138: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 10139: if (defined($packagetab{"$pack_type&$name&default"})) {
10140: return $packagetab{"$pack_type&$name&default"};
10141: }
1.585 albertel 10142: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 10143: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
10144: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 10145: }
10146: }
1.738 albertel 10147: # look for any posible extension_ match
10148: foreach my $package (@extension) {
10149: my ($package,$pack_type)=@{$package};
10150: if (defined($packagetab{"$pack_type&$name&default"})) {
10151: return $packagetab{"$pack_type&$name&default"};
10152: }
10153: if (defined($packagetab{$package."&$name&default"})) {
10154: return $packagetab{$package."&$name&default"};
10155: }
10156: }
10157: # look for a global default setting
10158: if ($do_default && defined($packagetab{"default&$name&default"})) {
10159: return $packagetab{"default&$name&default"};
10160: }
1.395 albertel 10161: return undef;
10162: }
10163:
1.334 albertel 10164: sub add_prefix_and_part {
10165: my ($prefix,$part)=@_;
10166: my $keyroot;
10167: if (defined($prefix) && $prefix !~ /^__/) {
10168: # prefix that has a part already
10169: $keyroot=$prefix;
10170: } elsif (defined($prefix)) {
10171: # prefix that is missing a part
10172: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
10173: } else {
10174: # no prefix at all
10175: if (defined($part)) { $keyroot='_'.$part; }
10176: }
10177: return $keyroot;
10178: }
10179:
1.71 www 10180: # ---------------------------------------------------------------- Get metadata
10181:
1.599 albertel 10182: my %metaentry;
1.1070 www 10183: my %importedpartids;
1.71 www 10184: sub metadata {
1.176 www 10185: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 10186: $uri=&declutter($uri);
1.288 albertel 10187: # if it is a non metadata possible uri return quickly
1.529 albertel 10188: if (($uri eq '') ||
10189: (($uri =~ m|^/*adm/|) &&
1.1217 raeburn 10190: ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108 raeburn 10191: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 10192: return undef;
10193: }
1.1140 www 10194: if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/)
1.924 albertel 10195: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 10196: return undef;
1.288 albertel 10197: }
1.73 www 10198: my $filename=$uri;
10199: $uri=~s/\.meta$//;
1.172 www 10200: #
10201: # Is the metadata already cached?
1.177 www 10202: # Look at timestamp of caching
1.172 www 10203: # Everything is cached by the main uri, libraries are never directly cached
10204: #
1.428 albertel 10205: if (!defined($liburi)) {
1.599 albertel 10206: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 10207: if (defined($cached)) { return $result->{':'.$what}; }
10208: }
10209: {
1.1069 www 10210: # Imported parts would go here
1.1070 www 10211: my %importedids=();
10212: my @origfileimportpartids=();
1.1069 www 10213: my $importedparts=0;
1.172 www 10214: #
10215: # Is this a recursive call for a library?
10216: #
1.599 albertel 10217: # if (! exists($metacache{$uri})) {
10218: # $metacache{$uri}={};
10219: # }
1.924 albertel 10220: my $cachetime = 60*60;
1.171 www 10221: if ($liburi) {
10222: $liburi=&declutter($liburi);
10223: $filename=$liburi;
1.401 bowersj2 10224: } else {
1.599 albertel 10225: &devalidate_cache_new('meta',$uri);
10226: undef(%metaentry);
1.401 bowersj2 10227: }
1.140 www 10228: my %metathesekeys=();
1.73 www 10229: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 10230: my $metastring;
1.1140 www 10231: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929 albertel 10232: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 10233: $metastring =
1.929 albertel 10234: &Apache::lonnet::ssi_body($which,
1.924 albertel 10235: ('grade_target' => 'meta'));
10236: $cachetime = 1; # only want this cached in the child not long term
1.1108 raeburn 10237: } elsif (($uri !~ m -^(editupload)/-) &&
10238: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 10239: my $file=&filelocation('',&clutter($filename));
1.599 albertel 10240: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 10241: $metastring=&getfile($file);
1.489 albertel 10242: }
1.208 albertel 10243: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 10244: my $token;
1.140 www 10245: undef %metathesekeys;
1.71 www 10246: while ($token=$parser->get_token) {
1.339 albertel 10247: if ($token->[0] eq 'S') {
10248: if (defined($token->[2]->{'package'})) {
1.172 www 10249: #
10250: # This is a package - get package info
10251: #
1.339 albertel 10252: my $package=$token->[2]->{'package'};
10253: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10254: if (defined($token->[2]->{'id'})) {
10255: $keyroot.='_'.$token->[2]->{'id'};
10256: }
1.599 albertel 10257: if ($metaentry{':packages'}) {
10258: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 10259: } else {
1.599 albertel 10260: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 10261: }
1.736 albertel 10262: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 10263: my $part=$keyroot;
10264: $part=~s/^\_//;
1.736 albertel 10265: if ($pack_entry=~/^\Q$package\E\&/ ||
10266: $pack_entry=~/^\Q$package\E_0\&/) {
10267: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 10268: # ignore package.tab specified default values
10269: # here &package_tab_default() will fetch those
10270: if ($subp eq 'default') { next; }
1.736 albertel 10271: my $value=$packagetab{$pack_entry};
1.432 albertel 10272: my $unikey;
10273: if ($pack =~ /_0$/) {
10274: $unikey='parameter_0_'.$name;
10275: $part=0;
10276: } else {
10277: $unikey='parameter'.$keyroot.'_'.$name;
10278: }
1.339 albertel 10279: if ($subp eq 'display') {
10280: $value.=' [Part: '.$part.']';
10281: }
1.599 albertel 10282: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 10283: $metathesekeys{$unikey}=1;
1.599 albertel 10284: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10285: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 10286: }
1.599 albertel 10287: if (defined($metaentry{':'.$unikey.'.default'})) {
10288: $metaentry{':'.$unikey}=
10289: $metaentry{':'.$unikey.'.default'};
1.356 albertel 10290: }
1.339 albertel 10291: }
10292: }
10293: } else {
1.172 www 10294: #
10295: # This is not a package - some other kind of start tag
1.339 albertel 10296: #
10297: my $entry=$token->[1];
1.1068 www 10298: my $unikey='';
1.175 www 10299:
1.339 albertel 10300: if ($entry eq 'import') {
1.175 www 10301: #
10302: # Importing a library here
1.339 albertel 10303: #
1.1067 www 10304: my $location=$parser->get_text('/import');
10305: my $dir=$filename;
10306: $dir=~s|[^/]*$||;
10307: $location=&filelocation($dir,$location);
1.1069 www 10308:
1.1068 www 10309: my $importmode=$token->[2]->{'importmode'};
10310: if ($importmode eq 'problem') {
1.1069 www 10311: # Import as problem/response
1.1068 www 10312: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10313: } elsif ($importmode eq 'part') {
10314: # Import as part(s)
1.1069 www 10315: $importedparts=1;
10316: # We need to get the original file and the imported file to get the part order correct
10317: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
10318: # Load and inspect original file
1.1070 www 10319: if ($#origfileimportpartids<0) {
10320: undef(%importedpartids);
10321: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
10322: my $origfile=&getfile($origfilelocation);
10323: @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10324: }
10325:
1.1069 www 10326: # Load and inspect imported file
10327: my $impfile=&getfile($location);
10328: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10329: if ($#impfilepartids>=0) {
10330: # This problem had parts
1.1070 www 10331: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 10332: } else {
10333: # Importing by turning a single problem into a problem part
10334: # It gets the import-tags ID as part-ID
10335: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 10336: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 10337: }
1.1068 www 10338: } else {
10339: # Normal import
10340: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10341: if (defined($token->[2]->{'id'})) {
10342: $unikey.='_'.$token->[2]->{'id'};
10343: }
1.1067 www 10344: }
10345:
1.339 albertel 10346: if ($depthcount<20) {
1.736 albertel 10347: my $metadata =
10348: &metadata($uri,'keys', $location,$unikey,
10349: $depthcount+1);
10350: foreach my $meta (split(',',$metadata)) {
10351: $metaentry{':'.$meta}=$metaentry{':'.$meta};
10352: $metathesekeys{$meta}=1;
1.339 albertel 10353: }
1.1068 www 10354:
10355: }
1.1067 www 10356: } else {
10357: #
10358: # Not importing, some other kind of non-package, non-library start tag
10359: #
10360: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
10361: if (defined($token->[2]->{'id'})) {
10362: $unikey.='_'.$token->[2]->{'id'};
10363: }
1.339 albertel 10364: if (defined($token->[2]->{'name'})) {
10365: $unikey.='_'.$token->[2]->{'name'};
10366: }
10367: $metathesekeys{$unikey}=1;
1.736 albertel 10368: foreach my $param (@{$token->[3]}) {
10369: $metaentry{':'.$unikey.'.'.$param} =
10370: $token->[2]->{$param};
1.339 albertel 10371: }
10372: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 10373: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 10374: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
10375: # only ws inside the tag, and not in default, so use default
10376: # as value
1.599 albertel 10377: $metaentry{':'.$unikey}=$default;
1.908 albertel 10378: } elsif ( $internaltext =~ /\S/ ) {
10379: # something interesting inside the tag
10380: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 10381: } else {
1.908 albertel 10382: # no interesting values, don't set a default
1.339 albertel 10383: }
1.172 www 10384: # end of not-a-package not-a-library import
1.339 albertel 10385: }
1.172 www 10386: # end of not-a-package start tag
1.339 albertel 10387: }
1.172 www 10388: # the next is the end of "start tag"
1.339 albertel 10389: }
10390: }
1.483 albertel 10391: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 10392: $extension = lc($extension);
10393: if ($extension eq 'htm') { $extension='html'; }
10394:
1.737 albertel 10395: foreach my $key (keys(%packagetab)) {
1.483 albertel 10396: #no specific packages #how's our extension
10397: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 10398: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 10399: \%metathesekeys);
10400: }
1.883 albertel 10401:
10402: if (!exists($metaentry{':packages'})
10403: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 10404: foreach my $key (keys(%packagetab)) {
1.483 albertel 10405: #no specific packages well let's get default then
10406: if ($key!~/^default&/) { next; }
1.488 albertel 10407: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 10408: \%metathesekeys);
10409: }
10410: }
1.338 www 10411: # are there custom rights to evaluate
1.599 albertel 10412: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 10413:
1.338 www 10414: #
10415: # Importing a rights file here
1.339 albertel 10416: #
10417: unless ($depthcount) {
1.599 albertel 10418: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 10419: my $dir=$filename;
10420: $dir=~s|[^/]*$||;
10421: $location=&filelocation($dir,$location);
1.736 albertel 10422: my $rights_metadata =
10423: &metadata($uri,'keys',$location,'_rights',
10424: $depthcount+1);
10425: foreach my $rights (split(',',$rights_metadata)) {
10426: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
10427: $metathesekeys{$rights}=1;
1.339 albertel 10428: }
10429: }
10430: }
1.737 albertel 10431: # uniqifiy package listing
10432: my %seen;
10433: my @uniq_packages =
10434: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
10435: $metaentry{':packages'} = join(',',@uniq_packages);
10436:
1.1070 www 10437: if ($importedparts) {
10438: # We had imported parts and need to rebuild partorder
10439: $metaentry{':partorder'}='';
10440: $metathesekeys{'partorder'}=1;
10441: for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
10442: if ($origfileimportpartids[$index] eq 'part') {
10443: # original part, part of the problem
10444: $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
10445: } else {
10446: # we have imported parts at this position
10447: $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
10448: }
10449: }
10450: $metaentry{':partorder'}=~s/^\,//;
10451: }
10452:
1.737 albertel 10453: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 10454: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
10455: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924 albertel 10456: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 10457: # this is the end of "was not already recently cached
1.71 www 10458: }
1.599 albertel 10459: return $metaentry{':'.$what};
1.261 albertel 10460: }
10461:
1.488 albertel 10462: sub metadata_create_package_def {
1.483 albertel 10463: my ($uri,$key,$package,$metathesekeys)=@_;
10464: my ($pack,$name,$subp)=split(/\&/,$key);
10465: if ($subp eq 'default') { next; }
10466:
1.599 albertel 10467: if (defined($metaentry{':packages'})) {
10468: $metaentry{':packages'}.=','.$package;
1.483 albertel 10469: } else {
1.599 albertel 10470: $metaentry{':packages'}=$package;
1.483 albertel 10471: }
10472: my $value=$packagetab{$key};
10473: my $unikey;
10474: $unikey='parameter_0_'.$name;
1.599 albertel 10475: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 10476: $$metathesekeys{$unikey}=1;
1.599 albertel 10477: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10478: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 10479: }
1.599 albertel 10480: if (defined($metaentry{':'.$unikey.'.default'})) {
10481: $metaentry{':'.$unikey}=
10482: $metaentry{':'.$unikey.'.default'};
1.483 albertel 10483: }
10484: }
10485:
1.261 albertel 10486: sub metadata_generate_part0 {
10487: my ($metadata,$metacache,$uri) = @_;
10488: my %allnames;
1.737 albertel 10489: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 10490: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 10491: my $part=$$metacache{':'.$metakey.'.part'};
10492: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 10493: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 10494: $allnames{$name}=$part;
10495: }
10496: }
10497: }
10498: foreach my $name (keys(%allnames)) {
10499: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 10500: my $key=":parameter_0_$name";
1.261 albertel 10501: $$metacache{"$key.part"}='0';
10502: $$metacache{"$key.name"}=$name;
1.428 albertel 10503: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 10504: $allnames{$name}.'_'.$name.
10505: '.type'};
1.428 albertel 10506: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 10507: '.display'};
1.644 www 10508: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 10509: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 10510: $$metacache{"$key.display"}=$olddis;
10511: }
1.71 www 10512: }
10513:
1.764 albertel 10514: # ------------------------------------------------------ Devalidate title cache
10515:
10516: sub devalidate_title_cache {
10517: my ($url)=@_;
10518: if (!$env{'request.course.id'}) { return; }
10519: my $symb=&symbread($url);
10520: if (!$symb) { return; }
10521: my $key=$env{'request.course.id'}."\0".$symb;
10522: &devalidate_cache_new('title',$key);
10523: }
10524:
1.1014 droeschl 10525: # ------------------------------------------------- Get the title of a course
10526:
10527: sub current_course_title {
10528: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
10529: }
1.301 www 10530: # ------------------------------------------------- Get the title of a resource
10531:
10532: sub gettitle {
10533: my $urlsymb=shift;
10534: my $symb=&symbread($urlsymb);
1.534 albertel 10535: if ($symb) {
1.620 albertel 10536: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 10537: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 10538: if (defined($cached)) {
10539: return $result;
10540: }
1.534 albertel 10541: my ($map,$resid,$url)=&decode_symb($symb);
10542: my $title='';
1.907 albertel 10543: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
10544: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
10545: } else {
10546: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10547: &GDBM_READER(),0640)) {
10548: my $mapid=$bighash{'map_pc_'.&clutter($map)};
10549: $title=$bighash{'title_'.$mapid.'.'.$resid};
10550: untie(%bighash);
10551: }
1.534 albertel 10552: }
10553: $title=~s/\&colon\;/\:/gs;
10554: if ($title) {
1.1159 www 10555: # Remember both $symb and $title for dynamic metadata
10556: $accesshash{$symb.'___crstitle'}=$title;
1.1161 www 10557: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159 www 10558: # Cache this title and then return it
1.599 albertel 10559: return &do_cache_new('title',$key,$title,600);
1.534 albertel 10560: }
10561: $urlsymb=$url;
10562: }
10563: my $title=&metadata($urlsymb,'title');
10564: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
10565: return $title;
1.301 www 10566: }
1.613 albertel 10567:
1.614 albertel 10568: sub get_slot {
10569: my ($which,$cnum,$cdom)=@_;
10570: if (!$cnum || !$cdom) {
1.790 albertel 10571: (undef,my $courseid)=&whichuser();
1.620 albertel 10572: $cdom=$env{'course.'.$courseid.'.domain'};
10573: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 10574: }
1.703 albertel 10575: my $key=join("\0",'slots',$cdom,$cnum,$which);
10576: my %slotinfo;
10577: if (exists($remembered{$key})) {
10578: $slotinfo{$which} = $remembered{$key};
10579: } else {
10580: %slotinfo=&get('slots',[$which],$cdom,$cnum);
10581: &Apache::lonhomework::showhash(%slotinfo);
10582: my ($tmp)=keys(%slotinfo);
10583: if ($tmp=~/^error:/) { return (); }
10584: $remembered{$key} = $slotinfo{$which};
10585: }
1.616 albertel 10586: if (ref($slotinfo{$which}) eq 'HASH') {
10587: return %{$slotinfo{$which}};
10588: }
10589: return $slotinfo{$which};
1.614 albertel 10590: }
1.1150 raeburn 10591:
10592: sub get_reservable_slots {
10593: my ($cnum,$cdom,$uname,$udom) = @_;
10594: my $now = time;
10595: my $reservable_info;
10596: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
10597: if (exists($remembered{$key})) {
10598: $reservable_info = $remembered{$key};
10599: } else {
10600: my %resv;
10601: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
10602: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
10603: $reservable_info = \%resv;
10604: $remembered{$key} = $reservable_info;
10605: }
10606: return $reservable_info;
10607: }
10608:
10609: sub get_course_slots {
10610: my ($cnum,$cdom) = @_;
10611: my $hashid=$cnum.':'.$cdom;
10612: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
10613: if (defined($cached)) {
10614: if (ref($result) eq 'HASH') {
10615: return %{$result};
10616: }
10617: } else {
10618: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
10619: my ($tmp) = keys(%slots);
10620: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1219 raeburn 10621: &do_cache_new('allslots',$hashid,\%slots,600);
1.1150 raeburn 10622: return %slots;
10623: }
10624: }
10625: return;
10626: }
10627:
10628: sub devalidate_slots_cache {
10629: my ($cnum,$cdom)=@_;
10630: my $hashid=$cnum.':'.$cdom;
10631: &devalidate_cache_new('allslots',$hashid);
10632: }
10633:
1.1181 raeburn 10634: sub get_coursechange {
10635: my ($cdom,$cnum) = @_;
10636: if ($cdom eq '' || $cnum eq '') {
10637: return unless ($env{'request.course.id'});
10638: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10639: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10640: }
10641: my $hashid=$cdom.'_'.$cnum;
10642: my ($change,$cached)=&is_cached_new('crschange',$hashid);
10643: if ((defined($cached)) && ($change ne '')) {
10644: return $change;
10645: } else {
10646: my %crshash;
10647: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
10648: if ($crshash{'internal.contentchange'} eq '') {
10649: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
10650: if ($change eq '') {
10651: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
10652: $change = $crshash{'internal.created'};
10653: }
10654: } else {
10655: $change = $crshash{'internal.contentchange'};
10656: }
10657: my $cachetime = 600;
10658: &do_cache_new('crschange',$hashid,$change,$cachetime);
10659: }
10660: return $change;
10661: }
10662:
10663: sub devalidate_coursechange_cache {
10664: my ($cnum,$cdom)=@_;
10665: my $hashid=$cnum.':'.$cdom;
10666: &devalidate_cache_new('crschange',$hashid);
10667: }
10668:
1.31 www 10669: # ------------------------------------------------- Update symbolic store links
10670:
10671: sub symblist {
10672: my ($mapname,%newhash)=@_;
1.438 www 10673: $mapname=&deversion(&declutter($mapname));
1.31 www 10674: my %hash;
1.620 albertel 10675: if (($env{'request.course.fn'}) && (%newhash)) {
10676: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 10677: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 10678: foreach my $url (keys(%newhash)) {
1.711 albertel 10679: next if ($url eq 'last_known'
10680: && $env{'form.no_update_last_known'});
10681: $hash{declutter($url)}=&encode_symb($mapname,
10682: $newhash{$url}->[1],
10683: $newhash{$url}->[0]);
1.191 harris41 10684: }
1.31 www 10685: if (untie(%hash)) {
10686: return 'ok';
10687: }
10688: }
10689: }
10690: return 'error';
1.212 www 10691: }
10692:
10693: # --------------------------------------------------------------- Verify a symb
10694:
10695: sub symbverify {
1.1190 raeburn 10696: my ($symb,$thisurl,$encstate)=@_;
1.510 www 10697: my $thisfn=$thisurl;
1.439 www 10698: $thisfn=&declutter($thisfn);
1.215 www 10699: # direct jump to resource in page or to a sequence - will construct own symbs
10700: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
10701: # check URL part
1.409 www 10702: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 10703:
1.431 www 10704: unless ($url eq $thisfn) { return 0; }
1.213 www 10705:
1.216 www 10706: $symb=&symbclean($symb);
1.510 www 10707: $thisurl=&deversion($thisurl);
1.439 www 10708: $thisfn=&deversion($thisfn);
1.213 www 10709:
10710: my %bighash;
10711: my $okay=0;
1.431 www 10712:
1.620 albertel 10713: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 10714: &GDBM_READER(),0640)) {
1.1204 raeburn 10715: my $noclutter;
1.1032 raeburn 10716: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
10717: $thisurl =~ s/\?.+$//;
1.1204 raeburn 10718: if ($map =~ m{^uploaded/.+\.page$}) {
10719: $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
10720: $thisurl =~ s{^\Qhttp://https://\E}{https://};
10721: $noclutter = 1;
10722: }
10723: }
10724: my $ids;
10725: if ($noclutter) {
10726: $ids=$bighash{'ids_'.$thisurl};
10727: } else {
10728: $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032 raeburn 10729: }
1.1102 raeburn 10730: unless ($ids) {
10731: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
10732: $ids=$bighash{$idkey};
1.216 www 10733: }
10734: if ($ids) {
10735: # ------------------------------------------------------------------- Has ID(s)
1.1202 raeburn 10736: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
1.1203 raeburn 10737: $symb =~ s/\?.+$//;
1.1202 raeburn 10738: }
1.800 albertel 10739: foreach my $id (split(/\,/,$ids)) {
10740: my ($mapid,$resid)=split(/\./,$id);
1.216 www 10741: if (
10742: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190 raeburn 10743: eq $symb) {
10744: if (ref($encstate)) {
10745: $$encstate = $bighash{'encrypted_'.$id};
10746: }
1.620 albertel 10747: if (($env{'request.role.adv'}) ||
1.1101 raeburn 10748: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
10749: ($thisurl eq '/adm/navmaps')) {
1.1190 raeburn 10750: $okay=1;
1.1202 raeburn 10751: last;
1.582 albertel 10752: }
10753: }
1.216 www 10754: }
10755: }
1.213 www 10756: untie(%bighash);
10757: }
10758: return $okay;
1.31 www 10759: }
10760:
1.210 www 10761: # --------------------------------------------------------------- Clean-up symb
10762:
10763: sub symbclean {
10764: my $symb=shift;
1.568 albertel 10765: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 10766: # remove version from map
10767: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 10768:
1.210 www 10769: # remove version from URL
10770: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 10771:
1.507 www 10772: # remove wrapper
10773:
1.510 www 10774: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 10775: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 10776: return $symb;
1.409 www 10777: }
10778:
10779: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 10780:
10781: sub encode_symb {
10782: my ($map,$resid,$url)=@_;
10783: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
10784: }
1.409 www 10785:
10786: sub decode_symb {
1.568 albertel 10787: my $symb=shift;
10788: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
10789: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 10790: return (&fixversion($map),$resid,&fixversion($url));
10791: }
10792:
10793: sub fixversion {
10794: my $fn=shift;
1.609 banghart 10795: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 10796: my %bighash;
10797: my $uri=&clutter($fn);
1.620 albertel 10798: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 10799: # is this cached?
1.599 albertel 10800: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 10801: if (defined($cached)) { return $result; }
10802: # unfortunately not cached, or expired
1.620 albertel 10803: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 10804: &GDBM_READER(),0640)) {
10805: if ($bighash{'version_'.$uri}) {
10806: my $version=$bighash{'version_'.$uri};
1.444 www 10807: unless (($version eq 'mostrecent') ||
10808: ($version==&getversion($uri))) {
1.440 www 10809: $uri=~s/\.(\w+)$/\.$version\.$1/;
10810: }
10811: }
10812: untie %bighash;
1.413 www 10813: }
1.599 albertel 10814: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 10815: }
10816:
10817: sub deversion {
10818: my $url=shift;
10819: $url=~s/\.\d+\.(\w+)$/\.$1/;
10820: return $url;
1.210 www 10821: }
10822:
1.31 www 10823: # ------------------------------------------------------ Return symb list entry
10824:
10825: sub symbread {
1.249 www 10826: my ($thisfn,$donotrecurse)=@_;
1.1206 raeburn 10827: my $cache_str;
10828: if ($thisfn ne '') {
10829: $cache_str='request.symbread.cached.'.$thisfn;
10830: if ($env{$cache_str} ne '') {
1.1179 raeburn 10831: return $env{$cache_str};
10832: }
1.1206 raeburn 10833: } else {
1.242 www 10834: # no filename provided? try from environment
1.620 albertel 10835: if ($env{'request.symb'}) {
10836: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 10837: }
1.620 albertel 10838: $thisfn=$env{'request.filename'};
1.44 www 10839: }
1.569 albertel 10840: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 10841: # is that filename actually a symb? Verify, clean, and return
10842: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 10843: if (&symbverify($thisfn,$1)) {
1.620 albertel 10844: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 10845: }
1.242 www 10846: }
1.44 www 10847: $thisfn=declutter($thisfn);
1.31 www 10848: my %hash;
1.37 www 10849: my %bighash;
10850: my $syval='';
1.620 albertel 10851: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 10852: my $targetfn = $thisfn;
1.609 banghart 10853: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 10854: $targetfn = 'adm/wrapper/'.$thisfn;
10855: }
1.687 albertel 10856: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
10857: $targetfn=$1;
10858: }
1.620 albertel 10859: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 10860: &GDBM_READER(),0640)) {
1.481 raeburn 10861: $syval=$hash{$targetfn};
1.37 www 10862: untie(%hash);
10863: }
10864: # ---------------------------------------------------------- There was an entry
10865: if ($syval) {
1.601 albertel 10866: #unless ($syval=~/\_\d+$/) {
1.620 albertel 10867: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 10868: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 10869: #return $env{$cache_str}='';
1.601 albertel 10870: #}
10871: #$syval.=$1;
10872: #}
1.37 www 10873: } else {
10874: # ------------------------------------------------------- Was not in symb table
1.620 albertel 10875: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 10876: &GDBM_READER(),0640)) {
1.37 www 10877: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 10878: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 10879: unless ($ids) {
10880: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 10881: }
10882: unless ($ids) {
10883: # alias?
10884: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 10885: }
1.37 www 10886: if ($ids) {
10887: # ------------------------------------------------------------------- Has ID(s)
10888: my @possibilities=split(/\,/,$ids);
1.39 www 10889: if ($#possibilities==0) {
10890: # ----------------------------------------------- There is only one possibility
1.37 www 10891: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 10892: $syval=&encode_symb($bighash{'map_id_'.$mapid},
10893: $resid,$thisfn);
1.249 www 10894: } elsif (!$donotrecurse) {
1.39 www 10895: # ------------------------------------------ There is more than one possibility
10896: my $realpossible=0;
1.800 albertel 10897: foreach my $id (@possibilities) {
10898: my $file=$bighash{'src_'.$id};
1.39 www 10899: if (&allowed('bre',$file)) {
1.800 albertel 10900: my ($mapid,$resid)=split(/\./,$id);
1.39 www 10901: if ($bighash{'map_type_'.$mapid} ne 'page') {
10902: $realpossible++;
1.626 albertel 10903: $syval=&encode_symb($bighash{'map_id_'.$mapid},
10904: $resid,$thisfn);
1.39 www 10905: }
10906: }
1.191 harris41 10907: }
1.39 www 10908: if ($realpossible!=1) { $syval=''; }
1.249 www 10909: } else {
10910: $syval='';
1.37 www 10911: }
10912: }
10913: untie(%bighash)
1.481 raeburn 10914: }
1.31 www 10915: }
1.62 www 10916: if ($syval) {
1.620 albertel 10917: return $env{$cache_str}=$syval;
1.62 www 10918: }
1.31 www 10919: }
1.949 raeburn 10920: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 10921: return $env{$cache_str}='';
1.31 www 10922: }
10923:
10924: # ---------------------------------------------------------- Return random seed
10925:
1.32 www 10926: sub numval {
10927: my $txt=shift;
10928: $txt=~tr/A-J/0-9/;
10929: $txt=~tr/a-j/0-9/;
10930: $txt=~tr/K-T/0-9/;
10931: $txt=~tr/k-t/0-9/;
10932: $txt=~tr/U-Z/0-5/;
10933: $txt=~tr/u-z/0-5/;
10934: $txt=~s/\D//g;
1.564 albertel 10935: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 10936: return int($txt);
1.368 albertel 10937: }
10938:
1.484 albertel 10939: sub numval2 {
10940: my $txt=shift;
10941: $txt=~tr/A-J/0-9/;
10942: $txt=~tr/a-j/0-9/;
10943: $txt=~tr/K-T/0-9/;
10944: $txt=~tr/k-t/0-9/;
10945: $txt=~tr/U-Z/0-5/;
10946: $txt=~tr/u-z/0-5/;
10947: $txt=~s/\D//g;
10948: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10949: my $total;
10950: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 10951: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 10952: return int($total);
10953: }
10954:
1.575 albertel 10955: sub numval3 {
10956: use integer;
10957: my $txt=shift;
10958: $txt=~tr/A-J/0-9/;
10959: $txt=~tr/a-j/0-9/;
10960: $txt=~tr/K-T/0-9/;
10961: $txt=~tr/k-t/0-9/;
10962: $txt=~tr/U-Z/0-5/;
10963: $txt=~tr/u-z/0-5/;
10964: $txt=~s/\D//g;
10965: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10966: my $total;
10967: foreach my $val (@txts) { $total+=$val; }
10968: if ($_64bit) { $total=(($total<<32)>>32); }
10969: return $total;
10970: }
10971:
1.675 albertel 10972: sub digest {
10973: my ($data)=@_;
10974: my $digest=&Digest::MD5::md5($data);
10975: my ($a,$b,$c,$d)=unpack("iiii",$digest);
10976: my ($e,$f);
10977: {
10978: use integer;
10979: $e=($a+$b);
10980: $f=($c+$d);
10981: if ($_64bit) {
10982: $e=(($e<<32)>>32);
10983: $f=(($f<<32)>>32);
10984: }
10985: }
10986: if (wantarray) {
10987: return ($e,$f);
10988: } else {
10989: my $g;
10990: {
10991: use integer;
10992: $g=($e+$f);
10993: if ($_64bit) {
10994: $g=(($g<<32)>>32);
10995: }
10996: }
10997: return $g;
10998: }
10999: }
11000:
1.368 albertel 11001: sub latest_rnd_algorithm_id {
1.675 albertel 11002: return '64bit5';
1.366 albertel 11003: }
1.32 www 11004:
1.503 albertel 11005: sub get_rand_alg {
11006: my ($courseid)=@_;
1.790 albertel 11007: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 11008: if ($courseid) {
1.620 albertel 11009: return $env{"course.$courseid.rndseed"};
1.503 albertel 11010: }
11011: return &latest_rnd_algorithm_id();
11012: }
11013:
1.562 albertel 11014: sub validCODE {
11015: my ($CODE)=@_;
11016: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
11017: return 0;
11018: }
11019:
1.491 albertel 11020: sub getCODE {
1.620 albertel 11021: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 11022: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
11023: defined($Apache::lonhomework::parsing_a_task) ) &&
11024: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 11025: return $Apache::lonhomework::history{'resource.CODE'};
11026: }
11027: return undef;
11028: }
1.1133 foxr 11029: #
11030: # Determines the random seed for a specific context:
11031: #
11032: # parameters:
11033: # symb - in course context the symb for the seed.
11034: # course_id - The course id of the form domain_coursenum.
11035: # domain - Domain for the user.
11036: # course - Course for the user.
11037: # cenv - environment of the course.
11038: #
11039: # NOTE:
11040: # All parameters are picked out of the environment if missing
11041: # or not defined.
11042: # If a symb cannot be determined the current time is used instead.
11043: #
11044: # For a given well defined symb, courside, domain, username,
11045: # and course environment, the seed is reproducible.
11046: #
1.31 www 11047: sub rndseed {
1.1133 foxr 11048: my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790 albertel 11049: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 11050: if (!defined($symb)) {
1.366 albertel 11051: unless ($symb=$wsymb) { return time; }
11052: }
1.1146 foxr 11053: if (!defined $courseid) {
11054: $courseid=$wcourseid;
11055: }
11056: if (!defined $domain) { $domain=$wdomain; }
11057: if (!defined $username) { $username=$wusername }
1.1133 foxr 11058:
11059: my $which;
11060: if (defined($cenv->{'rndseed'})) {
11061: $which = $cenv->{'rndseed'};
11062: } else {
11063: $which =&get_rand_alg($courseid);
11064: }
1.491 albertel 11065: if (defined(&getCODE())) {
1.1133 foxr 11066:
1.675 albertel 11067: if ($which eq '64bit5') {
11068: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
11069: } elsif ($which eq '64bit4') {
1.575 albertel 11070: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
11071: } else {
11072: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
11073: }
1.675 albertel 11074: } elsif ($which eq '64bit5') {
11075: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 11076: } elsif ($which eq '64bit4') {
11077: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 11078: } elsif ($which eq '64bit3') {
11079: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 11080: } elsif ($which eq '64bit2') {
11081: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 11082: } elsif ($which eq '64bit') {
11083: return &rndseed_64bit($symb,$courseid,$domain,$username);
11084: }
11085: return &rndseed_32bit($symb,$courseid,$domain,$username);
11086: }
11087:
11088: sub rndseed_32bit {
11089: my ($symb,$courseid,$domain,$username)=@_;
11090: {
11091: use integer;
11092: my $symbchck=unpack("%32C*",$symb) << 27;
11093: my $symbseed=numval($symb) << 22;
11094: my $namechck=unpack("%32C*",$username) << 17;
11095: my $nameseed=numval($username) << 12;
11096: my $domainseed=unpack("%32C*",$domain) << 7;
11097: my $courseseed=unpack("%32C*",$courseid);
11098: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 11099: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11100: #&logthis("rndseed :$num:$symb");
1.564 albertel 11101: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 11102: return $num;
11103: }
11104: }
11105:
11106: sub rndseed_64bit {
11107: my ($symb,$courseid,$domain,$username)=@_;
11108: {
11109: use integer;
11110: my $symbchck=unpack("%32S*",$symb) << 21;
11111: my $symbseed=numval($symb) << 10;
11112: my $namechck=unpack("%32S*",$username);
11113:
11114: my $nameseed=numval($username) << 21;
11115: my $domainseed=unpack("%32S*",$domain) << 10;
11116: my $courseseed=unpack("%32S*",$courseid);
11117:
11118: my $num1=$symbchck+$symbseed+$namechck;
11119: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11120: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11121: #&logthis("rndseed :$num:$symb");
1.564 albertel 11122: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 11123: return "$num1,$num2";
1.155 albertel 11124: }
1.366 albertel 11125: }
11126:
1.443 albertel 11127: sub rndseed_64bit2 {
11128: my ($symb,$courseid,$domain,$username)=@_;
11129: {
11130: use integer;
11131: # strings need to be an even # of cahracters long, it it is odd the
11132: # last characters gets thrown away
11133: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11134: my $symbseed=numval($symb) << 10;
11135: my $namechck=unpack("%32S*",$username.' ');
11136:
11137: my $nameseed=numval($username) << 21;
1.501 albertel 11138: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11139: my $courseseed=unpack("%32S*",$courseid.' ');
11140:
11141: my $num1=$symbchck+$symbseed+$namechck;
11142: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11143: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11144: #&logthis("rndseed :$num:$symb");
1.803 albertel 11145: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 11146: return "$num1,$num2";
11147: }
11148: }
11149:
11150: sub rndseed_64bit3 {
11151: my ($symb,$courseid,$domain,$username)=@_;
11152: {
11153: use integer;
11154: # strings need to be an even # of cahracters long, it it is odd the
11155: # last characters gets thrown away
11156: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11157: my $symbseed=numval2($symb) << 10;
11158: my $namechck=unpack("%32S*",$username.' ');
11159:
11160: my $nameseed=numval2($username) << 21;
1.443 albertel 11161: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11162: my $courseseed=unpack("%32S*",$courseid.' ');
11163:
11164: my $num1=$symbchck+$symbseed+$namechck;
11165: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11166: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11167: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 11168: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 11169:
1.503 albertel 11170: return "$num1:$num2";
1.443 albertel 11171: }
11172: }
11173:
1.575 albertel 11174: sub rndseed_64bit4 {
11175: my ($symb,$courseid,$domain,$username)=@_;
11176: {
11177: use integer;
11178: # strings need to be an even # of cahracters long, it it is odd the
11179: # last characters gets thrown away
11180: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11181: my $symbseed=numval3($symb) << 10;
11182: my $namechck=unpack("%32S*",$username.' ');
11183:
11184: my $nameseed=numval3($username) << 21;
11185: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11186: my $courseseed=unpack("%32S*",$courseid.' ');
11187:
11188: my $num1=$symbchck+$symbseed+$namechck;
11189: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11190: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11191: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 11192: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 11193:
1.575 albertel 11194: return "$num1:$num2";
11195: }
11196: }
11197:
1.675 albertel 11198: sub rndseed_64bit5 {
11199: my ($symb,$courseid,$domain,$username)=@_;
11200: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
11201: return "$num1:$num2";
11202: }
11203:
1.366 albertel 11204: sub rndseed_CODE_64bit {
11205: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 11206: {
1.366 albertel 11207: use integer;
1.443 albertel 11208: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 11209: my $symbseed=numval2($symb);
1.491 albertel 11210: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11211: my $CODEseed=numval(&getCODE());
1.443 albertel 11212: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 11213: my $num1=$symbseed+$CODEchck;
11214: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 11215: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11216: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 11217: if ($_64bit) { $num1=(($num1<<32)>>32); }
11218: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 11219: return "$num1:$num2";
1.366 albertel 11220: }
11221: }
11222:
1.575 albertel 11223: sub rndseed_CODE_64bit4 {
11224: my ($symb,$courseid,$domain,$username)=@_;
11225: {
11226: use integer;
11227: my $symbchck=unpack("%32S*",$symb.' ') << 16;
11228: my $symbseed=numval3($symb);
11229: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11230: my $CODEseed=numval3(&getCODE());
11231: my $courseseed=unpack("%32S*",$courseid.' ');
11232: my $num1=$symbseed+$CODEchck;
11233: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 11234: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11235: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 11236: if ($_64bit) { $num1=(($num1<<32)>>32); }
11237: if ($_64bit) { $num2=(($num2<<32)>>32); }
11238: return "$num1:$num2";
11239: }
11240: }
11241:
1.675 albertel 11242: sub rndseed_CODE_64bit5 {
11243: my ($symb,$courseid,$domain,$username)=@_;
11244: my $code = &getCODE();
11245: my ($num1,$num2)=&digest("$symb,$courseid,$code");
11246: return "$num1:$num2";
11247: }
11248:
1.366 albertel 11249: sub setup_random_from_rndseed {
11250: my ($rndseed)=@_;
1.503 albertel 11251: if ($rndseed =~/([,:])/) {
11252: my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366 albertel 11253: &Math::Random::random_set_seed(abs($num1),abs($num2));
11254: } else {
11255: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 11256: }
1.36 albertel 11257: }
11258:
1.474 albertel 11259: sub latest_receipt_algorithm_id {
1.835 albertel 11260: return 'receipt3';
1.474 albertel 11261: }
11262:
1.480 www 11263: sub recunique {
11264: my $fucourseid=shift;
11265: my $unique;
1.835 albertel 11266: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
11267: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 11268: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 11269: } else {
11270: $unique=$perlvar{'lonReceipt'};
11271: }
11272: return unpack("%32C*",$unique);
11273: }
11274:
11275: sub recprefix {
11276: my $fucourseid=shift;
11277: my $prefix;
1.835 albertel 11278: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
11279: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 11280: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 11281: } else {
11282: $prefix=$perlvar{'lonHostID'};
11283: }
11284: return unpack("%32C*",$prefix);
11285: }
11286:
1.76 www 11287: sub ireceipt {
1.474 albertel 11288: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 11289:
11290: my $return =&recprefix($fucourseid).'-';
11291:
11292: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
11293: $env{'request.state'} eq 'construct') {
11294: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
11295: return $return;
11296: }
11297:
1.76 www 11298: my $cuname=unpack("%32C*",$funame);
11299: my $cudom=unpack("%32C*",$fudom);
11300: my $cucourseid=unpack("%32C*",$fucourseid);
11301: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 11302: my $cunique=&recunique($fucourseid);
1.474 albertel 11303: my $cpart=unpack("%32S*",$part);
1.835 albertel 11304: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
11305:
1.790 albertel 11306: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 11307:
11308: $return.= ($cunique%$cuname+
11309: $cunique%$cudom+
11310: $cusymb%$cuname+
11311: $cusymb%$cudom+
11312: $cucourseid%$cuname+
11313: $cucourseid%$cudom+
11314: $cpart%$cuname+
11315: $cpart%$cudom);
11316: } else {
11317: $return.= ($cunique%$cuname+
11318: $cunique%$cudom+
11319: $cusymb%$cuname+
11320: $cusymb%$cudom+
11321: $cucourseid%$cuname+
11322: $cucourseid%$cudom);
11323: }
11324: return $return;
1.76 www 11325: }
11326:
11327: sub receipt {
1.474 albertel 11328: my ($part)=@_;
1.790 albertel 11329: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 11330: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 11331: }
1.260 ng 11332:
1.790 albertel 11333: sub whichuser {
11334: my ($passedsymb)=@_;
11335: my ($symb,$courseid,$domain,$name,$publicuser);
11336: if (defined($env{'form.grade_symb'})) {
11337: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
11338: my $allowed=&allowed('vgr',$tmp_courseid);
11339: if (!$allowed &&
11340: exists($env{'request.course.sec'}) &&
11341: $env{'request.course.sec'} !~ /^\s*$/) {
11342: $allowed=&allowed('vgr',$tmp_courseid.
11343: '/'.$env{'request.course.sec'});
11344: }
11345: if ($allowed) {
11346: ($symb)=&get_env_multiple('form.grade_symb');
11347: $courseid=$tmp_courseid;
11348: ($domain)=&get_env_multiple('form.grade_domain');
11349: ($name)=&get_env_multiple('form.grade_username');
11350: return ($symb,$courseid,$domain,$name,$publicuser);
11351: }
11352: }
11353: if (!$passedsymb) {
11354: $symb=&symbread();
11355: } else {
11356: $symb=$passedsymb;
11357: }
11358: $courseid=$env{'request.course.id'};
11359: $domain=$env{'user.domain'};
11360: $name=$env{'user.name'};
11361: if ($name eq 'public' && $domain eq 'public') {
11362: if (!defined($env{'form.username'})) {
11363: $env{'form.username'}.=time.rand(10000000);
11364: }
11365: $name.=$env{'form.username'};
11366: }
11367: return ($symb,$courseid,$domain,$name,$publicuser);
11368:
11369: }
11370:
1.36 albertel 11371: # ------------------------------------------------------------ Serves up a file
1.472 albertel 11372: # returns either the contents of the file or
11373: # -1 if the file doesn't exist
1.481 raeburn 11374: #
11375: # if the target is a file that was uploaded via DOCS,
11376: # a check will be made to see if a current copy exists on the local server,
11377: # if it does this will be served, otherwise a copy will be retrieved from
11378: # the home server for the course and stored in /home/httpd/html/userfiles on
11379: # the local server.
1.472 albertel 11380:
1.36 albertel 11381: sub getfile {
1.538 albertel 11382: my ($file) = @_;
1.609 banghart 11383: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 11384: &repcopy($file);
11385: return &readfile($file);
11386: }
11387:
11388: sub repcopy_userfile {
11389: my ($file)=@_;
1.1142 raeburn 11390: my $londocroot = $perlvar{'lonDocRoot'};
11391: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164 raeburn 11392: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538 albertel 11393: my ($cdom,$cnum,$filename) =
1.811 albertel 11394: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 11395: my $uri="/uploaded/$cdom/$cnum/$filename";
11396: if (-e "$file") {
1.828 www 11397: # we already have a local copy, check it out
1.538 albertel 11398: my @fileinfo = stat($file);
1.828 www 11399: my $rtncode;
11400: my $info;
1.538 albertel 11401: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 11402: if ($lwpresp ne 'ok') {
1.828 www 11403: # there is no such file anymore, even though we had a local copy
1.482 albertel 11404: if ($rtncode eq '404') {
1.538 albertel 11405: unlink($file);
1.482 albertel 11406: }
11407: return -1;
11408: }
11409: if ($info < $fileinfo[9]) {
1.828 www 11410: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 11411: return 'ok';
1.828 www 11412: } else {
11413: # the file is outdated, get rid of it
11414: unlink($file);
1.482 albertel 11415: }
1.828 www 11416: }
11417: # one way or the other, at this point, we don't have the file
11418: # construct the correct path for the file
11419: my @parts = ($cdom,$cnum);
11420: if ($filename =~ m|^(.+)/[^/]+$|) {
11421: push @parts, split(/\//,$1);
11422: }
11423: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
11424: foreach my $part (@parts) {
11425: $path .= '/'.$part;
11426: if (!-e $path) {
11427: mkdir($path,0770);
1.482 albertel 11428: }
11429: }
1.828 www 11430: # now the path exists for sure
11431: # get a user agent
11432: my $ua=new LWP::UserAgent;
11433: my $transferfile=$file.'.in.transfer';
11434: # FIXME: this should flock
11435: if (-e $transferfile) { return 'ok'; }
11436: my $request;
11437: $uri=~s/^\///;
1.980 raeburn 11438: my $homeserver = &homeserver($cnum,$cdom);
11439: my $protocol = $protocol{$homeserver};
11440: $protocol = 'http' if ($protocol ne 'https');
11441: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 11442: my $response=$ua->request($request,$transferfile);
11443: # did it work?
11444: if ($response->is_error()) {
11445: unlink($transferfile);
11446: &logthis("Userfile repcopy failed for $uri");
11447: return -1;
11448: }
11449: # worked, rename the transfer file
11450: rename($transferfile,$file);
1.607 raeburn 11451: return 'ok';
1.481 raeburn 11452: }
11453:
1.517 albertel 11454: sub tokenwrapper {
11455: my $uri=shift;
1.980 raeburn 11456: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 11457: $uri=~s|^/||;
1.620 albertel 11458: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 11459: my $token=$1;
1.552 albertel 11460: my (undef,$udom,$uname,$file)=split('/',$uri,4);
11461: if ($udom && $uname && $file) {
11462: $file=~s|(\?\.*)*$||;
1.949 raeburn 11463: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 11464: my $homeserver = &homeserver($uname,$udom);
11465: my $protocol = $protocol{$homeserver};
11466: $protocol = 'http' if ($protocol ne 'https');
11467: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 11468: (($uri=~/\?/)?'&':'?').'token='.$token.
11469: '&tokenissued='.$perlvar{'lonHostID'};
11470: } else {
11471: return '/adm/notfound.html';
11472: }
11473: }
11474:
1.828 www 11475: # call with reqtype HEAD: get last modification time
11476: # call with reqtype GET: get the file contents
11477: # Do not call this with reqtype GET for large files! It loads everything into memory
11478: #
1.481 raeburn 11479: sub getuploaded {
11480: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
11481: $uri=~s/^\///;
1.980 raeburn 11482: my $homeserver = &homeserver($cnum,$cdom);
11483: my $protocol = $protocol{$homeserver};
11484: $protocol = 'http' if ($protocol ne 'https');
11485: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 11486: my $ua=new LWP::UserAgent;
11487: my $request=new HTTP::Request($reqtype,$uri);
11488: my $response=$ua->request($request);
11489: $$rtncode = $response->code;
1.482 albertel 11490: if (! $response->is_success()) {
11491: return 'failed';
11492: }
11493: if ($reqtype eq 'HEAD') {
1.486 www 11494: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 11495: } elsif ($reqtype eq 'GET') {
11496: $$info = $response->content;
1.472 albertel 11497: }
1.482 albertel 11498: return 'ok';
1.36 albertel 11499: }
11500:
1.481 raeburn 11501: sub readfile {
11502: my $file = shift;
11503: if ( (! -e $file ) || ($file eq '') ) { return -1; };
11504: my $fh;
11505: open($fh,"<$file");
11506: my $a='';
1.800 albertel 11507: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 11508: return $a;
11509: }
11510:
1.36 albertel 11511: sub filelocation {
1.590 banghart 11512: my ($dir,$file) = @_;
11513: my $location;
11514: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 11515:
11516: if ($file =~ m-^/adm/-) {
11517: $file=~s-^/adm/wrapper/-/-;
11518: $file=~s-^/adm/coursedocs/showdoc/-/-;
11519: }
1.882 albertel 11520:
1.1139 www 11521: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956 raeburn 11522: $location = $file;
1.609 banghart 11523: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 11524: my ($udom,$uname,$filename)=
1.811 albertel 11525: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 11526: my $home=&homeserver($uname,$udom);
11527: my $is_me=0;
11528: my @ids=¤t_machine_ids();
11529: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
11530: if ($is_me) {
1.1117 foxr 11531: $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 11532: } else {
11533: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
11534: $udom.'/'.$uname.'/'.$filename;
11535: }
1.882 albertel 11536: } elsif ($file =~ m-^/adm/-) {
11537: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 11538: } else {
11539: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139 www 11540: $file=~s:^/(res|priv)/:/:;
11541: my $space=$1;
1.590 banghart 11542: if ( !( $file =~ m:^/:) ) {
11543: $location = $dir. '/'.$file;
11544: } else {
1.1142 raeburn 11545: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590 banghart 11546: }
1.59 albertel 11547: }
1.590 banghart 11548: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 11549: while ($location=~m{/\.\./}) {
11550: if ($location =~ m{/[^/]+/\.\./}) {
11551: $location=~ s{/[^/]+/\.\./}{/}g;
11552: } else {
11553: $location=~ s{/\.\./}{/}g;
11554: }
11555: } #remove dir/..
1.590 banghart 11556: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
11557: return $location;
1.46 www 11558: }
1.36 albertel 11559:
1.46 www 11560: sub hreflocation {
11561: my ($dir,$file)=@_;
1.980 raeburn 11562: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 11563: $file=filelocation($dir,$file);
1.700 albertel 11564: } elsif ($file=~m-^/adm/-) {
11565: $file=~s-^/adm/wrapper/-/-;
11566: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 11567: }
11568: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
11569: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
11570: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143 raeburn 11571: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
11572: {/uploaded/$1/$2/}x;
1.46 www 11573: }
1.913 albertel 11574: if ($file=~ m{^/userfiles/}) {
11575: $file =~ s{^/userfiles/}{/uploaded/};
11576: }
1.462 albertel 11577: return $file;
1.465 albertel 11578: }
11579:
1.1139 www 11580:
11581:
11582:
11583:
1.465 albertel 11584: sub current_machine_domains {
1.853 albertel 11585: return &machine_domains(&hostname($perlvar{'lonHostID'}));
11586: }
11587:
11588: sub machine_domains {
11589: my ($hostname) = @_;
1.465 albertel 11590: my @domains;
1.838 albertel 11591: my %hostname = &all_hostnames();
1.465 albertel 11592: while( my($id, $name) = each(%hostname)) {
1.467 matthew 11593: # &logthis("-$id-$name-$hostname-");
1.465 albertel 11594: if ($hostname eq $name) {
1.844 albertel 11595: push(@domains,&host_domain($id));
1.465 albertel 11596: }
11597: }
11598: return @domains;
11599: }
11600:
11601: sub current_machine_ids {
1.853 albertel 11602: return &machine_ids(&hostname($perlvar{'lonHostID'}));
11603: }
11604:
11605: sub machine_ids {
11606: my ($hostname) = @_;
11607: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 11608: my @ids;
1.888 albertel 11609: my %name_to_host = &all_names();
1.889 albertel 11610: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
11611: return @{ $name_to_host{$hostname} };
11612: }
11613: return;
1.31 www 11614: }
11615:
1.824 raeburn 11616: sub additional_machine_domains {
11617: my @domains;
11618: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
11619: while( my $line = <$fh>) {
11620: $line =~ s/\s//g;
11621: push(@domains,$line);
11622: }
11623: return @domains;
11624: }
11625:
11626: sub default_login_domain {
11627: my $domain = $perlvar{'lonDefDomain'};
11628: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
11629: foreach my $posdom (¤t_machine_domains(),
11630: &additional_machine_domains()) {
11631: if (lc($posdom) eq lc($testdomain)) {
11632: $domain=$posdom;
11633: last;
11634: }
11635: }
11636: return $domain;
11637: }
11638:
1.31 www 11639: # ------------------------------------------------------------- Declutters URLs
11640:
11641: sub declutter {
11642: my $thisfn=shift;
1.569 albertel 11643: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479 albertel 11644: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31 www 11645: $thisfn=~s/^\///;
1.697 albertel 11646: $thisfn=~s|^adm/wrapper/||;
11647: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 11648: $thisfn=~s/^res\///;
1.1172 bisitz 11649: $thisfn=~s/^priv\///;
1.1032 raeburn 11650: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
11651: $thisfn=~s/\?.+$//;
11652: }
1.268 www 11653: return $thisfn;
11654: }
11655:
11656: # ------------------------------------------------------------- Clutter up URLs
11657:
11658: sub clutter {
11659: my $thisfn='/'.&declutter(shift);
1.887 albertel 11660: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 11661: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 11662: $thisfn='/res'.$thisfn;
11663: }
1.1031 raeburn 11664: if ($thisfn !~m|^/adm|) {
11665: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 11666: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 11667: } else {
11668: my ($ext) = ($thisfn =~ /\.(\w+)$/);
11669: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 11670: if ($embstyle eq 'ssi'
11671: || ($embstyle eq 'hdn')
11672: || ($embstyle eq 'rat')
11673: || ($embstyle eq 'prv')
11674: || ($embstyle eq 'ign')) {
11675: #do nothing with these
11676: } elsif (($embstyle eq 'img')
1.695 albertel 11677: || ($embstyle eq 'emb')
11678: || ($embstyle eq 'wrp')) {
11679: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 11680: } elsif ($embstyle eq 'unk'
11681: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 11682: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 11683: } else {
1.718 www 11684: # &logthis("Got a blank emb style");
1.695 albertel 11685: }
1.694 albertel 11686: }
11687: }
1.31 www 11688: return $thisfn;
1.12 www 11689: }
11690:
1.787 albertel 11691: sub clutter_with_no_wrapper {
11692: my $uri = &clutter(shift);
11693: if ($uri =~ m-^/adm/-) {
11694: $uri =~ s-^/adm/wrapper/-/-;
11695: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
11696: }
11697: return $uri;
11698: }
11699:
1.557 albertel 11700: sub freeze_escape {
11701: my ($value)=@_;
11702: if (ref($value)) {
11703: $value=&nfreeze($value);
11704: return '__FROZEN__'.&escape($value);
11705: }
11706: return &escape($value);
11707: }
11708:
1.11 www 11709:
1.557 albertel 11710: sub thaw_unescape {
11711: my ($value)=@_;
11712: if ($value =~ /^__FROZEN__/) {
11713: substr($value,0,10,undef);
11714: $value=&unescape($value);
11715: return &thaw($value);
11716: }
11717: return &unescape($value);
11718: }
11719:
1.436 albertel 11720: sub correct_line_ends {
11721: my ($result)=@_;
11722: $$result =~s/\r\n/\n/mg;
11723: $$result =~s/\r/\n/mg;
1.415 albertel 11724: }
1.1 albertel 11725: # ================================================================ Main Program
11726:
1.184 www 11727: sub goodbye {
1.204 albertel 11728: &logthis("Starting Shut down");
1.443 albertel 11729: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 11730: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 11731: #converted
1.599 albertel 11732: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 11733: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
11734: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
11735: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 11736: #1.1 only
1.870 albertel 11737: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
11738: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
11739: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
11740: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
11741: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 11742: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
11743: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 11744: &flushcourselogs();
11745: &logthis("Shutting down");
11746: }
11747:
1.852 albertel 11748: sub get_dns {
1.1210 raeburn 11749: my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869 albertel 11750: if (!$ignore_cache) {
11751: my ($content,$cached)=
11752: &Apache::lonnet::is_cached_new('dns',$url);
11753: if ($cached) {
1.1210 raeburn 11754: &$func($content,$hashref);
1.869 albertel 11755: return;
11756: }
11757: }
11758:
11759: my %alldns;
1.852 albertel 11760: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11761: foreach my $dns (<$config>) {
11762: next if ($dns !~ /^\^(\S*)/x);
1.979 raeburn 11763: my $line = $1;
11764: my ($host,$protocol) = split(/:/,$line);
11765: if ($protocol ne 'https') {
11766: $protocol = 'http';
11767: }
11768: $alldns{$host} = $protocol;
1.869 albertel 11769: }
11770: while (%alldns) {
11771: my ($dns) = keys(%alldns);
1.852 albertel 11772: my $ua=new LWP::UserAgent;
1.1134 raeburn 11773: $ua->timeout(30);
1.979 raeburn 11774: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 11775: my $response=$ua->request($request);
1.979 raeburn 11776: delete($alldns{$dns});
1.852 albertel 11777: next if ($response->is_error());
11778: my @content = split("\n",$response->content);
1.1210 raeburn 11779: unless ($nocache) {
1.1219 raeburn 11780: &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1210 raeburn 11781: }
11782: &$func(\@content,$hashref);
1.869 albertel 11783: return;
1.852 albertel 11784: }
11785: close($config);
1.871 albertel 11786: my $which = (split('/',$url))[3];
11787: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
11788: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 11789: my @content = <$config>;
1.1210 raeburn 11790: &$func(\@content,$hashref);
11791: return;
11792: }
11793:
11794: # ------------------------------------------------------Get DNS checksums file
1.1211 raeburn 11795: sub parse_dns_checksums_tab {
1.1210 raeburn 11796: my ($lines,$hashref) = @_;
11797: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
11798: my $loncaparev = &get_server_loncaparev($machine_dom);
11799: my ($release,$timestamp) = split(/\-/,$loncaparev);
11800: my (%chksum,%revnum);
11801: if (ref($lines) eq 'ARRAY') {
11802: chomp(@{$lines});
1.1238 raeburn 11803: my $version = shift(@{$lines});
11804: if ($version eq $release) {
1.1210 raeburn 11805: foreach my $line (@{$lines}) {
1.1238 raeburn 11806: my ($file,$version,$shasum) = split(/,/,$line);
11807: $chksum{$file} = $shasum;
11808: $revnum{$file} = $version;
1.1210 raeburn 11809: }
11810: if (ref($hashref) eq 'HASH') {
11811: %{$hashref} = (
11812: sums => \%chksum,
11813: versions => \%revnum,
11814: );
11815: }
11816: }
11817: }
1.869 albertel 11818: return;
1.852 albertel 11819: }
1.1210 raeburn 11820:
11821: sub fetch_dns_checksums {
1.1238 raeburn 11822: my %checksums;
11823: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
11824: my $loncaparev = &get_server_loncaparev($machine_dom);
11825: my ($release,$timestamp) = split(/\-/,$loncaparev);
11826: &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1211 raeburn 11827: \%checksums);
1.1210 raeburn 11828: return \%checksums;
11829: }
11830:
1.327 albertel 11831: # ------------------------------------------------------------ Read domain file
11832: {
1.852 albertel 11833: my $loaded;
1.846 albertel 11834: my %domain;
11835:
1.852 albertel 11836: sub parse_domain_tab {
11837: my ($lines) = @_;
11838: foreach my $line (@$lines) {
11839: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 11840:
1.846 albertel 11841: chomp($line);
1.852 albertel 11842: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 11843: my %this_domain;
11844: foreach my $field ('description', 'auth_def', 'auth_arg_def',
11845: 'lang_def', 'city', 'longi', 'lati',
11846: 'primary') {
11847: $this_domain{$field} = shift(@elements);
11848: }
11849: $domain{$name} = \%this_domain;
1.852 albertel 11850: }
11851: }
1.864 albertel 11852:
11853: sub reset_domain_info {
11854: undef($loaded);
11855: undef(%domain);
11856: }
11857:
1.852 albertel 11858: sub load_domain_tab {
1.869 albertel 11859: my ($ignore_cache) = @_;
11860: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852 albertel 11861: my $fh;
11862: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
11863: my @lines = <$fh>;
11864: &parse_domain_tab(\@lines);
1.448 albertel 11865: }
1.852 albertel 11866: close($fh);
11867: $loaded = 1;
1.327 albertel 11868: }
1.846 albertel 11869:
11870: sub domain {
1.852 albertel 11871: &load_domain_tab() if (!$loaded);
11872:
1.846 albertel 11873: my ($name,$what) = @_;
11874: return if ( !exists($domain{$name}) );
11875:
11876: if (!$what) {
11877: return $domain{$name}{'description'};
11878: }
11879: return $domain{$name}{$what};
11880: }
1.974 raeburn 11881:
11882: sub domain_info {
11883: &load_domain_tab() if (!$loaded);
11884: return %domain;
11885: }
11886:
1.327 albertel 11887: }
11888:
11889:
1.1 albertel 11890: # ------------------------------------------------------------- Read hosts file
11891: {
1.838 albertel 11892: my %hostname;
1.844 albertel 11893: my %hostdom;
1.845 albertel 11894: my %libserv;
1.852 albertel 11895: my $loaded;
1.888 albertel 11896: my %name_to_host;
1.1074 raeburn 11897: my %internetdom;
1.1107 raeburn 11898: my %LC_dns_serv;
1.852 albertel 11899:
11900: sub parse_hosts_tab {
11901: my ($file) = @_;
11902: foreach my $configline (@$file) {
11903: next if ($configline =~ /^(\#|\s*$ )/x);
1.1107 raeburn 11904: chomp($configline);
11905: if ($configline =~ /^\^/) {
11906: if ($configline =~ /^\^([\w.\-]+)/) {
11907: $LC_dns_serv{$1} = 1;
11908: }
11909: next;
11910: }
1.1074 raeburn 11911: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 11912: $name=~s/\s//g;
11913: if ($id && $domain && $role && $name) {
11914: $hostname{$id}=$name;
1.888 albertel 11915: push(@{$name_to_host{$name}}, $id);
1.852 albertel 11916: $hostdom{$id}=$domain;
11917: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 11918: if (defined($protocol)) {
11919: if ($protocol eq 'https') {
11920: $protocol{$id} = $protocol;
11921: } else {
11922: $protocol{$id} = 'http';
11923: }
1.968 raeburn 11924: } else {
1.969 raeburn 11925: $protocol{$id} = 'http';
1.968 raeburn 11926: }
1.1074 raeburn 11927: if (defined($intdom)) {
11928: $internetdom{$id} = $intdom;
11929: }
1.852 albertel 11930: }
11931: }
11932: }
1.864 albertel 11933:
11934: sub reset_hosts_info {
1.897 albertel 11935: &purge_remembered();
1.864 albertel 11936: &reset_domain_info();
11937: &reset_hosts_ip_info();
1.892 albertel 11938: undef(%name_to_host);
1.864 albertel 11939: undef(%hostname);
11940: undef(%hostdom);
11941: undef(%libserv);
11942: undef($loaded);
11943: }
1.1 albertel 11944:
1.852 albertel 11945: sub load_hosts_tab {
1.869 albertel 11946: my ($ignore_cache) = @_;
11947: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852 albertel 11948: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11949: my @config = <$config>;
11950: &parse_hosts_tab(\@config);
11951: close($config);
11952: $loaded=1;
1.1 albertel 11953: }
1.852 albertel 11954:
1.838 albertel 11955: sub hostname {
1.852 albertel 11956: &load_hosts_tab() if (!$loaded);
11957:
1.838 albertel 11958: my ($lonid) = @_;
11959: return $hostname{$lonid};
11960: }
1.845 albertel 11961:
1.838 albertel 11962: sub all_hostnames {
1.852 albertel 11963: &load_hosts_tab() if (!$loaded);
11964:
1.838 albertel 11965: return %hostname;
11966: }
1.845 albertel 11967:
1.888 albertel 11968: sub all_names {
11969: &load_hosts_tab() if (!$loaded);
11970:
11971: return %name_to_host;
11972: }
11973:
1.974 raeburn 11974: sub all_host_domain {
11975: &load_hosts_tab() if (!$loaded);
11976: return %hostdom;
11977: }
11978:
1.845 albertel 11979: sub is_library {
1.852 albertel 11980: &load_hosts_tab() if (!$loaded);
11981:
1.845 albertel 11982: return exists($libserv{$_[0]});
11983: }
11984:
11985: sub all_library {
1.852 albertel 11986: &load_hosts_tab() if (!$loaded);
11987:
1.845 albertel 11988: return %libserv;
11989: }
11990:
1.1062 droeschl 11991: sub unique_library {
11992: #2x reverse removes all hostnames that appear more than once
11993: my %unique = reverse &all_library();
11994: return reverse %unique;
11995: }
11996:
1.841 albertel 11997: sub get_servers {
1.852 albertel 11998: &load_hosts_tab() if (!$loaded);
11999:
1.841 albertel 12000: my ($domain,$type) = @_;
12001: my %possible_hosts = ($type eq 'library') ? %libserv
12002: : %hostname;
12003: my %result;
1.842 albertel 12004: if (ref($domain) eq 'ARRAY') {
12005: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 12006: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 12007: $result{$host} = $hostname;
12008: }
12009: }
12010: } else {
12011: while ( my ($host,$hostname) = each(%possible_hosts)) {
12012: if ($hostdom{$host} eq $domain) {
12013: $result{$host} = $hostname;
12014: }
1.841 albertel 12015: }
12016: }
12017: return %result;
12018: }
1.845 albertel 12019:
1.1062 droeschl 12020: sub get_unique_servers {
12021: my %unique = reverse &get_servers(@_);
12022: return reverse %unique;
12023: }
12024:
1.844 albertel 12025: sub host_domain {
1.852 albertel 12026: &load_hosts_tab() if (!$loaded);
12027:
1.844 albertel 12028: my ($lonid) = @_;
12029: return $hostdom{$lonid};
12030: }
12031:
1.841 albertel 12032: sub all_domains {
1.852 albertel 12033: &load_hosts_tab() if (!$loaded);
12034:
1.841 albertel 12035: my %seen;
12036: my @uniq = grep(!$seen{$_}++, values(%hostdom));
12037: return @uniq;
12038: }
1.1074 raeburn 12039:
12040: sub internet_dom {
12041: &load_hosts_tab() if (!$loaded);
12042:
12043: my ($lonid) = @_;
12044: return $internetdom{$lonid};
12045: }
1.1107 raeburn 12046:
12047: sub is_LC_dns {
12048: &load_hosts_tab() if (!$loaded);
12049:
12050: my ($hostname) = @_;
12051: return exists($LC_dns_serv{$hostname});
12052: }
12053:
1.1 albertel 12054: }
12055:
1.847 albertel 12056: {
12057: my %iphost;
1.856 albertel 12058: my %name_to_ip;
12059: my %lonid_to_ip;
1.869 albertel 12060:
1.847 albertel 12061: sub get_hosts_from_ip {
12062: my ($ip) = @_;
12063: my %iphosts = &get_iphost();
12064: if (ref($iphosts{$ip})) {
12065: return @{$iphosts{$ip}};
12066: }
12067: return;
1.839 albertel 12068: }
1.864 albertel 12069:
12070: sub reset_hosts_ip_info {
12071: undef(%iphost);
12072: undef(%name_to_ip);
12073: undef(%lonid_to_ip);
12074: }
1.856 albertel 12075:
12076: sub get_host_ip {
12077: my ($lonid) = @_;
12078: if (exists($lonid_to_ip{$lonid})) {
12079: return $lonid_to_ip{$lonid};
12080: }
12081: my $name=&hostname($lonid);
12082: my $ip = gethostbyname($name);
12083: return if (!$ip || length($ip) ne 4);
12084: $ip=inet_ntoa($ip);
12085: $name_to_ip{$name} = $ip;
12086: $lonid_to_ip{$lonid} = $ip;
12087: return $ip;
12088: }
1.847 albertel 12089:
12090: sub get_iphost {
1.869 albertel 12091: my ($ignore_cache) = @_;
1.894 albertel 12092:
1.869 albertel 12093: if (!$ignore_cache) {
12094: if (%iphost) {
12095: return %iphost;
12096: }
12097: my ($ip_info,$cached)=
12098: &Apache::lonnet::is_cached_new('iphost','iphost');
12099: if ($cached) {
12100: %iphost = %{$ip_info->[0]};
12101: %name_to_ip = %{$ip_info->[1]};
12102: %lonid_to_ip = %{$ip_info->[2]};
12103: return %iphost;
12104: }
12105: }
1.894 albertel 12106:
12107: # get yesterday's info for fallback
12108: my %old_name_to_ip;
12109: my ($ip_info,$cached)=
12110: &Apache::lonnet::is_cached_new('iphost','iphost');
12111: if ($cached) {
12112: %old_name_to_ip = %{$ip_info->[1]};
12113: }
12114:
1.888 albertel 12115: my %name_to_host = &all_names();
12116: foreach my $name (keys(%name_to_host)) {
1.847 albertel 12117: my $ip;
12118: if (!exists($name_to_ip{$name})) {
12119: $ip = gethostbyname($name);
12120: if (!$ip || length($ip) ne 4) {
1.894 albertel 12121: if (defined($old_name_to_ip{$name})) {
12122: $ip = $old_name_to_ip{$name};
12123: &logthis("Can't find $name defaulting to old $ip");
12124: } else {
12125: &logthis("Name $name no IP found");
12126: next;
12127: }
12128: } else {
12129: $ip=inet_ntoa($ip);
1.847 albertel 12130: }
12131: $name_to_ip{$name} = $ip;
12132: } else {
12133: $ip = $name_to_ip{$name};
1.653 albertel 12134: }
1.888 albertel 12135: foreach my $id (@{ $name_to_host{$name} }) {
12136: $lonid_to_ip{$id} = $ip;
12137: }
12138: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 12139: }
1.1219 raeburn 12140: &do_cache_new('iphost','iphost',
12141: [\%iphost,\%name_to_ip,\%lonid_to_ip],
12142: 48*60*60);
1.869 albertel 12143:
1.847 albertel 12144: return %iphost;
1.598 albertel 12145: }
12146:
1.992 raeburn 12147: #
12148: # Given a DNS returns the loncapa host name for that DNS
12149: #
12150: sub host_from_dns {
12151: my ($dns) = @_;
12152: my @hosts;
12153: my $ip;
12154:
1.993 raeburn 12155: if (exists($name_to_ip{$dns})) {
1.992 raeburn 12156: $ip = $name_to_ip{$dns};
12157: }
12158: if (!$ip) {
12159: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
12160: if (length($ip) == 4) {
12161: $ip = &IO::Socket::inet_ntoa($ip);
12162: }
12163: }
12164: if ($ip) {
12165: @hosts = get_hosts_from_ip($ip);
12166: return $hosts[0];
12167: }
12168: return undef;
1.986 foxr 12169: }
1.992 raeburn 12170:
1.1074 raeburn 12171: sub get_internet_names {
12172: my ($lonid) = @_;
12173: return if ($lonid eq '');
12174: my ($idnref,$cached)=
12175: &Apache::lonnet::is_cached_new('internetnames',$lonid);
12176: if ($cached) {
12177: return $idnref;
12178: }
12179: my $ip = &get_host_ip($lonid);
12180: my @hosts = &get_hosts_from_ip($ip);
12181: my %iphost = &get_iphost();
12182: my (@idns,%seen);
12183: foreach my $id (@hosts) {
12184: my $dom = &host_domain($id);
12185: my $prim_id = &domain($dom,'primary');
12186: my $prim_ip = &get_host_ip($prim_id);
12187: next if ($seen{$prim_ip});
12188: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
12189: foreach my $id (@{$iphost{$prim_ip}}) {
12190: my $intdom = &internet_dom($id);
12191: unless (grep(/^\Q$intdom\E$/,@idns)) {
12192: push(@idns,$intdom);
12193: }
12194: }
12195: }
12196: $seen{$prim_ip} = 1;
12197: }
1.1219 raeburn 12198: return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074 raeburn 12199: }
12200:
1.986 foxr 12201: }
12202:
1.1079 raeburn 12203: sub all_loncaparevs {
1.1249 raeburn 12204: 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 12205: }
12206:
1.1227 raeburn 12207: # ---------------------------------------------------------- Read loncaparev table
12208: {
12209: sub load_loncaparevs {
12210: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
12211: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
12212: while (my $configline=<$config>) {
12213: chomp($configline);
12214: my ($hostid,$loncaparev)=split(/:/,$configline);
12215: $loncaparevs{$hostid}=$loncaparev;
12216: }
12217: close($config);
12218: }
12219: }
12220: }
12221: }
12222:
12223: # ---------------------------------------------------------- Read serverhostID table
12224: {
12225: sub load_serverhomeIDs {
12226: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
12227: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
12228: while (my $configline=<$config>) {
12229: chomp($configline);
12230: my ($name,$id)=split(/:/,$configline);
12231: $serverhomeIDs{$name}=$id;
12232: }
12233: close($config);
12234: }
12235: }
12236: }
12237: }
12238:
12239:
1.862 albertel 12240: BEGIN {
12241:
12242: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
12243: unless ($readit) {
12244: {
12245: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
12246: %perlvar = (%perlvar,%{$configvars});
12247: }
12248:
12249:
1.1 albertel 12250: # ------------------------------------------------------ Read spare server file
12251: {
1.448 albertel 12252: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 12253:
12254: while (my $configline=<$config>) {
12255: chomp($configline);
1.284 matthew 12256: if ($configline) {
1.784 albertel 12257: my ($host,$type) = split(':',$configline,2);
1.785 albertel 12258: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 12259: push(@{ $spareid{$type} }, $host);
1.1 albertel 12260: }
12261: }
1.448 albertel 12262: close($config);
1.1 albertel 12263: }
1.11 www 12264: # ------------------------------------------------------------ Read permissions
12265: {
1.448 albertel 12266: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 12267:
12268: while (my $configline=<$config>) {
1.448 albertel 12269: chomp($configline);
12270: if ($configline) {
12271: my ($role,$perm)=split(/ /,$configline);
12272: if ($perm ne '') { $pr{$role}=$perm; }
12273: }
1.11 www 12274: }
1.448 albertel 12275: close($config);
1.11 www 12276: }
12277:
12278: # -------------------------------------------- Read plain texts for permissions
12279: {
1.448 albertel 12280: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 12281:
12282: while (my $configline=<$config>) {
1.448 albertel 12283: chomp($configline);
12284: if ($configline) {
1.742 raeburn 12285: my ($short,@plain)=split(/:/,$configline);
12286: %{$prp{$short}} = ();
12287: if (@plain > 0) {
12288: $prp{$short}{'std'} = $plain[0];
12289: for (my $i=1; $i<@plain; $i++) {
12290: $prp{$short}{'alt'.$i} = $plain[$i];
12291: }
12292: }
1.448 albertel 12293: }
1.135 www 12294: }
1.448 albertel 12295: close($config);
1.135 www 12296: }
12297:
12298: # ---------------------------------------------------------- Read package table
12299: {
1.448 albertel 12300: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 12301:
12302: while (my $configline=<$config>) {
1.483 albertel 12303: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 12304: chomp($configline);
12305: my ($short,$plain)=split(/:/,$configline);
12306: my ($pack,$name)=split(/\&/,$short);
12307: if ($plain ne '') {
12308: $packagetab{$pack.'&'.$name.'&name'}=$name;
12309: $packagetab{$short}=$plain;
12310: }
1.11 www 12311: }
1.448 albertel 12312: close($config);
1.329 matthew 12313: }
12314:
1.1073 raeburn 12315: # ---------------------------------------------------------- Read loncaparev table
1.1227 raeburn 12316:
12317: &load_loncaparevs();
1.1073 raeburn 12318:
1.1074 raeburn 12319: # ---------------------------------------------------------- Read serverhostID table
12320:
1.1227 raeburn 12321: &load_serverhomeIDs();
12322:
12323: # ---------------------------------------------------------- Read releaseslist XML
1.1079 raeburn 12324: {
12325: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
12326: if (-e $file) {
12327: my $parser = HTML::LCParser->new($file);
12328: while (my $token = $parser->get_token()) {
12329: if ($token->[0] eq 'S') {
12330: my $item = $token->[1];
12331: my $name = $token->[2]{'name'};
12332: my $value = $token->[2]{'value'};
12333: if ($item ne '' && $name ne '' && $value ne '') {
12334: my $release = $parser->get_text();
12335: $release =~ s/(^\s*|\s*$ )//gx;
12336: $needsrelease{$item.':'.$name.':'.$value} = $release;
12337: }
12338: }
12339: }
12340: }
1.1073 raeburn 12341: }
12342:
1.1138 raeburn 12343: # ---------------------------------------------------------- Read managers table
12344: {
12345: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
12346: if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
12347: while (my $configline=<$config>) {
12348: chomp($configline);
12349: next if ($configline =~ /^\#/);
12350: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
12351: $managerstab{$configline} = 1;
12352: }
12353: }
12354: close($config);
12355: }
12356: }
12357: }
12358:
1.329 matthew 12359: # ------------- set up temporary directory
12360: {
1.1117 foxr 12361: $tmpdir = LONCAPA::tempdir();
1.329 matthew 12362:
1.11 www 12363: }
12364:
1.794 albertel 12365: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
12366: 'compress_threshold'=> 20_000,
12367: });
1.185 www 12368:
1.281 www 12369: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 12370: $dumpcount=0;
1.958 www 12371: $locknum=0;
1.22 www 12372:
1.163 harris41 12373: &logtouch();
1.672 albertel 12374: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 12375: $readit=1;
1.564 albertel 12376: {
12377: use integer;
12378: my $test=(2**32)+1;
1.568 albertel 12379: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 12380: &logthis(" Detected 64bit platform ($_64bit)");
12381: }
1.195 www 12382: }
1.1 albertel 12383: }
1.179 www 12384:
1.1 albertel 12385: 1;
1.191 harris41 12386: __END__
12387:
1.243 albertel 12388: =pod
12389:
1.191 harris41 12390: =head1 NAME
12391:
1.243 albertel 12392: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 12393:
12394: =head1 SYNOPSIS
12395:
1.243 albertel 12396: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 12397:
12398: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
12399:
1.243 albertel 12400: Common parameters:
12401:
12402: =over 4
12403:
12404: =item *
12405:
12406: $uname : an internal username (if $cname expecting a course Id specifically)
12407:
12408: =item *
12409:
12410: $udom : a domain (if $cdom expecting a course's domain specifically)
12411:
12412: =item *
12413:
12414: $symb : a resource instance identifier
12415:
12416: =item *
12417:
12418: $namespace : the name of a .db file that contains the data needed or
12419: being set.
12420:
12421: =back
12422:
1.394 bowersj2 12423: =head1 OVERVIEW
1.191 harris41 12424:
1.394 bowersj2 12425: lonnet provides subroutines which interact with the
12426: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
12427: about classes, users, and resources.
1.243 albertel 12428:
12429: For many of these objects you can also use this to store data about
12430: them or modify them in various ways.
1.191 harris41 12431:
1.394 bowersj2 12432: =head2 Symbs
1.191 harris41 12433:
1.394 bowersj2 12434: To identify a specific instance of a resource, LON-CAPA uses symbols
12435: or "symbs"X<symb>. These identifiers are built from the URL of the
12436: map, the resource number of the resource in the map, and the URL of
12437: the resource itself. The latter is somewhat redundant, but might help
12438: if maps change.
12439:
12440: An example is
12441:
12442: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
12443:
12444: The respective map entry is
12445:
12446: <resource id="19" src="/res/msu/korte/tests/part12.problem"
12447: title="Problem 2">
12448: </resource>
12449:
12450: Symbs are used by the random number generator, as well as to store and
12451: restore data specific to a certain instance of for example a problem.
12452:
12453: =head2 Storing And Retrieving Data
12454:
12455: X<store()>X<cstore()>X<restore()>Three of the most important functions
12456: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
12457: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
12458: is is the non-critical message twin of cstore. These functions are for
12459: handlers to store a perl hash to a user's permanent data space in an
12460: easy manner, and to retrieve it again on another call. It is expected
12461: that a handler would use this once at the beginning to retrieve data,
12462: and then again once at the end to send only the new data back.
12463:
12464: The data is stored in the user's data directory on the user's
12465: homeserver under the ID of the course.
12466:
12467: The hash that is returned by restore will have all of the previous
12468: value for all of the elements of the hash.
12469:
12470: Example:
12471:
12472: #creating a hash
12473: my %hash;
12474: $hash{'foo'}='bar';
12475:
12476: #storing it
12477: &Apache::lonnet::cstore(\%hash);
12478:
12479: #changing a value
12480: $hash{'foo'}='notbar';
12481:
12482: #adding a new value
12483: $hash{'bar'}='foo';
12484: &Apache::lonnet::cstore(\%hash);
12485:
12486: #retrieving the hash
12487: my %history=&Apache::lonnet::restore();
12488:
12489: #print the hash
12490: foreach my $key (sort(keys(%history))) {
12491: print("\%history{$key} = $history{$key}");
12492: }
12493:
12494: Will print out:
1.191 harris41 12495:
1.394 bowersj2 12496: %history{1:foo} = bar
12497: %history{1:keys} = foo:timestamp
12498: %history{1:timestamp} = 990455579
12499: %history{2:bar} = foo
12500: %history{2:foo} = notbar
12501: %history{2:keys} = foo:bar:timestamp
12502: %history{2:timestamp} = 990455580
12503: %history{bar} = foo
12504: %history{foo} = notbar
12505: %history{timestamp} = 990455580
12506: %history{version} = 2
12507:
12508: Note that the special hash entries C<keys>, C<version> and
12509: C<timestamp> were added to the hash. C<version> will be equal to the
12510: total number of versions of the data that have been stored. The
12511: C<timestamp> attribute will be the UNIX time the hash was
12512: stored. C<keys> is available in every historical section to list which
12513: keys were added or changed at a specific historical revision of a
12514: hash.
12515:
12516: B<Warning>: do not store the hash that restore returns directly. This
12517: will cause a mess since it will restore the historical keys as if the
12518: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 12519:
1.394 bowersj2 12520: Calling convention:
1.191 harris41 12521:
1.1225 raeburn 12522: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
12523: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname);
1.191 harris41 12524:
1.394 bowersj2 12525: For more detailed information, see lonnet specific documentation.
1.191 harris41 12526:
1.394 bowersj2 12527: =head1 RETURN MESSAGES
1.191 harris41 12528:
1.394 bowersj2 12529: =over 4
1.191 harris41 12530:
1.394 bowersj2 12531: =item * B<con_lost>: unable to contact remote host
1.191 harris41 12532:
1.394 bowersj2 12533: =item * B<con_delayed>: unable to contact remote host, message will be delivered
12534: when the connection is brought back up
1.191 harris41 12535:
1.394 bowersj2 12536: =item * B<con_failed>: unable to contact remote host and unable to save message
12537: for later delivery
1.191 harris41 12538:
1.967 bisitz 12539: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 12540:
1.394 bowersj2 12541: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 12542: that was requested
1.191 harris41 12543:
1.243 albertel 12544: =back
1.191 harris41 12545:
1.243 albertel 12546: =head1 PUBLIC SUBROUTINES
1.191 harris41 12547:
1.243 albertel 12548: =head2 Session Environment Functions
1.191 harris41 12549:
1.243 albertel 12550: =over 4
1.191 harris41 12551:
1.394 bowersj2 12552: =item *
12553: X<appenv()>
1.949 raeburn 12554: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 12555: the user envirnoment file, and will be restored for each access this
1.620 albertel 12556: user makes during this session, also modifies the %env for the current
1.949 raeburn 12557: process. Optional rolesarrayref - if defined contains a reference to an array
12558: of roles which are exempt from the restriction on modifying user.role entries
12559: in the user's environment.db and in %env.
1.191 harris41 12560:
12561: =item *
1.394 bowersj2 12562: X<delenv()>
1.987 raeburn 12563: B<delenv($delthis,$regexp)>: removes all items from the session
12564: environment file that begin with $delthis. If the
12565: optional second arg - $regexp - is true, $delthis is treated as a
12566: regular expression, otherwise \Q$delthis\E is used.
12567: The values are also deleted from the current processes %env.
1.191 harris41 12568:
1.795 albertel 12569: =item * get_env_multiple($name)
12570:
12571: gets $name from the %env hash, it seemlessly handles the cases where multiple
12572: values may be defined and end up as an array ref.
12573:
12574: returns an array of values
12575:
1.243 albertel 12576: =back
12577:
12578: =head2 User Information
1.191 harris41 12579:
1.243 albertel 12580: =over 4
1.191 harris41 12581:
12582: =item *
1.394 bowersj2 12583: X<queryauthenticate()>
12584: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 12585: authentication scheme
12586:
12587: =item *
1.394 bowersj2 12588: X<authenticate()>
1.1073 raeburn 12589: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 12590: authenticate user from domain's lib servers (first use the current
12591: one). C<$upass> should be the users password.
1.1073 raeburn 12592: $checkdefauth is optional (value is 1 if a check should be made to
12593: authenticate user using default authentication method, and allow
12594: account creation if username does not have account in the domain).
12595: $clientcancheckhost is optional (value is 1 if checking whether the
12596: server can host will occur on the client side in lonauth.pm).
1.191 harris41 12597:
12598: =item *
1.394 bowersj2 12599: X<homeserver()>
12600: B<homeserver($uname,$udom)>: find the server which has
12601: the user's directory and files (there must be only one), this caches
12602: the answer, and also caches if there is a borken connection.
1.191 harris41 12603:
12604: =item *
1.394 bowersj2 12605: X<idget()>
12606: B<idget($udom,@ids)>: find the usernames behind a list of IDs
12607: (IDs are a unique resource in a domain, there must be only 1 ID per
12608: username, and only 1 username per ID in a specific domain) (returns
12609: hash: id=>name,id=>name)
1.191 harris41 12610:
12611: =item *
1.394 bowersj2 12612: X<idrget()>
12613: B<idrget($udom,@unames)>: find the IDs behind a list of
12614: usernames (returns hash: name=>id,name=>id)
1.191 harris41 12615:
12616: =item *
1.394 bowersj2 12617: X<idput()>
12618: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 12619:
12620: =item *
1.394 bowersj2 12621: X<rolesinit()>
1.1169 droeschl 12622: B<rolesinit($udom,$username)>: get user privileges.
12623: returns user role, first access and timer interval hashes
1.243 albertel 12624:
12625: =item *
1.1171 droeschl 12626: X<privileged()>
12627: B<privileged($username,$domain)>: returns a true if user has a
12628: privileged and active role (i.e. su or dc), false otherwise.
12629:
12630: =item *
1.551 albertel 12631: X<getsection()>
12632: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 12633: course $cname, return section name/number or '' for "not in course"
12634: and '-1' for "no section"
12635:
12636: =item *
1.394 bowersj2 12637: X<userenvironment()>
12638: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 12639: passed in @what from the requested user's environment, returns a hash
12640:
1.858 raeburn 12641: =item *
12642: X<userlog_query()>
1.859 albertel 12643: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
12644: activity.log file. %filters defines filters applied when parsing the
12645: log file. These can be start or end timestamps, or the type of action
12646: - log to look for Login or Logout events, check for Checkin or
12647: Checkout, role for role selection. The response is in the form
12648: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
12649: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 12650:
1.243 albertel 12651: =back
12652:
12653: =head2 User Roles
12654:
12655: =over 4
12656:
12657: =item *
12658:
1.810 raeburn 12659: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243 albertel 12660: F: full access
12661: U,I,K: authentication modes (cxx only)
12662: '': forbidden
12663: 1: user needs to choose course
12664: 2: browse allowed
1.766 albertel 12665: A: passphrase authentication needed
1.243 albertel 12666:
12667: =item *
12668:
1.1192 raeburn 12669: constructaccess($url,$setpriv) : check for access to construction space URL
12670:
12671: See if the owner domain and name in the URL match those in the
12672: expected environment. If so, return three element list
12673: ($ownername,$ownerdomain,$ownerhome).
12674:
12675: Otherwise return the null string.
12676:
12677: If second argument 'setpriv' is true, it assigns the privileges,
12678: and returns the same three element list, unless the owner has
12679: blocked "ad hoc" Domain Coordinator access to the Author Space,
12680: in which case the null string is returned.
12681:
12682: =item *
12683:
1.243 albertel 12684: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
12685: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
12686: and course level
12687:
12688: =item *
12689:
1.988 raeburn 12690: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
12691: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 12692: $type is Course (default) or Community.
1.988 raeburn 12693: If $forcedefault evaluates to true, text returned will be default
12694: text for $type. Otherwise, if this is a course, the text returned
12695: will be a custom name for the role (if defined in the course's
12696: environment). If no custom name is defined the default is returned.
12697:
1.832 raeburn 12698: =item *
12699:
1.1219 raeburn 12700: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858 raeburn 12701: All arguments are optional. Returns a hash of a roles, either for
12702: co-author/assistant author roles for a user's Construction Space
1.906 albertel 12703: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 12704: In the hash, keys are set to colon-separated $uname,$udom,$role, and
12705: (optionally) if $withsec is true, a fourth colon-separated item - $section.
12706: For each key, value is set to colon-separated start and end times for
12707: the role. If no username and domain are specified, will default to
1.934 raeburn 12708: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 12709: of role statuses (active, future or previous), roles
12710: (e.g., cc,in, st etc.) and domains of the roles which can be used
12711: to restrict the list of roles reported. If no array ref is
12712: provided for types, will default to return only active roles.
1.834 albertel 12713:
1.1195 raeburn 12714: =item *
12715:
12716: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196 raeburn 12717: user: $uname:$udom has a role in the course: $cdom_$cnum.
12718:
12719: Additional optional arguments are: $type (if role checking is to be restricted
12720: to certain user status types -- previous (expired roles), active (currently
1.1195 raeburn 12721: available roles) or future (roles available in the future), and
12722: $hideprivileged -- if true will not report course roles for users who
1.1219 raeburn 12723: have active Domain Coordinator role in course's domain or in additional
12724: domains (specified in 'Domains to check for privileged users' in course
12725: environment -- set via: Course Settings -> Classlists and staff listing).
12726:
12727: =item *
12728:
12729: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
12730: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
12731: $possdomains and $possroles are optional array refs -- to domains to check and
12732: roles to check. If $possdomains is not specified, a dump will be done of the
12733: users' roles.db to check for a dc or su role in any domain. This can be
12734: time consuming if &privileged is called repeatedly (e.g., when displaying a
12735: classlist), so in such cases, supplying a $possdomains array is preferred, as
12736: this then allows &privileged_by_domain() to be used, which caches the identity
12737: of privileged users, eliminating the need for repeated calls to &dump().
12738:
12739: =item *
12740:
12741: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
12742: where the outer hash keys are domains specified in the $possdomains array ref,
12743: next inner hash keys are privileged roles specified in the $roles array ref,
12744: and the innermost hash contains key = value pairs for username:domain = end:start
12745: for active or future "privileged" users with that role in that domain. To avoid
12746: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
12747: innerhash are cached using priv_$role and $dom as the identifiers.
1.1195 raeburn 12748:
1.243 albertel 12749: =back
12750:
12751: =head2 User Modification
12752:
12753: =over 4
12754:
12755: =item *
12756:
1.957 raeburn 12757: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 12758: user for the level given by URL. Optional start and end dates (leave empty
12759: string or zero for "no date")
1.191 harris41 12760:
12761: =item *
12762:
1.243 albertel 12763: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
12764: change a users, password, possible return values are: ok,
12765: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
12766: refused
1.191 harris41 12767:
12768: =item *
12769:
1.243 albertel 12770: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 12771:
12772: =item *
12773:
1.1058 raeburn 12774: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
12775: $forceid,$desiredhome,$email,$inststatus,$candelete) :
12776:
12777: will update user information (firstname,middlename,lastname,generation,
12778: permanentemail), and if forceid is true, student/employee ID also.
12779: A user's institutional affiliation(s) can also be updated.
12780: User information fields will not be overwritten with empty entries
12781: unless the field is included in the $candelete array reference.
12782: This array is included when a single user is modified via "Manage Users",
12783: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 12784:
12785: =item *
12786:
1.286 matthew 12787: modifystudent
12788:
1.957 raeburn 12789: modify a student's enrollment and identification information.
1.1235 raeburn 12790: The course id is resolved based on the current user's environment.
12791: This means the invoking user must be a course coordinator or otherwise
1.286 matthew 12792: associated with a course.
12793:
1.297 matthew 12794: This call is essentially a wrapper for lonnet::modifyuser and
12795: lonnet::modify_student_enrollment
1.286 matthew 12796:
12797: Inputs:
12798:
12799: =over 4
12800:
1.957 raeburn 12801: =item B<$udom> Student's loncapa domain
1.286 matthew 12802:
1.957 raeburn 12803: =item B<$uname> Student's loncapa login name
1.286 matthew 12804:
1.964 bisitz 12805: =item B<$uid> Student/Employee ID
1.286 matthew 12806:
1.957 raeburn 12807: =item B<$umode> Student's authentication mode
1.286 matthew 12808:
1.957 raeburn 12809: =item B<$upass> Student's password
1.286 matthew 12810:
1.957 raeburn 12811: =item B<$first> Student's first name
1.286 matthew 12812:
1.957 raeburn 12813: =item B<$middle> Student's middle name
1.286 matthew 12814:
1.957 raeburn 12815: =item B<$last> Student's last name
1.286 matthew 12816:
1.957 raeburn 12817: =item B<$gene> Student's generation
1.286 matthew 12818:
1.957 raeburn 12819: =item B<$usec> Student's section in course
1.286 matthew 12820:
12821: =item B<$end> Unix time of the roles expiration
12822:
12823: =item B<$start> Unix time of the roles start date
12824:
12825: =item B<$forceid> If defined, allow $uid to be changed
12826:
12827: =item B<$desiredhome> server to use as home server for student
12828:
1.957 raeburn 12829: =item B<$email> Student's permanent e-mail address
12830:
12831: =item B<$type> Type of enrollment (auto or manual)
12832:
1.963 raeburn 12833: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
12834:
12835: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 12836:
1.963 raeburn 12837: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 12838:
1.963 raeburn 12839: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 12840:
1.1216 raeburn 12841: =item B<$inststatus> institutional status of user - : separated string of escaped status types
12842:
12843: =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 12844:
1.286 matthew 12845: =back
1.297 matthew 12846:
12847: =item *
12848:
12849: modify_student_enrollment
12850:
1.1235 raeburn 12851: Change a student's enrollment status in a class. The environment variable
1.297 matthew 12852: 'role.request.course' must be defined for this function to proceed.
12853:
12854: Inputs:
12855:
12856: =over 4
12857:
1.1235 raeburn 12858: =item $udom, student's domain
1.297 matthew 12859:
1.1235 raeburn 12860: =item $uname, student's name
1.297 matthew 12861:
1.1235 raeburn 12862: =item $uid, student's user id
1.297 matthew 12863:
1.1235 raeburn 12864: =item $first, student's first name
1.297 matthew 12865:
12866: =item $middle
12867:
12868: =item $last
12869:
12870: =item $gene
12871:
12872: =item $usec
12873:
12874: =item $end
12875:
12876: =item $start
12877:
1.957 raeburn 12878: =item $type
12879:
12880: =item $locktype
12881:
12882: =item $cid
12883:
12884: =item $selfenroll
12885:
12886: =item $context
12887:
1.1216 raeburn 12888: =item $credits, number of credits student will earn from this class
12889:
1.297 matthew 12890: =back
12891:
1.191 harris41 12892:
12893: =item *
12894:
1.243 albertel 12895: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
12896: custom role; give a custom role to a user for the level given by URL. Specify
12897: name and domain of role author, and role name
1.191 harris41 12898:
12899: =item *
12900:
1.243 albertel 12901: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 12902:
12903: =item *
12904:
1.243 albertel 12905: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
12906:
12907: =back
12908:
12909: =head2 Course Infomation
12910:
12911: =over 4
1.191 harris41 12912:
12913: =item *
12914:
1.1118 foxr 12915: coursedescription($courseid,$options) : returns a hash of information about the
1.631 albertel 12916: specified course id, including all environment settings for the
12917: course, the description of the course will be in the hash under the
12918: key 'description'
1.191 harris41 12919:
1.1118 foxr 12920: $options is an optional parameter that if supplied is a hash reference that controls
12921: what how this function works. It has the following key/values:
12922:
12923: =over 4
12924:
12925: =item freshen_cache
12926:
12927: If defined, and the environment cache for the course is valid, it is
12928: returned in the returned hash.
12929:
12930: =item one_time
12931:
12932: If defined, the last cache time is set to _now_
12933:
12934: =item user
12935:
12936: If defined, the supplied username is used instead of the current user.
12937:
12938:
12939: =back
12940:
1.191 harris41 12941: =item *
12942:
1.624 albertel 12943: resdata($name,$domain,$type,@which) : request for current parameter
12944: setting for a specific $type, where $type is either 'course' or 'user',
12945: @what should be a list of parameters to ask about. This routine caches
1.1235 raeburn 12946: answers for 10 minutes.
1.243 albertel 12947:
1.877 foxr 12948: =item *
12949:
12950: get_courseresdata($courseid, $domain) : dump the entire course resource
12951: data base, returning a hash that is keyed by the resource name and has
12952: values that are the resource value. I believe that the timestamps and
12953: versions are also returned.
12954:
1.1236 raeburn 12955: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
12956: supplemental content area. This routine caches the number of files for
12957: 10 minutes.
12958:
1.243 albertel 12959: =back
12960:
12961: =head2 Course Modification
12962:
12963: =over 4
1.191 harris41 12964:
12965: =item *
12966:
1.243 albertel 12967: writecoursepref($courseid,%prefs) : write preferences (environment
12968: database) for a course
1.191 harris41 12969:
12970: =item *
12971:
1.1011 raeburn 12972: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
12973:
12974: =item *
12975:
1.1038 raeburn 12976: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 12977:
1.1167 droeschl 12978: =item *
12979:
12980: is_course($courseid), is_course($cdom, $cnum)
12981:
12982: Accepts either a combined $courseid (in the form of domain_courseid) or the
12983: two component version $cdom, $cnum. It checks if the specified course exists.
12984:
12985: Returns:
12986: undef if the course doesn't exist, otherwise
12987: in scalar context the combined courseid.
12988: in list context the two components of the course identifier, domain and
12989: courseid.
12990:
1.243 albertel 12991: =back
12992:
12993: =head2 Resource Subroutines
12994:
12995: =over 4
1.191 harris41 12996:
12997: =item *
12998:
1.243 albertel 12999: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 13000:
13001: =item *
13002:
1.243 albertel 13003: repcopy($filename) : subscribes to the requested file, and attempts to
13004: replicate from the owning library server, Might return
1.607 raeburn 13005: 'unavailable', 'not_found', 'forbidden', 'ok', or
13006: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 13007: resource. Expects the local filesystem pathname
13008: (/home/httpd/html/res/....)
13009:
13010: =back
13011:
13012: =head2 Resource Information
13013:
13014: =over 4
1.191 harris41 13015:
13016: =item *
13017:
1.1228 raeburn 13018: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates
13019: and returns the value of a variety of different possible values,
13020: $varname should be a request string, and the other parameters can be
13021: used to specify who and what one is asking about. Ordinarily, $cid
13022: does not need to be specified, as it is retrived from
13023: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
13024: within lonuserstate::loadmap() when initializing a course, before
13025: $env{'request.course.id'} has been set, so it needs to be provided
13026: in that one case.
1.243 albertel 13027:
13028: Possible values for $varname are environment.lastname (or other item
13029: from the envirnment hash), user.name (or someother aspect about the
13030: user), resource.0.maxtries (or some other part and parameter of a
13031: resource)
1.204 albertel 13032:
13033: =item *
13034:
1.243 albertel 13035: directcondval($number) : get current value of a condition; reads from a state
13036: string
1.204 albertel 13037:
13038: =item *
13039:
1.243 albertel 13040: condval($condidx) : value of condition index based on state
1.204 albertel 13041:
13042: =item *
13043:
1.243 albertel 13044: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
13045: resource's metadata, $what should be either a specific key, or either
13046: 'keys' (to get a list of possible keys) or 'packages' to get a list of
13047: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
13048:
13049: this function automatically caches all requests
1.191 harris41 13050:
13051: =item *
13052:
1.243 albertel 13053: metadata_query($query,$custom,$customshow) : make a metadata query against the
13054: network of library servers; returns file handle of where SQL and regex results
13055: will be stored for query
1.191 harris41 13056:
13057: =item *
13058:
1.243 albertel 13059: symbread($filename) : return symbolic list entry (filename argument optional);
13060: returns the data handle
1.191 harris41 13061:
13062: =item *
13063:
1.1190 raeburn 13064: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
13065: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582 albertel 13066: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190 raeburn 13067: on failure, user must be in a course, as it assumes the existence of
13068: the course initial hash, and uses $env('request.course.id'}. The third
13069: arg is an optional reference to a scalar. If this arg is passed in the
13070: call to symbverify, it will be set to 1 if the symb has been set to be
13071: encrypted; otherwise it will be null.
1.191 harris41 13072:
13073: =item *
13074:
1.243 albertel 13075: symbclean($symb) : removes versions numbers from a symb, returns the
13076: cleaned symb
1.191 harris41 13077:
13078: =item *
13079:
1.243 albertel 13080: is_on_map($uri) : checks if the $uri is somewhere on the current
13081: course map, user must be in a course for it to work.
1.191 harris41 13082:
13083: =item *
13084:
1.243 albertel 13085: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 13086:
13087: =item *
13088:
1.243 albertel 13089: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
13090: a random seed, all arguments are optional, if they aren't sent it uses the
13091: environment to derive them. Note: if symb isn't sent and it can't get one
13092: from &symbread it will use the current time as its return value
1.191 harris41 13093:
13094: =item *
13095:
1.243 albertel 13096: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
13097: unfakeable, receipt
1.191 harris41 13098:
13099: =item *
13100:
1.620 albertel 13101: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 13102:
13103: =item *
13104:
1.243 albertel 13105: countacc($url) : count the number of accesses to a given URL
1.191 harris41 13106:
13107: =item *
13108:
1.243 albertel 13109: 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 13110:
13111: =item *
13112:
1.243 albertel 13113: 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 13114:
13115: =item *
13116:
1.243 albertel 13117: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 13118:
13119: =item *
13120:
1.243 albertel 13121: devalidate($symb) : devalidate temporary spreadsheet calculations,
13122: forcing spreadsheet to reevaluate the resource scores next time.
13123:
1.1195 raeburn 13124: =item *
13125:
1.1196 raeburn 13126: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
13127: when viewing in course context.
1.1195 raeburn 13128:
1.1196 raeburn 13129: input: six args -- filename (decluttered), course number, course domain,
13130: url, symb (if registered) and group (if this is a
13131: group item -- e.g., bulletin board, group page etc.).
1.1195 raeburn 13132:
1.1196 raeburn 13133: output: array of five scalars --
1.1195 raeburn 13134: $cfile -- url for file editing if editable on current server
13135: $home -- homeserver of resource (i.e., for author if published,
13136: or course if uploaded.).
13137: $switchserver -- 1 if server switch will be needed.
1.1196 raeburn 13138: $forceedit -- 1 if icon/link should be to go to edit mode
13139: $forceview -- 1 if icon/link should be to go to view mode
1.1195 raeburn 13140:
13141: =item *
13142:
13143: is_course_upload($file,$cnum,$cdom)
13144:
13145: Used in course context to determine if current file was uploaded to
13146: the course (i.e., would be found in /userfiles/docs on the course's
13147: homeserver.
13148:
13149: input: 3 args -- filename (decluttered), course number and course domain.
13150: output: boolean -- 1 if file was uploaded.
13151:
1.243 albertel 13152: =back
13153:
13154: =head2 Storing/Retreiving Data
13155:
13156: =over 4
1.191 harris41 13157:
13158: =item *
13159:
1.243 albertel 13160: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
13161: for this url; hashref needs to be given and should be a \%hashname; the
13162: remaining args aren't required and if they aren't passed or are '' they will
1.620 albertel 13163: be derived from the env
1.191 harris41 13164:
13165: =item *
13166:
1.243 albertel 13167: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
13168: uses critical subroutine
1.191 harris41 13169:
13170: =item *
13171:
1.243 albertel 13172: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
13173: all args are optional
1.191 harris41 13174:
13175: =item *
13176:
1.717 albertel 13177: dumpstore($namespace,$udom,$uname,$regexp,$range) :
13178: dumps the complete (or key matching regexp) namespace into a hash
13179: ($udom, $uname, $regexp, $range are optional) for a namespace that is
13180: normally &store()ed into
13181:
13182: $range should be either an integer '100' (give me the first 100
13183: matching records)
13184: or be two integers sperated by a - with no spaces
13185: '30-50' (give me the 30th through the 50th matching
13186: records)
13187:
13188:
13189: =item *
13190:
13191: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
13192: replaces a &store() version of data with a replacement set of data
13193: for a particular resource in a namespace passed in the $storehash hash
13194: reference
13195:
13196: =item *
13197:
1.243 albertel 13198: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
13199: works very similar to store/cstore, but all data is stored in a
13200: temporary location and can be reset using tmpreset, $storehash should
13201: be a hash reference, returns nothing on success
1.191 harris41 13202:
13203: =item *
13204:
1.243 albertel 13205: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
13206: similar to restore, but all data is stored in a temporary location and
13207: can be reset using tmpreset. Returns a hash of values on success,
13208: error string otherwise.
1.191 harris41 13209:
13210: =item *
13211:
1.243 albertel 13212: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
13213: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 13214:
13215: =item *
13216:
1.243 albertel 13217: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13218: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 13219:
13220: =item *
13221:
1.243 albertel 13222: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
13223: namesp ($udom and $uname are optional)
1.191 harris41 13224:
13225: =item *
13226:
1.702 albertel 13227: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 13228: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 13229: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 13230:
1.702 albertel 13231: $range should be either an integer '100' (give me the first 100
13232: matching records)
13233: or be two integers sperated by a - with no spaces
13234: '30-50' (give me the 30th through the 50th matching
13235: records)
1.449 matthew 13236: =item *
13237:
13238: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
13239: $store can be a scalar, an array reference, or if the amount to be
13240: incremented is > 1, a hash reference.
13241:
13242: ($udom and $uname are optional)
1.191 harris41 13243:
13244: =item *
13245:
1.243 albertel 13246: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
13247: ($udom and $uname are optional)
1.191 harris41 13248:
13249: =item *
13250:
1.243 albertel 13251: cput($namespace,$storehash,$udom,$uname) : critical put
13252: ($udom and $uname are optional)
1.191 harris41 13253:
13254: =item *
13255:
1.748 albertel 13256: newput($namespace,$storehash,$udom,$uname) :
13257:
13258: Attempts to store the items in the $storehash, but only if they don't
13259: currently exist, if this succeeds you can be certain that you have
13260: successfully created a new key value pair in the $namespace db.
13261:
13262:
13263: Args:
13264: $namespace: name of database to store values to
13265: $storehash: hashref to store to the db
13266: $udom: (optional) domain of user containing the db
13267: $uname: (optional) name of user caontaining the db
13268:
13269: Returns:
13270: 'ok' -> succeeded in storing all keys of $storehash
13271: 'key_exists: <key>' -> failed to anything out of $storehash, as at
13272: least <key> already existed in the db (other
13273: requested keys may also already exist)
1.967 bisitz 13274: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 13275: 'con_lost' -> unable to contact request server
13276: 'refused' -> action was not allowed by remote machine
13277:
13278:
13279: =item *
13280:
1.243 albertel 13281: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13282: reference filled in from namesp (encrypts the return communication)
13283: ($udom and $uname are optional)
1.191 harris41 13284:
13285: =item *
13286:
1.243 albertel 13287: log($udom,$name,$home,$message) : write to permanent log for user; use
13288: critical subroutine
13289:
1.806 raeburn 13290: =item *
13291:
1.860 raeburn 13292: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
13293: array reference filled in from namespace found in domain level on either
13294: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 13295:
13296: =item *
13297:
1.860 raeburn 13298: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
13299: domain level either on specified domain server ($uhome) or primary domain
13300: server ($udom and $uhome are optional)
1.806 raeburn 13301:
1.943 raeburn 13302: =item *
13303:
1.1240 raeburn 13304: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
13305: for: authentication, language, quotas, timezone, date locale, and portal URL in
13306: the target domain.
13307:
13308: May also include additional key => value pairs for the following groups:
13309:
13310: =over
13311:
13312: =item
13313: disk quotas (MB allocated by default to portfolios and authoring spaces).
13314:
13315: =over
13316:
13317: =item defaultquota, authorquota
13318:
13319: =back
13320:
13321: =item
13322: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
13323: portfolio for users).
13324:
13325: =over
13326:
13327: =item
13328: aboutme, blog, webdav, portfolio
13329:
13330: =back
13331:
13332: =item
13333: requestcourses: ability to request courses, and how requests are processed.
13334:
13335: =over
13336:
13337: =item
1.1246 raeburn 13338: official, unofficial, community, textbook
1.1240 raeburn 13339:
13340: =back
13341:
13342: =item
13343: inststatus: types of institutional affiliation, and order in which they are displayed.
13344:
13345: =over
13346:
13347: =item
13348: inststatustypes, inststatusorder
13349:
13350: =back
13351:
13352: =item
13353: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
13354: for course's uploaded content.
13355:
13356: =over
13357:
13358: =item
1.1246 raeburn 13359: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
13360: communityquota, textbookquota
1.1240 raeburn 13361:
13362: =back
13363:
13364: =item
13365: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
13366: on your servers.
13367:
13368: =over
13369:
13370: =item
13371: remotesessions, hostedsessions
13372:
13373: =back
13374:
13375: =back
13376:
13377: In cases where a domain coordinator has never used the "Set Domain Configuration"
13378: utility to create a configuration.db file on a domain's primary library server
13379: only the following domain defaults: auth_def, auth_arg_def, lang_def
13380: -- corresponding values are authentication type (internal, krb4, krb5,
13381: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
13382: will be available. Values are retrieved from cache (if current), unless the
13383: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
13384: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
13385:
13386: Typical usage:
1.943 raeburn 13387:
1.1240 raeburn 13388: %domdefaults = &get_domain_defaults($target_domain);
1.943 raeburn 13389:
1.243 albertel 13390: =back
13391:
13392: =head2 Network Status Functions
13393:
13394: =over 4
1.191 harris41 13395:
13396: =item *
13397:
1.1137 raeburn 13398: dirlist() : return directory list based on URI (first arg).
13399:
13400: Inputs: 1 required, 5 optional.
13401:
13402: =over
13403:
13404: =item
13405: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
13406:
13407: =item
13408: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
13409:
13410: =item
13411: $username - username of user/course to be listed. Extracted from $uri if absent.
13412:
13413: =item
13414: $getpropath - boolean: 1 if prepend path using &propath().
13415:
13416: =item
13417: $getuserdir - boolean: 1 if prepend path for "userfiles".
13418:
13419: =item
13420: $alternateRoot - path to prepend in place of path from $uri.
13421:
13422: =back
13423:
13424: Returns: Array of up to two items.
13425:
13426: =over
13427:
13428: a reference to an array of files/subdirectories
13429:
13430: =over
13431:
13432: Each element in the array of files/subdirectories is a & separated list of
13433: item name and the result of running stat on the item. If dirlist was requested
13434: for a file instead of a directory, the item name will be ''. For a directory
13435: listing, if the item is a metadata file, the element will end &N&M
13436: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
13437: default copyright set (1).
13438:
13439: =back
13440:
13441: a scalar containing error condition (if encountered).
13442:
13443: =over
13444:
13445: =item
13446: no_host (no homeserver identified for $username:$domain).
13447:
13448: =item
13449: no_such_host (server contacted for listing not identified as valid host).
13450:
13451: =item
13452: con_lost (connection to remote server failed).
13453:
13454: =item
13455: refused (invalid $username:$domain received on lond side).
13456:
13457: =item
13458: no_such_dir (directory at specified path on lond side does not exist).
13459:
13460: =item
13461: empty (directory at specified path on lond side is empty).
13462:
13463: =over
13464:
13465: This is currently not encountered because the &ls3, &ls2,
13466: &ls (_handler) routines on the lond side do not filter out
13467: . and .. from a directory listing.
13468:
13469: =back
13470:
13471: =back
13472:
13473: =back
1.191 harris41 13474:
13475: =item *
13476:
1.243 albertel 13477: spareserver() : find server with least workload from spare.tab
13478:
1.986 foxr 13479:
13480: =item *
13481:
13482: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
13483: if there is no corresponding loncapa host.
13484:
1.243 albertel 13485: =back
13486:
1.986 foxr 13487:
1.243 albertel 13488: =head2 Apache Request
13489:
13490: =over 4
1.191 harris41 13491:
13492: =item *
13493:
1.243 albertel 13494: ssi($url,%hash) : server side include, does a complete request cycle on url to
13495: localhost, posts hash
13496:
13497: =back
13498:
13499: =head2 Data to String to Data
13500:
13501: =over 4
1.191 harris41 13502:
13503: =item *
13504:
1.243 albertel 13505: hash2str(%hash) : convert a hash into a string complete with escaping and '='
13506: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 13507:
13508: =item *
13509:
1.243 albertel 13510: hashref2str($hashref) : convert a hashref into a string complete with
13511: escaping and '=' and '&' separators, supports elements that are
13512: arrayrefs and hashrefs
1.191 harris41 13513:
13514: =item *
13515:
1.243 albertel 13516: arrayref2str($arrayref) : convert an arrayref into a string complete
13517: with escaping and '&' separators, supports elements that are arrayrefs
13518: and hashrefs
1.191 harris41 13519:
13520: =item *
13521:
1.243 albertel 13522: str2hash($string) : convert string to hash using unescaping and
13523: splitting on '=' and '&', supports elements that are arrayrefs and
13524: hashrefs
1.191 harris41 13525:
13526: =item *
13527:
1.243 albertel 13528: str2array($string) : convert string to hash using unescaping and
13529: splitting on '&', supports elements that are arrayrefs and hashrefs
13530:
13531: =back
13532:
13533: =head2 Logging Routines
13534:
13535:
13536: These routines allow one to make log messages in the lonnet.log and
13537: lonnet.perm logfiles.
1.191 harris41 13538:
1.1119 foxr 13539: =over 4
13540:
1.191 harris41 13541: =item *
13542:
1.243 albertel 13543: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 13544:
13545: =item *
13546:
1.243 albertel 13547: logthis() : append message to the normal lonnet.log file, it gets
13548: preiodically rolled over and deleted.
1.191 harris41 13549:
13550: =item *
13551:
1.243 albertel 13552: logperm() : append a permanent message to lonnet.perm.log, this log
13553: file never gets deleted by any automated portion of the system, only
13554: messages of critical importance should go in here.
13555:
1.1119 foxr 13556:
1.243 albertel 13557: =back
13558:
13559: =head2 General File Helper Routines
13560:
13561: =over 4
1.191 harris41 13562:
13563: =item *
13564:
1.481 raeburn 13565: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
13566: (a) files in /uploaded
13567: (i) If a local copy of the file exists -
13568: compares modification date of local copy with last-modified date for
13569: definitive version stored on home server for course. If local copy is
13570: stale, requests a new version from the home server and stores it.
13571: If the original has been removed from the home server, then local copy
13572: is unlinked.
13573: (ii) If local copy does not exist -
13574: requests the file from the home server and stores it.
13575:
13576: If $caller is 'uploadrep':
13577: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
13578: for request for files originally uploaded via DOCS.
13579: - returns 'ok' if fresh local copy now available, -1 otherwise.
13580:
13581: Otherwise:
13582: This indicates a call from the content generation phase of the request.
13583: - returns the entire contents of the file or -1.
13584:
13585: (b) files in /res
13586: - returns the entire contents of a file or -1;
13587: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 13588:
1.712 albertel 13589:
13590: =item *
13591:
13592: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
13593: reference
13594:
13595: returns either a stat() list of data about the file or an empty list
13596: if the file doesn't exist or couldn't find out about it (connection
13597: problems or user unknown)
13598:
1.191 harris41 13599: =item *
13600:
1.243 albertel 13601: filelocation($dir,$file) : returns file system location of a file
13602: based on URI; meant to be "fairly clean" absolute reference, $dir is a
13603: directory that relative $file lookups are to looked in ($dir of /a/dir
13604: and a file of ../bob will become /a/bob)
1.191 harris41 13605:
13606: =item *
13607:
13608: hreflocation($dir,$file) : returns file system location or a URL; same as
13609: filelocation except for hrefs
13610:
13611: =item *
13612:
13613: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
13614:
1.243 albertel 13615: =back
13616:
1.608 albertel 13617: =head2 Usererfile file routines (/uploaded*)
13618:
13619: =over 4
13620:
13621: =item *
13622:
13623: userfileupload(): main rotine for putting a file in a user or course's
13624: filespace, arguments are,
13625:
1.620 albertel 13626: formname - required - this is the name of the element in $env where the
1.608 albertel 13627: filename, and the contents of the file to create/modifed exist
1.620 albertel 13628: the filename is in $env{'form.'.$formname.'.filename'} and the
13629: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 13630: context - if coursedoc, store the file in the course of the active role
13631: of the current user;
13632: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
13633: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 13634: subdir - required - subdirectory to put the file in under ../userfiles/
13635: if undefined, it will be placed in "unknown"
13636:
13637: (This routine calls clean_filename() to remove any dangerous
13638: characters from the filename, and then calls finuserfileupload() to
13639: complete the transaction)
13640:
13641: returns either the url of the uploaded file (/uploaded/....) if successful
13642: and /adm/notfound.html if unsuccessful
13643:
13644: =item *
13645:
13646: clean_filename(): routine for cleaing a filename up for storage in
13647: userfile space, argument is:
13648:
13649: filename - proposed filename
13650:
13651: returns: the new clean filename
13652:
13653: =item *
13654:
1.1090 raeburn 13655: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 13656: userspace, probably shouldn't be called directly
13657:
13658: docuname: username or courseid of destination for the file
13659: docudom: domain of user/course of destination for the file
13660: formname: same as for userfileupload()
1.1090 raeburn 13661: fname: filename (including subdirectories) for the file
13662: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
13663: allfiles: reference to hash used to store objects found by parser
13664: codebase: reference to hash used for codebases of java objects found by parser
13665: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
13666: thumbheight: height (pixels) of thumbnail to be created for uploaded image
13667: resizewidth: width to be used to resize image using resizeImage from ImageMagick
13668: resizeheight: height to be used to resize image using resizeImage from ImageMagick
13669: context: if 'overwrite', will move the uploaded file from its temporary location to
13670: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 13671: mimetype: reference to scalar to accommodate mime type determined
13672: from File::MMagic if $parser = parse.
1.608 albertel 13673:
13674: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 13675: and /adm/notfound.html if unsuccessful (or an error message if context
13676: was 'overwrite').
13677:
1.608 albertel 13678:
13679: =item *
13680:
13681: renameuserfile(): renames an existing userfile to a new name
13682:
13683: Args:
13684: docuname: username or courseid of destination for the file
13685: docudom: domain of user/course of destination for the file
13686: old: current file name (including any subdirs under userfiles)
13687: new: desired file name (including any subdirs under userfiles)
13688:
13689: =item *
13690:
13691: mkdiruserfile(): creates a directory is a userfiles dir
13692:
13693: Args:
13694: docuname: username or courseid of destination for the file
13695: docudom: domain of user/course of destination for the file
13696: dir: dir to create (including any subdirs under userfiles)
13697:
13698: =item *
13699:
13700: removeuserfile(): removes a file that exists in userfiles
13701:
13702: Args:
13703: docuname: username or courseid of destination for the file
13704: docudom: domain of user/course of destination for the file
13705: fname: filname to delete (including any subdirs under userfiles)
13706:
13707: =item *
13708:
13709: removeuploadedurl(): convience function for removeuserfile()
13710:
13711: Args:
13712: url: a full /uploaded/... url to delete
13713:
1.747 albertel 13714: =item *
13715:
13716: get_portfile_permissions():
13717: Args:
13718: domain: domain of user or course contain the portfolio files
13719: user: name of user or num of course contain the portfolio files
13720: Returns:
13721: hashref of a dump of the proper file_permissions.db
13722:
13723:
13724: =item *
13725:
13726: get_access_controls():
13727:
13728: Args:
13729: current_permissions: the hash ref returned from get_portfile_permissions()
13730: group: (optional) the group you want the files associated with
13731: file: (optional) the file you want access info on
13732:
13733: Returns:
1.749 raeburn 13734: a hash (keys are file names) of hashes containing
13735: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
13736: values are XML containing access control settings (see below)
1.747 albertel 13737:
13738: Internal notes:
13739:
1.749 raeburn 13740: access controls are stored in file_permissions.db as key=value pairs.
13741: key -> path to file/file_name\0uniqueID:scope_end_start
13742: where scope -> public,guest,course,group,domains or users.
13743: end -> UNIX time for end of access (0 -> no end date)
13744: start -> UNIX time for start of access
13745:
13746: value -> XML description of access control
13747: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
13748: <start></start>
13749: <end></end>
13750:
13751: <password></password> for scope type = guest
13752:
13753: <domain></domain> for scope type = course or group
13754: <number></number>
13755: <roles id="">
13756: <role></role>
13757: <access></access>
13758: <section></section>
13759: <group></group>
13760: </roles>
13761:
13762: <dom></dom> for scope type = domains
13763:
13764: <users> for scope type = users
13765: <user>
13766: <uname></uname>
13767: <udom></udom>
13768: </user>
13769: </users>
13770: </scope>
13771:
13772: Access data is also aggregated for each file in an additional key=value pair:
13773: key -> path to file/file_name\0accesscontrol
13774: value -> reference to hash
13775: hash contains key = value pairs
13776: where key = uniqueID:scope_end_start
13777: value = UNIX time record was last updated
13778:
13779: Used to improve speed of look-ups of access controls for each file.
13780:
13781: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
13782:
1.1198 raeburn 13783: =item *
13784:
1.749 raeburn 13785: modify_access_controls():
13786:
13787: Modifies access controls for a portfolio file
13788: Args
13789: 1. file name
13790: 2. reference to hash of required changes,
13791: 3. domain
13792: 4. username
13793: where domain,username are the domain of the portfolio owner
13794: (either a user or a course)
13795:
13796: Returns:
13797: 1. result of additions or updates ('ok' or 'error', with error message).
13798: 2. result of deletions ('ok' or 'error', with error message).
13799: 3. reference to hash of any new or updated access controls.
13800: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
13801: key = integer (inbound ID)
1.1198 raeburn 13802: value = uniqueID
13803:
13804: =item *
13805:
13806: get_timebased_id():
13807:
13808: Attempts to get a unique timestamp-based suffix for use with items added to a
13809: course via the Course Editor (e.g., folders, composite pages,
13810: group bulletin boards).
13811:
13812: Args: (first three required; six others optional)
13813:
13814: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
13815: docssequence, or name of group
13816:
13817: 2. keyid (alphanumeric): name of temporary locking key in hash,
13818: e.g., num, boardids
13819:
13820: 3. namespace: name of gdbm file used to store suffixes already assigned;
13821: file will be named nohist_namespace.db
13822:
13823: 4. cdom: domain of course; default is current course domain from %env
13824:
13825: 5. cnum: course number; default is current course number from %env
13826:
13827: 6. idtype: set to concat if an additional digit is to be appended to the
13828: unix timestamp to form the suffix, if the plain timestamp is already
13829: in use. Default is to not do this, but simply increment the unix
13830: timestamp by 1 until a unique key is obtained.
13831:
13832: 7. who: holder of locking key; defaults to user:domain for user.
13833:
13834: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
13835: retrying); default is 3.
13836:
13837: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
13838:
13839: Returns:
13840:
13841: 1. suffix obtained (numeric)
13842:
13843: 2. result of deleting locking key (ok if deleted, or lock never obtained)
13844:
13845: 3. error: contains (localized) error message if an error occurred.
13846:
1.747 albertel 13847:
1.608 albertel 13848: =back
13849:
1.243 albertel 13850: =head2 HTTP Helper Routines
13851:
13852: =over 4
13853:
1.191 harris41 13854: =item *
13855:
13856: escape() : unpack non-word characters into CGI-compatible hex codes
13857:
13858: =item *
13859:
13860: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
13861:
1.243 albertel 13862: =back
13863:
13864: =head1 PRIVATE SUBROUTINES
13865:
13866: =head2 Underlying communication routines (Shouldn't call)
13867:
13868: =over 4
13869:
13870: =item *
13871:
13872: subreply() : tries to pass a message to lonc, returns con_lost if incapable
13873:
13874: =item *
13875:
13876: reply() : uses subreply to send a message to remote machine, logs all failures
13877:
13878: =item *
13879:
13880: critical() : passes a critical message to another server; if cannot
13881: get through then place message in connection buffer directory and
13882: returns con_delayed, if incapable of saving message, returns
13883: con_failed
13884:
13885: =item *
13886:
13887: reconlonc() : tries to reconnect lonc client processes.
13888:
13889: =back
13890:
13891: =head2 Resource Access Logging
13892:
13893: =over 4
13894:
13895: =item *
13896:
13897: flushcourselogs() : flush (save) buffer logs and access logs
13898:
13899: =item *
13900:
13901: courselog($what) : save message for course in hash
13902:
13903: =item *
13904:
13905: courseacclog($what) : save message for course using &courselog(). Perform
13906: special processing for specific resource types (problems, exams, quizzes, etc).
13907:
1.191 harris41 13908: =item *
13909:
13910: goodbye() : flush course logs and log shutting down; it is called in srm.conf
13911: as a PerlChildExitHandler
1.243 albertel 13912:
13913: =back
13914:
13915: =head2 Other
13916:
13917: =over 4
13918:
13919: =item *
13920:
13921: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 13922:
13923: =back
13924:
13925: =cut
1.877 foxr 13926:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>