Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1243
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1243 ! raeburn 4: # $Id: lonnet.pm,v 1.1242 2013/10/12 01:15:38 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.1213 raeburn 81: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir $apache
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.1155 raeburn 609: my ($r,$name) = @_;
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.1213 raeburn 640: if (($r->user() eq '') && ($apache >= 2.4)) {
1.1212 raeburn 641: if ($disk_env{'user.domain'} eq $r->dir_config('lonDefDomain')) {
642: $r->user($disk_env{'user.name'});
643: } else {
644: $r->user($disk_env{'user.name'}.':'.$disk_env{'user.domain'});
645: }
646: }
1.916 albertel 647: return $handle;
648: }
649:
1.830 albertel 650: sub timed_flock {
651: my ($file,$lock_type) = @_;
652: my $failed=0;
653: eval {
654: local $SIG{__DIE__}='DEFAULT';
655: local $SIG{ALRM}=sub {
656: $failed=1;
657: die("failed lock");
658: };
659: alarm(13);
660: flock($file,$lock_type);
661: alarm(0);
662: };
663: if ($failed) {
664: return undef;
665: } else {
666: return 1;
667: }
668: }
669:
1.5 www 670: # ---------------------------------------------------------- Append Environment
671:
672: sub appenv {
1.949 raeburn 673: my ($newenv,$roles) = @_;
674: if (ref($newenv) eq 'HASH') {
675: foreach my $key (keys(%{$newenv})) {
676: my $refused = 0;
677: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
678: $refused = 1;
679: if (ref($roles) eq 'ARRAY') {
680: my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
681: if (grep(/^\Q$role\E$/,@{$roles})) {
682: $refused = 0;
683: }
684: }
685: }
686: if ($refused) {
687: &logthis("<font color=\"blue\">WARNING: ".
688: "Attempt to modify environment ".$key." to ".$newenv->{$key}
689: .'</font>');
690: delete($newenv->{$key});
691: } else {
692: $env{$key}=$newenv->{$key};
693: }
694: }
695: my $opened = open(my $env_file,'+<',$env{'user.environment'});
696: if ($opened
697: && &timed_flock($env_file,LOCK_EX)
698: &&
699: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
700: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
701: while (my ($key,$value) = each(%{$newenv})) {
702: $disk_env{$key} = $value;
703: }
704: untie(%disk_env);
1.35 www 705: }
1.191 harris41 706: }
1.56 www 707: return 'ok';
708: }
709: # ----------------------------------------------------- Delete from Environment
710:
711: sub delenv {
1.1104 raeburn 712: my ($delthis,$regexp,$roles) = @_;
713: if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
714: my $refused = 1;
715: if (ref($roles) eq 'ARRAY') {
716: my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
717: if (grep(/^\Q$role\E$/,@{$roles})) {
718: $refused = 0;
719: }
720: }
721: if ($refused) {
722: &logthis("<font color=\"blue\">WARNING: ".
723: "Attempt to delete from environment ".$delthis);
724: return 'error';
725: }
1.56 www 726: }
1.917 albertel 727: my $opened = open(my $env_file,'+<',$env{'user.environment'});
728: if ($opened
1.915 albertel 729: && &timed_flock($env_file,LOCK_EX)
1.830 albertel 730: &&
731: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
732: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 733: foreach my $key (keys(%disk_env)) {
1.987 raeburn 734: if ($regexp) {
735: if ($key=~/^$delthis/) {
736: delete($env{$key});
737: delete($disk_env{$key});
738: }
739: } else {
740: if ($key=~/^\Q$delthis\E/) {
741: delete($env{$key});
742: delete($disk_env{$key});
743: }
744: }
1.448 albertel 745: }
1.783 albertel 746: untie(%disk_env);
1.5 www 747: }
748: return 'ok';
1.369 albertel 749: }
750:
1.790 albertel 751: sub get_env_multiple {
752: my ($name) = @_;
753: my @values;
754: if (defined($env{$name})) {
755: # exists is it an array
756: if (ref($env{$name})) {
757: @values=@{ $env{$name} };
758: } else {
759: $values[0]=$env{$name};
760: }
761: }
762: return(@values);
763: }
764:
1.958 www 765: # ------------------------------------------------------------------- Locking
766:
767: sub set_lock {
768: my ($text)=@_;
769: $locknum++;
770: my $id=$$.'-'.$locknum;
771: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
772: 'session.lock.'.$id => $text});
773: return $id;
774: }
775:
776: sub get_locks {
777: my $num=0;
778: my %texts=();
779: foreach my $lock (split(/\,/,$env{'session.locks'})) {
780: if ($lock=~/\w/) {
781: $num++;
782: $texts{$lock}=$env{'session.lock.'.$lock};
783: }
784: }
785: return ($num,%texts);
786: }
787:
788: sub remove_lock {
789: my ($id)=@_;
790: my $newlocks='';
791: foreach my $lock (split(/\,/,$env{'session.locks'})) {
792: if (($lock=~/\w/) && ($lock ne $id)) {
793: $newlocks.=','.$lock;
794: }
795: }
796: &appenv({'session.locks' => $newlocks});
797: &delenv('session.lock.'.$id);
798: }
799:
800: sub remove_all_locks {
801: my $activelocks=$env{'session.locks'};
802: foreach my $lock (split(/\,/,$env{'session.locks'})) {
803: if ($lock=~/\w/) {
804: &remove_lock($lock);
805: }
806: }
807: }
808:
809:
1.369 albertel 810: # ------------------------------------------ Find out current server userload
811: sub userload {
812: my $numusers=0;
813: {
814: opendir(LONIDS,$perlvar{'lonIDsDir'});
815: my $filename;
816: my $curtime=time;
817: while ($filename=readdir(LONIDS)) {
1.925 albertel 818: next if ($filename eq '.' || $filename eq '..');
819: next if ($filename =~ /publicuser_\d+\.id/);
1.404 albertel 820: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437 albertel 821: if ($curtime-$mtime < 1800) { $numusers++; }
1.369 albertel 822: }
823: closedir(LONIDS);
824: }
825: my $userloadpercent=0;
826: my $maxuserload=$perlvar{'lonUserLoadLim'};
827: if ($maxuserload) {
1.371 albertel 828: $userloadpercent=100*$numusers/$maxuserload;
1.369 albertel 829: }
1.372 albertel 830: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369 albertel 831: return $userloadpercent;
1.283 www 832: }
833:
1.1 albertel 834: # ------------------------------ Find server with least workload from spare.tab
1.11 www 835:
1.1 albertel 836: sub spareserver {
1.1083 raeburn 837: my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784 albertel 838: my $spare_server;
1.370 albertel 839: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784 albertel 840: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
841: : $userloadpercent;
1.1083 raeburn 842: my ($uint_dom,$remotesessions);
843: if (($udom ne '') && (&domain($udom) ne '')) {
844: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
845: $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
846: my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
847: $remotesessions = $udomdefaults{'remotesessions'};
848: }
1.1123 raeburn 849: my $spareshash = &this_host_spares($udom);
850: if (ref($spareshash) eq 'HASH') {
851: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
852: foreach my $try_server (@{ $spareshash->{'primary'} }) {
853: if ($uint_dom) {
854: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
855: $try_server));
856: }
857: ($spare_server, $lowest_load) =
858: &compare_server_load($try_server, $spare_server, $lowest_load);
859: }
1.1083 raeburn 860: }
1.784 albertel 861:
1.1123 raeburn 862: my $found_server = ($spare_server ne '' && $lowest_load < 100);
863:
864: if (!$found_server) {
865: if (ref($spareshash->{'default'}) eq 'ARRAY') {
866: foreach my $try_server (@{ $spareshash->{'default'} }) {
867: if ($uint_dom) {
868: next unless (&spare_can_host($udom,$uint_dom,
869: $remotesessions,$try_server));
870: }
871: ($spare_server, $lowest_load) =
872: &compare_server_load($try_server, $spare_server, $lowest_load);
873: }
874: }
875: }
1.784 albertel 876: }
877:
878: if (!$want_server_name) {
1.968 raeburn 879: my $protocol = 'http';
880: if ($protocol{$spare_server} eq 'https') {
881: $protocol = $protocol{$spare_server};
882: }
1.1001 raeburn 883: if (defined($spare_server)) {
884: my $hostname = &hostname($spare_server);
1.1083 raeburn 885: if (defined($hostname)) {
1.1001 raeburn 886: $spare_server = $protocol.'://'.$hostname;
887: }
888: }
1.784 albertel 889: }
890: return $spare_server;
891: }
892:
893: sub compare_server_load {
894: my ($try_server, $spare_server, $lowest_load) = @_;
895:
896: my $loadans = &reply('load', $try_server);
897: my $userloadans = &reply('userload',$try_server);
898:
899: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114 raeburn 900: return ($spare_server, $lowest_load); #didn't get a number from the server
1.784 albertel 901: }
902:
903: my $load;
904: if ($loadans =~ /\d/) {
905: if ($userloadans =~ /\d/) {
906: #both are numbers, pick the bigger one
907: $load = ($loadans > $userloadans) ? $loadans
908: : $userloadans;
1.411 albertel 909: } else {
1.784 albertel 910: $load = $loadans;
1.411 albertel 911: }
1.784 albertel 912: } else {
913: $load = $userloadans;
914: }
915:
916: if (($load =~ /\d/) && ($load < $lowest_load)) {
917: $spare_server = $try_server;
918: $lowest_load = $load;
1.370 albertel 919: }
1.784 albertel 920: return ($spare_server,$lowest_load);
1.202 matthew 921: }
1.914 albertel 922:
923: # --------------------------- ask offload servers if user already has a session
924: sub find_existing_session {
925: my ($udom,$uname) = @_;
1.1123 raeburn 926: my $spareshash = &this_host_spares($udom);
927: if (ref($spareshash) eq 'HASH') {
928: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
929: foreach my $try_server (@{ $spareshash->{'primary'} }) {
930: return $try_server if (&has_user_session($try_server, $udom, $uname));
931: }
932: }
933: if (ref($spareshash->{'default'}) eq 'ARRAY') {
934: foreach my $try_server (@{ $spareshash->{'default'} }) {
935: return $try_server if (&has_user_session($try_server, $udom, $uname));
936: }
937: }
1.914 albertel 938: }
939: return;
940: }
941:
942: # -------------------------------- ask if server already has a session for user
943: sub has_user_session {
944: my ($lonid,$udom,$uname) = @_;
945: my $result = &reply(join(':','userhassession',
946: map {&escape($_)} ($udom,$uname)),$lonid);
947: return 1 if ($result eq 'ok');
948:
949: return 0;
950: }
951:
1.1076 raeburn 952: # --------- determine least loaded server in a user's domain which allows login
953:
954: sub choose_server {
1.1115 raeburn 955: my ($udom,$checkloginvia) = @_;
1.1076 raeburn 956: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077 raeburn 957: my %servers = &get_servers($udom);
1.1076 raeburn 958: my $lowest_load = 30000;
1.1151 raeburn 959: my ($login_host,$hostname,$portal_path,$isredirect);
1.1076 raeburn 960: foreach my $lonhost (keys(%servers)) {
1.1115 raeburn 961: my $loginvia;
962: if ($checkloginvia) {
963: $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116 raeburn 964: if ($loginvia) {
965: my ($server,$path) = split(/:/,$loginvia);
966: ($login_host, $lowest_load) =
967: &compare_server_load($server, $login_host, $lowest_load);
968: if ($login_host eq $server) {
969: $portal_path = $path;
1.1151 raeburn 970: $isredirect = 1;
1.1116 raeburn 971: }
972: } else {
973: ($login_host, $lowest_load) =
974: &compare_server_load($lonhost, $login_host, $lowest_load);
975: if ($login_host eq $lonhost) {
976: $portal_path = '';
1.1151 raeburn 977: $isredirect = '';
1.1116 raeburn 978: }
979: }
980: } else {
1.1076 raeburn 981: ($login_host, $lowest_load) =
1.1116 raeburn 982: &compare_server_load($lonhost, $login_host, $lowest_load);
1.1076 raeburn 983: }
984: }
985: if ($login_host ne '') {
1.1116 raeburn 986: $hostname = &hostname($login_host);
1.1076 raeburn 987: }
1.1151 raeburn 988: return ($login_host,$hostname,$portal_path,$isredirect);
1.1076 raeburn 989: }
990:
1.202 matthew 991: # --------------------------------------------- Try to change a user's password
992:
993: sub changepass {
1.799 raeburn 994: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 995: $currentpass = &escape($currentpass);
996: $newpass = &escape($newpass);
1.1030 raeburn 997: my $lonhost = $perlvar{'lonHostID'};
998: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202 matthew 999: $server);
1000: if (! $answer) {
1001: &logthis("No reply on password change request to $server ".
1002: "by $uname in domain $udom.");
1003: } elsif ($answer =~ "^ok") {
1004: &logthis("$uname in $udom successfully changed their password ".
1005: "on $server.");
1006: } elsif ($answer =~ "^pwchange_failure") {
1007: &logthis("$uname in $udom was unable to change their password ".
1008: "on $server. The action was blocked by either lcpasswd ".
1009: "or pwchange");
1010: } elsif ($answer =~ "^non_authorized") {
1011: &logthis("$uname in $udom did not get their password correct when ".
1012: "attempting to change it on $server.");
1013: } elsif ($answer =~ "^auth_mode_error") {
1014: &logthis("$uname in $udom attempted to change their password despite ".
1015: "not being locally or internally authenticated on $server.");
1016: } elsif ($answer =~ "^unknown_user") {
1017: &logthis("$uname in $udom attempted to change their password ".
1018: "on $server but were unable to because $server is not ".
1019: "their home server.");
1020: } elsif ($answer =~ "^refused") {
1021: &logthis("$server refused to change $uname in $udom password because ".
1022: "it was sent an unencrypted request to change the password.");
1.1030 raeburn 1023: } elsif ($answer =~ "invalid_client") {
1024: &logthis("$server refused to change $uname in $udom password because ".
1025: "it was a reset by e-mail originating from an invalid server.");
1.202 matthew 1026: }
1027: return $answer;
1.1 albertel 1028: }
1029:
1.169 harris41 1030: # ----------------------- Try to determine user's current authentication scheme
1031:
1032: sub queryauthenticate {
1033: my ($uname,$udom)=@_;
1.456 albertel 1034: my $uhome=&homeserver($uname,$udom);
1035: if (!$uhome) {
1036: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
1037: return 'no_host';
1038: }
1039: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
1040: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
1041: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 1042: }
1.456 albertel 1043: return $answer;
1.169 harris41 1044: }
1045:
1.1 albertel 1046: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 1047:
1.1 albertel 1048: sub authenticate {
1.1073 raeburn 1049: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807 albertel 1050: $upass=&escape($upass);
1051: $uname= &LONCAPA::clean_username($uname);
1.836 www 1052: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 1053: my $newhome;
1.836 www 1054: if ((!$uhome) || ($uhome eq 'no_host')) {
1055: # Maybe the machine was offline and only re-appeared again recently?
1056: &reconlonc();
1057: # One more
1.952 raeburn 1058: $uhome=&homeserver($uname,$udom,1);
1059: if (($uhome eq 'no_host') && $checkdefauth) {
1060: if (defined(&domain($udom,'primary'))) {
1061: $newhome=&domain($udom,'primary');
1062: }
1063: if ($newhome ne '') {
1064: $uhome = $newhome;
1065: }
1066: }
1.836 www 1067: if ((!$uhome) || ($uhome eq 'no_host')) {
1068: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 1069: return 'no_host';
1070: }
1.1 albertel 1071: }
1.1073 raeburn 1072: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471 albertel 1073: if ($answer eq 'authorized') {
1.952 raeburn 1074: if ($newhome) {
1075: &logthis("User $uname at $udom authorized by $uhome, but needs account");
1076: return 'no_account_on_host';
1077: } else {
1078: &logthis("User $uname at $udom authorized by $uhome");
1079: return $uhome;
1080: }
1.471 albertel 1081: }
1082: if ($answer eq 'non_authorized') {
1083: &logthis("User $uname at $udom rejected by $uhome");
1084: return 'no_host';
1.9 www 1085: }
1.471 albertel 1086: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 1087: return 'no_host';
1088: }
1089:
1.1073 raeburn 1090: sub can_host_session {
1.1074 raeburn 1091: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073 raeburn 1092: my $canhost = 1;
1.1074 raeburn 1093: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073 raeburn 1094: if (ref($remotesessions) eq 'HASH') {
1095: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074 raeburn 1096: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073 raeburn 1097: $canhost = 0;
1098: } else {
1099: $canhost = 1;
1100: }
1101: }
1102: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074 raeburn 1103: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073 raeburn 1104: $canhost = 1;
1105: } else {
1106: $canhost = 0;
1107: }
1108: }
1109: if ($canhost) {
1110: if ($remotesessions->{'version'} ne '') {
1111: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1112: if ($reqmajor ne '' && $reqminor ne '') {
1113: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1114: my $major = $1;
1115: my $minor = $2;
1116: if (($major < $reqmajor ) ||
1117: (($major == $reqmajor) && ($minor < $reqminor))) {
1118: $canhost = 0;
1119: }
1120: } else {
1121: $canhost = 0;
1122: }
1123: }
1124: }
1125: }
1126: }
1127: if ($canhost) {
1128: if (ref($hostedsessions) eq 'HASH') {
1.1120 raeburn 1129: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1130: my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073 raeburn 1131: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120 raeburn 1132: if (($uint_dom ne '') &&
1133: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073 raeburn 1134: $canhost = 0;
1135: } else {
1136: $canhost = 1;
1137: }
1138: }
1139: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120 raeburn 1140: if (($uint_dom ne '') &&
1141: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073 raeburn 1142: $canhost = 1;
1143: } else {
1144: $canhost = 0;
1145: }
1146: }
1147: }
1148: }
1149: return $canhost;
1150: }
1151:
1.1083 raeburn 1152: sub spare_can_host {
1153: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1154: my $canhost=1;
1155: my @intdoms;
1156: my $internet_names = &Apache::lonnet::get_internet_names($try_server);
1157: if (ref($internet_names) eq 'ARRAY') {
1158: @intdoms = @{$internet_names};
1159: }
1160: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1161: my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
1162: my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
1163: my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
1164: my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
1165: $canhost = &can_host_session($udom,$try_server,$remoterev,
1166: $remotesessions,
1167: $defdomdefaults{'hostedsessions'});
1168: }
1169: return $canhost;
1170: }
1171:
1.1123 raeburn 1172: sub this_host_spares {
1173: my ($dom) = @_;
1.1126 raeburn 1174: my ($dom_in_use,$lonhost_in_use,$result);
1.1123 raeburn 1175: my @hosts = ¤t_machine_ids();
1176: foreach my $lonhost (@hosts) {
1177: if (&host_domain($lonhost) eq $dom) {
1.1126 raeburn 1178: $dom_in_use = $dom;
1179: $lonhost_in_use = $lonhost;
1.1123 raeburn 1180: last;
1181: }
1182: }
1.1126 raeburn 1183: if ($dom_in_use ne '') {
1184: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1185: }
1186: if (ref($result) ne 'HASH') {
1187: $lonhost_in_use = $perlvar{'lonHostID'};
1188: $dom_in_use = &host_domain($lonhost_in_use);
1189: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1190: if (ref($result) ne 'HASH') {
1191: $result = \%spareid;
1192: }
1193: }
1194: return $result;
1195: }
1196:
1197: sub spares_for_offload {
1198: my ($dom_in_use,$lonhost_in_use) = @_;
1199: my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123 raeburn 1200: if (defined($cached)) {
1201: return $result;
1202: } else {
1.1126 raeburn 1203: my $cachetime = 60*60*24;
1204: my %domconfig =
1205: &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
1206: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1207: if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
1208: if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
1209: return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123 raeburn 1210: }
1211: }
1212: }
1213: }
1.1126 raeburn 1214: return;
1.1123 raeburn 1215: }
1216:
1.1129 raeburn 1217: sub get_lonbalancer_config {
1218: my ($servers) = @_;
1219: my ($currbalancer,$currtargets);
1220: if (ref($servers) eq 'HASH') {
1221: foreach my $server (keys(%{$servers})) {
1222: my %what = (
1223: spareid => 1,
1224: perlvar => 1,
1225: );
1226: my ($result,$returnhash) = &get_remote_globals($server,\%what);
1227: if ($result eq 'ok') {
1228: if (ref($returnhash) eq 'HASH') {
1229: if (ref($returnhash->{'perlvar'}) eq 'HASH') {
1230: if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
1231: $currbalancer = $server;
1232: $currtargets = {};
1233: if (ref($returnhash->{'spareid'}) eq 'HASH') {
1234: if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
1235: $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
1236: }
1237: if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
1238: $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
1239: }
1240: }
1241: last;
1242: }
1243: }
1244: }
1245: }
1246: }
1247: }
1248: return ($currbalancer,$currtargets);
1249: }
1250:
1251: sub check_loadbalancing {
1252: my ($uname,$udom) = @_;
1.1191 raeburn 1253: my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1254: $rule_in_effect,$offloadto,$otherserver);
1.1129 raeburn 1255: my $lonhost = $perlvar{'lonHostID'};
1.1175 raeburn 1256: my @hosts = ¤t_machine_ids();
1.1129 raeburn 1257: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1258: my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
1259: my $intdom = &Apache::lonnet::internet_dom($lonhost);
1260: my $serverhomedom = &host_domain($lonhost);
1261:
1262: my $cachetime = 60*60*24;
1263:
1264: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1265: $dom_in_use = $udom;
1266: $homeintdom = 1;
1267: } else {
1268: $dom_in_use = $serverhomedom;
1269: }
1270: my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
1271: unless (defined($cached)) {
1272: my %domconfig =
1273: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
1274: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1275: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129 raeburn 1276: }
1277: }
1278: if (ref($result) eq 'HASH') {
1.1191 raeburn 1279: ($is_balancer,$currtargets,$currrules) =
1280: &check_balancer_result($result,@hosts);
1.1129 raeburn 1281: if ($is_balancer) {
1282: if (ref($currrules) eq 'HASH') {
1283: if ($homeintdom) {
1284: if ($uname ne '') {
1285: if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
1286: my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
1287: if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
1288: $rule_in_effect = $currrules->{'_LC_author'};
1289: } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
1290: $rule_in_effect = $currrules->{'_LC_adv'}
1291: }
1292: }
1293: if ($rule_in_effect eq '') {
1294: my %userenv = &userenvironment($udom,$uname,'inststatus');
1295: if ($userenv{'inststatus'} ne '') {
1296: my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
1297: my ($othertitle,$usertypes,$types) =
1298: &Apache::loncommon::sorted_inst_types($udom);
1299: if (ref($types) eq 'ARRAY') {
1300: foreach my $type (@{$types}) {
1301: if (grep(/^\Q$type\E$/,@statuses)) {
1302: if (exists($currrules->{$type})) {
1303: $rule_in_effect = $currrules->{$type};
1304: }
1305: }
1306: }
1307: }
1308: } else {
1309: if (exists($currrules->{'default'})) {
1310: $rule_in_effect = $currrules->{'default'};
1311: }
1312: }
1313: }
1314: } else {
1315: if (exists($currrules->{'default'})) {
1316: $rule_in_effect = $currrules->{'default'};
1317: }
1318: }
1319: } else {
1320: if ($currrules->{'_LC_external'} ne '') {
1321: $rule_in_effect = $currrules->{'_LC_external'};
1322: }
1323: }
1324: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1325: $uname,$udom);
1326: }
1327: }
1328: } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1239 raeburn 1329: ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129 raeburn 1330: unless (defined($cached)) {
1331: my %domconfig =
1332: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
1333: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1334: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129 raeburn 1335: }
1336: }
1337: if (ref($result) eq 'HASH') {
1.1191 raeburn 1338: ($is_balancer,$currtargets,$currrules) =
1339: &check_balancer_result($result,@hosts);
1340: if ($is_balancer) {
1.1129 raeburn 1341: if (ref($currrules) eq 'HASH') {
1342: if ($currrules->{'_LC_internetdom'} ne '') {
1343: $rule_in_effect = $currrules->{'_LC_internetdom'};
1344: }
1345: }
1346: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1347: $uname,$udom);
1348: }
1349: } else {
1350: if ($perlvar{'lonBalancer'} eq 'yes') {
1351: $is_balancer = 1;
1352: $offloadto = &this_host_spares($dom_in_use);
1353: }
1354: }
1355: } else {
1356: if ($perlvar{'lonBalancer'} eq 'yes') {
1357: $is_balancer = 1;
1358: $offloadto = &this_host_spares($dom_in_use);
1359: }
1360: }
1.1176 raeburn 1361: if ($is_balancer) {
1362: my $lowest_load = 30000;
1363: if (ref($offloadto) eq 'HASH') {
1364: if (ref($offloadto->{'primary'}) eq 'ARRAY') {
1365: foreach my $try_server (@{$offloadto->{'primary'}}) {
1366: ($otherserver,$lowest_load) =
1367: &compare_server_load($try_server,$otherserver,$lowest_load);
1368: }
1.1129 raeburn 1369: }
1.1176 raeburn 1370: my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129 raeburn 1371:
1.1176 raeburn 1372: if (!$found_server) {
1373: if (ref($offloadto->{'default'}) eq 'ARRAY') {
1374: foreach my $try_server (@{$offloadto->{'default'}}) {
1375: ($otherserver,$lowest_load) =
1376: &compare_server_load($try_server,$otherserver,$lowest_load);
1377: }
1378: }
1379: }
1380: } elsif (ref($offloadto) eq 'ARRAY') {
1381: if (@{$offloadto} == 1) {
1382: $otherserver = $offloadto->[0];
1383: } elsif (@{$offloadto} > 1) {
1384: foreach my $try_server (@{$offloadto}) {
1.1129 raeburn 1385: ($otherserver,$lowest_load) =
1386: &compare_server_load($try_server,$otherserver,$lowest_load);
1387: }
1388: }
1389: }
1.1176 raeburn 1390: if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
1391: $is_balancer = 0;
1392: if ($uname ne '' && $udom ne '') {
1393: if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1394:
1395: &appenv({'user.loadbalexempt' => $lonhost,
1396: 'user.loadbalcheck.time' => time});
1397: }
1.1129 raeburn 1398: }
1399: }
1400: }
1401: return ($is_balancer,$otherserver);
1402: }
1403:
1.1191 raeburn 1404: sub check_balancer_result {
1405: my ($result,@hosts) = @_;
1406: my ($is_balancer,$currtargets,$currrules);
1407: if (ref($result) eq 'HASH') {
1408: if ($result->{'lonhost'} ne '') {
1409: my $currbalancer = $result->{'lonhost'};
1410: if (grep(/^\Q$currbalancer\E$/,@hosts)) {
1411: $is_balancer = 1;
1412: $currtargets = $result->{'targets'};
1413: $currrules = $result->{'rules'};
1414: }
1415: } else {
1416: foreach my $key (keys(%{$result})) {
1417: if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
1418: (ref($result->{$key}) eq 'HASH')) {
1419: $is_balancer = 1;
1420: $currrules = $result->{$key}{'rules'};
1421: $currtargets = $result->{$key}{'targets'};
1422: last;
1423: }
1424: }
1425: }
1426: }
1427: return ($is_balancer,$currtargets,$currrules);
1428: }
1429:
1.1129 raeburn 1430: sub get_loadbalancer_targets {
1431: my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
1432: my $offloadto;
1.1175 raeburn 1433: if ($rule_in_effect eq 'none') {
1434: return [$perlvar{'lonHostID'}];
1435: } elsif ($rule_in_effect eq '') {
1.1129 raeburn 1436: $offloadto = $currtargets;
1437: } else {
1438: if ($rule_in_effect eq 'homeserver') {
1439: my $homeserver = &homeserver($uname,$udom);
1440: if ($homeserver ne 'no_host') {
1441: $offloadto = [$homeserver];
1442: }
1443: } elsif ($rule_in_effect eq 'externalbalancer') {
1444: my %domconfig =
1445: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1446: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1447: if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
1448: if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
1449: $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
1450: }
1451: }
1452: } else {
1.1178 raeburn 1453: my %servers = &internet_dom_servers($udom);
1.1129 raeburn 1454: my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
1455: if (&hostname($remotebalancer) ne '') {
1456: $offloadto = [$remotebalancer];
1457: }
1458: }
1459: } elsif (&hostname($rule_in_effect) ne '') {
1460: $offloadto = [$rule_in_effect];
1461: }
1462: }
1463: return $offloadto;
1464: }
1465:
1.1127 raeburn 1466: sub internet_dom_servers {
1467: my ($dom) = @_;
1468: my (%uniqservers,%servers);
1469: my $primaryserver = &hostname(&domain($dom,'primary'));
1470: my @machinedoms = &machine_domains($primaryserver);
1471: foreach my $mdom (@machinedoms) {
1472: my %currservers = %servers;
1473: my %server = &get_servers($mdom);
1474: %servers = (%currservers,%server);
1475: }
1476: my %by_hostname;
1477: foreach my $id (keys(%servers)) {
1478: push(@{$by_hostname{$servers{$id}}},$id);
1479: }
1480: foreach my $hostname (sort(keys(%by_hostname))) {
1481: if (@{$by_hostname{$hostname}} > 1) {
1482: my $match = 0;
1483: foreach my $id (@{$by_hostname{$hostname}}) {
1484: if (&host_domain($id) eq $dom) {
1485: $uniqservers{$id} = $hostname;
1486: $match = 1;
1487: }
1488: }
1489: unless ($match) {
1490: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1491: }
1492: } else {
1493: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1494: }
1495: }
1496: return %uniqservers;
1497: }
1498:
1.1 albertel 1499: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 1500:
1.599 albertel 1501: my %homecache;
1.1 albertel 1502: sub homeserver {
1.230 stredwic 1503: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 1504: my $index="$uname:$udom";
1.426 albertel 1505:
1.599 albertel 1506: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 1507:
1508: my %servers = &get_servers($udom,'library');
1509: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 1510: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 1511: exists($badServerCache{$tryserver}));
1.841 albertel 1512:
1513: my $answer=reply("home:$udom:$uname",$tryserver);
1514: if ($answer eq 'found') {
1515: delete($badServerCache{$tryserver});
1516: return $homecache{$index}=$tryserver;
1517: } elsif ($answer eq 'no_host') {
1518: $badServerCache{$tryserver}=1;
1519: }
1.1 albertel 1520: }
1521: return 'no_host';
1.70 www 1522: }
1523:
1524: # ------------------------------------- Find the usernames behind a list of IDs
1525:
1526: sub idget {
1527: my ($udom,@ids)=@_;
1528: my %returnhash=();
1529:
1.841 albertel 1530: my %servers = &get_servers($udom,'library');
1531: foreach my $tryserver (keys(%servers)) {
1532: my $idlist=join('&',@ids);
1533: $idlist=~tr/A-Z/a-z/;
1534: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
1535: my @answer=();
1536: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1537: @answer=split(/\&/,$reply);
1538: } ;
1539: my $i;
1540: for ($i=0;$i<=$#ids;$i++) {
1541: if ($answer[$i]) {
1542: $returnhash{$ids[$i]}=$answer[$i];
1543: }
1544: }
1545: }
1.70 www 1546: return %returnhash;
1547: }
1548:
1549: # ------------------------------------- Find the IDs behind a list of usernames
1550:
1551: sub idrget {
1552: my ($udom,@unames)=@_;
1553: my %returnhash=();
1.800 albertel 1554: foreach my $uname (@unames) {
1555: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 1556: }
1.70 www 1557: return %returnhash;
1558: }
1559:
1560: # ------------------------------- Store away a list of names and associated IDs
1561:
1562: sub idput {
1563: my ($udom,%ids)=@_;
1564: my %servers=();
1.800 albertel 1565: foreach my $uname (keys(%ids)) {
1566: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1567: my $uhom=&homeserver($uname,$udom);
1.70 www 1568: if ($uhom ne 'no_host') {
1.800 albertel 1569: my $id=&escape($ids{$uname});
1.70 www 1570: $id=~tr/A-Z/a-z/;
1.800 albertel 1571: my $esc_unam=&escape($uname);
1.70 www 1572: if ($servers{$uhom}) {
1.800 albertel 1573: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70 www 1574: } else {
1.800 albertel 1575: $servers{$uhom}=$id.'='.$esc_unam;
1.70 www 1576: }
1577: }
1.191 harris41 1578: }
1.800 albertel 1579: foreach my $server (keys(%servers)) {
1580: &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191 harris41 1581: }
1.344 www 1582: }
1583:
1.1231 raeburn 1584: # ---------------------------------------- Delete unwanted IDs from ids.db file
1585:
1586: sub iddel {
1587: my ($udom,$idshashref,$uhome)=@_;
1588: my %result=();
1589: unless (ref($idshashref) eq 'HASH') {
1590: return %result;
1591: }
1592: my %servers=();
1593: while (my ($id,$uname) = each(%{$idshashref})) {
1594: my $uhom;
1595: if ($uhome) {
1596: $uhom = $uhome;
1597: } else {
1598: $uhom=&homeserver($uname,$udom);
1599: }
1600: if ($uhom ne 'no_host') {
1601: if ($servers{$uhom}) {
1602: $servers{$uhom}.='&'.&escape($id);
1603: } else {
1604: $servers{$uhom}=&escape($id);
1605: }
1606: }
1607: }
1608: foreach my $server (keys(%servers)) {
1609: $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
1610: }
1611: return %result;
1612: }
1613:
1.1023 raeburn 1614: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 1615: sub dump_dom {
1.1165 droeschl 1616: my ($namespace, $udom, $regexp) = @_;
1617:
1618: $udom ||= $env{'user.domain'};
1619:
1620: return () unless $udom;
1621:
1622: return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012 raeburn 1623: }
1624:
1.1023 raeburn 1625: # ------------------------------------------ get items from domain db files
1.806 raeburn 1626:
1627: sub get_dom {
1.860 raeburn 1628: my ($namespace,$storearr,$udom,$uhome)=@_;
1.806 raeburn 1629: my $items='';
1630: foreach my $item (@$storearr) {
1631: $items.=&escape($item).'&';
1632: }
1633: $items=~s/\&$//;
1.860 raeburn 1634: if (!$udom) {
1635: $udom=$env{'user.domain'};
1636: if (defined(&domain($udom,'primary'))) {
1637: $uhome=&domain($udom,'primary');
1638: } else {
1.874 albertel 1639: undef($uhome);
1.860 raeburn 1640: }
1641: } else {
1642: if (!$uhome) {
1643: if (defined(&domain($udom,'primary'))) {
1644: $uhome=&domain($udom,'primary');
1645: }
1646: }
1647: }
1648: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1649: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866 raeburn 1650: my %returnhash;
1.875 albertel 1651: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 1652: return %returnhash;
1653: }
1.806 raeburn 1654: my @pairs=split(/\&/,$rep);
1655: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1656: return @pairs;
1657: }
1658: my $i=0;
1659: foreach my $item (@$storearr) {
1660: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1661: $i++;
1662: }
1663: return %returnhash;
1664: } else {
1.880 banghart 1665: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 1666: }
1667: }
1668:
1669: # -------------------------------------------- put items in domain db files
1670:
1671: sub put_dom {
1.860 raeburn 1672: my ($namespace,$storehash,$udom,$uhome)=@_;
1673: if (!$udom) {
1674: $udom=$env{'user.domain'};
1675: if (defined(&domain($udom,'primary'))) {
1676: $uhome=&domain($udom,'primary');
1677: } else {
1.874 albertel 1678: undef($uhome);
1.860 raeburn 1679: }
1680: } else {
1681: if (!$uhome) {
1682: if (defined(&domain($udom,'primary'))) {
1683: $uhome=&domain($udom,'primary');
1684: }
1685: }
1686: }
1687: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1688: my $items='';
1689: foreach my $item (keys(%$storehash)) {
1690: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1691: }
1692: $items=~s/\&$//;
1693: return &reply("putdom:$udom:$namespace:$items",$uhome);
1694: } else {
1.860 raeburn 1695: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 1696: }
1697: }
1698:
1.1023 raeburn 1699: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 1700: sub newput_dom {
1.1023 raeburn 1701: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 1702: my $result;
1703: if (!$udom) {
1704: $udom=$env{'user.domain'};
1705: }
1.1023 raeburn 1706: if ($udom) {
1707: my $uname = &get_domainconfiguser($udom);
1708: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 1709: }
1710: return $result;
1711: }
1712:
1.1023 raeburn 1713: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 1714: sub del_dom {
1.1023 raeburn 1715: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 1716: if (ref($storearr) eq 'ARRAY') {
1717: if (!$udom) {
1718: $udom=$env{'user.domain'};
1719: }
1.1023 raeburn 1720: if ($udom) {
1721: my $uname = &get_domainconfiguser($udom);
1722: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 1723: }
1724: }
1725: }
1726:
1.1023 raeburn 1727: # ----------------------------------construct domainconfig user for a domain
1728: sub get_domainconfiguser {
1729: my ($udom) = @_;
1730: return $udom.'-domainconfig';
1731: }
1732:
1.837 raeburn 1733: sub retrieve_inst_usertypes {
1734: my ($udom) = @_;
1735: my (%returnhash,@order);
1.989 raeburn 1736: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1737: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1738: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1739: %returnhash = %{$domdefs{'inststatustypes'}};
1740: @order = @{$domdefs{'inststatusorder'}};
1741: } else {
1742: if (defined(&domain($udom,'primary'))) {
1743: my $uhome=&domain($udom,'primary');
1744: my $rep=&reply("inst_usertypes:$udom",$uhome);
1745: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1746: &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
1747: return (\%returnhash,\@order);
1748: }
1749: my ($hashitems,$orderitems) = split(/:/,$rep);
1750: my @pairs=split(/\&/,$hashitems);
1751: foreach my $item (@pairs) {
1752: my ($key,$value)=split(/=/,$item,2);
1753: $key = &unescape($key);
1754: next if ($key =~ /^error: 2 /);
1755: $returnhash{$key}=&thaw_unescape($value);
1756: }
1757: my @esc_order = split(/\&/,$orderitems);
1758: foreach my $item (@esc_order) {
1759: push(@order,&unescape($item));
1760: }
1761: } else {
1762: &logthis("get_dom failed - no primary domain server for $udom");
1.837 raeburn 1763: }
1764: }
1765: return (\%returnhash,\@order);
1766: }
1767:
1.868 raeburn 1768: sub is_domainimage {
1769: my ($url) = @_;
1770: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
1771: if (&domain($1) ne '') {
1772: return '1';
1773: }
1774: }
1775: return;
1776: }
1777:
1.899 raeburn 1778: sub inst_directory_query {
1779: my ($srch) = @_;
1780: my $udom = $srch->{'srchdomain'};
1781: my %results;
1782: my $homeserver = &domain($udom,'primary');
1.909 raeburn 1783: my $outcome;
1.899 raeburn 1784: if ($homeserver ne '') {
1.904 albertel 1785: my $queryid=&reply("querysend:instdirsearch:".
1786: &escape($srch->{'srchby'}).':'.
1787: &escape($srch->{'srchterm'}).':'.
1788: &escape($srch->{'srchtype'}),$homeserver);
1789: my $host=&hostname($homeserver);
1790: if ($queryid !~/^\Q$host\E\_/) {
1791: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1792: return;
1793: }
1794: my $response = &get_query_reply($queryid);
1795: my $maxtries = 5;
1796: my $tries = 1;
1797: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1798: $response = &get_query_reply($queryid);
1799: $tries ++;
1800: }
1801:
1802: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 1803: if ($response eq 'unavailable') {
1804: $outcome = $response;
1805: } else {
1806: $outcome = 'ok';
1807: my @matches = split(/\n/,$response);
1808: foreach my $match (@matches) {
1809: my ($key,$value) = split(/=/,$match);
1810: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1811: }
1.899 raeburn 1812: }
1813: }
1814: }
1.909 raeburn 1815: return ($outcome,%results);
1.899 raeburn 1816: }
1817:
1818: sub usersearch {
1819: my ($srch) = @_;
1820: my $dom = $srch->{'srchdomain'};
1821: my %results;
1822: my %libserv = &all_library();
1823: my $query = 'usersearch';
1824: foreach my $tryserver (keys(%libserv)) {
1825: if (&host_domain($tryserver) eq $dom) {
1826: my $host=&hostname($tryserver);
1827: my $queryid=
1.911 raeburn 1828: &reply("querysend:".&escape($query).':'.
1829: &escape($srch->{'srchby'}).':'.
1.899 raeburn 1830: &escape($srch->{'srchtype'}).':'.
1831: &escape($srch->{'srchterm'}),$tryserver);
1832: if ($queryid !~/^\Q$host\E\_/) {
1833: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 1834: next;
1.899 raeburn 1835: }
1836: my $reply = &get_query_reply($queryid);
1837: my $maxtries = 1;
1838: my $tries = 1;
1839: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1840: $reply = &get_query_reply($queryid);
1841: $tries ++;
1842: }
1843: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1844: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1845: } else {
1.911 raeburn 1846: my @matches;
1847: if ($reply =~ /\n/) {
1848: @matches = split(/\n/,$reply);
1849: } else {
1850: @matches = split(/\&/,$reply);
1851: }
1.899 raeburn 1852: foreach my $match (@matches) {
1853: my ($uname,$udom,%userhash);
1.911 raeburn 1854: foreach my $entry (split(/:/,$match)) {
1855: my ($key,$value) =
1856: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 1857: $userhash{$key} = $value;
1858: if ($key eq 'username') {
1859: $uname = $value;
1860: } elsif ($key eq 'domain') {
1861: $udom = $value;
1.911 raeburn 1862: }
1.899 raeburn 1863: }
1864: $results{$uname.':'.$udom} = \%userhash;
1865: }
1866: }
1867: }
1868: }
1869: return %results;
1870: }
1871:
1.912 raeburn 1872: sub get_instuser {
1873: my ($udom,$uname,$id) = @_;
1874: my $homeserver = &domain($udom,'primary');
1875: my ($outcome,%results);
1876: if ($homeserver ne '') {
1877: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1878: &escape($id).':'.&escape($udom),$homeserver);
1879: my $host=&hostname($homeserver);
1880: if ($queryid !~/^\Q$host\E\_/) {
1881: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1882: return;
1883: }
1884: my $response = &get_query_reply($queryid);
1885: my $maxtries = 5;
1886: my $tries = 1;
1887: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1888: $response = &get_query_reply($queryid);
1889: $tries ++;
1890: }
1891: if (!&error($response) && $response ne 'refused') {
1892: if ($response eq 'unavailable') {
1893: $outcome = $response;
1894: } else {
1895: $outcome = 'ok';
1896: my @matches = split(/\n/,$response);
1897: foreach my $match (@matches) {
1898: my ($key,$value) = split(/=/,$match);
1899: $results{&unescape($key)} = &thaw_unescape($value);
1900: }
1901: }
1902: }
1903: }
1904: my %userinfo;
1905: if (ref($results{$uname}) eq 'HASH') {
1906: %userinfo = %{$results{$uname}};
1907: }
1908: return ($outcome,%userinfo);
1909: }
1910:
1911: sub inst_rulecheck {
1.923 raeburn 1912: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 1913: my %returnhash;
1914: if ($udom ne '') {
1915: if (ref($rules) eq 'ARRAY') {
1916: @{$rules} = map {&escape($_);} (@{$rules});
1917: my $rulestr = join(':',@{$rules});
1918: my $homeserver=&domain($udom,'primary');
1919: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1920: my $response;
1921: if ($item eq 'username') {
1922: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
1923: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 1924: $homeserver));
1.923 raeburn 1925: } elsif ($item eq 'id') {
1926: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
1927: ':'.&escape($id).':'.$rulestr,
1928: $homeserver));
1.945 raeburn 1929: } elsif ($item eq 'selfcreate') {
1930: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 1931: &escape($udom).':'.&escape($uname).
1932: ':'.$rulestr,$homeserver));
1.923 raeburn 1933: }
1.912 raeburn 1934: if ($response ne 'refused') {
1935: my @pairs=split(/\&/,$response);
1936: foreach my $item (@pairs) {
1937: my ($key,$value)=split(/=/,$item,2);
1938: $key = &unescape($key);
1939: next if ($key =~ /^error: 2 /);
1940: $returnhash{$key}=&thaw_unescape($value);
1941: }
1942: }
1943: }
1944: }
1945: }
1946: return %returnhash;
1947: }
1948:
1949: sub inst_userrules {
1.923 raeburn 1950: my ($udom,$check) = @_;
1.912 raeburn 1951: my (%ruleshash,@ruleorder);
1952: if ($udom ne '') {
1953: my $homeserver=&domain($udom,'primary');
1954: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1955: my $response;
1956: if ($check eq 'id') {
1957: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 1958: $homeserver);
1.943 raeburn 1959: } elsif ($check eq 'email') {
1960: $response=&reply('instemailrules:'.&escape($udom),
1961: $homeserver);
1.923 raeburn 1962: } else {
1963: $response=&reply('instuserrules:'.&escape($udom),
1964: $homeserver);
1965: }
1.912 raeburn 1966: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 1967: ($response ne 'unknown_cmd') &&
1.912 raeburn 1968: ($response ne 'no_such_host')) {
1969: my ($hashitems,$orderitems) = split(/:/,$response);
1970: my @pairs=split(/\&/,$hashitems);
1971: foreach my $item (@pairs) {
1972: my ($key,$value)=split(/=/,$item,2);
1973: $key = &unescape($key);
1974: next if ($key =~ /^error: 2 /);
1975: $ruleshash{$key}=&thaw_unescape($value);
1976: }
1977: my @esc_order = split(/\&/,$orderitems);
1978: foreach my $item (@esc_order) {
1979: push(@ruleorder,&unescape($item));
1980: }
1981: }
1982: }
1983: }
1984: return (\%ruleshash,\@ruleorder);
1985: }
1986:
1.976 raeburn 1987: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 1988:
1989: sub get_domain_defaults {
1.1240 raeburn 1990: my ($domain,$ignore_cache) = @_;
1.1242 raeburn 1991: return if (($domain eq '') || ($domain eq 'public'));
1.943 raeburn 1992: my $cachetime = 60*60*24;
1.1240 raeburn 1993: unless ($ignore_cache) {
1994: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
1995: if (defined($cached)) {
1996: if (ref($result) eq 'HASH') {
1997: return %{$result};
1998: }
1.943 raeburn 1999: }
2000: }
2001: my %domdefaults;
2002: my %domconfig =
1.989 raeburn 2003: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 2004: 'requestcourses','inststatus',
1.1183 raeburn 2005: 'coursedefaults','usersessions',
2006: 'requestauthor'],$domain);
1.943 raeburn 2007: if (ref($domconfig{'defaults'}) eq 'HASH') {
2008: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
2009: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
2010: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 2011: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 2012: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147 raeburn 2013: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943 raeburn 2014: } else {
2015: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
2016: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
2017: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
2018: }
1.976 raeburn 2019: if (ref($domconfig{'quotas'}) eq 'HASH') {
2020: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
2021: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
2022: } else {
2023: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1229 raeburn 2024: }
1.1177 raeburn 2025: my @usertools = ('aboutme','blog','webdav','portfolio');
1.976 raeburn 2026: foreach my $item (@usertools) {
2027: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
2028: $domdefaults{$item} = $domconfig{'quotas'}{$item};
2029: }
2030: }
1.1229 raeburn 2031: if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
2032: $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
2033: }
1.976 raeburn 2034: }
1.985 raeburn 2035: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006 raeburn 2036: foreach my $item ('official','unofficial','community') {
1.985 raeburn 2037: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
2038: }
2039: }
1.1183 raeburn 2040: if (ref($domconfig{'requestauthor'}) eq 'HASH') {
2041: $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
2042: }
1.989 raeburn 2043: if (ref($domconfig{'inststatus'}) eq 'HASH') {
2044: foreach my $item ('inststatustypes','inststatusorder') {
2045: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
2046: }
2047: }
1.1047 raeburn 2048: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1230 raeburn 2049: $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
1.1216 raeburn 2050: if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
2051: $domdefaults{'officialcredits'} = $domconfig{'coursedefaults'}{'coursecredits'}{'official'};
2052: $domdefaults{'unofficialcredits'} = $domconfig{'coursedefaults'}{'coursecredits'}{'unofficial'};
2053: }
1.1230 raeburn 2054: if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
2055: $domdefaults{'officialquota'} = $domconfig{'coursedefaults'}{'uploadquota'}{'official'};
2056: $domdefaults{'unofficialquota'} = $domconfig{'coursedefaults'}{'uploadquota'}{'unofficial'};
2057: $domdefaults{'communityquota'} = $domconfig{'coursedefaults'}{'uploadquota'}{'community'};
2058: }
1.1047 raeburn 2059: }
1.1073 raeburn 2060: if (ref($domconfig{'usersessions'}) eq 'HASH') {
2061: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
2062: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
2063: }
2064: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
2065: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
2066: }
2067: }
1.1219 raeburn 2068: &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943 raeburn 2069: return %domdefaults;
2070: }
2071:
1.344 www 2072: # --------------------------------------------------- Assign a key to a student
2073:
2074: sub assign_access_key {
1.364 www 2075: #
2076: # a valid key looks like uname:udom#comments
2077: # comments are being appended
2078: #
1.498 www 2079: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
2080: $kdom=
1.620 albertel 2081: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 2082: $knum=
1.620 albertel 2083: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 2084: $cdom=
1.620 albertel 2085: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2086: $cnum=
1.620 albertel 2087: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2088: $udom=$env{'user.name'} unless (defined($udom));
2089: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 2090: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 2091: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 2092: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 2093: # assigned to this person
2094: # - this should not happen,
1.345 www 2095: # unless something went wrong
2096: # the first time around
2097: # ready to assign
1.364 www 2098: $logentry=$1.'; '.$logentry;
1.496 www 2099: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 2100: $kdom,$knum) eq 'ok') {
1.345 www 2101: # key now belongs to user
1.346 www 2102: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 2103: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 2104: &appenv({'environment.'.$envkey => $ckey});
1.345 www 2105: return 'ok';
2106: } else {
2107: return
2108: 'error: Count not permanently assign key, will need to be re-entered later.';
2109: }
2110: } else {
2111: return 'error: Could not assign key, try again later.';
2112: }
1.364 www 2113: } elsif (!$existing{$ckey}) {
1.345 www 2114: # the key does not exist
2115: return 'error: The key does not exist';
2116: } else {
2117: # the key is somebody else's
2118: return 'error: The key is already in use';
2119: }
1.344 www 2120: }
2121:
1.364 www 2122: # ------------------------------------------ put an additional comment on a key
2123:
2124: sub comment_access_key {
2125: #
2126: # a valid key looks like uname:udom#comments
2127: # comments are being appended
2128: #
2129: my ($ckey,$cdom,$cnum,$logentry)=@_;
2130: $cdom=
1.620 albertel 2131: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 2132: $cnum=
1.620 albertel 2133: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 2134: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2135: if ($existing{$ckey}) {
2136: $existing{$ckey}.='; '.$logentry;
2137: # ready to assign
1.367 www 2138: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 2139: $cdom,$cnum) eq 'ok') {
2140: return 'ok';
2141: } else {
2142: return 'error: Count not store comment.';
2143: }
2144: } else {
2145: # the key does not exist
2146: return 'error: The key does not exist';
2147: }
2148: }
2149:
1.344 www 2150: # ------------------------------------------------------ Generate a set of keys
2151:
2152: sub generate_access_keys {
1.364 www 2153: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 2154: $cdom=
1.620 albertel 2155: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2156: $cnum=
1.620 albertel 2157: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 2158: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 2159: unless (($cdom) && ($cnum)) { return 0; }
2160: if ($number>10000) { return 0; }
2161: sleep(2); # make sure don't get same seed twice
2162: srand(time()^($$+($$<<15))); # from "Programming Perl"
2163: my $total=0;
2164: for (my $i=1;$i<=$number;$i++) {
2165: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
2166: sprintf("%lx",int(100000*rand)).'-'.
2167: sprintf("%lx",int(100000*rand));
2168: $newkey=~s/1/g/g; # folks mix up 1 and l
2169: $newkey=~s/0/h/g; # and also 0 and O
2170: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
2171: if ($existing{$newkey}) {
2172: $i--;
2173: } else {
1.364 www 2174: if (&put('accesskeys',
2175: { $newkey => '# generated '.localtime().
1.620 albertel 2176: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 2177: '; '.$logentry },
2178: $cdom,$cnum) eq 'ok') {
1.344 www 2179: $total++;
2180: }
2181: }
2182: }
1.620 albertel 2183: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 2184: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
2185: return $total;
2186: }
2187:
2188: # ------------------------------------------------------- Validate an accesskey
2189:
2190: sub validate_access_key {
2191: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
2192: $cdom=
1.620 albertel 2193: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2194: $cnum=
1.620 albertel 2195: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2196: $udom=$env{'user.domain'} unless (defined($udom));
2197: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 2198: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 2199: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 2200: }
2201:
2202: # ------------------------------------- Find the section of student in a course
1.652 albertel 2203: sub devalidate_getsection_cache {
2204: my ($udom,$unam,$courseid)=@_;
2205: my $hashid="$udom:$unam:$courseid";
2206: &devalidate_cache_new('getsection',$hashid);
2207: }
1.298 matthew 2208:
1.815 albertel 2209: sub courseid_to_courseurl {
2210: my ($courseid) = @_;
2211: #already url style courseid
2212: return $courseid if ($courseid =~ m{^/});
2213:
2214: if (exists($env{'course.'.$courseid.'.num'})) {
2215: my $cnum = $env{'course.'.$courseid.'.num'};
2216: my $cdom = $env{'course.'.$courseid.'.domain'};
2217: return "/$cdom/$cnum";
2218: }
2219:
2220: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
2221: if (exists($courseinfo{'num'})) {
2222: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
2223: }
2224:
2225: return undef;
2226: }
2227:
1.298 matthew 2228: sub getsection {
2229: my ($udom,$unam,$courseid)=@_;
1.599 albertel 2230: my $cachetime=1800;
1.551 albertel 2231:
2232: my $hashid="$udom:$unam:$courseid";
1.599 albertel 2233: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 2234: if (defined($cached)) { return $result; }
2235:
1.298 matthew 2236: my %Pending;
2237: my %Expired;
2238: #
2239: # Each role can either have not started yet (pending), be active,
2240: # or have expired.
2241: #
2242: # If there is an active role, we are done.
2243: #
2244: # If there is more than one role which has not started yet,
2245: # choose the one which will start sooner
2246: # If there is one role which has not started yet, return it.
2247: #
2248: # If there is more than one expired role, choose the one which ended last.
2249: # If there is a role which has expired, return it.
2250: #
1.815 albertel 2251: $courseid = &courseid_to_courseurl($courseid);
1.1166 raeburn 2252: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817 raeburn 2253: foreach my $key (keys(%roleshash)) {
1.479 albertel 2254: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 2255: my $section=$1;
2256: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 2257: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 2258: my $now=time;
1.548 albertel 2259: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 2260: $Expired{$end}=$section;
2261: next;
2262: }
1.548 albertel 2263: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 2264: $Pending{$start}=$section;
2265: next;
2266: }
1.599 albertel 2267: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 2268: }
2269: #
2270: # Presumedly there will be few matching roles from the above
2271: # loop and the sorting time will be negligible.
2272: if (scalar(keys(%Pending))) {
2273: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 2274: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 2275: }
2276: if (scalar(keys(%Expired))) {
2277: my @sorted = sort {$a <=> $b} keys(%Expired);
2278: my $time = pop(@sorted);
1.599 albertel 2279: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 2280: }
1.599 albertel 2281: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 2282: }
1.70 www 2283:
1.599 albertel 2284: sub save_cache {
2285: &purge_remembered();
1.722 albertel 2286: #&Apache::loncommon::validate_page();
1.620 albertel 2287: undef(%env);
1.780 albertel 2288: undef($env_loaded);
1.599 albertel 2289: }
1.452 albertel 2290:
1.599 albertel 2291: my $to_remember=-1;
2292: my %remembered;
2293: my %accessed;
2294: my $kicks=0;
2295: my $hits=0;
1.849 albertel 2296: sub make_key {
2297: my ($name,$id) = @_;
1.872 albertel 2298: if (length($id) > 65
2299: && length(&escape($id)) > 200) {
2300: $id=length($id).':'.&Digest::MD5::md5_hex($id);
2301: }
1.849 albertel 2302: return &escape($name.':'.$id);
2303: }
2304:
1.599 albertel 2305: sub devalidate_cache_new {
2306: my ($name,$id,$debug) = @_;
2307: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849 albertel 2308: $id=&make_key($name,$id);
1.599 albertel 2309: $memcache->delete($id);
2310: delete($remembered{$id});
2311: delete($accessed{$id});
2312: }
2313:
2314: sub is_cached_new {
2315: my ($name,$id,$debug) = @_;
1.849 albertel 2316: $id=&make_key($name,$id);
1.599 albertel 2317: if (exists($remembered{$id})) {
1.1133 foxr 2318: if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
1.599 albertel 2319: $accessed{$id}=[&gettimeofday()];
2320: $hits++;
2321: return ($remembered{$id},1);
2322: }
2323: my $value = $memcache->get($id);
2324: if (!(defined($value))) {
2325: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 2326: return (undef,undef);
1.416 albertel 2327: }
1.599 albertel 2328: if ($value eq '__undef__') {
2329: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
2330: $value=undef;
2331: }
2332: &make_room($id,$value,$debug);
2333: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
2334: return ($value,1);
2335: }
2336:
2337: sub do_cache_new {
2338: my ($name,$id,$value,$time,$debug) = @_;
1.849 albertel 2339: $id=&make_key($name,$id);
1.599 albertel 2340: my $setvalue=$value;
2341: if (!defined($setvalue)) {
2342: $setvalue='__undef__';
2343: }
1.623 albertel 2344: if (!defined($time) ) {
2345: $time=600;
2346: }
1.599 albertel 2347: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 2348: my $result = $memcache->set($id,$setvalue,$time);
2349: if (! $result) {
1.872 albertel 2350: &logthis("caching of id -> $id failed");
1.910 albertel 2351: $memcache->disconnect_all();
1.872 albertel 2352: }
1.600 albertel 2353: # need to make a copy of $value
1.919 albertel 2354: &make_room($id,$value,$debug);
1.599 albertel 2355: return $value;
2356: }
2357:
2358: sub make_room {
2359: my ($id,$value,$debug)=@_;
1.919 albertel 2360:
2361: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
2362: : $value;
1.599 albertel 2363: if ($to_remember<0) { return; }
2364: $accessed{$id}=[&gettimeofday()];
2365: if (scalar(keys(%remembered)) <= $to_remember) { return; }
2366: my $to_kick;
2367: my $max_time=0;
2368: foreach my $other (keys(%accessed)) {
2369: if (&tv_interval($accessed{$other}) > $max_time) {
2370: $to_kick=$other;
2371: $max_time=&tv_interval($accessed{$other});
2372: }
2373: }
2374: delete($remembered{$to_kick});
2375: delete($accessed{$to_kick});
2376: $kicks++;
2377: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 2378: return;
2379: }
2380:
1.599 albertel 2381: sub purge_remembered {
1.604 albertel 2382: #&logthis("Tossing ".scalar(keys(%remembered)));
2383: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 2384: undef(%remembered);
2385: undef(%accessed);
1.428 albertel 2386: }
1.70 www 2387: # ------------------------------------- Read an entry from a user's environment
2388:
2389: sub userenvironment {
2390: my ($udom,$unam,@what)=@_;
1.976 raeburn 2391: my $items;
2392: foreach my $item (@what) {
2393: $items.=&escape($item).'&';
2394: }
2395: $items=~s/\&$//;
1.70 www 2396: my %returnhash=();
1.1009 raeburn 2397: my $uhome = &homeserver($unam,$udom);
2398: unless ($uhome eq 'no_host') {
2399: my @answer=split(/\&/,
2400: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 2401: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
2402: return %returnhash;
2403: }
1.1009 raeburn 2404: my $i;
2405: for ($i=0;$i<=$#what;$i++) {
2406: $returnhash{$what[$i]}=&unescape($answer[$i]);
2407: }
1.70 www 2408: }
2409: return %returnhash;
1.1 albertel 2410: }
2411:
1.617 albertel 2412: # ---------------------------------------------------------- Get a studentphoto
2413: sub studentphoto {
2414: my ($udom,$unam,$ext) = @_;
2415: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 2416: if (defined($env{'request.course.id'})) {
1.708 raeburn 2417: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 2418: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
2419: return(&retrievestudentphoto($udom,$unam,$ext));
2420: } else {
2421: my ($result,$perm_reqd)=
1.707 albertel 2422: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2423: if ($result eq 'ok') {
2424: if (!($perm_reqd eq 'yes')) {
2425: return(&retrievestudentphoto($udom,$unam,$ext));
2426: }
2427: }
2428: }
2429: }
2430: } else {
2431: my ($result,$perm_reqd) =
1.707 albertel 2432: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2433: if ($result eq 'ok') {
2434: if (!($perm_reqd eq 'yes')) {
2435: return(&retrievestudentphoto($udom,$unam,$ext));
2436: }
2437: }
2438: }
2439: return '/adm/lonKaputt/lonlogo_broken.gif';
2440: }
2441:
2442: sub retrievestudentphoto {
2443: my ($udom,$unam,$ext,$type) = @_;
2444: my $home=&Apache::lonnet::homeserver($unam,$udom);
2445: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
2446: if ($ret eq 'ok') {
2447: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
2448: if ($type eq 'thumbnail') {
2449: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
2450: }
2451: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
2452: return $tokenurl;
2453: } else {
2454: if ($type eq 'thumbnail') {
2455: return '/adm/lonKaputt/genericstudent_tn.gif';
2456: } else {
2457: return '/adm/lonKaputt/lonlogo_broken.gif';
2458: }
1.617 albertel 2459: }
2460: }
2461:
1.263 www 2462: # -------------------------------------------------------------------- New chat
2463:
2464: sub chatsend {
1.724 raeburn 2465: my ($newentry,$anon,$group)=@_;
1.620 albertel 2466: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
2467: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2468: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 2469: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 2470: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 2471: &escape($newentry)).':'.$group,$chome);
1.292 www 2472: }
2473:
2474: # ------------------------------------------ Find current version of a resource
2475:
2476: sub getversion {
2477: my $fname=&clutter(shift);
1.1189 raeburn 2478: unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292 www 2479: return ¤tversion(&filelocation('',$fname));
2480: }
2481:
2482: sub currentversion {
2483: my $fname=shift;
2484: my $author=$fname;
2485: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2486: my ($udom,$uname)=split(/\//,$author);
1.1112 www 2487: my $home=&homeserver($uname,$udom);
1.292 www 2488: if ($home eq 'no_host') {
2489: return -1;
2490: }
1.1112 www 2491: my $answer=&reply("currentversion:$fname",$home);
1.292 www 2492: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2493: return -1;
2494: }
1.1112 www 2495: return $answer;
1.263 www 2496: }
2497:
1.1111 www 2498: #
2499: # Return special version number of resource if set by override, empty otherwise
2500: #
2501: sub usedversion {
2502: my $fname=shift;
2503: unless ($fname) { $fname=$env{'request.uri'}; }
2504: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
2505: if ($urlversion) { return $urlversion; }
2506: return '';
2507: }
2508:
1.1 albertel 2509: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 2510:
1.1 albertel 2511: sub subscribe {
2512: my $fname=shift;
1.761 raeburn 2513: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 2514: $fname=~s/[\n\r]//g;
1.1 albertel 2515: my $author=$fname;
2516: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2517: my ($udom,$uname)=split(/\//,$author);
2518: my $home=homeserver($uname,$udom);
1.335 albertel 2519: if ($home eq 'no_host') {
2520: return 'not_found';
1.1 albertel 2521: }
2522: my $answer=reply("sub:$fname",$home);
1.64 www 2523: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2524: $answer.=' by '.$home;
2525: }
1.1 albertel 2526: return $answer;
2527: }
2528:
1.8 www 2529: # -------------------------------------------------------------- Replicate file
2530:
2531: sub repcopy {
2532: my $filename=shift;
1.23 www 2533: $filename=~s/\/+/\//g;
1.1142 raeburn 2534: my $londocroot = $perlvar{'lonDocRoot'};
2535: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164 raeburn 2536: if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142 raeburn 2537: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
2538: $filename=~m{^/*(uploaded|editupload)/}) {
1.538 albertel 2539: return &repcopy_userfile($filename);
2540: }
1.532 albertel 2541: $filename=~s/[\n\r]//g;
1.8 www 2542: my $transname="$filename.in.transfer";
1.828 www 2543: # FIXME: this should flock
1.607 raeburn 2544: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 2545: my $remoteurl=subscribe($filename);
1.64 www 2546: if ($remoteurl =~ /^con_lost by/) {
2547: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2548: return 'unavailable';
1.8 www 2549: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 2550: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 2551: return 'not_found';
1.64 www 2552: } elsif ($remoteurl =~ /^rejected by/) {
2553: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2554: return 'forbidden';
1.20 www 2555: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 2556: return 'ok';
1.8 www 2557: } else {
1.290 www 2558: my $author=$filename;
2559: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2560: my ($udom,$uname)=split(/\//,$author);
2561: my $home=homeserver($uname,$udom);
2562: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 2563: my @parts=split(/\//,$filename);
2564: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142 raeburn 2565: if ($path ne "$londocroot/res") {
1.8 www 2566: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 2567: return 'bad_request';
1.8 www 2568: }
2569: my $count;
2570: for ($count=5;$count<$#parts;$count++) {
2571: $path.="/$parts[$count]";
2572: if ((-e $path)!=1) {
2573: mkdir($path,0777);
2574: }
2575: }
2576: my $ua=new LWP::UserAgent;
2577: my $request=new HTTP::Request('GET',"$remoteurl");
2578: my $response=$ua->request($request,$transname);
2579: if ($response->is_error()) {
2580: unlink($transname);
2581: my $message=$response->status_line;
1.672 albertel 2582: &logthis("<font color=\"blue\">WARNING:"
1.12 www 2583: ." LWP get: $message: $filename</font>");
1.607 raeburn 2584: return 'unavailable';
1.8 www 2585: } else {
1.16 www 2586: if ($remoteurl!~/\.meta$/) {
2587: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2588: my $mresponse=$ua->request($mrequest,$filename.'.meta');
2589: if ($mresponse->is_error()) {
2590: unlink($filename.'.meta');
2591: &logthis(
1.672 albertel 2592: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 2593: }
2594: }
1.8 www 2595: rename($transname,$filename);
1.607 raeburn 2596: return 'ok';
1.8 www 2597: }
1.290 www 2598: }
1.8 www 2599: }
1.330 www 2600: }
2601:
2602: # ------------------------------------------------ Get server side include body
2603: sub ssi_body {
1.381 albertel 2604: my ($filelink,%form)=@_;
1.606 matthew 2605: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
2606: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
2607: }
1.953 www 2608: my $output='';
2609: my $response;
1.980 raeburn 2610: if ($filelink=~/^https?\:/) {
1.954 raeburn 2611: ($output,$response)=&externalssi($filelink);
1.953 www 2612: } else {
1.1004 droeschl 2613: $filelink .= $filelink=~/\?/ ? '&' : '?';
2614: $filelink .= 'inhibitmenu=yes';
1.953 www 2615: ($output,$response)=&ssi($filelink,%form);
2616: }
1.778 albertel 2617: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 2618: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 2619: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 2620: if (wantarray) {
2621: return ($output, $response);
2622: } else {
2623: return $output;
2624: }
1.8 www 2625: }
2626:
1.15 www 2627: # --------------------------------------------------------- Server Side Include
2628:
1.782 albertel 2629: sub absolute_url {
2630: my ($host_name) = @_;
2631: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
2632: if ($host_name eq '') {
2633: $host_name = $ENV{'SERVER_NAME'};
2634: }
2635: return $protocol.$host_name;
2636: }
2637:
1.942 foxr 2638: #
2639: # Server side include.
2640: # Parameters:
2641: # fn Possibly encrypted resource name/id.
2642: # form Hash that describes how the rendering should be done
2643: # and other things.
1.944 foxr 2644: # Returns:
1.950 raeburn 2645: # Scalar context: The content of the response.
2646: # Array context: 2 element list of the content and the full response object.
1.942 foxr 2647: #
1.15 www 2648: sub ssi {
2649:
1.944 foxr 2650: my ($fn,%form)=@_;
1.15 www 2651: my $ua=new LWP::UserAgent;
1.23 www 2652: my $request;
1.711 albertel 2653:
2654: $form{'no_update_last_known'}=1;
1.895 albertel 2655: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 2656: if (%form) {
1.782 albertel 2657: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000 raeburn 2658: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23 www 2659: } else {
1.782 albertel 2660: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 2661: }
2662:
1.15 www 2663: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1173 foxr 2664: my $response= $ua->request($request);
1.1182 foxr 2665: my $content = $response->content;
2666:
2667:
1.944 foxr 2668: if (wantarray) {
1.1173 foxr 2669: return ($content, $response);
1.944 foxr 2670: } else {
1.1173 foxr 2671: return $content;
1.942 foxr 2672: }
1.324 www 2673: }
2674:
2675: sub externalssi {
2676: my ($url)=@_;
2677: my $ua=new LWP::UserAgent;
2678: my $request=new HTTP::Request('GET',$url);
2679: my $response=$ua->request($request);
1.954 raeburn 2680: if (wantarray) {
2681: return ($response->content, $response);
2682: } else {
2683: return $response->content;
2684: }
1.15 www 2685: }
1.254 www 2686:
1.492 albertel 2687: # -------------------------------- Allow a /uploaded/ URI to be vouched for
2688:
2689: sub allowuploaded {
2690: my ($srcurl,$url)=@_;
2691: $url=&clutter(&declutter($url));
2692: my $dir=$url;
2693: $dir=~s/\/[^\/]+$//;
2694: my %httpref=();
2695: my $httpurl=&hreflocation('',$url);
2696: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 2697: &Apache::lonnet::appenv(\%httpref);
1.254 www 2698: }
1.477 raeburn 2699:
1.1193 raeburn 2700: #
2701: # Determine if the current user should be able to edit a particular resource,
2702: # when viewing in course context.
2703: # (a) When viewing resource used to determine if "Edit" item is included in
2704: # Functions.
2705: # (b) When displaying folder contents in course editor, used to determine if
2706: # "Edit" link will be displayed alongside resource.
2707: #
1.1196 raeburn 2708: # input: six args -- filename (decluttered), course number, course domain,
2709: # url, symb (if registered) and group (if this is a group
2710: # item -- e.g., bulletin board, group page etc.).
2711: # output: array of five scalars --
1.1193 raeburn 2712: # $cfile -- url for file editing if editable on current server
2713: # $home -- homeserver of resource (i.e., for author if published,
2714: # or course if uploaded.).
2715: # $switchserver -- 1 if server switch will be needed.
1.1196 raeburn 2716: # $forceedit -- 1 if icon/link should be to go to edit mode
2717: # $forceview -- 1 if icon/link should be to go to view mode
1.1193 raeburn 2718: #
2719:
2720: sub can_edit_resource {
1.1194 raeburn 2721: my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
2722: my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
2723: #
2724: # For aboutme pages user can only edit his/her own.
2725: #
1.1199 raeburn 2726: if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
1.1194 raeburn 2727: my ($sdom,$sname) = ($1,$2);
2728: if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
2729: $home = $env{'user.home'};
2730: $cfile = $resurl;
2731: if ($env{'form.forceedit'}) {
2732: $forceview = 1;
2733: } else {
2734: $forceedit = 1;
2735: }
2736: return ($cfile,$home,$switchserver,$forceedit,$forceview);
2737: } else {
2738: return;
2739: }
2740: }
2741:
2742: if ($env{'request.course.id'}) {
2743: my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
2744: if ($group ne '') {
2745: # if this is a group homepage or group bulletin board, check group privs
2746: my $allowed = 0;
1.1197 raeburn 2747: if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
2748: if ((&allowed('mdg',$env{'request.course.id'}.
1.1198 raeburn 2749: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
1.1194 raeburn 2750: (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
2751: $allowed = 1;
2752: }
1.1197 raeburn 2753: } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
2754: if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
2755: (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
1.1194 raeburn 2756: $allowed = 1;
2757: }
2758: }
2759: if ($allowed) {
2760: $home=&homeserver($cnum,$cdom);
2761: if ($env{'form.forceedit'}) {
2762: $forceview = 1;
2763: } else {
2764: $forceedit = 1;
2765: }
2766: $cfile = $resurl;
2767: } else {
2768: return;
2769: }
2770: } else {
1.1208 raeburn 2771: if ($resurl =~ m{^/?adm/viewclasslist$}) {
2772: unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
2773: return;
2774: }
2775: } elsif (!$crsedit) {
1.1194 raeburn 2776: #
2777: # No edit allowed where CC has switched to student role.
2778: #
2779: return;
2780: }
2781: }
2782: }
2783:
1.1193 raeburn 2784: if ($file ne '') {
2785: if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
1.1194 raeburn 2786: if (&is_course_upload($file,$cnum,$cdom)) {
2787: $uploaded = 1;
2788: $incourse = 1;
1.1193 raeburn 2789: if ($file =~/\.(htm|html|css|js|txt)$/) {
2790: $cfile = &hreflocation('',$file);
1.1201 raeburn 2791: if ($env{'form.forceedit'}) {
2792: $forceview = 1;
2793: } else {
2794: $forceedit = 1;
2795: }
1.1194 raeburn 2796: }
2797: } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
2798: $incourse = 1;
2799: if ($env{'form.forceedit'}) {
2800: $forceview = 1;
2801: } else {
2802: $forceedit = 1;
2803: }
2804: $cfile = $resurl;
2805: } elsif (($resurl ne '') && (&is_on_map($resurl))) {
2806: if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
2807: $incourse = 1;
2808: if ($env{'form.forceedit'}) {
2809: $forceview = 1;
2810: } else {
2811: $forceedit = 1;
2812: }
2813: $cfile = $resurl;
1.1199 raeburn 2814: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
1.1194 raeburn 2815: $incourse = 1;
2816: $cfile = $resurl.'/smpedit';
1.1199 raeburn 2817: } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
1.1194 raeburn 2818: $incourse = 1;
1.1199 raeburn 2819: if ($env{'form.forceedit'}) {
2820: $forceview = 1;
2821: } else {
2822: $forceedit = 1;
2823: }
2824: $cfile = $resurl;
1.1208 raeburn 2825: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
2826: $incourse = 1;
2827: if ($env{'form.forceedit'}) {
2828: $forceview = 1;
2829: } else {
2830: $forceedit = 1;
2831: }
2832: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1194 raeburn 2833: }
2834: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
2835: my $template = '/res/lib/templates/simpleproblem.problem';
2836: if (&is_on_map($template)) {
2837: $incourse = 1;
2838: $forceview = 1;
2839: $cfile = $template;
1.1193 raeburn 2840: }
1.1199 raeburn 2841: } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
2842: $incourse = 1;
2843: if ($env{'form.forceedit'}) {
2844: $forceview = 1;
2845: } else {
2846: $forceedit = 1;
2847: }
2848: $cfile = $resurl;
2849: } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
2850: $incourse = 1;
2851: $forceview = 1;
2852: if ($symb) {
2853: my ($map,$id,$res)=&decode_symb($symb);
2854: $env{'request.symb'} = $symb;
2855: $cfile = &clutter($res);
2856: } else {
2857: $cfile = $env{'form.suppurl'};
2858: $cfile =~ s{^http://}{};
2859: $cfile = '/adm/wrapper/ext/'.$cfile;
2860: }
1.1234 raeburn 2861: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
2862: if ($env{'form.forceedit'}) {
2863: $forceview = 1;
2864: } else {
2865: $forceedit = 1;
2866: }
2867: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1193 raeburn 2868: }
2869: }
1.1194 raeburn 2870: if ($uploaded || $incourse) {
2871: $home=&homeserver($cnum,$cdom);
1.1207 raeburn 2872: } elsif ($file !~ m{/$}) {
1.1193 raeburn 2873: $file=~s{^(priv/$match_domain/$match_username)}{/$1};
2874: $file=~s{^($match_domain/$match_username)}{/priv/$1};
2875: # Check that the user has permission to edit this resource
2876: my $setpriv = 1;
2877: my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
2878: if (defined($cfudom)) {
2879: $home=&homeserver($cfuname,$cfudom);
2880: $cfile=$file;
2881: }
2882: }
1.1194 raeburn 2883: if (($cfile ne '') && (!$incourse || $uploaded) &&
2884: (($home ne '') && ($home ne 'no_host'))) {
1.1193 raeburn 2885: my @ids=¤t_machine_ids();
2886: unless (grep(/^\Q$home\E$/,@ids)) {
2887: $switchserver=1;
2888: }
2889: }
2890: }
1.1194 raeburn 2891: return ($cfile,$home,$switchserver,$forceedit,$forceview);
1.1193 raeburn 2892: }
2893:
2894: sub is_course_upload {
2895: my ($file,$cnum,$cdom) = @_;
2896: my $uploadpath = &LONCAPA::propath($cdom,$cnum);
2897: $uploadpath =~ s{^\/}{};
1.1201 raeburn 2898: if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
2899: ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
1.1193 raeburn 2900: return 1;
2901: }
2902: return;
2903: }
2904:
1.1194 raeburn 2905: sub in_course {
1.1195 raeburn 2906: my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
2907: if ($hideprivileged) {
2908: my $skipuser;
1.1219 raeburn 2909: my %coursehash = &coursedescription($cdom.'_'.$cnum);
2910: my @possdoms = ($cdom);
2911: if ($coursehash{'checkforpriv'}) {
2912: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
2913: }
2914: if (&privileged($uname,$udom,\@possdoms)) {
1.1195 raeburn 2915: $skipuser = 1;
2916: if ($coursehash{'nothideprivileged'}) {
2917: foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
2918: my $user;
2919: if ($item =~ /:/) {
2920: $user = $item;
2921: } else {
2922: $user = join(':',split(/[\@]/,$item));
2923: }
2924: if ($user eq $uname.':'.$udom) {
2925: undef($skipuser);
2926: last;
2927: }
2928: }
2929: }
2930: if ($skipuser) {
2931: return 0;
2932: }
2933: }
2934: }
1.1194 raeburn 2935: $type ||= 'any';
2936: if (!defined($cdom) || !defined($cnum)) {
2937: my $cid = $env{'request.course.id'};
2938: $cdom = $env{'course.'.$cid.'.domain'};
2939: $cnum = $env{'course.'.$cid.'.num'};
2940: }
2941: my $typesref;
1.1195 raeburn 2942: if (($type eq 'any') || ($type eq 'all')) {
1.1194 raeburn 2943: $typesref = ['active','previous','future'];
2944: } elsif ($type eq 'previous' || $type eq 'future') {
2945: $typesref = [$type];
2946: }
2947: my %roles = &get_my_roles($uname,$udom,'userroles',
2948: $typesref,undef,[$cdom]);
2949: my ($tmp) = keys(%roles);
2950: return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
2951: my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
2952: if (@course_roles > 0) {
2953: return 1;
2954: }
2955: return 0;
2956: }
2957:
1.478 albertel 2958: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 2959: # input: action, courseID, current domain, intended
1.637 raeburn 2960: # path to file, source of file, instruction to parse file for objects,
2961: # ref to hash for embedded objects,
2962: # ref to hash for codebase of java objects.
1.1095 raeburn 2963: # reference to scalar to accommodate mime type determined
2964: # from File::MMagic if $parser = parse.
1.637 raeburn 2965: #
1.485 raeburn 2966: # output: url to file (if action was uploaddoc),
2967: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 2968: #
1.478 albertel 2969: # Allows directory structure to be used within lonUsers/../userfiles/ for a
2970: # course.
1.477 raeburn 2971: #
1.478 albertel 2972: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2973: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
2974: # course's home server.
1.477 raeburn 2975: #
1.478 albertel 2976: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
2977: # be copied from $source (current location) to
2978: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2979: # and will then be copied to
2980: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
2981: # course's home server.
1.485 raeburn 2982: #
1.481 raeburn 2983: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 2984: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 2985: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2986: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
2987: # in course's home server.
1.637 raeburn 2988: #
1.477 raeburn 2989:
2990: sub process_coursefile {
1.1095 raeburn 2991: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
2992: $mimetype)=@_;
1.477 raeburn 2993: my $fetchresult;
1.638 albertel 2994: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 2995: if ($action eq 'propagate') {
1.638 albertel 2996: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2997: $home);
1.481 raeburn 2998: } else {
1.477 raeburn 2999: my $fpath = '';
3000: my $fname = $file;
1.478 albertel 3001: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 3002: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 3003: my $filepath = &build_filepath($fpath);
1.481 raeburn 3004: if ($action eq 'copy') {
3005: if ($source eq '') {
3006: $fetchresult = 'no source file';
3007: return $fetchresult;
3008: } else {
3009: my $destination = $filepath.'/'.$fname;
3010: rename($source,$destination);
3011: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3012: $home);
1.481 raeburn 3013: }
3014: } elsif ($action eq 'uploaddoc') {
3015: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 3016: print $fh $env{'form.'.$source};
1.481 raeburn 3017: close($fh);
1.637 raeburn 3018: if ($parser eq 'parse') {
1.1024 raeburn 3019: my $mm = new File::MMagic;
1.1095 raeburn 3020: my $type = $mm->checktype_filename($filepath.'/'.$fname);
3021: if ($type eq 'text/html') {
1.1024 raeburn 3022: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
3023: unless ($parse_result eq 'ok') {
3024: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
3025: }
1.637 raeburn 3026: }
1.1095 raeburn 3027: if (ref($mimetype)) {
3028: $$mimetype = $type;
3029: }
1.637 raeburn 3030: }
1.477 raeburn 3031: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3032: $home);
1.481 raeburn 3033: if ($fetchresult eq 'ok') {
3034: return '/uploaded/'.$fpath.'/'.$fname;
3035: } else {
3036: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3037: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 3038: return '/adm/notfound.html';
3039: }
1.477 raeburn 3040: }
3041: }
1.485 raeburn 3042: unless ( $fetchresult eq 'ok') {
1.477 raeburn 3043: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3044: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 3045: }
3046: return $fetchresult;
3047: }
3048:
1.637 raeburn 3049: sub build_filepath {
3050: my ($fpath) = @_;
3051: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
3052: unless ($fpath eq '') {
3053: my @parts=split('/',$fpath);
3054: foreach my $part (@parts) {
3055: $filepath.= '/'.$part;
3056: if ((-e $filepath)!=1) {
3057: mkdir($filepath,0777);
3058: }
3059: }
3060: }
3061: return $filepath;
3062: }
3063:
3064: sub store_edited_file {
1.638 albertel 3065: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 3066: my $file = $primary_url;
3067: $file =~ s#^/uploaded/$docudom/$docuname/##;
3068: my $fpath = '';
3069: my $fname = $file;
3070: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
3071: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
3072: my $filepath = &build_filepath($fpath);
3073: open(my $fh,'>'.$filepath.'/'.$fname);
3074: print $fh $content;
3075: close($fh);
1.638 albertel 3076: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 3077: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3078: $home);
1.637 raeburn 3079: if ($$fetchresult eq 'ok') {
3080: return '/uploaded/'.$fpath.'/'.$fname;
3081: } else {
1.638 albertel 3082: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
3083: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 3084: return '/adm/notfound.html';
3085: }
3086: }
3087:
1.531 albertel 3088: sub clean_filename {
1.831 albertel 3089: my ($fname,$args)=@_;
1.315 www 3090: # Replace Windows backslashes by forward slashes
1.257 www 3091: $fname=~s/\\/\//g;
1.831 albertel 3092: if (!$args->{'keep_path'}) {
3093: # Get rid of everything but the actual filename
3094: $fname=~s/^.*\/([^\/]+)$/$1/;
3095: }
1.315 www 3096: # Replace spaces by underscores
3097: $fname=~s/\s+/\_/g;
3098: # Replace all other weird characters by nothing
1.831 albertel 3099: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 3100: # Replace all .\d. sequences with _\d. so they no longer look like version
3101: # numbers
3102: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 3103: return $fname;
3104: }
1.1051 raeburn 3105: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
3106: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
3107: # image with the same aspect ratio as the original, but with dimensions which do
3108: # not exceed $resizewidth and $resizeheight.
3109:
1.984 neumanie 3110: sub resizeImage {
1.1051 raeburn 3111: my ($img_path,$resizewidth,$resizeheight) = @_;
3112: my $ima = Image::Magick->new;
3113: my $resized;
3114: if (-e $img_path) {
3115: $ima->Read($img_path);
3116: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
3117: my $width = $ima->Get('width');
3118: my $height = $ima->Get('height');
3119: if ($width > $resizewidth) {
3120: my $factor = $width/$resizewidth;
3121: my $newheight = $height/$factor;
3122: $ima->Scale(width=>$resizewidth,height=>$newheight);
3123: $resized = 1;
3124: }
3125: }
3126: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
3127: my $width = $ima->Get('width');
3128: my $height = $ima->Get('height');
3129: if ($height > $resizeheight) {
3130: my $factor = $height/$resizeheight;
3131: my $newwidth = $width/$factor;
3132: $ima->Scale(width=>$newwidth,height=>$resizeheight);
3133: $resized = 1;
3134: }
3135: }
3136: if ($resized) {
3137: $ima->Write($img_path);
3138: }
3139: }
3140: return;
1.977 amueller 3141: }
3142:
1.608 albertel 3143: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 3144: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093 raeburn 3145: # the desired filename is in $env{"form.$formname.filename"}
1.1090 raeburn 3146: # $context - possible values: coursedoc, existingfile, overwrite,
3147: # canceloverwrite, or ''.
3148: # if 'coursedoc': upload to the current course
3149: # if 'existingfile': write file to tmp/overwrites directory
3150: # if 'canceloverwrite': delete file written to tmp/overwrites directory
3151: # $context is passed as argument to &finishuserfileupload
1.686 albertel 3152: # $subdir - directory in userfile to store the file into
1.858 raeburn 3153: # $parser - instruction to parse file for objects ($parser = parse)
3154: # $allfiles - reference to hash for embedded objects
3155: # $codebase - reference to hash for codebase of java objects
3156: # $desuname - username for permanent storage of uploaded file
3157: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 3158: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
3159: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 3160: # $resizewidth - width (pixels) to which to resize uploaded image
3161: # $resizeheight - height (pixels) to which to resize uploaded image
1.1095 raeburn 3162: # $mimetype - reference to scalar to accommodate mime type determined
1.1152 raeburn 3163: # from File::MMagic.
1.858 raeburn 3164: #
1.686 albertel 3165: # output: url of file in userspace, or error: <message>
3166: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 3167:
1.531 albertel 3168: sub userfileupload {
1.1090 raeburn 3169: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095 raeburn 3170: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531 albertel 3171: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 3172: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 3173: $fname=&clean_filename($fname);
1.1090 raeburn 3174: # See if there is anything left
1.257 www 3175: unless ($fname) { return 'error: no uploaded file'; }
1.1090 raeburn 3176: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
3177: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
3178: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
3179: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523 raeburn 3180: my $now = time;
1.1090 raeburn 3181: my $filepath;
1.1095 raeburn 3182: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090 raeburn 3183: $filepath = 'tmp/helprequests/'.$now;
3184: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
3185: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
3186: '_'.$env{'user.domain'}.'/pending';
3187: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
3188: my ($docuname,$docudom);
3189: if ($destudom) {
3190: $docudom = $destudom;
3191: } else {
3192: $docudom = $env{'user.domain'};
3193: }
3194: if ($destuname) {
3195: $docuname = $destuname;
3196: } else {
3197: $docuname = $env{'user.name'};
3198: }
3199: if (exists($env{'form.group'})) {
3200: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3201: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3202: }
3203: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
3204: if ($context eq 'canceloverwrite') {
3205: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
3206: if (-e $tempfile) {
3207: my @info = stat($tempfile);
3208: if ($info[9] eq $env{'form.timestamp'}) {
3209: unlink($tempfile);
3210: }
3211: }
3212: return;
1.523 raeburn 3213: }
3214: }
1.1090 raeburn 3215: # Create the directory if not present
1.741 raeburn 3216: my @parts=split(/\//,$filepath);
3217: my $fullpath = $perlvar{'lonDaemons'};
3218: for (my $i=0;$i<@parts;$i++) {
3219: $fullpath .= '/'.$parts[$i];
3220: if ((-e $fullpath)!=1) {
3221: mkdir($fullpath,0777);
3222: }
3223: }
3224: open(my $fh,'>'.$fullpath.'/'.$fname);
3225: print $fh $env{'form.'.$formname};
3226: close($fh);
1.1090 raeburn 3227: if ($context eq 'existingfile') {
3228: my @info = stat($fullpath.'/'.$fname);
3229: return ($fullpath.'/'.$fname,$info[9]);
3230: } else {
3231: return $fullpath.'/'.$fname;
3232: }
1.523 raeburn 3233: }
1.995 raeburn 3234: if ($subdir eq 'scantron') {
3235: $fname = 'scantron_orig_'.$fname;
1.1093 raeburn 3236: } else {
1.995 raeburn 3237: $fname="$subdir/$fname";
3238: }
1.1090 raeburn 3239: if ($context eq 'coursedoc') {
1.638 albertel 3240: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3241: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 3242: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 3243: return &finishuserfileupload($docuname,$docudom,
3244: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 3245: $codebase,$thumbwidth,$thumbheight,
1.1095 raeburn 3246: $resizewidth,$resizeheight,$context,$mimetype);
1.481 raeburn 3247: } else {
1.1218 raeburn 3248: if ($env{'form.folder'}) {
3249: $fname=$env{'form.folder'}.'/'.$fname;
3250: }
1.638 albertel 3251: return &process_coursefile('uploaddoc',$docuname,$docudom,
3252: $fname,$formname,$parser,
1.1095 raeburn 3253: $allfiles,$codebase,$mimetype);
1.481 raeburn 3254: }
1.719 banghart 3255: } elsif (defined($destuname)) {
3256: my $docuname=$destuname;
3257: my $docudom=$destudom;
1.860 raeburn 3258: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3259: $parser,$allfiles,$codebase,
1.1051 raeburn 3260: $thumbwidth,$thumbheight,
1.1095 raeburn 3261: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3262: } else {
1.638 albertel 3263: my $docuname=$env{'user.name'};
3264: my $docudom=$env{'user.domain'};
1.1220 raeburn 3265: if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714 raeburn 3266: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3267: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3268: }
1.860 raeburn 3269: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3270: $parser,$allfiles,$codebase,
1.1051 raeburn 3271: $thumbwidth,$thumbheight,
1.1095 raeburn 3272: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3273: }
1.271 www 3274: }
3275:
3276: sub finishuserfileupload {
1.860 raeburn 3277: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095 raeburn 3278: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477 raeburn 3279: my $path=$docudom.'/'.$docuname.'/';
1.258 www 3280: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 3281:
1.860 raeburn 3282: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 3283: $file=$fname;
3284: if ($fname=~m|/|) {
3285: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
3286: $path.=$fnamepath.'/';
3287: }
1.259 www 3288: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 3289: my $count;
3290: for ($count=4;$count<=$#parts;$count++) {
3291: $filepath.="/$parts[$count]";
3292: if ((-e $filepath)!=1) {
3293: mkdir($filepath,0777);
3294: }
3295: }
1.984 neumanie 3296:
1.258 www 3297: # Save the file
3298: {
1.701 albertel 3299: if (!open(FH,'>'.$filepath.'/'.$file)) {
3300: &logthis('Failed to create '.$filepath.'/'.$file);
3301: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
3302: return '/adm/notfound.html';
3303: }
1.1090 raeburn 3304: if ($context eq 'overwrite') {
1.1117 foxr 3305: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090 raeburn 3306: my $target = $filepath.'/'.$file;
3307: if (-e $source) {
3308: my @info = stat($source);
3309: if ($info[9] eq $env{'form.timestamp'}) {
3310: unless (&File::Copy::move($source,$target)) {
3311: &logthis('Failed to overwrite '.$filepath.'/'.$file);
3312: return "Moving from $source failed";
3313: }
3314: } else {
3315: return "Temporary file: $source had unexpected date/time for last modification";
3316: }
3317: } else {
3318: return "Temporary file: $source missing";
3319: }
3320: } elsif (!print FH ($env{'form.'.$formname})) {
1.701 albertel 3321: &logthis('Failed to write to '.$filepath.'/'.$file);
3322: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
3323: return '/adm/notfound.html';
3324: }
1.570 albertel 3325: close(FH);
1.1051 raeburn 3326: if ($resizewidth && $resizeheight) {
3327: my $mm = new File::MMagic;
3328: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
3329: if ($mime_type =~ m{^image/}) {
3330: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
3331: }
1.977 amueller 3332: }
1.258 www 3333: }
1.1152 raeburn 3334: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
3335: if (ref($mimetype)) {
3336: if ($$mimetype eq '') {
3337: my $mm = new File::MMagic;
3338: my $type = $mm->checktype_filename($filepath.'/'.$file);
3339: $$mimetype = $type;
3340: }
3341: }
3342: }
1.637 raeburn 3343: if ($parser eq 'parse') {
1.1152 raeburn 3344: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024 raeburn 3345: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
3346: $allfiles,$codebase);
3347: unless ($parse_result eq 'ok') {
3348: &logthis('Failed to parse '.$filepath.$file.
3349: ' for embedded media: '.$parse_result);
3350: }
1.637 raeburn 3351: }
3352: }
1.860 raeburn 3353: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
3354: my $input = $filepath.'/'.$file;
3355: my $output = $filepath.'/'.'tn-'.$file;
3356: my $thumbsize = $thumbwidth.'x'.$thumbheight;
3357: system("convert -sample $thumbsize $input $output");
3358: if (-e $filepath.'/'.'tn-'.$file) {
3359: $fetchthumb = 1;
3360: }
3361: }
1.858 raeburn 3362:
1.259 www 3363: # Notify homeserver to grep it
3364: #
1.984 neumanie 3365: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 3366: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 3367: if ($fetchresult eq 'ok') {
1.860 raeburn 3368: if ($fetchthumb) {
3369: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
3370: if ($thumbresult ne 'ok') {
3371: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
3372: $docuhome.': '.$thumbresult);
3373: }
3374: }
1.259 www 3375: #
1.258 www 3376: # Return the URL to it
1.494 albertel 3377: return '/uploaded/'.$path.$file;
1.263 www 3378: } else {
1.494 albertel 3379: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
3380: ': '.$fetchresult);
1.263 www 3381: return '/adm/notfound.html';
1.858 raeburn 3382: }
1.493 albertel 3383: }
3384:
1.637 raeburn 3385: sub extract_embedded_items {
1.961 raeburn 3386: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 3387: my @state = ();
1.1164 raeburn 3388: my (%lastids,%related,%shockwave,%flashvars);
1.637 raeburn 3389: my %javafiles = (
3390: codebase => '',
3391: code => '',
3392: archive => ''
3393: );
3394: my %mediafiles = (
3395: src => '',
3396: movie => '',
3397: );
1.648 raeburn 3398: my $p;
3399: if ($content) {
3400: $p = HTML::LCParser->new($content);
3401: } else {
1.961 raeburn 3402: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 3403: }
1.641 albertel 3404: while (my $t=$p->get_token()) {
1.640 albertel 3405: if ($t->[0] eq 'S') {
3406: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 3407: push(@state, $tagname);
1.648 raeburn 3408: if (lc($tagname) eq 'allow') {
3409: &add_filetype($allfiles,$attr->{'src'},'src');
3410: }
1.640 albertel 3411: if (lc($tagname) eq 'img') {
3412: &add_filetype($allfiles,$attr->{'src'},'src');
3413: }
1.886 albertel 3414: if (lc($tagname) eq 'a') {
1.1222 raeburn 3415: unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
1.1221 raeburn 3416: &add_filetype($allfiles,$attr->{'href'},'href');
3417: }
1.886 albertel 3418: }
1.645 raeburn 3419: if (lc($tagname) eq 'script') {
1.1164 raeburn 3420: my $src;
1.645 raeburn 3421: if ($attr->{'archive'} =~ /\.jar$/i) {
3422: &add_filetype($allfiles,$attr->{'archive'},'archive');
3423: } else {
1.1164 raeburn 3424: if ($attr->{'src'} ne '') {
3425: $src = $attr->{'src'};
3426: &add_filetype($allfiles,$src,'src');
3427: }
3428: }
3429: my $text = $p->get_trimmed_text();
3430: if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
3431: my @swfargs = split(/,/,$1);
3432: foreach my $item (@swfargs) {
3433: $item =~ s/["']//g;
3434: $item =~ s/^\s+//;
3435: $item =~ s/\s+$//;
3436: }
3437: if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
3438: if (ref($related{$swfargs[0]}) eq 'ARRAY') {
3439: push(@{$related{$swfargs[0]}},$swfargs[2]);
3440: } else {
3441: $related{$swfargs[0]} = [$swfargs[2]];
3442: }
3443: }
1.645 raeburn 3444: }
3445: }
3446: if (lc($tagname) eq 'link') {
3447: if (lc($attr->{'rel'}) eq 'stylesheet') {
3448: &add_filetype($allfiles,$attr->{'href'},'href');
3449: }
3450: }
1.640 albertel 3451: if (lc($tagname) eq 'object' ||
3452: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
3453: foreach my $item (keys(%javafiles)) {
3454: $javafiles{$item} = '';
3455: }
1.1164 raeburn 3456: if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
3457: $lastids{lc($tagname)} = $attr->{'id'};
3458: }
1.640 albertel 3459: }
3460: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
3461: my $name = lc($attr->{'name'});
3462: foreach my $item (keys(%javafiles)) {
3463: if ($name eq $item) {
3464: $javafiles{$item} = $attr->{'value'};
3465: last;
3466: }
3467: }
1.1164 raeburn 3468: my $pathfrom;
1.640 albertel 3469: foreach my $item (keys(%mediafiles)) {
3470: if ($name eq $item) {
1.1164 raeburn 3471: $pathfrom = $attr->{'value'};
3472: $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
3473: &add_filetype($allfiles,$pathfrom,$name);
1.640 albertel 3474: last;
3475: }
3476: }
1.1164 raeburn 3477: if ($name eq 'flashvars') {
3478: $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
3479: }
3480: if ($pathfrom ne '') {
3481: &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
3482: $pathfrom);
3483: }
1.640 albertel 3484: }
3485: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
3486: foreach my $item (keys(%javafiles)) {
3487: if ($attr->{$item}) {
3488: $javafiles{$item} = $attr->{$item};
3489: last;
3490: }
3491: }
3492: foreach my $item (keys(%mediafiles)) {
3493: if ($attr->{$item}) {
3494: &add_filetype($allfiles,$attr->{$item},$item);
3495: last;
3496: }
3497: }
1.1164 raeburn 3498: if (lc($tagname) eq 'embed') {
3499: if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
3500: &embedded_dependency($allfiles,\%related,$attr->{'name'},
3501: $attr->{'src'});
3502: }
3503: }
1.640 albertel 3504: }
1.1243 ! raeburn 3505: if (lc($tagname) eq 'iframe') {
! 3506: my $src = $attr->{'src'} ;
! 3507: if (($src ne '') && ($src !~ m{^(/|https?://)})) {
! 3508: &add_filetype($allfiles,$src,'src');
! 3509: } elsif ($src =~ m{^/}) {
! 3510: if ($env{'request.course.id'}) {
! 3511: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
! 3512: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
! 3513: my $url = &hreflocation('',$fullpath);
! 3514: if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
! 3515: my $relpath = $1;
! 3516: if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
! 3517: &add_filetype($allfiles,$1,'src');
! 3518: }
! 3519: }
! 3520: }
! 3521: }
! 3522: }
1.1164 raeburn 3523: if ($t->[4] =~ m{/>$}) {
1.1243 ! raeburn 3524: pop(@state);
1.1164 raeburn 3525: }
1.640 albertel 3526: } elsif ($t->[0] eq 'E') {
3527: my ($tagname) = ($t->[1]);
3528: if ($javafiles{'codebase'} ne '') {
3529: $javafiles{'codebase'} .= '/';
3530: }
3531: if (lc($tagname) eq 'applet' ||
3532: lc($tagname) eq 'object' ||
3533: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
3534: ) {
3535: foreach my $item (keys(%javafiles)) {
3536: if ($item ne 'codebase' && $javafiles{$item} ne '') {
3537: my $file=$javafiles{'codebase'}.$javafiles{$item};
3538: &add_filetype($allfiles,$file,$item);
3539: }
3540: }
3541: }
3542: pop @state;
3543: }
3544: }
1.1164 raeburn 3545: foreach my $id (sort(keys(%flashvars))) {
3546: if ($shockwave{$id} ne '') {
3547: my @pairs = split(/\&/,$flashvars{$id});
3548: foreach my $pair (@pairs) {
3549: my ($key,$value) = split(/\=/,$pair);
3550: if ($key eq 'thumb') {
3551: &add_filetype($allfiles,$value,$key);
3552: } elsif ($key eq 'content') {
3553: my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
3554: my ($ext) = ($value =~ /\.([^.]+)$/);
3555: if ($ext ne '') {
3556: &add_filetype($allfiles,$path.$value,$ext);
3557: }
3558: }
3559: }
3560: }
3561: }
1.637 raeburn 3562: return 'ok';
3563: }
3564:
1.639 albertel 3565: sub add_filetype {
3566: my ($allfiles,$file,$type)=@_;
3567: if (exists($allfiles->{$file})) {
3568: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
3569: push(@{$allfiles->{$file}}, &escape($type));
3570: }
3571: } else {
3572: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 3573: }
3574: }
3575:
1.1164 raeburn 3576: sub embedded_dependency {
3577: my ($allfiles,$related,$identifier,$pathfrom) = @_;
3578: if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
3579: if (($identifier ne '') &&
3580: (ref($related->{$identifier}) eq 'ARRAY') &&
3581: ($pathfrom ne '')) {
3582: my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
3583: foreach my $dep (@{$related->{$identifier}}) {
3584: &add_filetype($allfiles,$path.$dep,'object');
3585: }
3586: }
3587: }
3588: return;
3589: }
3590:
1.493 albertel 3591: sub removeuploadedurl {
1.984 neumanie 3592: my ($url)=@_;
3593: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 3594: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 3595: }
3596:
3597: sub removeuserfile {
3598: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 3599: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3600: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 3601: if ($result eq 'ok') {
1.798 raeburn 3602: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
3603: my $metafile = $fname.'.meta';
3604: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 3605: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 3606: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3607: my $sqlresult =
1.823 albertel 3608: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3609: 'portfolio_metadata',$group,
3610: 'delete');
1.798 raeburn 3611: }
3612: }
3613: return $result;
1.257 www 3614: }
1.15 www 3615:
1.530 albertel 3616: sub mkdiruserfile {
3617: my ($docuname,$docudom,$dir)=@_;
3618: my $home=&homeserver($docuname,$docudom);
3619: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
3620: }
3621:
1.531 albertel 3622: sub renameuserfile {
3623: my ($docuname,$docudom,$old,$new)=@_;
3624: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3625: my $result = &reply("renameuserfile:$docudom:$docuname:".
3626: &escape("$old").':'.&escape("$new"),$home);
3627: if ($result eq 'ok') {
3628: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
3629: my $oldmeta = $old.'.meta';
3630: my $newmeta = $new.'.meta';
3631: my $metaresult =
3632: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 3633: my $url = "/uploaded/$docudom/$docuname/$old";
3634: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3635: my $sqlresult =
1.823 albertel 3636: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3637: 'portfolio_metadata',$group,
3638: 'delete');
1.798 raeburn 3639: }
3640: }
3641: return $result;
1.531 albertel 3642: }
3643:
1.14 www 3644: # ------------------------------------------------------------------------- Log
3645:
3646: sub log {
3647: my ($dom,$nam,$hom,$what)=@_;
1.47 www 3648: return critical("log:$dom:$nam:$what",$hom);
1.157 www 3649: }
3650:
3651: # ------------------------------------------------------------------ Course Log
1.352 www 3652: #
3653: # This routine flushes several buffers of non-mission-critical nature
3654: #
1.157 www 3655:
3656: sub flushcourselogs {
1.352 www 3657: &logthis('Flushing log buffers');
3658: #
3659: # course logs
3660: # This is a log of all transactions in a course, which can be used
3661: # for data mining purposes
3662: #
3663: # It also collects the courseid database, which lists last transaction
3664: # times and course titles for all courseids
3665: #
3666: my %courseidbuffer=();
1.921 raeburn 3667: foreach my $crsid (keys(%courselogs)) {
1.352 www 3668: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 3669: &escape($courselogs{$crsid}),
3670: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 3671: delete $courselogs{$crsid};
3672: } else {
3673: &logthis('Failed to flush log buffer for '.$crsid);
3674: if (length($courselogs{$crsid})>40000) {
1.672 albertel 3675: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 3676: " exceeded maximum size, deleting.</font>");
3677: delete $courselogs{$crsid};
3678: }
1.352 www 3679: }
1.920 raeburn 3680: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 3681: 'description' => $coursedescrbuf{$crsid},
3682: 'inst_code' => $courseinstcodebuf{$crsid},
3683: 'type' => $coursetypebuf{$crsid},
3684: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 3685: };
1.191 harris41 3686: }
1.352 www 3687: #
3688: # Write course id database (reverse lookup) to homeserver of courses
3689: # Is used in pickcourse
3690: #
1.840 albertel 3691: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 3692: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 3693: $courseidbuffer{$crs_home},
3694: $crs_home,'timeonly');
1.352 www 3695: }
3696: #
3697: # File accesses
3698: # Writes to the dynamic metadata of resources to get hit counts, etc.
3699: #
1.449 matthew 3700: foreach my $entry (keys(%accesshash)) {
1.458 matthew 3701: if ($entry =~ /___count$/) {
3702: my ($dom,$name);
1.807 albertel 3703: ($dom,$name,undef)=
1.811 albertel 3704: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 3705: if (! defined($dom) || $dom eq '' ||
3706: ! defined($name) || $name eq '') {
1.620 albertel 3707: my $cid = $env{'request.course.id'};
3708: $dom = $env{'request.'.$cid.'.domain'};
3709: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 3710: }
1.450 matthew 3711: my $value = $accesshash{$entry};
3712: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
3713: my %temphash=($url => $value);
1.449 matthew 3714: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
3715: if ($result eq 'ok') {
3716: delete $accesshash{$entry};
3717: }
3718: } else {
1.811 albertel 3719: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159 www 3720: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450 matthew 3721: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 3722: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
3723: delete $accesshash{$entry};
3724: }
1.185 www 3725: }
1.191 harris41 3726: }
1.352 www 3727: #
3728: # Roles
3729: # Reverse lookup of user roles for course faculty/staff and co-authorship
3730: #
1.800 albertel 3731: foreach my $entry (keys(%userrolehash)) {
1.351 www 3732: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 3733: split(/\:/,$entry);
3734: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 3735: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 3736: $rudom,$runame) eq 'ok') {
3737: delete $userrolehash{$entry};
3738: }
3739: }
1.662 raeburn 3740: #
3741: # Reverse lookup of domain roles (dc, ad, li, sc, au)
3742: #
3743: my %domrolebuffer = ();
1.1000 raeburn 3744: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 3745: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 3746: if ($domrolebuffer{$rudom}) {
3747: $domrolebuffer{$rudom}.='&'.&escape($entry).
3748: '='.&escape($domainrolehash{$entry});
3749: } else {
3750: $domrolebuffer{$rudom}.=&escape($entry).
3751: '='.&escape($domainrolehash{$entry});
3752: }
3753: delete $domainrolehash{$entry};
3754: }
3755: foreach my $dom (keys(%domrolebuffer)) {
1.841 albertel 3756: my %servers = &get_servers($dom,'library');
3757: foreach my $tryserver (keys(%servers)) {
3758: unless (&reply('domroleput:'.$dom.':'.
3759: $domrolebuffer{$dom},$tryserver) eq 'ok') {
3760: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
3761: }
1.662 raeburn 3762: }
3763: }
1.186 www 3764: $dumpcount++;
1.157 www 3765: }
3766:
3767: sub courselog {
3768: my $what=shift;
1.158 www 3769: $what=time.':'.$what;
1.620 albertel 3770: unless ($env{'request.course.id'}) { return ''; }
3771: $coursedombuf{$env{'request.course.id'}}=
3772: $env{'course.'.$env{'request.course.id'}.'.domain'};
3773: $coursenumbuf{$env{'request.course.id'}}=
3774: $env{'course.'.$env{'request.course.id'}.'.num'};
3775: $coursehombuf{$env{'request.course.id'}}=
3776: $env{'course.'.$env{'request.course.id'}.'.home'};
3777: $coursedescrbuf{$env{'request.course.id'}}=
3778: $env{'course.'.$env{'request.course.id'}.'.description'};
3779: $courseinstcodebuf{$env{'request.course.id'}}=
3780: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
3781: $courseownerbuf{$env{'request.course.id'}}=
3782: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 3783: $coursetypebuf{$env{'request.course.id'}}=
3784: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 3785: if (defined $courselogs{$env{'request.course.id'}}) {
3786: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 3787: } else {
1.620 albertel 3788: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 3789: }
1.620 albertel 3790: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 3791: &flushcourselogs();
3792: }
1.158 www 3793: }
3794:
3795: sub courseacclog {
3796: my $fnsymb=shift;
1.620 albertel 3797: unless ($env{'request.course.id'}) { return ''; }
3798: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144 www 3799: if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187 www 3800: $what.=':POST';
1.583 matthew 3801: # FIXME: Probably ought to escape things....
1.800 albertel 3802: foreach my $key (keys(%env)) {
3803: if ($key=~/^form\.(.*)/) {
1.975 raeburn 3804: my $formitem = $1;
3805: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
3806: $what.=':'.$formitem.'='.$env{$key};
3807: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
3808: $what.=':'.$formitem.'='.$env{$key};
3809: }
1.158 www 3810: }
1.191 harris41 3811: }
1.583 matthew 3812: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
3813: # FIXME: We should not be depending on a form parameter that someone
3814: # editing lonsearchcat.pm might change in the future.
1.620 albertel 3815: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 3816: $what.= ':POST';
3817: # FIXME: Probably ought to escape things....
3818: foreach my $element ('courseexp','crsfulltext','crsrelated',
3819: 'crsdiscuss') {
1.620 albertel 3820: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 3821: }
3822: }
1.158 www 3823: }
3824: &courselog($what);
1.149 www 3825: }
3826:
1.185 www 3827: sub countacc {
3828: my $url=&declutter(shift);
1.458 matthew 3829: return if (! defined($url) || $url eq '');
1.620 albertel 3830: unless ($env{'request.course.id'}) { return ''; }
1.1158 www 3831: #
3832: # Mark that this url was used in this course
3833: #
1.620 albertel 3834: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158 www 3835: #
3836: # Increase the access count for this resource in this child process
3837: #
1.281 www 3838: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 3839: $accesshash{$key}++;
1.185 www 3840: }
1.349 www 3841:
1.361 www 3842: sub linklog {
3843: my ($from,$to)=@_;
3844: $from=&declutter($from);
3845: $to=&declutter($to);
3846: $accesshash{$from.'___'.$to.'___comefrom'}=1;
3847: $accesshash{$to.'___'.$from.'___goto'}=1;
3848: }
1.1160 www 3849:
3850: sub statslog {
3851: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
3852: if ($users<2) { return; }
3853: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
3854: 'course' => $env{'request.course.id'},
3855: 'sections' => '"all"',
3856: 'num_students' => $users,
3857: 'part' => $part,
3858: 'symb' => $symb,
3859: 'mean_tries' => $av_attempts,
3860: 'deg_of_diff' => $degdiff});
3861: foreach my $key (keys(%dynstore)) {
3862: $accesshash{$key}=$dynstore{$key};
3863: }
3864: }
1.361 www 3865:
1.349 www 3866: sub userrolelog {
3867: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169 droeschl 3868: if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350 www 3869: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3870: $userrolehash
3871: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 3872: =$tend.':'.$tstart;
1.662 raeburn 3873: }
1.1169 droeschl 3874: if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898 albertel 3875: $userrolehash
3876: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
3877: =$tend.':'.$tstart;
3878: }
1.1169 droeschl 3879: if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
1.662 raeburn 3880: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3881: $domainrolehash
3882: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
3883: = $tend.':'.$tstart;
3884: }
1.351 www 3885: }
3886:
1.957 raeburn 3887: sub courserolelog {
3888: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1184 raeburn 3889: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
3890: my $cdom = $1;
3891: my $cnum = $2;
3892: my $sec = $3;
3893: my $namespace = 'rolelog';
3894: my %storehash = (
3895: role => $trole,
3896: start => $tstart,
3897: end => $tend,
3898: selfenroll => $selfenroll,
3899: context => $context,
3900: );
3901: if ($trole eq 'gr') {
3902: $namespace = 'groupslog';
3903: $storehash{'group'} = $sec;
3904: } else {
3905: $storehash{'section'} = $sec;
3906: }
1.1188 raeburn 3907: &write_log('course',$namespace,\%storehash,$delflag,$username,
3908: $domain,$cnum,$cdom);
1.1184 raeburn 3909: if (($trole ne 'st') || ($sec ne '')) {
3910: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957 raeburn 3911: }
3912: }
3913: return;
3914: }
3915:
1.1184 raeburn 3916: sub domainrolelog {
3917: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
3918: if ($area =~ m{^/($match_domain)/$}) {
3919: my $cdom = $1;
3920: my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
3921: my $namespace = 'rolelog';
3922: my %storehash = (
3923: role => $trole,
3924: start => $tstart,
3925: end => $tend,
3926: context => $context,
3927: );
1.1188 raeburn 3928: &write_log('domain',$namespace,\%storehash,$delflag,$username,
3929: $domain,$domconfiguser,$cdom);
1.1184 raeburn 3930: }
3931: return;
3932:
3933: }
3934:
3935: sub coauthorrolelog {
3936: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
3937: if ($area =~ m{^/($match_domain)/($match_username)$}) {
3938: my $audom = $1;
3939: my $auname = $2;
3940: my $namespace = 'rolelog';
3941: my %storehash = (
3942: role => $trole,
3943: start => $tstart,
3944: end => $tend,
3945: context => $context,
3946: );
1.1188 raeburn 3947: &write_log('author',$namespace,\%storehash,$delflag,$username,
3948: $domain,$auname,$audom);
1.1184 raeburn 3949: }
3950: return;
3951: }
3952:
1.351 www 3953: sub get_course_adv_roles {
1.948 raeburn 3954: my ($cid,$codes) = @_;
1.620 albertel 3955: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 3956: my %coursehash=&coursedescription($cid);
1.988 raeburn 3957: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 3958: my %nothide=();
1.800 albertel 3959: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 3960: if ($user !~ /:/) {
3961: $nothide{join(':',split(/[\@]/,$user))}=1;
3962: } else {
3963: $nothide{$user}=1;
3964: }
1.470 www 3965: }
1.1219 raeburn 3966: my @possdoms = ($coursehash{'domain'});
3967: if ($coursehash{'checkforpriv'}) {
3968: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
3969: }
1.351 www 3970: my %returnhash=();
3971: my %dumphash=
3972: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
3973: my $now=time;
1.997 raeburn 3974: my %privileged;
1.1000 raeburn 3975: foreach my $entry (keys(%dumphash)) {
1.800 albertel 3976: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 3977: if (($tstart) && ($tstart<0)) { next; }
3978: if (($tend) && ($tend<$now)) { next; }
3979: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 3980: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 3981: if ($username eq '' || $domain eq '') { next; }
1.1219 raeburn 3982: if ((&privileged($username,$domain,\@possdoms)) &&
1.997 raeburn 3983: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 3984: if ($role eq 'cr') { next; }
1.948 raeburn 3985: if ($codes) {
3986: if ($section) { $role .= ':'.$section; }
3987: if ($returnhash{$role}) {
3988: $returnhash{$role}.=','.$username.':'.$domain;
3989: } else {
3990: $returnhash{$role}=$username.':'.$domain;
3991: }
1.351 www 3992: } else {
1.988 raeburn 3993: my $key=&plaintext($role,$crstype);
1.973 bisitz 3994: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 3995: if ($returnhash{$key}) {
3996: $returnhash{$key}.=','.$username.':'.$domain;
3997: } else {
3998: $returnhash{$key}=$username.':'.$domain;
3999: }
1.351 www 4000: }
1.948 raeburn 4001: }
1.400 www 4002: return %returnhash;
4003: }
4004:
4005: sub get_my_roles {
1.937 raeburn 4006: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 4007: unless (defined($uname)) { $uname=$env{'user.name'}; }
4008: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 4009: my (%dumphash,%nothide);
1.1086 raeburn 4010: if ($context eq 'userroles') {
1.1166 raeburn 4011: %dumphash = &dump('roles',$udom,$uname);
1.858 raeburn 4012: } else {
1.1219 raeburn 4013: %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 4014: if ($hidepriv) {
4015: my %coursehash=&coursedescription($udom.'_'.$uname);
4016: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
4017: if ($user !~ /:/) {
4018: $nothide{join(':',split(/[\@]/,$user))} = 1;
4019: } else {
4020: $nothide{$user} = 1;
4021: }
4022: }
4023: }
1.858 raeburn 4024: }
1.400 www 4025: my %returnhash=();
4026: my $now=time;
1.999 raeburn 4027: my %privileged;
1.800 albertel 4028: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 4029: my ($role,$tend,$tstart);
4030: if ($context eq 'userroles') {
1.1149 raeburn 4031: next if ($entry =~ /^rolesdef/);
1.867 raeburn 4032: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
4033: } else {
4034: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
4035: }
1.400 www 4036: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 4037: my $status = 'active';
1.939 raeburn 4038: if (($tend) && ($tend<=$now)) {
1.832 raeburn 4039: $status = 'previous';
4040: }
4041: if (($tstart) && ($now<$tstart)) {
4042: $status = 'future';
4043: }
4044: if (ref($types) eq 'ARRAY') {
4045: if (!grep(/^\Q$status\E$/,@{$types})) {
4046: next;
4047: }
4048: } else {
4049: if ($status ne 'active') {
4050: next;
4051: }
4052: }
1.867 raeburn 4053: my ($rolecode,$username,$domain,$section,$area);
4054: if ($context eq 'userroles') {
1.1186 raeburn 4055: ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867 raeburn 4056: (undef,$domain,$username,$section) = split(/\//,$area);
4057: } else {
4058: ($role,$username,$domain,$section) = split(/\:/,$entry);
4059: }
1.832 raeburn 4060: if (ref($roledoms) eq 'ARRAY') {
4061: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
4062: next;
4063: }
4064: }
4065: if (ref($roles) eq 'ARRAY') {
4066: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 4067: if ($role =~ /^cr\//) {
4068: if (!grep(/^cr$/,@{$roles})) {
4069: next;
4070: }
1.1104 raeburn 4071: } elsif ($role =~ /^gr\//) {
4072: if (!grep(/^gr$/,@{$roles})) {
4073: next;
4074: }
1.922 raeburn 4075: } else {
4076: next;
4077: }
1.832 raeburn 4078: }
1.867 raeburn 4079: }
1.937 raeburn 4080: if ($hidepriv) {
1.1219 raeburn 4081: my @privroles = ('dc','su');
1.999 raeburn 4082: if ($context eq 'userroles') {
1.1219 raeburn 4083: next if (grep(/^\Q$role\E$/,@privroles));
1.999 raeburn 4084: } else {
1.1219 raeburn 4085: my $possdoms = [$domain];
4086: if (ref($roledoms) eq 'ARRAY') {
4087: push(@{$possdoms},@{$roledoms});
1.999 raeburn 4088: }
1.1219 raeburn 4089: if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999 raeburn 4090: if (!$nothide{$username.':'.$domain}) {
4091: next;
4092: }
4093: }
1.937 raeburn 4094: }
4095: }
1.933 raeburn 4096: if ($withsec) {
4097: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
4098: $tstart.':'.$tend;
4099: } else {
4100: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
4101: }
1.832 raeburn 4102: }
1.373 www 4103: return %returnhash;
1.399 www 4104: }
4105:
4106: # ----------------------------------------------------- Frontpage Announcements
4107: #
4108: #
4109:
4110: sub postannounce {
4111: my ($server,$text)=@_;
1.844 albertel 4112: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 4113: unless ($text=~/\w/) { $text=''; }
4114: return &reply('setannounce:'.&escape($text),$server);
4115: }
4116:
4117: sub getannounce {
1.448 albertel 4118:
4119: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 4120: my $announcement='';
1.800 albertel 4121: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 4122: close($fh);
1.399 www 4123: if ($announcement=~/\w/) {
4124: return
4125: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 4126: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 4127: } else {
4128: return '';
4129: }
4130: } else {
4131: return '';
4132: }
1.351 www 4133: }
1.353 www 4134:
4135: # ---------------------------------------------------------- Course ID routines
4136: # Deal with domain's nohist_courseid.db files
4137: #
4138:
4139: sub courseidput {
1.921 raeburn 4140: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 4141: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 4142: my $outcome;
4143: if ($caller eq 'timeonly') {
4144: my $cids = '';
4145: foreach my $item (keys(%$storehash)) {
4146: $cids.=&escape($item).'&';
4147: }
4148: $cids=~s/\&$//;
4149: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
4150: $coursehome);
4151: } else {
4152: my $items = '';
4153: foreach my $item (keys(%$storehash)) {
4154: $items.= &escape($item).'='.
4155: &freeze_escape($$storehash{$item}).'&';
4156: }
4157: $items=~s/\&$//;
4158: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
4159: $coursehome);
1.918 raeburn 4160: }
4161: if ($outcome eq 'unknown_cmd') {
4162: my $what;
4163: foreach my $cid (keys(%$storehash)) {
4164: $what .= &escape($cid).'=';
1.921 raeburn 4165: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 4166: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 4167: }
4168: $what =~ s/\:$/&/;
4169: }
4170: $what =~ s/\&$//;
4171: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
4172: } else {
4173: return $outcome;
4174: }
1.353 www 4175: }
4176:
4177: sub courseiddump {
1.921 raeburn 4178: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 4179: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 4180: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1071 raeburn 4181: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918 raeburn 4182: my $as_hash = 1;
4183: my %returnhash;
4184: if (!$domfilter) { $domfilter=''; }
1.845 albertel 4185: my %libserv = &all_library();
4186: foreach my $tryserver (keys(%libserv)) {
4187: if ( ( $hostidflag == 1
4188: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
4189: || (!defined($hostidflag)) ) {
4190:
1.918 raeburn 4191: if (($domfilter eq '') ||
4192: (&host_domain($tryserver) eq $domfilter)) {
1.1180 droeschl 4193: my $rep;
4194: if (grep { $_ eq $tryserver } current_machine_ids()) {
4195: $rep = LONCAPA::Lond::dump_course_id_handler(
4196: join(":", (&host_domain($tryserver), $sincefilter,
4197: &escape($descfilter), &escape($instcodefilter),
4198: &escape($ownerfilter), &escape($coursefilter),
4199: &escape($typefilter), &escape($regexp_ok),
4200: $as_hash, &escape($selfenrollonly),
4201: &escape($catfilter), $showhidden, $caller,
4202: &escape($cloner), &escape($cc_clone), $cloneonly,
4203: &escape($createdbefore), &escape($createdafter),
4204: &escape($creationcontext), $domcloner)));
4205: } else {
4206: $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
4207: $sincefilter.':'.&escape($descfilter).':'.
4208: &escape($instcodefilter).':'.&escape($ownerfilter).
4209: ':'.&escape($coursefilter).':'.&escape($typefilter).
4210: ':'.&escape($regexp_ok).':'.$as_hash.':'.
4211: &escape($selfenrollonly).':'.&escape($catfilter).':'.
4212: $showhidden.':'.$caller.':'.&escape($cloner).':'.
4213: &escape($cc_clone).':'.$cloneonly.':'.
4214: &escape($createdbefore).':'.&escape($createdafter).':'.
4215: &escape($creationcontext).':'.$domcloner,
4216: $tryserver);
4217: }
4218:
1.918 raeburn 4219: my @pairs=split(/\&/,$rep);
4220: foreach my $item (@pairs) {
4221: my ($key,$value)=split(/\=/,$item,2);
4222: $key = &unescape($key);
4223: next if ($key =~ /^error: 2 /);
4224: my $result = &thaw_unescape($value);
4225: if (ref($result) eq 'HASH') {
4226: $returnhash{$key}=$result;
4227: } else {
1.921 raeburn 4228: my @responses = split(/:/,$value);
4229: my @items = ('description','inst_code','owner','type');
1.918 raeburn 4230: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 4231: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 4232: }
1.1008 raeburn 4233: }
1.353 www 4234: }
4235: }
4236: }
4237: }
4238: return %returnhash;
4239: }
4240:
1.1055 raeburn 4241: sub courselastaccess {
4242: my ($cdom,$cnum,$hostidref) = @_;
4243: my %returnhash;
4244: if ($cdom && $cnum) {
4245: my $chome = &homeserver($cnum,$cdom);
4246: if ($chome ne 'no_host') {
4247: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
4248: &extract_lastaccess(\%returnhash,$rep);
4249: }
4250: } else {
4251: if (!$cdom) { $cdom=''; }
4252: my %libserv = &all_library();
4253: foreach my $tryserver (keys(%libserv)) {
4254: if (ref($hostidref) eq 'ARRAY') {
4255: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
4256: }
4257: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
4258: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
4259: &extract_lastaccess(\%returnhash,$rep);
4260: }
4261: }
4262: }
4263: return %returnhash;
4264: }
4265:
4266: sub extract_lastaccess {
4267: my ($returnhash,$rep) = @_;
4268: if (ref($returnhash) eq 'HASH') {
4269: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
4270: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
4271: $rep eq '') {
4272: my @pairs=split(/\&/,$rep);
4273: foreach my $item (@pairs) {
4274: my ($key,$value)=split(/\=/,$item,2);
4275: $key = &unescape($key);
4276: next if ($key =~ /^error: 2 /);
4277: $returnhash->{$key} = &thaw_unescape($value);
4278: }
4279: }
4280: }
4281: return;
4282: }
4283:
1.658 raeburn 4284: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 4285:
4286: sub dcmailput {
1.685 raeburn 4287: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 4288: my $status = &Apache::lonnet::critical(
1.740 www 4289: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
4290: &escape($message),$server);
1.662 raeburn 4291: return $status;
4292: }
4293:
1.658 raeburn 4294: sub dcmaildump {
4295: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 4296: my %returnhash=();
1.846 albertel 4297:
4298: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 4299: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
4300: &escape($enddate).':';
4301: my @esc_senders=map { &escape($_)} @$senders;
4302: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 4303: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 4304: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 4305: if (($key) && ($value)) {
4306: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 4307: }
4308: }
4309: }
4310: return %returnhash;
4311: }
1.662 raeburn 4312: # ---------------------------------------------------------- Domain roles
4313:
4314: sub get_domain_roles {
4315: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 4316: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 4317: $startdate = '.';
4318: }
1.1018 raeburn 4319: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 4320: $enddate = '.';
4321: }
1.922 raeburn 4322: my $rolelist;
4323: if (ref($roles) eq 'ARRAY') {
1.1219 raeburn 4324: $rolelist = join('&',@{$roles});
1.922 raeburn 4325: }
1.662 raeburn 4326: my %personnel = ();
1.841 albertel 4327:
4328: my %servers = &get_servers($dom,'library');
4329: foreach my $tryserver (keys(%servers)) {
4330: %{$personnel{$tryserver}}=();
4331: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
4332: &escape($startdate).':'.
4333: &escape($enddate).':'.
4334: &escape($rolelist), $tryserver))) {
4335: my ($key,$value) = split(/\=/,$line,2);
4336: if (($key) && ($value)) {
4337: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
4338: }
4339: }
1.662 raeburn 4340: }
4341: return %personnel;
4342: }
1.658 raeburn 4343:
1.1057 www 4344: # ----------------------------------------------------------- Interval timing
1.149 www 4345:
1.1153 www 4346: {
4347: # Caches needed for speedup of navmaps
4348: # We don't want to cache this for very long at all (5 seconds at most)
4349: #
4350: # The user for whom we cache
4351: my $cachedkey='';
4352: # The cached times for this user
4353: my %cachedtimes=();
4354: # When this was last done
4355: my $cachedtime=();
4356:
4357: sub load_all_first_access {
1.1154 raeburn 4358: my ($uname,$udom)=@_;
1.1156 www 4359: if (($cachedkey eq $uname.':'.$udom) &&
1.1174 raeburn 4360: (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154 raeburn 4361: return;
4362: }
4363: $cachedtime=time;
4364: $cachedkey=$uname.':'.$udom;
4365: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153 www 4366: }
4367:
1.504 albertel 4368: sub get_first_access {
1.1162 raeburn 4369: my ($type,$argsymb,$argmap)=@_;
1.790 albertel 4370: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4371: if ($argsymb) { $symb=$argsymb; }
4372: my ($map,$id,$res)=&decode_symb($symb);
1.1162 raeburn 4373: if ($argmap) { $map = $argmap; }
1.926 albertel 4374: if ($type eq 'course') {
4375: $res='course';
4376: } elsif ($type eq 'map') {
1.588 albertel 4377: $res=&symbread($map);
4378: } else {
4379: $res=$symb;
4380: }
1.1153 www 4381: &load_all_first_access($uname,$udom);
4382: return $cachedtimes{"$courseid\0$res"};
1.504 albertel 4383: }
4384:
4385: sub set_first_access {
1.1162 raeburn 4386: my ($type,$interval)=@_;
1.790 albertel 4387: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4388: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 4389: if ($type eq 'course') {
4390: $res='course';
4391: } elsif ($type eq 'map') {
1.588 albertel 4392: $res=&symbread($map);
4393: } else {
4394: $res=$symb;
4395: }
1.1153 www 4396: $cachedkey='';
1.1162 raeburn 4397: my $firstaccess=&get_first_access($type,$symb,$map);
1.505 albertel 4398: if (!$firstaccess) {
1.1162 raeburn 4399: my $start = time;
4400: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
4401: $udom,$uname);
4402: if ($putres eq 'ok') {
4403: &put('timerinterval',{"$courseid\0$res"=>$interval},
4404: $udom,$uname);
4405: &appenv(
4406: {
4407: 'course.'.$courseid.'.firstaccess.'.$res => $start,
4408: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
4409: }
4410: );
4411: }
4412: return $putres;
1.505 albertel 4413: }
4414: return 'already_set';
1.504 albertel 4415: }
1.1153 www 4416: }
1.110 www 4417: # --------------------------------------------- Set Expire Date for Spreadsheet
4418:
4419: sub expirespread {
4420: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 4421: my $cid=$env{'request.course.id'};
1.110 www 4422: if ($cid) {
4423: my $now=time;
4424: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 4425: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
4426: $env{'course.'.$cid.'.num'}.
1.110 www 4427: ':nohist_expirationdates:'.
4428: &escape($key).'='.$now,
1.620 albertel 4429: $env{'course.'.$cid.'.home'})
1.110 www 4430: }
4431: return 'ok';
1.14 www 4432: }
4433:
1.109 www 4434: # ----------------------------------------------------- Devalidate Spreadsheets
4435:
4436: sub devalidate {
1.325 www 4437: my ($symb,$uname,$udom)=@_;
1.620 albertel 4438: my $cid=$env{'request.course.id'};
1.109 www 4439: if ($cid) {
1.391 matthew 4440: # delete the stored spreadsheets for
4441: # - the student level sheet of this user in course's homespace
4442: # - the assessment level sheet for this resource
4443: # for this user in user's homespace
1.553 albertel 4444: # - current conditional state info
1.325 www 4445: my $key=$uname.':'.$udom.':';
1.109 www 4446: my $status=
1.299 matthew 4447: &del('nohist_calculatedsheets',
1.391 matthew 4448: [$key.'studentcalc:'],
1.620 albertel 4449: $env{'course.'.$cid.'.domain'},
4450: $env{'course.'.$cid.'.num'})
1.133 albertel 4451: .' '.
4452: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 4453: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 4454: unless ($status eq 'ok ok') {
4455: &logthis('Could not devalidate spreadsheet '.
1.325 www 4456: $uname.' at '.$udom.' for '.
1.109 www 4457: $symb.': '.$status);
1.133 albertel 4458: }
1.553 albertel 4459: &delenv('user.state.'.$cid);
1.109 www 4460: }
4461: }
4462:
1.265 albertel 4463: sub get_scalar {
4464: my ($string,$end) = @_;
4465: my $value;
4466: if ($$string =~ s/^([^&]*?)($end)/$2/) {
4467: $value = $1;
4468: } elsif ($$string =~ s/^([^&]*?)&//) {
4469: $value = $1;
4470: }
4471: return &unescape($value);
4472: }
4473:
4474: sub array2str {
4475: my (@array) = @_;
4476: my $result=&arrayref2str(\@array);
4477: $result=~s/^__ARRAY_REF__//;
4478: $result=~s/__END_ARRAY_REF__$//;
4479: return $result;
4480: }
4481:
1.204 albertel 4482: sub arrayref2str {
4483: my ($arrayref) = @_;
1.265 albertel 4484: my $result='__ARRAY_REF__';
1.204 albertel 4485: foreach my $elem (@$arrayref) {
1.265 albertel 4486: if(ref($elem) eq 'ARRAY') {
4487: $result.=&arrayref2str($elem).'&';
4488: } elsif(ref($elem) eq 'HASH') {
4489: $result.=&hashref2str($elem).'&';
4490: } elsif(ref($elem)) {
4491: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 4492: } else {
4493: $result.=&escape($elem).'&';
4494: }
4495: }
4496: $result=~s/\&$//;
1.265 albertel 4497: $result .= '__END_ARRAY_REF__';
1.204 albertel 4498: return $result;
4499: }
4500:
1.168 albertel 4501: sub hash2str {
1.204 albertel 4502: my (%hash) = @_;
4503: my $result=&hashref2str(\%hash);
1.265 albertel 4504: $result=~s/^__HASH_REF__//;
4505: $result=~s/__END_HASH_REF__$//;
1.204 albertel 4506: return $result;
4507: }
4508:
4509: sub hashref2str {
4510: my ($hashref)=@_;
1.265 albertel 4511: my $result='__HASH_REF__';
1.800 albertel 4512: foreach my $key (sort(keys(%$hashref))) {
4513: if (ref($key) eq 'ARRAY') {
4514: $result.=&arrayref2str($key).'=';
4515: } elsif (ref($key) eq 'HASH') {
4516: $result.=&hashref2str($key).'=';
4517: } elsif (ref($key)) {
1.265 albertel 4518: $result.='=';
1.800 albertel 4519: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 4520: } else {
1.1132 raeburn 4521: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 4522: }
4523:
1.800 albertel 4524: if(ref($hashref->{$key}) eq 'ARRAY') {
4525: $result.=&arrayref2str($hashref->{$key}).'&';
4526: } elsif(ref($hashref->{$key}) eq 'HASH') {
4527: $result.=&hashref2str($hashref->{$key}).'&';
4528: } elsif(ref($hashref->{$key})) {
1.265 albertel 4529: $result.='&';
1.800 albertel 4530: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 4531: } else {
1.800 albertel 4532: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 4533: }
4534: }
1.168 albertel 4535: $result=~s/\&$//;
1.265 albertel 4536: $result .= '__END_HASH_REF__';
1.168 albertel 4537: return $result;
4538: }
4539:
4540: sub str2hash {
1.265 albertel 4541: my ($string)=@_;
4542: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
4543: return %$hash;
4544: }
4545:
4546: sub str2hashref {
1.168 albertel 4547: my ($string) = @_;
1.265 albertel 4548:
4549: my %hash;
4550:
4551: if($string !~ /^__HASH_REF__/) {
4552: if (! ($string eq '' || !defined($string))) {
4553: $hash{'error'}='Not hash reference';
4554: }
4555: return (\%hash, $string);
4556: }
4557:
4558: $string =~ s/^__HASH_REF__//;
4559:
4560: while($string !~ /^__END_HASH_REF__/) {
4561: #key
4562: my $key='';
4563: if($string =~ /^__HASH_REF__/) {
4564: ($key, $string)=&str2hashref($string);
4565: if(defined($key->{'error'})) {
4566: $hash{'error'}='Bad data';
4567: return (\%hash, $string);
4568: }
4569: } elsif($string =~ /^__ARRAY_REF__/) {
4570: ($key, $string)=&str2arrayref($string);
4571: if($key->[0] eq 'Array reference error') {
4572: $hash{'error'}='Bad data';
4573: return (\%hash, $string);
4574: }
4575: } else {
4576: $string =~ s/^(.*?)=//;
1.267 albertel 4577: $key=&unescape($1);
1.265 albertel 4578: }
4579: $string =~ s/^=//;
4580:
4581: #value
4582: my $value='';
4583: if($string =~ /^__HASH_REF__/) {
4584: ($value, $string)=&str2hashref($string);
4585: if(defined($value->{'error'})) {
4586: $hash{'error'}='Bad data';
4587: return (\%hash, $string);
4588: }
4589: } elsif($string =~ /^__ARRAY_REF__/) {
4590: ($value, $string)=&str2arrayref($string);
4591: if($value->[0] eq 'Array reference error') {
4592: $hash{'error'}='Bad data';
4593: return (\%hash, $string);
4594: }
4595: } else {
4596: $value=&get_scalar(\$string,'__END_HASH_REF__');
4597: }
4598: $string =~ s/^&//;
4599:
4600: $hash{$key}=$value;
1.204 albertel 4601: }
1.265 albertel 4602:
4603: $string =~ s/^__END_HASH_REF__//;
4604:
4605: return (\%hash, $string);
1.204 albertel 4606: }
4607:
4608: sub str2array {
1.265 albertel 4609: my ($string)=@_;
4610: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
4611: return @$array;
4612: }
4613:
4614: sub str2arrayref {
1.204 albertel 4615: my ($string) = @_;
1.265 albertel 4616: my @array;
4617:
4618: if($string !~ /^__ARRAY_REF__/) {
4619: if (! ($string eq '' || !defined($string))) {
4620: $array[0]='Array reference error';
4621: }
4622: return (\@array, $string);
4623: }
4624:
4625: $string =~ s/^__ARRAY_REF__//;
4626:
4627: while($string !~ /^__END_ARRAY_REF__/) {
4628: my $value='';
4629: if($string =~ /^__HASH_REF__/) {
4630: ($value, $string)=&str2hashref($string);
4631: if(defined($value->{'error'})) {
4632: $array[0] ='Array reference error';
4633: return (\@array, $string);
4634: }
4635: } elsif($string =~ /^__ARRAY_REF__/) {
4636: ($value, $string)=&str2arrayref($string);
4637: if($value->[0] eq 'Array reference error') {
4638: $array[0] ='Array reference error';
4639: return (\@array, $string);
4640: }
4641: } else {
4642: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
4643: }
4644: $string =~ s/^&//;
4645:
4646: push(@array, $value);
1.191 harris41 4647: }
1.265 albertel 4648:
4649: $string =~ s/^__END_ARRAY_REF__//;
4650:
4651: return (\@array, $string);
1.168 albertel 4652: }
4653:
1.167 albertel 4654: # -------------------------------------------------------------------Temp Store
4655:
1.168 albertel 4656: sub tmpreset {
4657: my ($symb,$namespace,$domain,$stuname) = @_;
4658: if (!$symb) {
4659: $symb=&symbread();
1.620 albertel 4660: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4661: }
4662: $symb=escape($symb);
4663:
1.620 albertel 4664: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 4665: $namespace=~s/\//\_/g;
4666: $namespace=~s/\W//g;
4667:
1.620 albertel 4668: if (!$domain) { $domain=$env{'user.domain'}; }
4669: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4670: if ($domain eq 'public' && $stuname eq 'public') {
4671: $stuname=$ENV{'REMOTE_ADDR'};
4672: }
1.1117 foxr 4673: my $path=LONCAPA::tempdir();
1.168 albertel 4674: my %hash;
4675: if (tie(%hash,'GDBM_File',
4676: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4677: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 4678: foreach my $key (keys(%hash)) {
1.180 albertel 4679: if ($key=~ /:$symb/) {
1.168 albertel 4680: delete($hash{$key});
4681: }
4682: }
4683: }
4684: }
4685:
1.167 albertel 4686: sub tmpstore {
1.168 albertel 4687: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4688:
4689: if (!$symb) {
4690: $symb=&symbread();
1.620 albertel 4691: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4692: }
4693: $symb=escape($symb);
4694:
4695: if (!$namespace) {
4696: # I don't think we would ever want to store this for a course.
4697: # it seems this will only be used if we don't have a course.
1.620 albertel 4698: #$namespace=$env{'request.course.id'};
1.168 albertel 4699: #if (!$namespace) {
1.620 albertel 4700: $namespace=$env{'request.state'};
1.168 albertel 4701: #}
4702: }
4703: $namespace=~s/\//\_/g;
4704: $namespace=~s/\W//g;
1.620 albertel 4705: if (!$domain) { $domain=$env{'user.domain'}; }
4706: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4707: if ($domain eq 'public' && $stuname eq 'public') {
4708: $stuname=$ENV{'REMOTE_ADDR'};
4709: }
1.168 albertel 4710: my $now=time;
4711: my %hash;
1.1117 foxr 4712: my $path=LONCAPA::tempdir();
1.168 albertel 4713: if (tie(%hash,'GDBM_File',
4714: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4715: &GDBM_WRCREAT(),0640)) {
1.168 albertel 4716: $hash{"version:$symb"}++;
4717: my $version=$hash{"version:$symb"};
4718: my $allkeys='';
4719: foreach my $key (keys(%$storehash)) {
4720: $allkeys.=$key.':';
1.591 albertel 4721: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 4722: }
4723: $hash{"$version:$symb:timestamp"}=$now;
4724: $allkeys.='timestamp';
4725: $hash{"$version:keys:$symb"}=$allkeys;
4726: if (untie(%hash)) {
4727: return 'ok';
4728: } else {
4729: return "error:$!";
4730: }
4731: } else {
4732: return "error:$!";
4733: }
4734: }
1.167 albertel 4735:
1.168 albertel 4736: # -----------------------------------------------------------------Temp Restore
1.167 albertel 4737:
1.168 albertel 4738: sub tmprestore {
4739: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 4740:
1.168 albertel 4741: if (!$symb) {
4742: $symb=&symbread();
1.620 albertel 4743: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4744: }
4745: $symb=escape($symb);
4746:
1.620 albertel 4747: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 4748:
1.620 albertel 4749: if (!$domain) { $domain=$env{'user.domain'}; }
4750: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4751: if ($domain eq 'public' && $stuname eq 'public') {
4752: $stuname=$ENV{'REMOTE_ADDR'};
4753: }
1.168 albertel 4754: my %returnhash;
4755: $namespace=~s/\//\_/g;
4756: $namespace=~s/\W//g;
4757: my %hash;
1.1117 foxr 4758: my $path=LONCAPA::tempdir();
1.168 albertel 4759: if (tie(%hash,'GDBM_File',
4760: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4761: &GDBM_READER(),0640)) {
1.168 albertel 4762: my $version=$hash{"version:$symb"};
4763: $returnhash{'version'}=$version;
4764: my $scope;
4765: for ($scope=1;$scope<=$version;$scope++) {
4766: my $vkeys=$hash{"$scope:keys:$symb"};
4767: my @keys=split(/:/,$vkeys);
4768: my $key;
4769: $returnhash{"$scope:keys"}=$vkeys;
4770: foreach $key (@keys) {
1.591 albertel 4771: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
4772: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 4773: }
4774: }
1.168 albertel 4775: if (!(untie(%hash))) {
4776: return "error:$!";
4777: }
4778: } else {
4779: return "error:$!";
4780: }
4781: return %returnhash;
1.167 albertel 4782: }
4783:
1.9 www 4784: # ----------------------------------------------------------------------- Store
4785:
4786: sub store {
1.124 www 4787: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4788: my $home='';
4789:
1.168 albertel 4790: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4791:
1.213 www 4792: $symb=&symbclean($symb);
1.122 albertel 4793: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 4794:
1.620 albertel 4795: if (!$domain) { $domain=$env{'user.domain'}; }
4796: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 4797:
4798: &devalidate($symb,$stuname,$domain);
1.109 www 4799:
4800: $symb=escape($symb);
1.187 www 4801: if (!$namespace) {
1.620 albertel 4802: unless ($namespace=$env{'request.course.id'}) {
1.187 www 4803: return '';
4804: }
4805: }
1.620 albertel 4806: if (!$home) { $home=$env{'user.home'}; }
1.447 www 4807:
4808: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4809: $$storehash{'host'}=$perlvar{'lonHostID'};
4810:
1.12 www 4811: my $namevalue='';
1.800 albertel 4812: foreach my $key (keys(%$storehash)) {
4813: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 4814: }
1.12 www 4815: $namevalue=~s/\&$//;
1.187 www 4816: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124 www 4817: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9 www 4818: }
4819:
1.47 www 4820: # -------------------------------------------------------------- Critical Store
4821:
4822: sub cstore {
1.124 www 4823: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4824: my $home='';
4825:
1.168 albertel 4826: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4827:
1.213 www 4828: $symb=&symbclean($symb);
1.122 albertel 4829: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 4830:
1.620 albertel 4831: if (!$domain) { $domain=$env{'user.domain'}; }
4832: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 4833:
4834: &devalidate($symb,$stuname,$domain);
1.109 www 4835:
4836: $symb=escape($symb);
1.187 www 4837: if (!$namespace) {
1.620 albertel 4838: unless ($namespace=$env{'request.course.id'}) {
1.187 www 4839: return '';
4840: }
4841: }
1.620 albertel 4842: if (!$home) { $home=$env{'user.home'}; }
1.447 www 4843:
4844: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4845: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 4846:
1.47 www 4847: my $namevalue='';
1.800 albertel 4848: foreach my $key (keys(%$storehash)) {
4849: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 4850: }
1.47 www 4851: $namevalue=~s/\&$//;
1.187 www 4852: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 4853: return critical
4854: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47 www 4855: }
4856:
1.9 www 4857: # --------------------------------------------------------------------- Restore
4858:
4859: sub restore {
1.124 www 4860: my ($symb,$namespace,$domain,$stuname) = @_;
4861: my $home='';
4862:
1.168 albertel 4863: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4864:
1.122 albertel 4865: if (!$symb) {
1.1224 raeburn 4866: return if ($namespace eq 'courserequests');
4867: unless ($symb=escape(&symbread())) { return ''; }
1.122 albertel 4868: } else {
1.1224 raeburn 4869: unless ($namespace eq 'courserequests') {
4870: $symb=&escape(&symbclean($symb));
4871: }
1.122 albertel 4872: }
1.188 www 4873: if (!$namespace) {
1.620 albertel 4874: unless ($namespace=$env{'request.course.id'}) {
1.188 www 4875: return '';
4876: }
4877: }
1.620 albertel 4878: if (!$domain) { $domain=$env{'user.domain'}; }
4879: if (!$stuname) { $stuname=$env{'user.name'}; }
4880: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 4881: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
4882:
1.12 www 4883: my %returnhash=();
1.800 albertel 4884: foreach my $line (split(/\&/,$answer)) {
4885: my ($name,$value)=split(/\=/,$line);
1.591 albertel 4886: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 4887: }
1.75 www 4888: my $version;
4889: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 4890: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
4891: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 4892: }
1.75 www 4893: }
1.13 www 4894: return %returnhash;
1.34 www 4895: }
4896:
4897: # ---------------------------------------------------------- Course Description
1.1118 foxr 4898: #
4899: #
1.34 www 4900:
4901: sub coursedescription {
1.731 albertel 4902: my ($courseid,$args)=@_;
1.34 www 4903: $courseid=~s/^\///;
1.49 www 4904: $courseid=~s/\_/\//g;
1.34 www 4905: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 4906: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 4907: my $normalid=$cdomain.'_'.$cnum;
4908: # need to always cache even if we get errors otherwise we keep
4909: # trying and trying and trying to get the course description.
4910: my %envhash=();
4911: my %returnhash=();
1.731 albertel 4912:
4913: my $expiretime=600;
4914: if ($env{'request.course.id'} eq $normalid) {
4915: $expiretime=120;
4916: }
4917:
4918: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
4919: if (!$args->{'freshen_cache'}
4920: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
4921: foreach my $key (keys(%env)) {
4922: next if ($key !~ /^\Q$prefix\E(.*)/);
4923: my ($setting) = $1;
4924: $returnhash{$setting} = $env{$key};
4925: }
4926: return %returnhash;
4927: }
4928:
1.1118 foxr 4929: # get the data again
4930:
1.731 albertel 4931: if (!$args->{'one_time'}) {
4932: $envhash{'course.'.$normalid.'.last_cache'}=time;
4933: }
1.811 albertel 4934:
1.34 www 4935: if ($chome ne 'no_host') {
1.302 albertel 4936: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 4937: if (!exists($returnhash{'con_lost'})) {
1.1118 foxr 4938: my $username = $env{'user.name'}; # Defult username
4939: if(defined $args->{'user'}) {
4940: $username = $args->{'user'};
4941: }
1.129 albertel 4942: $returnhash{'home'}= $chome;
4943: $returnhash{'domain'} = $cdomain;
4944: $returnhash{'num'} = $cnum;
1.741 raeburn 4945: if (!defined($returnhash{'type'})) {
4946: $returnhash{'type'} = 'Course';
4947: }
1.130 albertel 4948: while (my ($name,$value) = each %returnhash) {
1.53 www 4949: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 4950: }
1.270 www 4951: $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117 foxr 4952: $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118 foxr 4953: $username.'_'.$cdomain.'_'.$cnum;
1.60 www 4954: $envhash{'course.'.$normalid.'.home'}=$chome;
4955: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
4956: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 4957: }
4958: }
1.731 albertel 4959: if (!$args->{'one_time'}) {
1.949 raeburn 4960: &appenv(\%envhash);
1.731 albertel 4961: }
1.302 albertel 4962: return %returnhash;
1.461 www 4963: }
4964:
1.1080 raeburn 4965: sub update_released_required {
4966: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
4967: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
4968: $cid = $env{'request.course.id'};
4969: $cdom = $env{'course.'.$cid.'.domain'};
4970: $cnum = $env{'course.'.$cid.'.num'};
4971: $chome = $env{'course.'.$cid.'.home'};
4972: }
4973: if ($needsrelease) {
4974: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
4975: my $needsupdate;
4976: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
4977: $needsupdate = 1;
4978: } else {
4979: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
4980: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
4981: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
4982: $needsupdate = 1;
4983: }
4984: }
4985: if ($needsupdate) {
4986: my %needshash = (
4987: 'internal.releaserequired' => $needsrelease,
4988: );
4989: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
4990: if ($putresult eq 'ok') {
4991: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
4992: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
4993: if (ref($crsinfo{$cid}) eq 'HASH') {
4994: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
4995: &courseidput($cdom,\%crsinfo,$chome,'notime');
4996: }
4997: }
4998: }
4999: }
5000: return;
5001: }
5002:
1.461 www 5003: # -------------------------------------------------See if a user is privileged
5004:
5005: sub privileged {
1.1219 raeburn 5006: my ($username,$domain,$possdomains,$possroles)=@_;
1.1170 droeschl 5007: my $now = time;
1.1219 raeburn 5008: my $roles;
5009: if (ref($possroles) eq 'ARRAY') {
5010: $roles = $possroles;
5011: } else {
5012: $roles = ['dc','su'];
5013: }
5014: if (ref($possdomains) eq 'ARRAY') {
5015: my %privileged = &privileged_by_domain($possdomains,$roles);
5016: foreach my $dom (@{$possdomains}) {
5017: if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
5018: (ref($privileged{$dom}) eq 'HASH')) {
5019: foreach my $role (@{$roles}) {
5020: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5021: if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
5022: my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
5023: return 1 unless (($end && $end < $now) ||
5024: ($start && $start > $now));
5025: }
5026: }
5027: }
5028: }
5029: }
5030: } else {
5031: my %rolesdump = &dump("roles", $domain, $username) or return 0;
5032: my $now = time;
1.1170 droeschl 5033:
1.1219 raeburn 5034: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys %rolesdump}) {
1.1170 droeschl 5035: my ($trole, $tend, $tstart) = split(/_/, $role);
1.1219 raeburn 5036: if (grep(/^\Q$trole\E$/,@{$roles})) {
1.1170 droeschl 5037: return 1 unless ($tend && $tend < $now)
1.1219 raeburn 5038: or ($tstart && $tstart > $now);
1.1170 droeschl 5039: }
1.1219 raeburn 5040: }
5041: }
5042: return 0;
5043: }
1.1170 droeschl 5044:
1.1219 raeburn 5045: sub privileged_by_domain {
5046: my ($domains,$roles) = @_;
5047: my %privileged = ();
5048: my $cachetime = 60*60*24;
5049: my $now = time;
5050: unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
5051: return %privileged;
5052: }
5053: foreach my $dom (@{$domains}) {
5054: next if (ref($privileged{$dom}) eq 'HASH');
5055: my $needroles;
5056: foreach my $role (@{$roles}) {
5057: my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
5058: if (defined($cached)) {
5059: if (ref($result) eq 'HASH') {
5060: $privileged{$dom}{$role} = $result;
5061: }
5062: } else {
5063: $needroles = 1;
5064: }
5065: }
5066: if ($needroles) {
5067: my %dompersonnel = &get_domain_roles($dom,$roles);
5068: $privileged{$dom} = {};
5069: foreach my $server (keys(%dompersonnel)) {
5070: if (ref($dompersonnel{$server}) eq 'HASH') {
5071: foreach my $item (keys(%{$dompersonnel{$server}})) {
5072: my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
5073: my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
5074: next if ($end && $end < $now);
5075: $privileged{$dom}{$trole}{$uname.':'.$udom} =
5076: $dompersonnel{$server}{$item};
5077: }
5078: }
5079: }
5080: if (ref($privileged{$dom}) eq 'HASH') {
5081: foreach my $role (@{$roles}) {
5082: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5083: &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
5084: } else {
5085: my %hash = ();
5086: &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
5087: }
5088: }
5089: }
5090: }
5091: }
5092: return %privileged;
1.9 www 5093: }
1.1 albertel 5094:
1.103 harris41 5095: # -------------------------------------------------------- Get user privileges
1.11 www 5096:
5097: sub rolesinit {
1.1169 droeschl 5098: my ($domain, $username) = @_;
5099: my %userroles = ('user.login.time' => time);
5100: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
5101:
5102: # firstaccess and timerinterval are related to timed maps/resources.
5103: # also, blocking can be triggered by an activating timer
5104: # it's saved in the user's %env.
5105: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
5106: my %timerinterval = &dump('timerinterval', $domain, $username);
5107: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
5108: %timerintchk, %timerintenv);
5109:
1.1162 raeburn 5110: foreach my $key (keys(%firstaccess)) {
1.1169 droeschl 5111: my ($cid, $rest) = split(/\0/, $key);
1.1162 raeburn 5112: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
5113: }
1.1169 droeschl 5114:
1.1162 raeburn 5115: foreach my $key (keys(%timerinterval)) {
5116: my ($cid,$rest) = split(/\0/,$key);
5117: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
5118: }
1.1169 droeschl 5119:
1.11 www 5120: my %allroles=();
1.1162 raeburn 5121: my %allgroups=();
1.11 www 5122:
1.1169 droeschl 5123: for my $area (grep { ! /^rolesdef_/ } keys %rolesdump) {
5124: my $role = $rolesdump{$area};
5125: $area =~ s/\_\w\w$//;
5126:
5127: my ($trole, $tend, $tstart, $group_privs);
5128:
5129: if ($role =~ /^cr/) {
5130: # Custom role, defined by a user
5131: # e.g., user.role.cr/msu/smith/mynewrole
5132: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
5133: $trole = $1;
5134: ($tend, $tstart) = split('_', $2);
5135: } else {
5136: $trole = $role;
5137: }
5138: } elsif ($role =~ m|^gr/|) {
5139: # Role of member in a group, defined within a course/community
5140: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
5141: ($trole, $tend, $tstart) = split(/_/, $role);
5142: next if $tstart eq '-1';
5143: ($trole, $group_privs) = split(/\//, $trole);
5144: $group_privs = &unescape($group_privs);
5145: } else {
5146: # Just a normal role, defined in roles.tab
5147: ($trole, $tend, $tstart) = split(/_/,$role);
5148: }
5149:
5150: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
5151: $username);
5152: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
5153:
5154: # role expired or not available yet?
5155: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
5156: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
5157:
5158: next if $area eq '' or $trole eq '';
5159:
5160: my $spec = "$trole.$area";
5161: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
5162:
5163: if ($trole =~ /^cr\//) {
5164: # Custom role, defined by a user
5165: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5166: } elsif ($trole eq 'gr') {
5167: # Role of a member in a group, defined within a course/community
5168: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
5169: next;
5170: } else {
5171: # Normal role, defined in roles.tab
5172: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5173: }
5174:
5175: my $cid = $tdomain.'_'.$trest;
5176: unless ($firstaccchk{$cid}) {
5177: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
5178: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
5179: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
5180: $coursetimerstarts{$cid}{$item};
5181: }
5182: }
5183: $firstaccchk{$cid} = 1;
5184: }
5185: unless ($timerintchk{$cid}) {
5186: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
5187: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
5188: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
5189: $coursetimerintervals{$cid}{$item};
1.1162 raeburn 5190: }
1.12 www 5191: }
1.1169 droeschl 5192: $timerintchk{$cid} = 1;
1.191 harris41 5193: }
1.11 www 5194: }
1.1169 droeschl 5195:
5196: @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
5197: \%allroles, \%allgroups);
5198: $env{'user.adv'} = $userroles{'user.adv'};
5199:
1.1162 raeburn 5200: return (\%userroles,\%firstaccenv,\%timerintenv);
1.11 www 5201: }
5202:
1.567 raeburn 5203: sub set_arearole {
1.1215 raeburn 5204: my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
5205: unless ($nolog) {
1.567 raeburn 5206: # log the associated role with the area
1.1215 raeburn 5207: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
5208: }
1.743 albertel 5209: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 5210: }
5211:
5212: sub custom_roleprivs {
5213: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
5214: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
5215: my $homsvr=homeserver($rauthor,$rdomain);
1.838 albertel 5216: if (&hostname($homsvr) ne '') {
1.567 raeburn 5217: my ($rdummy,$roledef)=
5218: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
5219: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
5220: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
5221: if (defined($syspriv)) {
1.1043 raeburn 5222: if ($trest =~ /^$match_community$/) {
5223: $syspriv =~ s/bre\&S//;
5224: }
1.567 raeburn 5225: $$allroles{'cm./'}.=':'.$syspriv;
5226: $$allroles{$spec.'./'}.=':'.$syspriv;
5227: }
5228: if ($tdomain ne '') {
5229: if (defined($dompriv)) {
5230: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
5231: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
5232: }
5233: if (($trest ne '') && (defined($coursepriv))) {
5234: $$allroles{'cm.'.$area}.=':'.$coursepriv;
5235: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
5236: }
5237: }
5238: }
5239: }
5240: }
5241:
1.678 raeburn 5242: sub group_roleprivs {
5243: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
5244: my $access = 1;
5245: my $now = time;
5246: if (($tend!=0) && ($tend<$now)) { $access = 0; }
5247: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
5248: if ($access) {
1.811 albertel 5249: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 5250: $$allgroups{$course}{$group} .=':'.$group_privs;
5251: }
5252: }
1.567 raeburn 5253:
5254: sub standard_roleprivs {
5255: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
5256: if (defined($pr{$trole.':s'})) {
5257: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
5258: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
5259: }
5260: if ($tdomain ne '') {
5261: if (defined($pr{$trole.':d'})) {
5262: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5263: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5264: }
5265: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
5266: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
5267: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
5268: }
5269: }
5270: }
5271:
5272: sub set_userprivs {
1.1064 raeburn 5273: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 5274: my $author=0;
5275: my $adv=0;
1.678 raeburn 5276: my %grouproles = ();
5277: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 5278: my @groupkeys;
1.1000 raeburn 5279: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 5280: push(@groupkeys,$role);
5281: }
5282: if (ref($groups_roles) eq 'HASH') {
5283: foreach my $key (keys(%{$groups_roles})) {
5284: unless (grep(/^\Q$key\E$/,@groupkeys)) {
5285: push(@groupkeys,$key);
5286: }
5287: }
5288: }
5289: if (@groupkeys > 0) {
5290: foreach my $role (@groupkeys) {
5291: my ($trole,$area,$sec,$extendedarea);
5292: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
5293: $trole = $1;
5294: $area = $2;
5295: $sec = $3;
5296: $extendedarea = $area.$sec;
5297: if (exists($$allgroups{$area})) {
5298: foreach my $group (keys(%{$$allgroups{$area}})) {
5299: my $spec = $trole.'.'.$extendedarea;
5300: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 5301: $$allgroups{$area}{$group};
1.1064 raeburn 5302: }
1.678 raeburn 5303: }
5304: }
5305: }
5306: }
5307: }
1.800 albertel 5308: foreach my $group (keys(%grouproles)) {
5309: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 5310: }
1.800 albertel 5311: foreach my $role (keys(%{$allroles})) {
5312: my %thesepriv;
1.941 raeburn 5313: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 5314: foreach my $item (split(/:/,$$allroles{$role})) {
5315: if ($item ne '') {
5316: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 5317: if ($restrictions eq '') {
5318: $thesepriv{$privilege}='F';
5319: } elsif ($thesepriv{$privilege} ne 'F') {
5320: $thesepriv{$privilege}.=$restrictions;
5321: }
5322: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
5323: }
5324: }
5325: my $thesestr='';
1.1104 raeburn 5326: foreach my $priv (sort(keys(%thesepriv))) {
1.800 albertel 5327: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
5328: }
5329: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 5330: }
5331: return ($author,$adv);
5332: }
5333:
1.994 raeburn 5334: sub role_status {
1.1104 raeburn 5335: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 5336: my @pwhere = ();
5337: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
5338: (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
5339: unless (!defined($$role) || $$role eq '') {
5340: $$where=join('.',@pwhere);
5341: $$trolecode=$$role.'.'.$$where;
5342: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
5343: $$tstatus='is';
1.1104 raeburn 5344: if ($$tstart && $$tstart>$update) {
1.994 raeburn 5345: $$tstatus='future';
1.1034 raeburn 5346: if ($$tstart<$now) {
5347: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 5348: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 5349: my (%allroles,%allgroups,$group_privs,
5350: %groups_roles,@rolecodes);
1.1002 raeburn 5351: my %userroles = (
5352: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
5353: );
1.1064 raeburn 5354: @rolecodes = ('cm');
1.1002 raeburn 5355: my $spec=$$role.'.'.$$where;
5356: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
5357: if ($$role =~ /^cr\//) {
5358: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 5359: push(@rolecodes,'cr');
1.1002 raeburn 5360: } elsif ($$role eq 'gr') {
1.1064 raeburn 5361: push(@rolecodes,$$role);
1.1002 raeburn 5362: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
5363: $env{'user.name'});
1.1064 raeburn 5364: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 5365: (undef,my $group_privs) = split(/\//,$trole);
5366: $group_privs = &unescape($group_privs);
5367: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 5368: 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 5369: &get_groups_roles($tdomain,$trest,
5370: \%course_roles,\@rolecodes,
5371: \%groups_roles);
1.1002 raeburn 5372: } else {
1.1064 raeburn 5373: push(@rolecodes,$$role);
1.1002 raeburn 5374: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
5375: }
1.1064 raeburn 5376: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
5377: &appenv(\%userroles,\@rolecodes);
1.1002 raeburn 5378: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
5379: }
5380: }
1.1034 raeburn 5381: $$tstatus = 'is';
1.1002 raeburn 5382: }
1.994 raeburn 5383: }
5384: if ($$tend) {
1.1104 raeburn 5385: if ($$tend<$update) {
1.994 raeburn 5386: $$tstatus='expired';
5387: } elsif ($$tend<$now) {
5388: $$tstatus='will_not';
5389: }
5390: }
5391: }
5392: }
5393: }
5394:
1.1104 raeburn 5395: sub get_groups_roles {
5396: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
5397: return unless((ref($cdom_courseroles) eq 'HASH') &&
5398: (ref($rolecodes) eq 'ARRAY') &&
5399: (ref($groups_roles) eq 'HASH'));
5400: if (keys(%{$cdom_courseroles}) > 0) {
5401: my ($cnum) = ($rest =~ /^($match_courseid)/);
5402: if ($cdom ne '' && $cnum ne '') {
5403: foreach my $key (keys(%{$cdom_courseroles})) {
5404: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
5405: my $crsrole = $1;
5406: my $crssec = $2;
5407: if ($crsrole =~ /^cr/) {
5408: unless (grep(/^cr$/,@{$rolecodes})) {
5409: push(@{$rolecodes},'cr');
5410: }
5411: } else {
5412: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
5413: push(@{$rolecodes},$crsrole);
5414: }
5415: }
5416: my $rolekey = "$crsrole./$cdom/$cnum";
5417: if ($crssec ne '') {
5418: $rolekey .= "/$crssec";
5419: }
5420: $rolekey .= './';
5421: $groups_roles->{$rolekey} = $rolecodes;
5422: }
5423: }
5424: }
5425: }
5426: return;
5427: }
5428:
5429: sub delete_env_groupprivs {
5430: my ($where,$courseroles,$possroles) = @_;
5431: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
5432: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
5433: unless (ref($courseroles->{$udom}) eq 'HASH') {
5434: %{$courseroles->{$udom}} =
5435: &get_my_roles('','','userroles',['active'],
5436: $possroles,[$udom],1);
5437: }
5438: if (ref($courseroles->{$udom}) eq 'HASH') {
5439: foreach my $item (keys(%{$courseroles->{$udom}})) {
5440: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
5441: my $area = '/'.$cdom.'/'.$cnum;
5442: my $privkey = "user.priv.$crsrole.$area";
5443: if ($crssec ne '') {
5444: $privkey .= '/'.$crssec;
5445: }
5446: $privkey .= ".$area/$group";
5447: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
5448: }
5449: }
5450: return;
5451: }
5452:
1.994 raeburn 5453: sub check_adhoc_privs {
1.1104 raeburn 5454: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994 raeburn 5455: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1185 raeburn 5456: my $setprivs;
1.994 raeburn 5457: if ($env{$cckey}) {
5458: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104 raeburn 5459: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 5460: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088 raeburn 5461: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185 raeburn 5462: $setprivs = 1;
1.994 raeburn 5463: }
5464: } else {
1.1088 raeburn 5465: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185 raeburn 5466: $setprivs = 1;
1.994 raeburn 5467: }
1.1185 raeburn 5468: return $setprivs;
1.994 raeburn 5469: }
5470:
5471: sub set_adhoc_privileges {
5472: # role can be cc or ca
1.1088 raeburn 5473: my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994 raeburn 5474: my $area = '/'.$dcdom.'/'.$pickedcourse;
5475: my $spec = $role.'.'.$area;
5476: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1215 raeburn 5477: $env{'user.name'},1);
1.994 raeburn 5478: my %ccrole = ();
5479: &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
5480: my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
5481: &appenv(\%userroles,[$role,'cm']);
5482: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088 raeburn 5483: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
5484: &appenv( {'request.role' => $spec,
5485: 'request.role.domain' => $dcdom,
5486: 'request.course.sec' => ''
5487: }
5488: );
5489: my $tadv=0;
5490: if (&allowed('adv') eq 'F') { $tadv=1; }
5491: &appenv({'request.role.adv' => $tadv});
5492: }
1.994 raeburn 5493: }
5494:
1.12 www 5495: # --------------------------------------------------------------- get interface
5496:
5497: sub get {
1.131 albertel 5498: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 5499: my $items='';
1.800 albertel 5500: foreach my $item (@$storearr) {
5501: $items.=&escape($item).'&';
1.191 harris41 5502: }
1.12 www 5503: $items=~s/\&$//;
1.620 albertel 5504: if (!$udomain) { $udomain=$env{'user.domain'}; }
5505: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 5506: my $uhome=&homeserver($uname,$udomain);
5507:
1.133 albertel 5508: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 5509: my @pairs=split(/\&/,$rep);
1.273 albertel 5510: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
5511: return @pairs;
5512: }
1.15 www 5513: my %returnhash=();
1.42 www 5514: my $i=0;
1.800 albertel 5515: foreach my $item (@$storearr) {
5516: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 5517: $i++;
1.191 harris41 5518: }
1.15 www 5519: return %returnhash;
1.27 www 5520: }
5521:
5522: # --------------------------------------------------------------- del interface
5523:
5524: sub del {
1.133 albertel 5525: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 5526: my $items='';
1.800 albertel 5527: foreach my $item (@$storearr) {
5528: $items.=&escape($item).'&';
1.191 harris41 5529: }
1.984 neumanie 5530:
1.27 www 5531: $items=~s/\&$//;
1.620 albertel 5532: if (!$udomain) { $udomain=$env{'user.domain'}; }
5533: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 5534: my $uhome=&homeserver($uname,$udomain);
5535: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 5536: }
5537:
5538: # -------------------------------------------------------------- dump interface
5539:
1.1180 droeschl 5540: sub unserialize {
5541: my ($rep, $escapedkeys) = @_;
5542:
5543: return {} if $rep =~ /^error/;
5544:
5545: my %returnhash=();
5546: foreach my $item (split /\&/, $rep) {
5547: my ($key, $value) = split(/=/, $item, 2);
5548: $key = unescape($key) unless $escapedkeys;
5549: next if $key =~ /^error: 2 /;
5550: $returnhash{$key} = Apache::lonnet::thaw_unescape($value);
5551: }
5552: #return %returnhash;
5553: return \%returnhash;
5554: }
5555:
5556: # see Lond::dump_with_regexp
5557: # if $escapedkeys hash keys won't get unescaped.
1.15 www 5558: sub dump {
1.1180 droeschl 5559: my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755 albertel 5560: if (!$udomain) { $udomain=$env{'user.domain'}; }
5561: if (!$uname) { $uname=$env{'user.name'}; }
5562: my $uhome=&homeserver($uname,$udomain);
1.1167 droeschl 5563:
1.1180 droeschl 5564: my $reply;
5565: if (grep { $_ eq $uhome } current_machine_ids()) {
5566: # user is hosted on this machine
5567: $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
1.1226 raeburn 5568: $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1180 droeschl 5569: return %{unserialize($reply, $escapedkeys)};
5570: }
1.755 albertel 5571: if ($regexp) {
5572: $regexp=&escape($regexp);
5573: } else {
5574: $regexp='.';
5575: }
1.1166 raeburn 5576: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755 albertel 5577: my @pairs=split(/\&/,$rep);
5578: my %returnhash=();
1.1098 foxr 5579: if (!($rep =~ /^error/ )) {
5580: foreach my $item (@pairs) {
5581: my ($key,$value)=split(/=/,$item,2);
1.1180 droeschl 5582: $key = unescape($key) unless $escapedkeys;
5583: #$key = &unescape($key);
1.1098 foxr 5584: next if ($key =~ /^error: 2 /);
5585: $returnhash{$key}=&thaw_unescape($value);
5586: }
1.755 albertel 5587: }
5588: return %returnhash;
1.407 www 5589: }
5590:
1.1098 foxr 5591:
1.717 albertel 5592: # --------------------------------------------------------- dumpstore interface
5593:
5594: sub dumpstore {
5595: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180 droeschl 5596: # same as dump but keys must be escaped. They may contain colon separated
5597: # lists of values that may themself contain colons (e.g. symbs).
5598: return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717 albertel 5599: }
5600:
1.407 www 5601: # -------------------------------------------------------------- keys interface
5602:
5603: sub getkeys {
5604: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 5605: if (!$udomain) { $udomain=$env{'user.domain'}; }
5606: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 5607: my $uhome=&homeserver($uname,$udomain);
5608: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
5609: my @keyarray=();
1.800 albertel 5610: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 5611: next if ($key =~ /^error: 2 /);
1.800 albertel 5612: push(@keyarray,&unescape($key));
1.407 www 5613: }
5614: return @keyarray;
1.318 matthew 5615: }
5616:
1.319 matthew 5617: # --------------------------------------------------------------- currentdump
5618: sub currentdump {
1.328 matthew 5619: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 5620: $courseid = $env{'request.course.id'} if (! defined($courseid));
5621: $sdom = $env{'user.domain'} if (! defined($sdom));
5622: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 5623: my $uhome = &homeserver($sname,$sdom);
1.1180 droeschl 5624: my $rep;
5625:
5626: if (grep { $_ eq $uhome } current_machine_ids()) {
5627: $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
5628: $courseid)));
5629: } else {
5630: $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
5631: }
5632:
1.318 matthew 5633: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 5634: #
1.318 matthew 5635: my %returnhash=();
1.319 matthew 5636: #
5637: if ($rep eq "unknown_cmd") {
5638: # an old lond will not know currentdump
5639: # Do a dump and make it look like a currentdump
1.822 albertel 5640: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 5641: return if ($tmp[0] =~ /^(error:|no_such_host)/);
5642: my %hash = @tmp;
5643: @tmp=();
1.424 matthew 5644: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 5645: } else {
5646: my @pairs=split(/\&/,$rep);
1.800 albertel 5647: foreach my $pair (@pairs) {
5648: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 5649: my ($symb,$param) = split(/:/,$key);
5650: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 5651: &thaw_unescape($value);
1.319 matthew 5652: }
1.191 harris41 5653: }
1.12 www 5654: return %returnhash;
1.424 matthew 5655: }
5656:
5657: sub convert_dump_to_currentdump{
5658: my %hash = %{shift()};
5659: my %returnhash;
5660: # Code ripped from lond, essentially. The only difference
5661: # here is the unescaping done by lonnet::dump(). Conceivably
5662: # we might run in to problems with parameter names =~ /^v\./
5663: while (my ($key,$value) = each(%hash)) {
5664: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 5665: $symb = &unescape($symb);
5666: $param = &unescape($param);
1.424 matthew 5667: next if ($v eq 'version' || $symb eq 'keys');
5668: next if (exists($returnhash{$symb}) &&
5669: exists($returnhash{$symb}->{$param}) &&
5670: $returnhash{$symb}->{'v.'.$param} > $v);
5671: $returnhash{$symb}->{$param}=$value;
5672: $returnhash{$symb}->{'v.'.$param}=$v;
5673: }
5674: #
5675: # Remove all of the keys in the hashes which keep track of
5676: # the version of the parameter.
5677: while (my ($symb,$param_hash) = each(%returnhash)) {
5678: # use a foreach because we are going to delete from the hash.
5679: foreach my $key (keys(%$param_hash)) {
5680: delete($param_hash->{$key}) if ($key =~ /^v\./);
5681: }
5682: }
5683: return \%returnhash;
1.12 www 5684: }
5685:
1.627 albertel 5686: # ------------------------------------------------------ critical inc interface
5687:
5688: sub cinc {
5689: return &inc(@_,'critical');
5690: }
5691:
1.449 matthew 5692: # --------------------------------------------------------------- inc interface
5693:
5694: sub inc {
1.627 albertel 5695: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 5696: if (!$udomain) { $udomain=$env{'user.domain'}; }
5697: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 5698: my $uhome=&homeserver($uname,$udomain);
5699: my $items='';
5700: if (! ref($store)) {
5701: # got a single value, so use that instead
5702: $items = &escape($store).'=&';
5703: } elsif (ref($store) eq 'SCALAR') {
5704: $items = &escape($$store).'=&';
5705: } elsif (ref($store) eq 'ARRAY') {
5706: $items = join('=&',map {&escape($_);} @{$store});
5707: } elsif (ref($store) eq 'HASH') {
5708: while (my($key,$value) = each(%{$store})) {
5709: $items.= &escape($key).'='.&escape($value).'&';
5710: }
5711: }
5712: $items=~s/\&$//;
1.627 albertel 5713: if ($critical) {
5714: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
5715: } else {
5716: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
5717: }
1.449 matthew 5718: }
5719:
1.12 www 5720: # --------------------------------------------------------------- put interface
5721:
5722: sub put {
1.134 albertel 5723: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 5724: if (!$udomain) { $udomain=$env{'user.domain'}; }
5725: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 5726: my $uhome=&homeserver($uname,$udomain);
1.12 www 5727: my $items='';
1.800 albertel 5728: foreach my $item (keys(%$storehash)) {
5729: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 5730: }
1.12 www 5731: $items=~s/\&$//;
1.134 albertel 5732: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 5733: }
5734:
1.631 albertel 5735: # ------------------------------------------------------------ newput interface
5736:
5737: sub newput {
5738: my ($namespace,$storehash,$udomain,$uname)=@_;
5739: if (!$udomain) { $udomain=$env{'user.domain'}; }
5740: if (!$uname) { $uname=$env{'user.name'}; }
5741: my $uhome=&homeserver($uname,$udomain);
5742: my $items='';
5743: foreach my $key (keys(%$storehash)) {
5744: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
5745: }
5746: $items=~s/\&$//;
5747: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
5748: }
5749:
5750: # --------------------------------------------------------- putstore interface
5751:
1.524 raeburn 5752: sub putstore {
1.715 albertel 5753: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620 albertel 5754: if (!$udomain) { $udomain=$env{'user.domain'}; }
5755: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 5756: my $uhome=&homeserver($uname,$udomain);
5757: my $items='';
1.715 albertel 5758: foreach my $key (keys(%$storehash)) {
5759: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 5760: }
1.715 albertel 5761: $items=~s/\&$//;
1.716 albertel 5762: my $esc_symb=&escape($symb);
5763: my $esc_v=&escape($version);
1.715 albertel 5764: my $reply =
1.716 albertel 5765: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 5766: $uhome);
5767: if ($reply eq 'unknown_cmd') {
1.716 albertel 5768: # gfall back to way things use to be done
1.715 albertel 5769: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
5770: $uname);
1.524 raeburn 5771: }
1.715 albertel 5772: return $reply;
5773: }
5774:
5775: sub old_putstore {
1.716 albertel 5776: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
5777: if (!$udomain) { $udomain=$env{'user.domain'}; }
5778: if (!$uname) { $uname=$env{'user.name'}; }
5779: my $uhome=&homeserver($uname,$udomain);
5780: my %newstorehash;
1.800 albertel 5781: foreach my $item (keys(%$storehash)) {
5782: my $key = $version.':'.&escape($symb).':'.$item;
5783: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 5784: }
5785: my $items='';
5786: my %allitems = ();
1.800 albertel 5787: foreach my $item (keys(%newstorehash)) {
5788: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 5789: my $key = $1.':keys:'.$2;
5790: $allitems{$key} .= $3.':';
5791: }
1.800 albertel 5792: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 5793: }
1.800 albertel 5794: foreach my $item (keys(%allitems)) {
5795: $allitems{$item} =~ s/\:$//;
5796: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 5797: }
5798: $items=~s/\&$//;
5799: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 5800: }
5801:
1.47 www 5802: # ------------------------------------------------------ critical put interface
5803:
5804: sub cput {
1.134 albertel 5805: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 5806: if (!$udomain) { $udomain=$env{'user.domain'}; }
5807: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 5808: my $uhome=&homeserver($uname,$udomain);
1.47 www 5809: my $items='';
1.800 albertel 5810: foreach my $item (keys(%$storehash)) {
5811: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 5812: }
1.47 www 5813: $items=~s/\&$//;
1.134 albertel 5814: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 5815: }
5816:
5817: # -------------------------------------------------------------- eget interface
5818:
5819: sub eget {
1.133 albertel 5820: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 5821: my $items='';
1.800 albertel 5822: foreach my $item (@$storearr) {
5823: $items.=&escape($item).'&';
1.191 harris41 5824: }
1.12 www 5825: $items=~s/\&$//;
1.620 albertel 5826: if (!$udomain) { $udomain=$env{'user.domain'}; }
5827: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 5828: my $uhome=&homeserver($uname,$udomain);
5829: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 5830: my @pairs=split(/\&/,$rep);
5831: my %returnhash=();
1.42 www 5832: my $i=0;
1.800 albertel 5833: foreach my $item (@$storearr) {
5834: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 5835: $i++;
1.191 harris41 5836: }
1.12 www 5837: return %returnhash;
5838: }
5839:
1.667 albertel 5840: # ------------------------------------------------------------ tmpput interface
5841: sub tmpput {
1.802 raeburn 5842: my ($storehash,$server,$context)=@_;
1.667 albertel 5843: my $items='';
1.800 albertel 5844: foreach my $item (keys(%$storehash)) {
5845: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 5846: }
5847: $items=~s/\&$//;
1.802 raeburn 5848: if (defined($context)) {
5849: $items .= ':'.&escape($context);
5850: }
1.667 albertel 5851: return &reply("tmpput:$items",$server);
5852: }
5853:
5854: # ------------------------------------------------------------ tmpget interface
5855: sub tmpget {
1.688 albertel 5856: my ($token,$server)=@_;
5857: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5858: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 5859: my %returnhash;
5860: foreach my $item (split(/\&/,$rep)) {
5861: my ($key,$value)=split(/=/,$item);
1.951 raeburn 5862: next if ($key =~ /^error: 2 /);
1.667 albertel 5863: $returnhash{&unescape($key)}=&thaw_unescape($value);
5864: }
5865: return %returnhash;
5866: }
5867:
1.1113 raeburn 5868: # ------------------------------------------------------------ tmpdel interface
1.688 albertel 5869: sub tmpdel {
5870: my ($token,$server)=@_;
5871: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5872: return &reply("tmpdel:$token",$server);
5873: }
5874:
1.1198 raeburn 5875: # ------------------------------------------------------------ get_timebased_id
5876:
5877: sub get_timebased_id {
5878: my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
5879: $maxtries) = @_;
5880: my ($newid,$error,$dellock);
5881: unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
5882: return ('','ok','invalid call to get suffix');
5883: }
5884:
5885: # set defaults for any optional args for which values were not supplied
5886: if ($who eq '') {
5887: $who = $env{'user.name'}.':'.$env{'user.domain'};
5888: }
5889: if (!$locktries) {
5890: $locktries = 3;
5891: }
5892: if (!$maxtries) {
5893: $maxtries = 10;
5894: }
5895:
5896: if (($cdom eq '') || ($cnum eq '')) {
5897: if ($env{'request.course.id'}) {
5898: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
5899: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
5900: }
5901: if (($cdom eq '') || ($cnum eq '')) {
5902: return ('','ok','call to get suffix not in course context');
5903: }
5904: }
5905:
5906: # construct locking item
5907: my $lockhash = {
5908: $prefix."\0".'locked_'.$keyid => $who,
5909: };
5910: my $tries = 0;
5911:
5912: # attempt to get lock on nohist_$namespace file
5913: my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
5914: while (($gotlock ne 'ok') && $tries <$locktries) {
5915: $tries ++;
5916: sleep 1;
5917: $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
5918: }
5919:
5920: # attempt to get unique identifier, based on current timestamp
5921: if ($gotlock eq 'ok') {
5922: my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
5923: my $id = time;
5924: $newid = $id;
5925: my $idtries = 0;
5926: while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
5927: if ($idtype eq 'concat') {
5928: $newid = $id.$idtries;
5929: } else {
5930: $newid ++;
5931: }
5932: $idtries ++;
5933: }
5934: if (!exists($inuse{$prefix."\0".$newid})) {
5935: my %new_item = (
5936: $prefix."\0".$newid => $who,
5937: );
5938: my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
5939: $cdom,$cnum);
5940: if ($putresult ne 'ok') {
5941: undef($newid);
5942: $error = 'error saving new item: '.$putresult;
5943: }
5944: } else {
5945: $error = ('error: no unique suffix available for the new item ');
5946: }
5947: # remove lock
5948: my @del_lock = ($prefix."\0".'locked_'.$keyid);
5949: $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
5950: } else {
5951: $error = "error: could not obtain lockfile\n";
5952: $dellock = 'ok';
5953: }
5954: return ($newid,$dellock,$error);
5955: }
5956:
1.765 albertel 5957: # -------------------------------------------------- portfolio access checking
5958:
5959: sub portfolio_access {
1.766 albertel 5960: my ($requrl) = @_;
1.765 albertel 5961: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
5962: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814 raeburn 5963: if ($result) {
5964: my %setters;
5965: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
5966: my ($startblock,$endblock) =
5967: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
5968: if ($startblock && $endblock) {
5969: return 'B';
5970: }
5971: } else {
5972: my ($startblock,$endblock) =
5973: &Apache::loncommon::blockcheck(\%setters,'port');
5974: if ($startblock && $endblock) {
5975: return 'B';
5976: }
5977: }
5978: }
1.765 albertel 5979: if ($result eq 'ok') {
1.766 albertel 5980: return 'F';
1.765 albertel 5981: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 5982: return 'A';
1.765 albertel 5983: }
1.766 albertel 5984: return '';
1.765 albertel 5985: }
5986:
5987: sub get_portfolio_access {
1.767 albertel 5988: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
5989:
5990: if (!ref($access_hash)) {
5991: my $current_perms = &get_portfile_permissions($udom,$unum);
5992: my %access_controls = &get_access_controls($current_perms,$group,
5993: $file_name);
5994: $access_hash = $access_controls{$file_name};
5995: }
5996:
1.765 albertel 5997: my ($public,$guest,@domains,@users,@courses,@groups);
5998: my $now = time;
5999: if (ref($access_hash) eq 'HASH') {
6000: foreach my $key (keys(%{$access_hash})) {
6001: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
6002: if ($start > $now) {
6003: next;
6004: }
6005: if ($end && $end<$now) {
6006: next;
6007: }
6008: if ($scope eq 'public') {
6009: $public = $key;
6010: last;
6011: } elsif ($scope eq 'guest') {
6012: $guest = $key;
6013: } elsif ($scope eq 'domains') {
6014: push(@domains,$key);
6015: } elsif ($scope eq 'users') {
6016: push(@users,$key);
6017: } elsif ($scope eq 'course') {
6018: push(@courses,$key);
6019: } elsif ($scope eq 'group') {
6020: push(@groups,$key);
6021: }
6022: }
6023: if ($public) {
6024: return 'ok';
6025: }
6026: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6027: if ($guest) {
6028: return $guest;
6029: }
6030: } else {
6031: if (@domains > 0) {
6032: foreach my $domkey (@domains) {
6033: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
6034: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
6035: return 'ok';
6036: }
6037: }
6038: }
6039: }
6040: if (@users > 0) {
6041: foreach my $userkey (@users) {
1.865 raeburn 6042: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
6043: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
6044: if (ref($item) eq 'HASH') {
6045: if (($item->{'uname'} eq $env{'user.name'}) &&
6046: ($item->{'udom'} eq $env{'user.domain'})) {
6047: return 'ok';
6048: }
6049: }
6050: }
6051: }
1.765 albertel 6052: }
6053: }
6054: my %roleshash;
6055: my @courses_and_groups = @courses;
6056: push(@courses_and_groups,@groups);
6057: if (@courses_and_groups > 0) {
6058: my (%allgroups,%allroles);
6059: my ($start,$end,$role,$sec,$group);
6060: foreach my $envkey (%env) {
1.1060 raeburn 6061: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6062: my $cid = $2.'_'.$3;
6063: if ($1 eq 'gr') {
6064: $group = $4;
6065: $allgroups{$cid}{$group} = $env{$envkey};
6066: } else {
6067: if ($4 eq '') {
6068: $sec = 'none';
6069: } else {
6070: $sec = $4;
6071: }
6072: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6073: }
1.811 albertel 6074: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6075: my $cid = $2.'_'.$3;
6076: if ($4 eq '') {
6077: $sec = 'none';
6078: } else {
6079: $sec = $4;
6080: }
6081: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6082: }
6083: }
6084: if (keys(%allroles) == 0) {
6085: return;
6086: }
6087: foreach my $key (@courses_and_groups) {
6088: my %content = %{$$access_hash{$key}};
6089: my $cnum = $content{'number'};
6090: my $cdom = $content{'domain'};
6091: my $cid = $cdom.'_'.$cnum;
6092: if (!exists($allroles{$cid})) {
6093: next;
6094: }
6095: foreach my $role_id (keys(%{$content{'roles'}})) {
6096: my @sections = @{$content{'roles'}{$role_id}{'section'}};
6097: my @groups = @{$content{'roles'}{$role_id}{'group'}};
6098: my @status = @{$content{'roles'}{$role_id}{'access'}};
6099: my @roles = @{$content{'roles'}{$role_id}{'role'}};
6100: foreach my $role (keys(%{$allroles{$cid}})) {
6101: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
6102: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
6103: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
6104: if (grep/^all$/,@sections) {
6105: return 'ok';
6106: } else {
6107: if (grep/^$sec$/,@sections) {
6108: return 'ok';
6109: }
6110: }
6111: }
6112: }
6113: if (keys(%{$allgroups{$cid}}) == 0) {
6114: if (grep/^none$/,@groups) {
6115: return 'ok';
6116: }
6117: } else {
6118: if (grep/^all$/,@groups) {
6119: return 'ok';
6120: }
6121: foreach my $group (keys(%{$allgroups{$cid}})) {
6122: if (grep/^$group$/,@groups) {
6123: return 'ok';
6124: }
6125: }
6126: }
6127: }
6128: }
6129: }
6130: }
6131: }
6132: if ($guest) {
6133: return $guest;
6134: }
6135: }
6136: }
6137: return;
6138: }
6139:
6140: sub course_group_datechecker {
6141: my ($dates,$now,$status) = @_;
6142: my ($start,$end) = split(/\./,$dates);
6143: if (!$start && !$end) {
6144: return 'ok';
6145: }
6146: if (grep/^active$/,@{$status}) {
6147: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
6148: return 'ok';
6149: }
6150: }
6151: if (grep/^previous$/,@{$status}) {
6152: if ($end > $now ) {
6153: return 'ok';
6154: }
6155: }
6156: if (grep/^future$/,@{$status}) {
6157: if ($start > $now) {
6158: return 'ok';
6159: }
6160: }
6161: return;
6162: }
6163:
6164: sub parse_portfolio_url {
6165: my ($url) = @_;
6166:
6167: my ($type,$udom,$unum,$group,$file_name);
6168:
1.823 albertel 6169: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 6170: $type = 1;
6171: $udom = $1;
6172: $unum = $2;
6173: $file_name = $3;
1.823 albertel 6174: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 6175: $type = 2;
6176: $udom = $1;
6177: $unum = $2;
6178: $group = $3;
6179: $file_name = $3.'/'.$4;
6180: }
6181: if (wantarray) {
6182: return ($type,$udom,$unum,$file_name,$group);
6183: }
6184: return $type;
6185: }
6186:
6187: sub is_portfolio_url {
6188: my ($url) = @_;
6189: return scalar(&parse_portfolio_url($url));
6190: }
6191:
1.798 raeburn 6192: sub is_portfolio_file {
6193: my ($file) = @_;
1.820 raeburn 6194: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 6195: return 1;
6196: }
6197: return;
6198: }
6199:
1.976 raeburn 6200: sub usertools_access {
1.1084 raeburn 6201: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 6202: my ($access,%tools);
6203: if ($context eq '') {
6204: $context = 'tools';
6205: }
6206: if ($context eq 'requestcourses') {
6207: %tools = (
6208: official => 1,
6209: unofficial => 1,
1.1006 raeburn 6210: community => 1,
1.985 raeburn 6211: );
1.1183 raeburn 6212: } elsif ($context eq 'requestauthor') {
6213: %tools = (
6214: requestauthor => 1,
6215: );
1.985 raeburn 6216: } else {
6217: %tools = (
6218: aboutme => 1,
6219: blog => 1,
1.1177 raeburn 6220: webdav => 1,
1.985 raeburn 6221: portfolio => 1,
6222: );
6223: }
1.976 raeburn 6224: return if (!defined($tools{$tool}));
6225:
1.1242 raeburn 6226: if (($udom eq '') || ($uname eq '')) {
1.976 raeburn 6227: $udom = $env{'user.domain'};
6228: $uname = $env{'user.name'};
6229: }
6230:
1.978 raeburn 6231: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
6232: if ($action ne 'reload') {
1.985 raeburn 6233: if ($context eq 'requestcourses') {
6234: return $env{'environment.canrequest.'.$tool};
1.1183 raeburn 6235: } elsif ($context eq 'requestauthor') {
6236: return $env{'environment.canrequest.author'};
1.985 raeburn 6237: } else {
6238: return $env{'environment.availabletools.'.$tool};
6239: }
6240: }
1.976 raeburn 6241: }
6242:
1.1183 raeburn 6243: my ($toolstatus,$inststatus,$envkey);
6244: if ($context eq 'requestauthor') {
6245: $envkey = $context;
6246: } else {
6247: $envkey = $context.'.'.$tool;
6248: }
1.976 raeburn 6249:
1.985 raeburn 6250: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
6251: ($action ne 'reload')) {
1.1183 raeburn 6252: $toolstatus = $env{'environment.'.$envkey};
1.976 raeburn 6253: $inststatus = $env{'environment.inststatus'};
6254: } else {
1.1084 raeburn 6255: if (ref($userenvref) eq 'HASH') {
1.1183 raeburn 6256: $toolstatus = $userenvref->{$envkey};
1.1084 raeburn 6257: $inststatus = $userenvref->{'inststatus'};
6258: } else {
1.1183 raeburn 6259: my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
6260: $toolstatus = $userenv{$envkey};
1.1084 raeburn 6261: $inststatus = $userenv{'inststatus'};
6262: }
1.976 raeburn 6263: }
6264:
6265: if ($toolstatus ne '') {
6266: if ($toolstatus) {
6267: $access = 1;
6268: } else {
6269: $access = 0;
6270: }
6271: return $access;
6272: }
6273:
1.1084 raeburn 6274: my ($is_adv,%domdef);
6275: if (ref($is_advref) eq 'HASH') {
6276: $is_adv = $is_advref->{'is_adv'};
6277: } else {
6278: $is_adv = &is_advanced_user($udom,$uname);
6279: }
6280: if (ref($domdefref) eq 'HASH') {
6281: %domdef = %{$domdefref};
6282: } else {
6283: %domdef = &get_domain_defaults($udom);
6284: }
1.976 raeburn 6285: if (ref($domdef{$tool}) eq 'HASH') {
6286: if ($is_adv) {
6287: if ($domdef{$tool}{'_LC_adv'} ne '') {
6288: if ($domdef{$tool}{'_LC_adv'}) {
6289: $access = 1;
6290: } else {
6291: $access = 0;
6292: }
6293: return $access;
6294: }
6295: }
6296: if ($inststatus ne '') {
6297: my ($hasaccess,$hasnoaccess);
6298: foreach my $affiliation (split(/:/,$inststatus)) {
6299: if ($domdef{$tool}{$affiliation} ne '') {
6300: if ($domdef{$tool}{$affiliation}) {
6301: $hasaccess = 1;
6302: } else {
6303: $hasnoaccess = 1;
6304: }
6305: }
6306: }
6307: if ($hasaccess || $hasnoaccess) {
6308: if ($hasaccess) {
6309: $access = 1;
6310: } elsif ($hasnoaccess) {
6311: $access = 0;
6312: }
6313: return $access;
6314: }
6315: } else {
6316: if ($domdef{$tool}{'default'} ne '') {
6317: if ($domdef{$tool}{'default'}) {
6318: $access = 1;
6319: } elsif ($domdef{$tool}{'default'} == 0) {
6320: $access = 0;
6321: }
6322: return $access;
6323: }
6324: }
6325: } else {
1.1177 raeburn 6326: if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985 raeburn 6327: $access = 1;
6328: } else {
6329: $access = 0;
6330: }
1.976 raeburn 6331: return $access;
6332: }
6333: }
6334:
1.1050 raeburn 6335: sub is_course_owner {
6336: my ($cdom,$cnum,$udom,$uname) = @_;
6337: if (($udom eq '') || ($uname eq '')) {
6338: $udom = $env{'user.domain'};
6339: $uname = $env{'user.name'};
6340: }
6341: unless (($udom eq '') || ($uname eq '')) {
6342: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
6343: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
6344: return 1;
6345: } else {
6346: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
6347: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
6348: return 1;
6349: }
6350: }
6351: }
6352: }
6353: return;
6354: }
6355:
1.976 raeburn 6356: sub is_advanced_user {
6357: my ($udom,$uname) = @_;
1.1085 raeburn 6358: if ($udom ne '' && $uname ne '') {
6359: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128 raeburn 6360: if (wantarray) {
6361: return ($env{'user.adv'},$env{'user.author'});
6362: } else {
6363: return $env{'user.adv'};
6364: }
1.1085 raeburn 6365: }
6366: }
1.976 raeburn 6367: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
6368: my %allroles;
1.1128 raeburn 6369: my ($is_adv,$is_author);
1.976 raeburn 6370: foreach my $role (keys(%roleshash)) {
6371: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
6372: my $area = '/'.$tdomain.'/'.$trest;
6373: if ($sec ne '') {
6374: $area .= '/'.$sec;
6375: }
6376: if (($area ne '') && ($trole ne '')) {
6377: my $spec=$trole.'.'.$area;
6378: if ($trole =~ /^cr\//) {
6379: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
6380: } elsif ($trole ne 'gr') {
6381: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
6382: }
1.1128 raeburn 6383: if ($trole eq 'au') {
6384: $is_author = 1;
6385: }
1.976 raeburn 6386: }
6387: }
6388: foreach my $role (keys(%allroles)) {
6389: last if ($is_adv);
6390: foreach my $item (split(/:/,$allroles{$role})) {
6391: if ($item ne '') {
6392: my ($privilege,$restrictions)=split(/&/,$item);
6393: if ($privilege eq 'adv') {
6394: $is_adv = 1;
6395: last;
6396: }
6397: }
6398: }
6399: }
1.1128 raeburn 6400: if (wantarray) {
6401: return ($is_adv,$is_author);
6402: }
1.976 raeburn 6403: return $is_adv;
6404: }
1.798 raeburn 6405:
1.1035 raeburn 6406: sub check_can_request {
1.1036 raeburn 6407: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 6408: my $canreq = 0;
6409: my ($types,$typename) = &Apache::loncommon::course_types();
6410: my @options = ('approval','validate','autolimit');
6411: my $optregex = join('|',@options);
6412: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
6413: foreach my $type (@{$types}) {
6414: if (&usertools_access($env{'user.name'},
6415: $env{'user.domain'},
6416: $type,undef,'requestcourses')) {
6417: $canreq ++;
1.1036 raeburn 6418: if (ref($request_domains) eq 'HASH') {
6419: push(@{$request_domains->{$type}},$env{'user.domain'});
6420: }
1.1035 raeburn 6421: if ($dom eq $env{'user.domain'}) {
6422: $can_request->{$type} = 1;
6423: }
6424: }
6425: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
6426: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
6427: if (@curr > 0) {
1.1036 raeburn 6428: foreach my $item (@curr) {
6429: if (ref($request_domains) eq 'HASH') {
6430: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
6431: if ($otherdom ne '') {
6432: if (ref($request_domains->{$type}) eq 'ARRAY') {
6433: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
6434: push(@{$request_domains->{$type}},$otherdom);
6435: }
6436: } else {
6437: push(@{$request_domains->{$type}},$otherdom);
6438: }
6439: }
6440: }
6441: }
6442: unless($dom eq $env{'user.domain'}) {
6443: $canreq ++;
1.1035 raeburn 6444: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
6445: $can_request->{$type} = 1;
6446: }
6447: }
6448: }
6449: }
6450: }
6451: }
6452: return $canreq;
6453: }
6454:
1.341 www 6455: # ---------------------------------------------- Custom access rule evaluation
6456:
6457: sub customaccess {
6458: my ($priv,$uri)=@_;
1.807 albertel 6459: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 6460: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 6461: $udom = &LONCAPA::clean_domain($udom);
6462: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 6463: my $access=0;
1.800 albertel 6464: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 6465: my ($effect,$realm,$role,$type)=split(/\:/,$right);
6466: if ($type eq 'user') {
6467: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 6468: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 6469: if ($tdom) {
6470: if ($tdom ne $env{'user.domain'}) { next; }
6471: }
1.896 albertel 6472: if ($tuname) {
6473: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 6474: }
6475: $access=($effect eq 'allow');
6476: last;
6477: }
6478: } else {
6479: if ($role) {
6480: if ($role ne $urole) { next; }
6481: }
6482: foreach my $scope (split(/\s*\,\s*/,$realm)) {
6483: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
6484: if ($tdom) {
6485: if ($tdom ne $udom) { next; }
6486: }
6487: if ($tcrs) {
6488: if ($tcrs ne $ucrs) { next; }
6489: }
6490: if ($tsec) {
6491: if ($tsec ne $usec) { next; }
6492: }
6493: $access=($effect eq 'allow');
6494: last;
6495: }
6496: if ($realm eq '' && $role eq '') {
6497: $access=($effect eq 'allow');
6498: }
1.402 bowersj2 6499: }
1.341 www 6500: }
6501: return $access;
6502: }
6503:
1.103 harris41 6504: # ------------------------------------------------- Check for a user privilege
1.12 www 6505:
6506: sub allowed {
1.810 raeburn 6507: my ($priv,$uri,$symb,$role)=@_;
1.705 albertel 6508: my $ver_orguri=$uri;
1.439 www 6509: $uri=&deversion($uri);
1.152 www 6510: my $orguri=$uri;
1.52 www 6511: $uri=&declutter($uri);
1.809 raeburn 6512:
1.810 raeburn 6513: if ($priv eq 'evb') {
6514: # Evade communication block restrictions for specified role in a course
6515: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
6516: return $1;
6517: } else {
6518: return;
6519: }
6520: }
6521:
1.620 albertel 6522: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 6523: # Free bre access to adm and meta resources
1.775 albertel 6524: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 6525: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
6526: && ($priv eq 'bre')) {
1.14 www 6527: return 'F';
1.159 www 6528: }
6529:
1.545 banghart 6530: # Free bre access to user's own portfolio contents
1.714 raeburn 6531: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 6532: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 6533: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 6534: my %setters;
6535: my ($startblock,$endblock) =
6536: &Apache::loncommon::blockcheck(\%setters,'port');
6537: if ($startblock && $endblock) {
6538: return 'B';
6539: } else {
6540: return 'F';
6541: }
1.545 banghart 6542: }
6543:
1.762 raeburn 6544: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 6545: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
6546: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
6547: if (exists($env{'request.course.id'})) {
6548: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6549: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6550: if (($domain eq $cdom) && ($name eq $cnum)) {
6551: my $courseprivid=$env{'request.course.id'};
6552: $courseprivid=~s/\_/\//;
6553: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
6554: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
6555: return $1;
1.762 raeburn 6556: } else {
6557: if ($env{'request.course.sec'}) {
6558: $courseprivid.='/'.$env{'request.course.sec'};
6559: }
6560: if ($env{'user.priv.'.$env{'request.role'}.'./'.
6561: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
6562: return $2;
6563: }
1.714 raeburn 6564: }
6565: }
6566: }
6567: }
6568:
1.159 www 6569: # Free bre to public access
6570:
6571: if ($priv eq 'bre') {
1.238 www 6572: my $copyright=&metadata($uri,'copyright');
1.620 albertel 6573: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 6574: return 'F';
6575: }
1.238 www 6576: if ($copyright eq 'priv') {
6577: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 6578: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 6579: return '';
6580: }
6581: }
6582: if ($copyright eq 'domain') {
6583: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 6584: unless (($env{'user.domain'} eq $1) ||
6585: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 6586: return '';
6587: }
1.262 matthew 6588: }
1.620 albertel 6589: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 6590: # Library role, so allow browsing of resources in this domain.
6591: return 'F';
1.238 www 6592: }
1.341 www 6593: if ($copyright eq 'custom') {
6594: unless (&customaccess($priv,$uri)) { return ''; }
6595: }
1.14 www 6596: }
1.264 matthew 6597: # Domain coordinator is trying to create a course
1.620 albertel 6598: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 6599: # uri is the requested domain in this case.
6600: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 6601: # a role of dc for the domain in question.
1.620 albertel 6602: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 6603: }
1.29 www 6604:
1.52 www 6605: my $thisallowed='';
6606: my $statecond=0;
6607: my $courseprivid='';
6608:
1.1039 raeburn 6609: my $ownaccess;
1.1043 raeburn 6610: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 6611: if (($priv eq 'bro') && ($env{'user.author'})) {
6612: if ($uri eq '') {
6613: $ownaccess = 1;
6614: } else {
6615: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
6616: my $udom = $env{'user.domain'};
6617: my $uname = $env{'user.name'};
6618: if ($uri =~ m{^\Q$udom\E/?$}) {
6619: $ownaccess = 1;
1.1040 raeburn 6620: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 6621: unless ($uri =~ m{\.\./}) {
6622: $ownaccess = 1;
6623: }
6624: } elsif (($udom ne 'public') && ($uname ne 'public')) {
6625: my $now = time;
6626: if ($uri =~ m{^([^/]+)/?$}) {
6627: my $adom = $1;
6628: foreach my $key (keys(%env)) {
1.1042 raeburn 6629: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 6630: my ($start,$end) = split('.',$env{$key});
6631: if (($now >= $start) && (!$end || $end < $now)) {
6632: $ownaccess = 1;
6633: last;
6634: }
6635: }
6636: }
6637: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
6638: my $adom = $1;
6639: my $aname = $2;
1.1042 raeburn 6640: foreach my $role ('ca','aa') {
6641: if ($env{"user.role.$role./$adom/$aname"}) {
6642: my ($start,$end) =
6643: split('.',$env{"user.role.$role./$adom/$aname"});
6644: if (($now >= $start) && (!$end || $end < $now)) {
6645: $ownaccess = 1;
6646: last;
6647: }
1.1039 raeburn 6648: }
6649: }
6650: }
6651: }
6652: }
6653: }
6654: }
6655:
1.52 www 6656: # Course
6657:
1.620 albertel 6658: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6659: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6660: $thisallowed.=$1;
6661: }
1.52 www 6662: }
1.29 www 6663:
1.52 www 6664: # Domain
6665:
1.620 albertel 6666: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 6667: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6668: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6669: $thisallowed.=$1;
6670: }
1.12 www 6671: }
1.52 www 6672:
1.1141 raeburn 6673: # User who is not author or co-author might still be able to edit
6674: # resource of an author in the domain (e.g., if Domain Coordinator).
6675: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
6676: (&allowed('mdc',$env{'request.course.id'}))) {
6677: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
6678: $thisallowed.=$1;
6679: }
6680: }
6681:
1.52 www 6682: # Course: uri itself is a course
1.66 www 6683: my $courseuri=$uri;
6684: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 6685: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 6686:
1.620 albertel 6687: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 6688: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6689: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6690: $thisallowed.=$1;
6691: }
1.12 www 6692: }
1.29 www 6693:
1.665 albertel 6694: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 6695: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 6696: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 6697: $thisallowed='';
1.671 raeburn 6698: my ($match)=&is_on_map($uri);
6699: if ($match) {
6700: if ($env{'user.priv.'.$env{'request.role'}.'./'}
6701: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6702: my @blockers = &has_comm_blocking($priv,$symb,$uri);
6703: if (@blockers > 0) {
6704: $thisallowed = 'B';
6705: } else {
6706: $thisallowed.=$1;
6707: }
1.671 raeburn 6708: }
6709: } else {
1.705 albertel 6710: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 6711: if ($refuri) {
6712: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 6713: $thisallowed='F';
1.671 raeburn 6714: } else {
6715: $refuri=&declutter($refuri);
6716: my ($match) = &is_on_map($refuri);
6717: if ($match) {
1.1162 raeburn 6718: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
6719: if (@blockers > 0) {
6720: $thisallowed = 'B';
6721: } else {
6722: $thisallowed='F';
6723: }
1.671 raeburn 6724: }
1.669 raeburn 6725: }
1.671 raeburn 6726: }
6727: }
1.314 www 6728: }
1.492 albertel 6729:
1.766 albertel 6730: if ($priv eq 'bre'
6731: && $thisallowed ne 'F'
6732: && $thisallowed ne '2'
6733: && &is_portfolio_url($uri)) {
6734: $thisallowed = &portfolio_access($uri);
6735: }
6736:
1.52 www 6737: # Full access at system, domain or course-wide level? Exit.
1.29 www 6738: if ($thisallowed=~/F/) {
6739: return 'F';
6740: }
6741:
1.52 www 6742: # If this is generating or modifying users, exit with special codes
1.29 www 6743:
1.643 www 6744: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
6745: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 6746: my ($audom,$auname)=split('/',$uri);
1.643 www 6747: # no author name given, so this just checks on the general right to make a co-author in this domain
6748: unless ($auname) { return $thisallowed; }
6749: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 6750: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
6751: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
6752: ($audom ne $env{'request.role.domain'}))) { return ''; }
6753: }
1.52 www 6754: return $thisallowed;
6755: }
6756: #
1.103 harris41 6757: # Gathered so far: system, domain and course wide privileges
1.52 www 6758: #
6759: # Course: See if uri or referer is an individual resource that is part of
6760: # the course
6761:
1.620 albertel 6762: if ($env{'request.course.id'}) {
1.232 www 6763:
1.620 albertel 6764: $courseprivid=$env{'request.course.id'};
6765: if ($env{'request.course.sec'}) {
6766: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 6767: }
6768: $courseprivid=~s/\_/\//;
6769: my $checkreferer=1;
1.232 www 6770: my ($match,$cond)=&is_on_map($uri);
6771: if ($match) {
6772: $statecond=$cond;
1.620 albertel 6773: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 6774: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6775: my $value = $1;
6776: if ($priv eq 'bre') {
6777: my @blockers = &has_comm_blocking($priv,$symb,$uri);
6778: if (@blockers > 0) {
6779: $thisallowed = 'B';
6780: } else {
6781: $thisallowed.=$value;
6782: }
6783: } else {
6784: $thisallowed.=$value;
6785: }
1.52 www 6786: $checkreferer=0;
6787: }
1.29 www 6788: }
1.83 www 6789:
1.148 www 6790: if ($checkreferer) {
1.620 albertel 6791: my $refuri=$env{'httpref.'.$orguri};
1.148 www 6792: unless ($refuri) {
1.800 albertel 6793: foreach my $key (keys(%env)) {
6794: if ($key=~/^httpref\..*\*/) {
6795: my $pattern=$key;
1.156 www 6796: $pattern=~s/^httpref\.\/res\///;
1.148 www 6797: $pattern=~s/\*/\[\^\/\]\+/g;
6798: $pattern=~s/\//\\\//g;
1.152 www 6799: if ($orguri=~/$pattern/) {
1.800 albertel 6800: $refuri=$env{$key};
1.148 www 6801: }
6802: }
1.191 harris41 6803: }
1.148 www 6804: }
1.232 www 6805:
1.148 www 6806: if ($refuri) {
1.152 www 6807: $refuri=&declutter($refuri);
1.232 www 6808: my ($match,$cond)=&is_on_map($refuri);
6809: if ($match) {
6810: my $refstatecond=$cond;
1.620 albertel 6811: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 6812: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6813: my $value = $1;
6814: if ($priv eq 'bre') {
6815: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
6816: if (@blockers > 0) {
6817: $thisallowed = 'B';
6818: } else {
6819: $thisallowed.=$value;
6820: }
6821: } else {
6822: $thisallowed.=$value;
6823: }
1.53 www 6824: $uri=$refuri;
6825: $statecond=$refstatecond;
1.52 www 6826: }
6827: }
1.148 www 6828: }
1.29 www 6829: }
1.52 www 6830: }
1.29 www 6831:
1.52 www 6832: #
1.103 harris41 6833: # Gathered now: all privileges that could apply, and condition number
1.52 www 6834: #
6835: #
6836: # Full or no access?
6837: #
1.29 www 6838:
1.52 www 6839: if ($thisallowed=~/F/) {
6840: return 'F';
6841: }
1.29 www 6842:
1.52 www 6843: unless ($thisallowed) {
6844: return '';
6845: }
1.29 www 6846:
1.52 www 6847: # Restrictions exist, deal with them
6848: #
6849: # C:according to course preferences
6850: # R:according to resource settings
6851: # L:unless locked
6852: # X:according to user session state
6853: #
6854:
6855: # Possibly locked functionality, check all courses
1.54 www 6856: # Locks might take effect only after 10 minutes cache expiration for other
6857: # courses, and 2 minutes for current course
1.52 www 6858:
6859: my $envkey;
6860: if ($thisallowed=~/L/) {
1.1000 raeburn 6861: foreach $envkey (keys(%env)) {
1.54 www 6862: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
6863: my $courseid=$2;
6864: my $roleid=$1.'.'.$2;
1.92 www 6865: $courseid=~s/^\///;
1.54 www 6866: my $expiretime=600;
1.620 albertel 6867: if ($env{'request.role'} eq $roleid) {
1.54 www 6868: $expiretime=120;
6869: }
6870: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
6871: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 6872: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 6873: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 6874: }
1.620 albertel 6875: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
6876: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
6877: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
6878: &log($env{'user.domain'},$env{'user.name'},
6879: $env{'user.home'},
1.57 www 6880: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 6881: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 6882: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 6883: return '';
6884: }
6885: }
1.620 albertel 6886: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
6887: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
6888: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
6889: &log($env{'user.domain'},$env{'user.name'},
6890: $env{'user.home'},
1.57 www 6891: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 6892: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 6893: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 6894: return '';
6895: }
6896: }
6897: }
1.29 www 6898: }
1.52 www 6899: }
6900:
6901: #
6902: # Rest of the restrictions depend on selected course
6903: #
6904:
1.620 albertel 6905: unless ($env{'request.course.id'}) {
1.766 albertel 6906: if ($thisallowed eq 'A') {
6907: return 'A';
1.814 raeburn 6908: } elsif ($thisallowed eq 'B') {
6909: return 'B';
1.766 albertel 6910: } else {
6911: return '1';
6912: }
1.52 www 6913: }
1.29 www 6914:
1.52 www 6915: #
6916: # Now user is definitely in a course
6917: #
1.53 www 6918:
6919:
6920: # Course preferences
6921:
6922: if ($thisallowed=~/C/) {
1.620 albertel 6923: my $rolecode=(split(/\./,$env{'request.role'}))[0];
6924: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
6925: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 6926: =~/\Q$rolecode\E/) {
1.1103 raeburn 6927: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 6928: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
6929: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
6930: $env{'request.course.id'});
6931: }
1.237 www 6932: return '';
6933: }
6934:
1.620 albertel 6935: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 6936: =~/\Q$unamedom\E/) {
1.1103 raeburn 6937: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 6938: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
6939: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
6940: $env{'request.course.id'});
6941: }
1.54 www 6942: return '';
6943: }
1.53 www 6944: }
6945:
6946: # Resource preferences
6947:
6948: if ($thisallowed=~/R/) {
1.620 albertel 6949: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 6950: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103 raeburn 6951: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 6952: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
6953: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
6954: }
6955: return '';
1.54 www 6956: }
1.53 www 6957: }
1.30 www 6958:
1.246 www 6959: # Restricted by state or randomout?
1.30 www 6960:
1.52 www 6961: if ($thisallowed=~/X/) {
1.620 albertel 6962: if ($env{'acc.randomout'}) {
1.579 albertel 6963: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 6964: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 6965: return '';
6966: }
1.247 www 6967: }
6968: if (&condval($statecond)) {
1.52 www 6969: return '2';
6970: } else {
6971: return '';
6972: }
6973: }
1.30 www 6974:
1.766 albertel 6975: if ($thisallowed eq 'A') {
6976: return 'A';
1.814 raeburn 6977: } elsif ($thisallowed eq 'B') {
6978: return 'B';
1.766 albertel 6979: }
1.52 www 6980: return 'F';
1.232 www 6981: }
1.1162 raeburn 6982:
1.1192 raeburn 6983: # ------------------------------------------- Check construction space access
6984:
6985: sub constructaccess {
6986: my ($url,$setpriv)=@_;
6987:
6988: # We do not allow editing of previous versions of files
6989: if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
6990:
6991: # Get username and domain from URL
6992: my ($ownername,$ownerdomain,$ownerhome);
6993:
6994: ($ownerdomain,$ownername) =
6995: ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
6996:
6997: # The URL does not really point to any authorspace, forget it
6998: unless (($ownername) && ($ownerdomain)) { return ''; }
6999:
7000: # Now we need to see if the user has access to the authorspace of
7001: # $ownername at $ownerdomain
7002:
7003: if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
7004: # Real author for this?
7005: $ownerhome = $env{'user.home'};
7006: if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
7007: return ($ownername,$ownerdomain,$ownerhome);
7008: }
7009: } else {
7010: # Co-author for this?
7011: if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
7012: exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
7013: $ownerhome = &homeserver($ownername,$ownerdomain);
7014: return ($ownername,$ownerdomain,$ownerhome);
7015: }
7016: }
7017:
7018: # We don't have any access right now. If we are not possibly going to do anything about this,
7019: # we might as well leave
7020: unless ($setpriv) { return ''; }
7021:
7022: # Backdoor access?
7023: my $allowed=&allowed('eco',$ownerdomain);
7024: # Nope
7025: unless ($allowed) { return ''; }
7026: # Looks like we may have access, but could be locked by the owner of the construction space
7027: if ($allowed eq 'U') {
7028: my %blocked=&get('environment',['domcoord.author'],
7029: $ownerdomain,$ownername);
7030: # Is blocked by owner
7031: if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
7032: }
7033: if (($allowed eq 'F') || ($allowed eq 'U')) {
7034: # Grant temporary access
7035: my $then=$env{'user.login.time'};
1.1209 raeburn 7036: my $update=$env{'user.update.time'};
1.1192 raeburn 7037: if (!$update) { $update = $then; }
7038: my $refresh=$env{'user.refresh.time'};
7039: if (!$refresh) { $refresh = $update; }
7040: my $now = time;
7041: &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
7042: $now,'ca','constructaccess');
7043: $ownerhome = &homeserver($ownername,$ownerdomain);
7044: return($ownername,$ownerdomain,$ownerhome);
7045: }
7046: # No business here
7047: return '';
7048: }
7049:
1.1162 raeburn 7050: sub get_comm_blocks {
7051: my ($cdom,$cnum) = @_;
7052: if ($cdom eq '' || $cnum eq '') {
7053: return unless ($env{'request.course.id'});
7054: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7055: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7056: }
7057: my %commblocks;
7058: my $hashid=$cdom.'_'.$cnum;
7059: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
7060: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
7061: %commblocks = %{$blocksref};
7062: } else {
7063: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
7064: my $cachetime = 600;
7065: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
7066: }
7067: return %commblocks;
7068: }
7069:
7070: sub has_comm_blocking {
7071: my ($priv,$symb,$uri,$blocks) = @_;
7072: return unless ($env{'request.course.id'});
7073: return unless ($priv eq 'bre');
7074: return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
7075: my %commblocks;
7076: if (ref($blocks) eq 'HASH') {
7077: %commblocks = %{$blocks};
7078: } else {
7079: %commblocks = &get_comm_blocks();
7080: }
7081: return unless (keys(%commblocks) > 0);
7082: if (!$symb) { $symb=&symbread($uri,1); }
7083: my ($map,$resid,undef)=&decode_symb($symb);
7084: my %tocheck = (
7085: maps => $map,
7086: resources => $symb,
7087: );
7088: my @blockers;
7089: my $now = time;
1.1163 raeburn 7090: my $navmap = Apache::lonnavmaps::navmap->new();
1.1162 raeburn 7091: foreach my $block (keys(%commblocks)) {
7092: if ($block =~ /^(\d+)____(\d+)$/) {
7093: my ($start,$end) = ($1,$2);
7094: if ($start <= $now && $end >= $now) {
7095: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7096: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
7097: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
7098: if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
7099: unless (grep(/^\Q$block\E$/,@blockers)) {
7100: push(@blockers,$block);
7101: }
7102: }
7103: }
7104: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
7105: if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
7106: unless (grep(/^\Q$block\E$/,@blockers)) {
7107: push(@blockers,$block);
7108: }
7109: }
7110: }
7111: }
7112: }
7113: }
7114: } elsif ($block =~ /^firstaccess____(.+)$/) {
7115: my $item = $1;
1.1163 raeburn 7116: my @to_test;
1.1162 raeburn 7117: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7118: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
7119: my $check_interval;
7120: if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
7121: my @interval;
7122: my $type = 'map';
7123: if ($item eq 'course') {
7124: $type = 'course';
7125: @interval=&EXT("resource.0.interval");
7126: } else {
7127: if ($item =~ /___\d+___/) {
7128: $type = 'resource';
7129: @interval=&EXT("resource.0.interval",$item);
1.1163 raeburn 7130: if (ref($navmap)) {
7131: my $res = $navmap->getBySymb($item);
7132: push(@to_test,$res);
7133: }
1.1162 raeburn 7134: } else {
7135: my $mapsymb = &symbread($item,1);
7136: if ($mapsymb) {
7137: if (ref($navmap)) {
7138: my $mapres = $navmap->getBySymb($mapsymb);
1.1163 raeburn 7139: @to_test = $mapres->retrieveResources($mapres,undef,0,1);
7140: foreach my $res (@to_test) {
1.1162 raeburn 7141: my $symb = $res->symb();
7142: next if ($symb eq $mapsymb);
7143: if ($symb ne '') {
7144: @interval=&EXT("resource.0.interval",$symb);
7145: last;
7146: }
7147: }
7148: }
7149: }
7150: }
7151: }
7152: if ($interval[0] =~ /\d+/) {
7153: my $first_access;
7154: if ($type eq 'resource') {
7155: $first_access=&get_first_access($interval[1],$item);
7156: } elsif ($type eq 'map') {
7157: $first_access=&get_first_access($interval[1],undef,$item);
7158: } else {
7159: $first_access=&get_first_access($interval[1]);
7160: }
7161: if ($first_access) {
7162: my $timesup = $first_access+$interval[0];
7163: if ($timesup > $now) {
1.1163 raeburn 7164: foreach my $res (@to_test) {
7165: if ($res->is_problem()) {
7166: if ($res->completable()) {
7167: unless (grep(/^\Q$block\E$/,@blockers)) {
7168: push(@blockers,$block);
7169: }
7170: last;
7171: }
7172: }
1.1162 raeburn 7173: }
7174: }
7175: }
7176: }
7177: }
7178: }
7179: }
7180: }
7181: }
7182: return @blockers;
7183: }
7184:
7185: sub check_docs_block {
7186: my ($docsblock,$tocheck) =@_;
7187: if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
7188: return;
7189: }
7190: if (ref($docsblock->{'maps'}) eq 'HASH') {
7191: if ($tocheck->{'maps'}) {
7192: if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
7193: return 1;
7194: }
7195: }
7196: }
7197: if (ref($docsblock->{'resources'}) eq 'HASH') {
7198: if ($tocheck->{'resources'}) {
7199: if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
7200: return 1;
7201: }
7202: }
7203: }
7204: return;
7205: }
7206:
1.1133 foxr 7207: #
7208: # Removes the versino from a URI and
7209: # splits it in to its filename and path to the filename.
7210: # Seems like File::Basename could have done this more clearly.
7211: # Parameters:
7212: # $uri - input URI
7213: # Returns:
7214: # Two element list consisting of
7215: # $pathname - the URI up to and excluding the trailing /
7216: # $filename - The part of the URI following the last /
7217: # NOTE:
7218: # Another realization of this is simply:
7219: # use File::Basename;
7220: # ...
7221: # $uri = shift;
7222: # $filename = basename($uri);
7223: # $path = dirname($uri);
7224: # return ($filename, $path);
7225: #
7226: # The implementation below is probably faster however.
7227: #
1.710 albertel 7228: sub split_uri_for_cond {
7229: my $uri=&deversion(&declutter(shift));
7230: my @uriparts=split(/\//,$uri);
7231: my $filename=pop(@uriparts);
7232: my $pathname=join('/',@uriparts);
7233: return ($pathname,$filename);
7234: }
1.232 www 7235: # --------------------------------------------------- Is a resource on the map?
7236:
7237: sub is_on_map {
1.710 albertel 7238: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 7239: #Trying to find the conditional for the file
1.620 albertel 7240: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 7241: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 7242: if ($match) {
1.289 bowersj2 7243: return (1,$1);
7244: } else {
1.434 www 7245: return (0,0);
1.289 bowersj2 7246: }
1.12 www 7247: }
7248:
1.427 www 7249: # --------------------------------------------------------- Get symb from alias
7250:
7251: sub get_symb_from_alias {
7252: my $symb=shift;
7253: my ($map,$resid,$url)=&decode_symb($symb);
7254: # Already is a symb
7255: if ($url) { return $symb; }
7256: # Must be an alias
7257: my $aliassymb='';
7258: my %bighash;
1.620 albertel 7259: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 7260: &GDBM_READER(),0640)) {
7261: my $rid=$bighash{'mapalias_'.$symb};
7262: if ($rid) {
7263: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 7264: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
7265: $resid,$bighash{'src_'.$rid});
1.427 www 7266: }
7267: untie %bighash;
7268: }
7269: return $aliassymb;
7270: }
7271:
1.12 www 7272: # ----------------------------------------------------------------- Define Role
7273:
7274: sub definerole {
7275: if (allowed('mcr','/')) {
7276: my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800 albertel 7277: foreach my $role (split(':',$sysrole)) {
7278: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7279: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
7280: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
7281: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 7282: return "refused:s:$crole&$cqual";
7283: }
7284: }
1.191 harris41 7285: }
1.800 albertel 7286: foreach my $role (split(':',$domrole)) {
7287: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7288: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
7289: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
7290: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 7291: return "refused:d:$crole&$cqual";
7292: }
7293: }
1.191 harris41 7294: }
1.800 albertel 7295: foreach my $role (split(':',$courole)) {
7296: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7297: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
7298: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
7299: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 7300: return "refused:c:$crole&$cqual";
7301: }
7302: }
1.191 harris41 7303: }
1.620 albertel 7304: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
7305: "$env{'user.domain'}:$env{'user.name'}:".
1.21 www 7306: "rolesdef_$rolename=".
7307: escape($sysrole.'_'.$domrole.'_'.$courole);
1.620 albertel 7308: return reply($command,$env{'user.home'});
1.12 www 7309: } else {
7310: return 'refused';
7311: }
1.105 harris41 7312: }
7313:
7314: # ---------------- Make a metadata query against the network of library servers
7315:
7316: sub metadata_query {
1.1237 raeburn 7317: my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120 harris41 7318: my %rhash;
1.845 albertel 7319: my %libserv = &all_library();
1.244 matthew 7320: my @server_list = (defined($server_array) ? @$server_array
7321: : keys(%libserv) );
7322: for my $server (@server_list) {
1.1237 raeburn 7323: my $domains = '';
7324: if (ref($domains_hash) eq 'HASH') {
7325: $domains = $domains_hash->{$server};
7326: }
1.118 harris41 7327: unless ($custom or $customshow) {
1.1237 raeburn 7328: my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118 harris41 7329: $rhash{$server}=$reply;
7330: }
7331: else {
7332: my $reply=&reply("querysend:".&escape($query).':'.
1.1237 raeburn 7333: &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118 harris41 7334: $server);
7335: $rhash{$server}=$reply;
7336: }
1.112 harris41 7337: }
1.118 harris41 7338: return \%rhash;
1.240 www 7339: }
7340:
7341: # ----------------------------------------- Send log queries and wait for reply
7342:
7343: sub log_query {
7344: my ($uname,$udom,$query,%filters)=@_;
7345: my $uhome=&homeserver($uname,$udom);
7346: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 7347: my $uhost=&hostname($uhome);
1.800 albertel 7348: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 7349: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
7350: $uhome);
1.479 albertel 7351: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 7352: return get_query_reply($queryid);
7353: }
7354:
1.818 raeburn 7355: # -------------------------- Update MySQL table for portfolio file
7356:
7357: sub update_portfolio_table {
1.821 raeburn 7358: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 7359: if ($group ne '') {
7360: $file_name =~s /^\Q$group\E//;
7361: }
1.818 raeburn 7362: my $homeserver = &homeserver($uname,$udom);
7363: my $queryid=
1.821 raeburn 7364: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
7365: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 7366: my $reply = &get_query_reply($queryid);
7367: return $reply;
7368: }
7369:
1.899 raeburn 7370: # -------------------------- Update MySQL allusers table
7371:
7372: sub update_allusers_table {
7373: my ($uname,$udom,$names) = @_;
7374: my $homeserver = &homeserver($uname,$udom);
7375: my $queryid=
7376: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
7377: 'lastname='.&escape($names->{'lastname'}).'%%'.
7378: 'firstname='.&escape($names->{'firstname'}).'%%'.
7379: 'middlename='.&escape($names->{'middlename'}).'%%'.
7380: 'generation='.&escape($names->{'generation'}).'%%'.
7381: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
7382: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 7383: return;
1.899 raeburn 7384: }
7385:
1.508 raeburn 7386: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 7387:
7388: sub fetch_enrollment_query {
1.511 raeburn 7389: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508 raeburn 7390: my $homeserver;
1.547 raeburn 7391: my $maxtries = 1;
1.508 raeburn 7392: if ($context eq 'automated') {
7393: $homeserver = $perlvar{'lonHostID'};
1.547 raeburn 7394: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 7395: } else {
7396: $homeserver = &homeserver($cnum,$dom);
7397: }
1.838 albertel 7398: my $host=&hostname($homeserver);
1.506 raeburn 7399: my $cmd = '';
1.1000 raeburn 7400: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 7401: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 7402: }
7403: $cmd =~ s/%%$//;
7404: $cmd = &escape($cmd);
7405: my $query = 'fetchenrollment';
1.620 albertel 7406: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 7407: unless ($queryid=~/^\Q$host\E\_/) {
7408: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
7409: return 'error: '.$queryid;
7410: }
1.506 raeburn 7411: my $reply = &get_query_reply($queryid);
1.547 raeburn 7412: my $tries = 1;
7413: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
7414: $reply = &get_query_reply($queryid);
7415: $tries ++;
7416: }
1.526 raeburn 7417: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 7418: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 7419: } else {
1.901 albertel 7420: my @responses = split(/:/,$reply);
1.515 raeburn 7421: if ($homeserver eq $perlvar{'lonHostID'}) {
1.800 albertel 7422: foreach my $line (@responses) {
7423: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 7424: $$replyref{$key} = $value;
7425: }
7426: } else {
1.1117 foxr 7427: my $pathname = LONCAPA::tempdir();
1.800 albertel 7428: foreach my $line (@responses) {
7429: my ($key,$value) = split(/=/,$line);
1.506 raeburn 7430: $$replyref{$key} = $value;
7431: if ($value > 0) {
1.800 albertel 7432: foreach my $item (@{$$affiliatesref{$key}}) {
7433: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 7434: my $destname = $pathname.'/'.$filename;
7435: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 7436: if ($xml_classlist =~ /^error/) {
7437: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
7438: } else {
1.506 raeburn 7439: if ( open(FILE,">$destname") ) {
7440: print FILE &unescape($xml_classlist);
7441: close(FILE);
1.526 raeburn 7442: } else {
7443: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 7444: }
7445: }
7446: }
7447: }
7448: }
7449: }
7450: return 'ok';
7451: }
7452: return 'error';
7453: }
7454:
1.242 www 7455: sub get_query_reply {
7456: my $queryid=shift;
1.1117 foxr 7457: my $replyfile=LONCAPA::tempdir().$queryid;
1.240 www 7458: my $reply='';
7459: for (1..100) {
7460: sleep 2;
7461: if (-e $replyfile.'.end') {
1.448 albertel 7462: if (open(my $fh,$replyfile)) {
1.904 albertel 7463: $reply = join('',<$fh>);
7464: close($fh);
1.240 www 7465: } else { return 'error: reply_file_error'; }
1.242 www 7466: return &unescape($reply);
7467: }
1.240 www 7468: }
1.242 www 7469: return 'timeout:'.$queryid;
1.240 www 7470: }
7471:
7472: sub courselog_query {
1.241 www 7473: #
7474: # possible filters:
7475: # url: url or symb
7476: # username
7477: # domain
7478: # action: view, submit, grade
7479: # start: timestamp
7480: # end: timestamp
7481: #
1.240 www 7482: my (%filters)=@_;
1.620 albertel 7483: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 7484: if ($filters{'url'}) {
7485: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
7486: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
7487: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
7488: }
1.620 albertel 7489: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
7490: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 7491: return &log_query($cname,$cdom,'courselog',%filters);
7492: }
7493:
7494: sub userlog_query {
1.858 raeburn 7495: #
7496: # possible filters:
7497: # action: log check role
7498: # start: timestamp
7499: # end: timestamp
7500: #
1.240 www 7501: my ($uname,$udom,%filters)=@_;
7502: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 7503: }
7504:
1.506 raeburn 7505: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
7506:
7507: sub auto_run {
1.508 raeburn 7508: my ($cnum,$cdom) = @_;
1.876 raeburn 7509: my $response = 0;
7510: my $settings;
7511: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
7512: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
7513: $settings = $domconfig{'autoenroll'};
7514: if ($settings->{'run'} eq '1') {
7515: $response = 1;
7516: }
7517: } else {
1.934 raeburn 7518: my $homeserver;
7519: if (&is_course($cdom,$cnum)) {
7520: $homeserver = &homeserver($cnum,$cdom);
7521: } else {
7522: $homeserver = &domain($cdom,'primary');
7523: }
7524: if ($homeserver ne 'no_host') {
7525: $response = &reply('autorun:'.$cdom,$homeserver);
7526: }
1.876 raeburn 7527: }
1.506 raeburn 7528: return $response;
7529: }
1.776 albertel 7530:
1.506 raeburn 7531: sub auto_get_sections {
1.508 raeburn 7532: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 7533: my $homeserver;
7534: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7535: $homeserver = &homeserver($cnum,$cdom);
7536: }
7537: if (!defined($homeserver)) {
7538: if ($cdom =~ /^$match_domain$/) {
7539: $homeserver = &domain($cdom,'primary');
7540: }
7541: }
7542: my @secs;
7543: if (defined($homeserver)) {
7544: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
7545: unless ($response eq 'refused') {
7546: @secs = split(/:/,$response);
7547: }
1.506 raeburn 7548: }
7549: return @secs;
7550: }
1.776 albertel 7551:
1.506 raeburn 7552: sub auto_new_course {
1.1099 raeburn 7553: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 7554: my $homeserver = &homeserver($cnum,$cdom);
1.1099 raeburn 7555: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 7556: return $response;
7557: }
1.776 albertel 7558:
1.506 raeburn 7559: sub auto_validate_courseID {
1.508 raeburn 7560: my ($cnum,$cdom,$inst_course_id) = @_;
7561: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 7562: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 7563: return $response;
7564: }
1.776 albertel 7565:
1.1007 raeburn 7566: sub auto_validate_instcode {
1.1020 raeburn 7567: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 7568: my ($homeserver,$response);
7569: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7570: $homeserver = &homeserver($cnum,$cdom);
7571: }
7572: if (!defined($homeserver)) {
7573: if ($cdom =~ /^$match_domain$/) {
7574: $homeserver = &domain($cdom,'primary');
7575: }
7576: }
1.1065 raeburn 7577: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
7578: &escape($instcode).':'.&escape($owner),$homeserver));
1.1216 raeburn 7579: my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
7580: return ($outcome,$description,$defaultcredits);
1.1007 raeburn 7581: }
7582:
1.506 raeburn 7583: sub auto_create_password {
1.873 raeburn 7584: my ($cnum,$cdom,$authparam,$udom) = @_;
7585: my ($homeserver,$response);
1.506 raeburn 7586: my $create_passwd = 0;
7587: my $authchk = '';
1.873 raeburn 7588: if ($udom =~ /^$match_domain$/) {
7589: $homeserver = &domain($udom,'primary');
7590: }
7591: if ($homeserver eq '') {
7592: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7593: $homeserver = &homeserver($cnum,$cdom);
7594: }
7595: }
7596: if ($homeserver eq '') {
7597: $authchk = 'nodomain';
1.506 raeburn 7598: } else {
1.873 raeburn 7599: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
7600: if ($response eq 'refused') {
7601: $authchk = 'refused';
7602: } else {
1.901 albertel 7603: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 7604: }
1.506 raeburn 7605: }
7606: return ($authparam,$create_passwd,$authchk);
7607: }
7608:
1.706 raeburn 7609: sub auto_photo_permission {
7610: my ($cnum,$cdom,$students) = @_;
7611: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 7612: my ($outcome,$perm_reqd,$conditions) =
7613: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 7614: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7615: return (undef,undef);
7616: }
1.706 raeburn 7617: return ($outcome,$perm_reqd,$conditions);
7618: }
7619:
7620: sub auto_checkphotos {
7621: my ($uname,$udom,$pid) = @_;
7622: my $homeserver = &homeserver($uname,$udom);
7623: my ($result,$resulttype);
7624: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 7625: &escape($uname).':'.&escape($pid),
7626: $homeserver));
1.709 albertel 7627: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7628: return (undef,undef);
7629: }
1.706 raeburn 7630: if ($outcome) {
7631: ($result,$resulttype) = split(/:/,$outcome);
7632: }
7633: return ($result,$resulttype);
7634: }
7635:
7636: sub auto_photochoice {
7637: my ($cnum,$cdom) = @_;
7638: my $homeserver = &homeserver($cnum,$cdom);
7639: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 7640: &escape($cdom),
7641: $homeserver)));
1.709 albertel 7642: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7643: return (undef,undef);
7644: }
1.706 raeburn 7645: return ($update,$comment);
7646: }
7647:
7648: sub auto_photoupdate {
7649: my ($affiliatesref,$dom,$cnum,$photo) = @_;
7650: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 7651: my $host=&hostname($homeserver);
1.706 raeburn 7652: my $cmd = '';
7653: my $maxtries = 1;
1.800 albertel 7654: foreach my $affiliate (keys(%{$affiliatesref})) {
7655: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 7656: }
7657: $cmd =~ s/%%$//;
7658: $cmd = &escape($cmd);
7659: my $query = 'institutionalphotos';
7660: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
7661: unless ($queryid=~/^\Q$host\E\_/) {
7662: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
7663: return 'error: '.$queryid;
7664: }
7665: my $reply = &get_query_reply($queryid);
7666: my $tries = 1;
7667: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
7668: $reply = &get_query_reply($queryid);
7669: $tries ++;
7670: }
7671: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
7672: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
7673: } else {
7674: my @responses = split(/:/,$reply);
7675: my $outcome = shift(@responses);
7676: foreach my $item (@responses) {
7677: my ($key,$value) = split(/=/,$item);
7678: $$photo{$key} = $value;
7679: }
7680: return $outcome;
7681: }
7682: return 'error';
7683: }
7684:
1.521 raeburn 7685: sub auto_instcode_format {
1.793 albertel 7686: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
7687: $cat_order) = @_;
1.521 raeburn 7688: my $courses = '';
1.772 raeburn 7689: my @homeservers;
1.521 raeburn 7690: if ($caller eq 'global') {
1.841 albertel 7691: my %servers = &get_servers($codedom,'library');
7692: foreach my $tryserver (keys(%servers)) {
7693: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7694: push(@homeservers,$tryserver);
7695: }
1.584 raeburn 7696: }
1.1022 raeburn 7697: } elsif ($caller eq 'requests') {
7698: if ($codedom =~ /^$match_domain$/) {
7699: my $chome = &domain($codedom,'primary');
7700: unless ($chome eq 'no_host') {
7701: push(@homeservers,$chome);
7702: }
7703: }
1.521 raeburn 7704: } else {
1.772 raeburn 7705: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 7706: }
1.793 albertel 7707: foreach my $code (keys(%{$instcodes})) {
7708: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 7709: }
7710: chop($courses);
1.772 raeburn 7711: my $ok_response = 0;
7712: my $response;
7713: while (@homeservers > 0 && $ok_response == 0) {
7714: my $server = shift(@homeservers);
7715: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
7716: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
7717: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 7718: split(/:/,$response);
1.772 raeburn 7719: %{$codes} = (%{$codes},&str2hash($codes_str));
7720: push(@{$codetitles},&str2array($codetitles_str));
7721: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
7722: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
7723: $ok_response = 1;
7724: }
7725: }
7726: if ($ok_response) {
1.521 raeburn 7727: return 'ok';
1.772 raeburn 7728: } else {
7729: return $response;
1.521 raeburn 7730: }
7731: }
7732:
1.792 raeburn 7733: sub auto_instcode_defaults {
7734: my ($domain,$returnhash,$code_order) = @_;
7735: my @homeservers;
1.841 albertel 7736:
7737: my %servers = &get_servers($domain,'library');
7738: foreach my $tryserver (keys(%servers)) {
7739: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7740: push(@homeservers,$tryserver);
7741: }
1.792 raeburn 7742: }
1.841 albertel 7743:
1.792 raeburn 7744: my $response;
1.841 albertel 7745: foreach my $server (@homeservers) {
1.792 raeburn 7746: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 7747: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
7748:
7749: foreach my $pair (split(/\&/,$response)) {
7750: my ($name,$value)=split(/\=/,$pair);
7751: if ($name eq 'code_order') {
7752: @{$code_order} = split(/\&/,&unescape($value));
7753: } else {
7754: $returnhash->{&unescape($name)}=&unescape($value);
7755: }
7756: }
7757: return 'ok';
1.792 raeburn 7758: }
1.841 albertel 7759:
7760: return $response;
1.1003 raeburn 7761: }
7762:
7763: sub auto_possible_instcodes {
1.1007 raeburn 7764: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
7765: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
7766: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
7767: return;
7768: }
1.1003 raeburn 7769: my (@homeservers,$uhome);
7770: if (defined(&domain($domain,'primary'))) {
7771: $uhome=&domain($domain,'primary');
7772: push(@homeservers,&domain($domain,'primary'));
7773: } else {
7774: my %servers = &get_servers($domain,'library');
7775: foreach my $tryserver (keys(%servers)) {
7776: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7777: push(@homeservers,$tryserver);
7778: }
7779: }
7780: }
7781: my $response;
7782: foreach my $server (@homeservers) {
7783: $response=&reply('autopossibleinstcodes:'.$domain,$server);
7784: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 7785: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
7786: split(':',$response);
7787: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
7788: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 7789: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 7790: my ($name,$value)=split('=',$item);
7791: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 7792: }
7793: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 7794: my ($name,$value)=split('=',$item);
7795: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 7796: }
7797: return 'ok';
7798: }
7799: return $response;
7800: }
1.792 raeburn 7801:
1.1010 raeburn 7802: sub auto_courserequest_checks {
7803: my ($dom) = @_;
1.1020 raeburn 7804: my ($homeserver,%validations);
7805: if ($dom =~ /^$match_domain$/) {
7806: $homeserver = &domain($dom,'primary');
7807: }
7808: unless ($homeserver eq 'no_host') {
7809: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
7810: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
7811: my @items = split(/&/,$response);
7812: foreach my $item (@items) {
7813: my ($key,$value) = split('=',$item);
7814: $validations{&unescape($key)} = &thaw_unescape($value);
7815: }
7816: }
7817: }
1.1010 raeburn 7818: return %validations;
7819: }
7820:
1.1020 raeburn 7821: sub auto_courserequest_validation {
7822: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
7823: my ($homeserver,$response);
7824: if ($dom =~ /^$match_domain$/) {
7825: $homeserver = &domain($dom,'primary');
7826: }
7827: unless ($homeserver eq 'no_host') {
1.1021 raeburn 7828:
1.1020 raeburn 7829: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 7830: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020 raeburn 7831: ':'.&escape($instcode).':'.&escape($instseclist),
7832: $homeserver));
7833: }
7834: return $response;
7835: }
7836:
1.777 albertel 7837: sub auto_validate_class_sec {
1.918 raeburn 7838: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 7839: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 7840: my $ownerlist;
7841: if (ref($owners) eq 'ARRAY') {
7842: $ownerlist = join(',',@{$owners});
7843: } else {
7844: $ownerlist = $owners;
7845: }
1.773 raeburn 7846: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 7847: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 7848: return $response;
7849: }
7850:
1.679 raeburn 7851: # ------------------------------------------------------- Course Group routines
7852:
7853: sub get_coursegroups {
1.809 raeburn 7854: my ($cdom,$cnum,$group,$namespace) = @_;
7855: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 7856: }
7857:
1.679 raeburn 7858: sub modify_coursegroup {
7859: my ($cdom,$cnum,$groupsettings) = @_;
7860: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
7861: }
7862:
1.809 raeburn 7863: sub toggle_coursegroup_status {
7864: my ($cdom,$cnum,$group,$action) = @_;
7865: my ($from_namespace,$to_namespace);
7866: if ($action eq 'delete') {
7867: $from_namespace = 'coursegroups';
7868: $to_namespace = 'deleted_groups';
7869: } else {
7870: $from_namespace = 'deleted_groups';
7871: $to_namespace = 'coursegroups';
7872: }
7873: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 7874: if (my $tmp = &error(%curr_group)) {
7875: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
7876: return ('read error',$tmp);
7877: } else {
7878: my %savedsettings = %curr_group;
1.809 raeburn 7879: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 7880: my $deloutcome;
7881: if ($result eq 'ok') {
1.809 raeburn 7882: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 7883: } else {
7884: return ('write error',$result);
7885: }
7886: if ($deloutcome eq 'ok') {
7887: return 'ok';
7888: } else {
7889: return ('delete error',$deloutcome);
7890: }
7891: }
7892: }
7893:
1.679 raeburn 7894: sub modify_group_roles {
1.957 raeburn 7895: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 7896: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
7897: my $role = 'gr/'.&escape($userprivs);
7898: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 7899: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 7900: if ($result eq 'ok') {
7901: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
7902: }
1.679 raeburn 7903: return $result;
7904: }
7905:
7906: sub modify_coursegroup_membership {
7907: my ($cdom,$cnum,$membership) = @_;
7908: my $result = &put('groupmembership',$membership,$cdom,$cnum);
7909: return $result;
7910: }
7911:
1.682 raeburn 7912: sub get_active_groups {
7913: my ($udom,$uname,$cdom,$cnum) = @_;
7914: my $now = time;
7915: my %groups = ();
7916: foreach my $key (keys(%env)) {
1.811 albertel 7917: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 7918: my ($start,$end) = split(/\./,$env{$key});
7919: if (($end!=0) && ($end<$now)) { next; }
7920: if (($start!=0) && ($start>$now)) { next; }
7921: if ($1 eq $cdom && $2 eq $cnum) {
7922: $groups{$3} = $env{$key} ;
7923: }
7924: }
7925: }
7926: return %groups;
7927: }
7928:
1.683 raeburn 7929: sub get_group_membership {
7930: my ($cdom,$cnum,$group) = @_;
7931: return(&dump('groupmembership',$cdom,$cnum,$group));
7932: }
7933:
7934: sub get_users_groups {
7935: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 7936: my @usersgroups;
1.683 raeburn 7937: my $cachetime=1800;
7938:
7939: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 7940: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
7941: if (defined($cached)) {
1.734 albertel 7942: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 7943: } else {
7944: $grouplist = '';
1.816 raeburn 7945: my $courseurl = &courseid_to_courseurl($courseid);
1.1166 raeburn 7946: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 7947: my $access_end = $env{'course.'.$courseid.
7948: '.default_enrollment_end_date'};
7949: my $now = time;
7950: foreach my $key (keys(%roleshash)) {
7951: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
7952: my $group = $1;
7953: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
7954: my $start = $2;
7955: my $end = $1;
7956: if ($start == -1) { next; } # deleted from group
7957: if (($start!=0) && ($start>$now)) { next; }
7958: if (($end!=0) && ($end<$now)) {
7959: if ($access_end && $access_end < $now) {
7960: if ($access_end - $end < 86400) {
7961: push(@usersgroups,$group);
1.733 raeburn 7962: }
7963: }
1.817 raeburn 7964: next;
1.733 raeburn 7965: }
1.817 raeburn 7966: push(@usersgroups,$group);
1.683 raeburn 7967: }
7968: }
7969: }
1.817 raeburn 7970: @usersgroups = &sort_course_groups($courseid,@usersgroups);
7971: $grouplist = join(':',@usersgroups);
7972: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 7973: }
1.733 raeburn 7974: return @usersgroups;
1.683 raeburn 7975: }
7976:
7977: sub devalidate_getgroups_cache {
7978: my ($udom,$uname,$cdom,$cnum)=@_;
7979: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 7980:
1.683 raeburn 7981: my $hashid="$udom:$uname:$courseid";
7982: &devalidate_cache_new('getgroups',$hashid);
7983: }
7984:
1.12 www 7985: # ------------------------------------------------------------------ Plain Text
7986:
7987: sub plaintext {
1.988 raeburn 7988: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 7989: if ($short =~ m{^cr/}) {
1.758 albertel 7990: return (split('/',$short))[-1];
7991: }
1.742 raeburn 7992: if (!defined($cid)) {
7993: $cid = $env{'request.course.id'};
7994: }
7995: my %rolenames = (
1.1008 raeburn 7996: Course => 'std',
7997: Community => 'alt1',
1.742 raeburn 7998: );
1.1037 raeburn 7999: if ($cid ne '') {
8000: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
8001: unless ($forcedefault) {
8002: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
8003: &Apache::lonlocal::mt_escape(\$roletext);
8004: return &Apache::lonlocal::mt($roletext);
8005: }
8006: }
8007: }
8008: if ((defined($type)) && (defined($rolenames{$type})) &&
8009: (defined($rolenames{$type})) &&
8010: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 8011: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 8012: } elsif ($cid ne '') {
8013: my $crstype = $env{'course.'.$cid.'.type'};
8014: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
8015: (defined($prp{$short}{$rolenames{$crstype}}))) {
8016: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
8017: }
1.742 raeburn 8018: }
1.1037 raeburn 8019: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 8020: }
8021:
8022: # ----------------------------------------------------------------- Assign Role
8023:
8024: sub assignrole {
1.957 raeburn 8025: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
8026: $context)=@_;
1.21 www 8027: my $mrole;
8028: if ($role =~ /^cr\//) {
1.393 www 8029: my $cwosec=$url;
1.811 albertel 8030: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 8031: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 8032: my $refused = 1;
8033: if ($context eq 'requestcourses') {
8034: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
8035: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
8036: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
8037: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8038: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8039: if ($crsenv{'internal.courseowner'} eq
8040: $env{'user.name'}.':'.$env{'user.domain'}) {
8041: $refused = '';
8042: }
8043: }
8044: }
8045: }
8046: }
8047: if ($refused) {
8048: &logthis('Refused custom assignrole: '.
8049: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
8050: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
8051: return 'refused';
8052: }
1.104 www 8053: }
1.21 www 8054: $mrole='cr';
1.678 raeburn 8055: } elsif ($role =~ /^gr\//) {
8056: my $cwogrp=$url;
1.811 albertel 8057: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 8058: unless (&allowed('mdg',$cwogrp)) {
8059: &logthis('Refused group assignrole: '.
8060: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
8061: $env{'user.name'}.' at '.$env{'user.domain'});
8062: return 'refused';
8063: }
8064: $mrole='gr';
1.21 www 8065: } else {
1.82 www 8066: my $cwosec=$url;
1.811 albertel 8067: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 8068: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
8069: my $refused;
8070: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
8071: if (!(&allowed('c'.$role,$url))) {
8072: $refused = 1;
8073: }
8074: } else {
8075: $refused = 1;
8076: }
1.947 raeburn 8077: if ($refused) {
1.1045 raeburn 8078: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8079: if (!$selfenroll && $context eq 'course') {
8080: my %crsenv;
8081: if ($role eq 'cc' || $role eq 'co') {
8082: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8083: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
8084: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
8085: if ($crsenv{'internal.courseowner'} eq
8086: $env{'user.name'}.':'.$env{'user.domain'}) {
8087: $refused = '';
8088: }
8089: }
8090: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
8091: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
8092: if ($crsenv{'internal.courseowner'} eq
8093: $env{'user.name'}.':'.$env{'user.domain'}) {
8094: $refused = '';
8095: }
8096: }
8097: }
8098: }
8099: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 8100: $refused = '';
1.1017 raeburn 8101: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 8102: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 8103: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 8104: my $wrongcc;
8105: if ($cnum =~ /^$match_community$/) {
8106: $wrongcc = 1 if ($role eq 'cc');
8107: } else {
8108: $wrongcc = 1 if ($role eq 'co');
8109: }
8110: unless ($wrongcc) {
8111: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8112: if ($crsenv{'internal.courseowner'} eq
8113: $env{'user.name'}.':'.$env{'user.domain'}) {
8114: $refused = '';
8115: }
1.1017 raeburn 8116: }
8117: }
1.1183 raeburn 8118: } elsif ($context eq 'requestauthor') {
8119: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
8120: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
8121: if ($env{'environment.requestauthor'} eq 'automatic') {
8122: $refused = '';
8123: } else {
8124: my %domdefaults = &get_domain_defaults($udom);
8125: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
8126: my $checkbystatus;
8127: if ($env{'user.adv'}) {
8128: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
8129: if ($disposition eq 'automatic') {
8130: $refused = '';
8131: } elsif ($disposition eq '') {
8132: $checkbystatus = 1;
8133: }
8134: } else {
8135: $checkbystatus = 1;
8136: }
8137: if ($checkbystatus) {
8138: if ($env{'environment.inststatus'}) {
8139: my @inststatuses = split(/,/,$env{'environment.inststatus'});
8140: foreach my $type (@inststatuses) {
8141: if (($type ne '') &&
8142: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
8143: $refused = '';
8144: }
8145: }
8146: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
8147: $refused = '';
8148: }
8149: }
8150: }
8151: }
8152: }
1.1017 raeburn 8153: }
8154: if ($refused) {
1.947 raeburn 8155: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
8156: ' '.$role.' '.$end.' '.$start.' by '.
8157: $env{'user.name'}.' at '.$env{'user.domain'});
8158: return 'refused';
8159: }
1.932 raeburn 8160: }
1.1131 raeburn 8161: } elsif ($role eq 'au') {
8162: if ($url ne '/'.$udom.'/') {
8163: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
8164: ' to assign author role for '.$uname.':'.$udom.
8165: ' in domain: '.$url.' refused (wrong domain).');
8166: return 'refused';
8167: }
1.104 www 8168: }
1.21 www 8169: $mrole=$role;
8170: }
1.620 albertel 8171: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 8172: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 8173: if ($end) { $command.='_'.$end; }
1.21 www 8174: if ($start) {
8175: if ($end) {
1.81 www 8176: $command.='_'.$start;
1.21 www 8177: } else {
1.81 www 8178: $command.='_0_'.$start;
1.21 www 8179: }
8180: }
1.739 raeburn 8181: my $origstart = $start;
8182: my $origend = $end;
1.957 raeburn 8183: my $delflag;
1.357 www 8184: # actually delete
8185: if ($deleteflag) {
1.373 www 8186: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 8187: # modify command to delete the role
1.620 albertel 8188: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 8189: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 8190: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 8191: # set start and finish to negative values for userrolelog
8192: $start=-1;
8193: $end=-1;
1.957 raeburn 8194: $delflag = 1;
1.357 www 8195: }
8196: }
8197: # send command
1.349 www 8198: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 8199: # log new user role if status is ok
1.349 www 8200: if ($answer eq 'ok') {
1.663 raeburn 8201: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.1184 raeburn 8202: if (($role eq 'cc') || ($role eq 'in') ||
8203: ($role eq 'ep') || ($role eq 'ad') ||
8204: ($role eq 'ta') || ($role eq 'st') ||
8205: ($role=~/^cr/) || ($role eq 'gr') ||
8206: ($role eq 'co')) {
1.1200 raeburn 8207: # for course roles, perform group memberships changes triggered by role change.
8208: unless ($role =~ /^gr/) {
8209: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
8210: $origstart,$selfenroll,$context);
8211: }
1.1184 raeburn 8212: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8213: $selfenroll,$context);
8214: } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
8215: ($role eq 'au') || ($role eq 'dc')) {
8216: &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8217: $context);
8218: } elsif (($role eq 'ca') || ($role eq 'aa')) {
8219: &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8220: $context);
8221: }
1.1053 raeburn 8222: if ($role eq 'cc') {
8223: &autoupdate_coowners($url,$end,$start,$uname,$udom);
8224: }
1.349 www 8225: }
8226: return $answer;
1.169 harris41 8227: }
8228:
1.1053 raeburn 8229: sub autoupdate_coowners {
8230: my ($url,$end,$start,$uname,$udom) = @_;
8231: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
8232: if (($cdom ne '') && ($cnum ne '')) {
8233: my $now = time;
8234: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
8235: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
8236: my %coursehash = &coursedescription($cdom.'_'.$cnum);
8237: my $instcode = $coursehash{'internal.coursecode'};
8238: if ($instcode ne '') {
1.1056 raeburn 8239: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
8240: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 8241: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 8242: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
8243: if ($result eq 'valid') {
8244: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 8245: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
8246: push(@newcoowners,$coowner);
8247: }
8248: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
8249: push(@newcoowners,$uname.':'.$udom);
8250: }
8251: @newcoowners = sort(@newcoowners);
8252: } else {
8253: push(@newcoowners,$uname.':'.$udom);
8254: }
8255: } else {
8256: if ($coursehash{'internal.co-owners'}) {
8257: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
8258: unless ($coowner eq $uname.':'.$udom) {
8259: push(@newcoowners,$coowner);
8260: }
8261: }
8262: unless (@newcoowners > 0) {
8263: $delcoowners = 1;
8264: $coowners = '';
8265: }
8266: }
8267: }
8268: if (@newcoowners || $delcoowners) {
8269: &store_coowners($cdom,$cnum,$coursehash{'home'},
8270: $delcoowners,@newcoowners);
8271: }
8272: }
8273: }
8274: }
8275: }
8276: }
8277: }
8278:
8279: sub store_coowners {
8280: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
8281: my $cid = $cdom.'_'.$cnum;
8282: my ($coowners,$delresult,$putresult);
8283: if (@newcoowners) {
8284: $coowners = join(',',@newcoowners);
8285: my %coownershash = (
8286: 'internal.co-owners' => $coowners,
8287: );
8288: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
8289: if ($putresult eq 'ok') {
8290: if ($env{'course.'.$cid.'.num'} eq $cnum) {
8291: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
8292: }
8293: }
8294: }
8295: if ($delcoowners) {
8296: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
8297: if ($delresult eq 'ok') {
8298: if ($env{'course.'.$cid.'.internal.co-owners'}) {
8299: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
8300: }
8301: }
8302: }
8303: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
8304: my %crsinfo =
8305: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
8306: if (ref($crsinfo{$cid}) eq 'HASH') {
8307: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
8308: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
8309: }
8310: }
8311: }
8312:
1.169 harris41 8313: # -------------------------------------------------- Modify user authentication
1.197 www 8314: # Overrides without validation
8315:
1.169 harris41 8316: sub modifyuserauth {
8317: my ($udom,$uname,$umode,$upass)=@_;
8318: my $uhome=&homeserver($uname,$udom);
1.197 www 8319: unless (&allowed('mau',$udom)) { return 'refused'; }
8320: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 8321: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
8322: ' in domain '.$env{'request.role.domain'});
1.169 harris41 8323: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
8324: &escape($upass),$uhome);
1.620 albertel 8325: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 8326: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
8327: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
8328: &log($udom,,$uname,$uhome,
1.620 albertel 8329: 'Authentication changed by '.$env{'user.domain'}.', '.
8330: $env{'user.name'}.', '.$umode.
1.197 www 8331: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 8332: unless ($reply eq 'ok') {
1.197 www 8333: &logthis('Authentication mode error: '.$reply);
1.169 harris41 8334: return 'error: '.$reply;
8335: }
1.170 harris41 8336: return 'ok';
1.80 www 8337: }
8338:
1.81 www 8339: # --------------------------------------------------------------- Modify a user
1.80 www 8340:
1.81 www 8341: sub modifyuser {
1.206 matthew 8342: my ($udom, $uname, $uid,
8343: $umode, $upass, $first,
8344: $middle, $last, $gene,
1.1058 raeburn 8345: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 8346: $udom= &LONCAPA::clean_domain($udom);
8347: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 8348: my $showcandelete = 'none';
8349: if (ref($candelete) eq 'ARRAY') {
8350: if (@{$candelete} > 0) {
8351: $showcandelete = join(', ',@{$candelete});
8352: }
8353: }
1.81 www 8354: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 8355: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 8356: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 8357: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
8358: ' desiredhome not specified').
1.620 albertel 8359: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
8360: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 8361: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 8362: my $newuser;
8363: if ($uhome eq 'no_host') {
8364: $newuser = 1;
8365: }
1.80 www 8366: # ----------------------------------------------------------------- Create User
1.406 albertel 8367: if (($uhome eq 'no_host') &&
8368: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 8369: my $unhome='';
1.844 albertel 8370: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 8371: $unhome = $desiredhome;
1.620 albertel 8372: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
8373: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 8374: } else { # load balancing routine for determining $unhome
1.81 www 8375: my $loadm=10000000;
1.841 albertel 8376: my %servers = &get_servers($udom,'library');
8377: foreach my $tryserver (keys(%servers)) {
8378: my $answer=reply('load',$tryserver);
8379: if (($answer=~/\d+/) && ($answer<$loadm)) {
8380: $loadm=$answer;
8381: $unhome=$tryserver;
8382: }
1.80 www 8383: }
8384: }
8385: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 8386: return 'error: unable to find a home server for '.$uname.
8387: ' in domain '.$udom;
1.80 www 8388: }
8389: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
8390: &escape($upass),$unhome);
8391: unless ($reply eq 'ok') {
8392: return 'error: '.$reply;
8393: }
1.230 stredwic 8394: $uhome=&homeserver($uname,$udom,'true');
1.80 www 8395: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 8396: return 'error: unable verify users home machine.';
1.80 www 8397: }
1.209 matthew 8398: } # End of creation of new user
1.80 www 8399: # ---------------------------------------------------------------------- Add ID
8400: if ($uid) {
8401: $uid=~tr/A-Z/a-z/;
8402: my %uidhash=&idrget($udom,$uname);
1.196 www 8403: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
8404: && (!$forceid)) {
1.80 www 8405: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 8406: return 'error: user id "'.$uid.'" does not match '.
8407: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 8408: }
8409: } else {
8410: &idput($udom,($uname => $uid));
8411: }
8412: }
8413: # -------------------------------------------------------------- Add names, etc
1.313 matthew 8414: my @tmp=&get('environment',
1.899 raeburn 8415: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 8416: 'permanentemail','inststatus'],
1.134 albertel 8417: $udom,$uname);
1.1075 raeburn 8418: my (%names,%oldnames);
1.313 matthew 8419: if ($tmp[0] =~ m/^error:.*/) {
8420: %names=();
8421: } else {
8422: %names = @tmp;
1.1075 raeburn 8423: %oldnames = %names;
1.313 matthew 8424: }
1.388 www 8425: #
1.1058 raeburn 8426: # If name, email and/or uid are blank (e.g., because an uploaded file
8427: # of users did not contain them), do not overwrite existing values
8428: # unless field is in $candelete array ref.
8429: #
8430:
8431: my @fields = ('firstname','middlename','lastname','generation',
8432: 'permanentemail','id');
8433: my %newvalues;
8434: if (ref($candelete) eq 'ARRAY') {
8435: foreach my $field (@fields) {
8436: if (grep(/^\Q$field\E$/,@{$candelete})) {
8437: if ($field eq 'firstname') {
8438: $names{$field} = $first;
8439: } elsif ($field eq 'middlename') {
8440: $names{$field} = $middle;
8441: } elsif ($field eq 'lastname') {
8442: $names{$field} = $last;
8443: } elsif ($field eq 'generation') {
8444: $names{$field} = $gene;
8445: } elsif ($field eq 'permanentemail') {
8446: $names{$field} = $email;
8447: } elsif ($field eq 'id') {
8448: $names{$field} = $uid;
8449: }
8450: }
8451: }
8452: }
1.388 www 8453: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 8454: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 8455: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 8456: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 8457: if ($email) {
8458: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 8459: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 8460: }
1.899 raeburn 8461: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 8462: if (defined($inststatus)) {
8463: $names{'inststatus'} = '';
8464: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
8465: if (ref($usertypes) eq 'HASH') {
8466: my @okstatuses;
8467: foreach my $item (split(/:/,$inststatus)) {
8468: if (defined($usertypes->{$item})) {
8469: push(@okstatuses,$item);
8470: }
8471: }
8472: if (@okstatuses) {
8473: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
8474: }
8475: }
8476: }
1.1075 raeburn 8477: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 8478: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 8479: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 8480: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
8481: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
8482: } else {
8483: $logmsg .= ' during self creation';
8484: }
1.1075 raeburn 8485: my $changed;
8486: if ($newuser) {
8487: $changed = 1;
8488: } else {
8489: foreach my $field (@fields) {
8490: if ($names{$field} ne $oldnames{$field}) {
8491: $changed = 1;
8492: last;
8493: }
8494: }
8495: }
8496: unless ($changed) {
8497: $logmsg = 'No changes in user information needed for: '.$logmsg;
8498: &logthis($logmsg);
8499: return 'ok';
8500: }
8501: my $reply = &put('environment', \%names, $udom,$uname);
8502: if ($reply ne 'ok') {
8503: return 'error: '.$reply;
8504: }
1.1087 raeburn 8505: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
8506: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
8507: }
1.1075 raeburn 8508: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
8509: &devalidate_cache_new('namescache',$uname.':'.$udom);
8510: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 8511: &logthis($logmsg);
1.134 albertel 8512: return 'ok';
1.80 www 8513: }
8514:
1.81 www 8515: # -------------------------------------------------------------- Modify student
1.80 www 8516:
1.81 www 8517: sub modifystudent {
8518: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 8519: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1216 raeburn 8520: $selfenroll,$context,$inststatus,$credits)=@_;
1.455 albertel 8521: if (!$cid) {
1.620 albertel 8522: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 8523: return 'not_in_class';
8524: }
1.80 www 8525: }
8526: # --------------------------------------------------------------- Make the user
1.81 www 8527: my $reply=&modifyuser
1.209 matthew 8528: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 8529: $desiredhome,$email,$inststatus);
1.80 www 8530: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 8531: # This will cause &modify_student_enrollment to get the uid from the
1.1235 raeburn 8532: # student's environment
1.297 matthew 8533: $uid = undef if (!$forceid);
1.455 albertel 8534: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1216 raeburn 8535: $gene,$usec,$end,$start,$type,$locktype,
8536: $cid,$selfenroll,$context,$credits);
1.297 matthew 8537: return $reply;
8538: }
8539:
8540: sub modify_student_enrollment {
1.1216 raeburn 8541: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
8542: $locktype,$cid,$selfenroll,$context,$credits) = @_;
1.455 albertel 8543: my ($cdom,$cnum,$chome);
8544: if (!$cid) {
1.620 albertel 8545: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 8546: return 'not_in_class';
8547: }
1.620 albertel 8548: $cdom=$env{'course.'.$cid.'.domain'};
8549: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 8550: } else {
8551: ($cdom,$cnum)=split(/_/,$cid);
8552: }
1.620 albertel 8553: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 8554: if (!$chome) {
1.457 raeburn 8555: $chome=&homeserver($cnum,$cdom);
1.297 matthew 8556: }
1.455 albertel 8557: if (!$chome) { return 'unknown_course'; }
1.297 matthew 8558: # Make sure the user exists
1.81 www 8559: my $uhome=&homeserver($uname,$udom);
8560: if (($uhome eq '') || ($uhome eq 'no_host')) {
8561: return 'error: no such user';
8562: }
1.297 matthew 8563: # Get student data if we were not given enough information
8564: if (!defined($first) || $first eq '' ||
8565: !defined($last) || $last eq '' ||
8566: !defined($uid) || $uid eq '' ||
8567: !defined($middle) || $middle eq '' ||
8568: !defined($gene) || $gene eq '') {
1.294 matthew 8569: # They did not supply us with enough data to enroll the student, so
8570: # we need to pick up more information.
1.297 matthew 8571: my %tmp = &get('environment',
1.294 matthew 8572: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 8573: ,$udom,$uname);
8574:
1.800 albertel 8575: #foreach my $key (keys(%tmp)) {
8576: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 8577: #}
1.294 matthew 8578: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
8579: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
8580: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 8581: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 8582: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
8583: }
1.556 albertel 8584: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148 raeburn 8585: my $user = "$uname:$udom";
8586: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487 albertel 8587: my $reply=cput('classlist',
1.1148 raeburn 8588: {$user =>
1.1216 raeburn 8589: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits) },
1.487 albertel 8590: $cdom,$cnum);
1.1148 raeburn 8591: if (($reply eq 'ok') || ($reply eq 'delayed')) {
8592: &devalidate_getsection_cache($udom,$uname,$cid);
8593: } else {
1.81 www 8594: return 'error: '.$reply;
8595: }
1.297 matthew 8596: # Add student role to user
1.83 www 8597: my $uurl='/'.$cid;
1.81 www 8598: $uurl=~s/\_/\//g;
8599: if ($usec) {
8600: $uurl.='/'.$usec;
8601: }
1.1148 raeburn 8602: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
8603: $selfenroll,$context);
8604: if ($result ne 'ok') {
8605: if ($old_entry{$user} ne '') {
8606: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
8607: } else {
8608: $reply = &del('classlist',[$user],$cdom,$cnum);
8609: }
8610: }
8611: return $result;
1.21 www 8612: }
8613:
1.556 albertel 8614: sub format_name {
8615: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
8616: my $name;
8617: if ($first ne 'lastname') {
8618: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
8619: } else {
8620: if ($lastname=~/\S/) {
8621: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
8622: $name=~s/\s+,/,/;
8623: } else {
8624: $name.= $firstname.' '.$middlename.' '.$generation;
8625: }
8626: }
8627: $name=~s/^\s+//;
8628: $name=~s/\s+$//;
8629: $name=~s/\s+/ /g;
8630: return $name;
8631: }
8632:
1.84 www 8633: # ------------------------------------------------- Write to course preferences
8634:
8635: sub writecoursepref {
8636: my ($courseid,%prefs)=@_;
8637: $courseid=~s/^\///;
8638: $courseid=~s/\_/\//g;
8639: my ($cdomain,$cnum)=split(/\//,$courseid);
8640: my $chome=homeserver($cnum,$cdomain);
8641: if (($chome eq '') || ($chome eq 'no_host')) {
8642: return 'error: no such course';
8643: }
8644: my $cstring='';
1.800 albertel 8645: foreach my $pref (keys(%prefs)) {
8646: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 8647: }
1.84 www 8648: $cstring=~s/\&$//;
8649: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
8650: }
8651:
8652: # ---------------------------------------------------------- Make/modify course
8653:
8654: sub createcourse {
1.741 raeburn 8655: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 8656: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 8657: $url=&declutter($url);
8658: my $cid='';
1.1028 raeburn 8659: if ($context eq 'requestcourses') {
8660: my $can_create = 0;
8661: my ($ownername,$ownerdom) = split(':',$course_owner);
8662: if ($udom eq $ownerdom) {
8663: if (&usertools_access($ownername,$ownerdom,$category,undef,
8664: $context)) {
8665: $can_create = 1;
8666: }
8667: } else {
8668: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
8669: $category);
8670: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
8671: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
8672: if (@curr > 0) {
8673: my @options = qw(approval validate autolimit);
8674: my $optregex = join('|',@options);
8675: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
8676: $can_create = 1;
8677: }
8678: }
8679: }
8680: }
8681: if ($can_create) {
8682: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
8683: unless (&allowed('ccc',$udom)) {
8684: return 'refused';
8685: }
1.1017 raeburn 8686: }
8687: } else {
8688: return 'refused';
8689: }
1.1028 raeburn 8690: } elsif (!&allowed('ccc',$udom)) {
8691: return 'refused';
1.84 www 8692: }
1.1011 raeburn 8693: # --------------------------------------------------------------- Get Unique ID
8694: my $uname;
8695: if ($cnum =~ /^$match_courseid$/) {
8696: my $chome=&homeserver($cnum,$udom,'true');
8697: if (($chome eq '') || ($chome eq 'no_host')) {
8698: $uname = $cnum;
8699: } else {
1.1038 raeburn 8700: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 8701: }
8702: } else {
1.1038 raeburn 8703: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 8704: }
8705: return $uname if ($uname =~ /^error/);
8706: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 8707: if (!defined($course_server)) {
8708: if (defined(&domain($udom,'primary'))) {
8709: $course_server = &domain($udom,'primary');
8710: } else {
8711: $course_server = $env{'user.home'};
8712: }
8713: }
8714: my %host_servers =
8715: &Apache::lonnet::get_servers($udom,'library');
8716: unless ($host_servers{$course_server}) {
8717: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 8718: }
1.84 www 8719: # ------------------------------------------------------------- Make the course
8720: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 8721: $course_server);
1.84 www 8722: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 8723: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 8724: if (($uhome eq '') || ($uhome eq 'no_host')) {
8725: return 'error: no such course';
8726: }
1.271 www 8727: # ----------------------------------------------------------------- Course made
1.516 raeburn 8728: # log existence
1.1029 raeburn 8729: my $now = time;
1.918 raeburn 8730: my $newcourse = {
8731: $udom.'_'.$uname => {
1.921 raeburn 8732: description => $description,
8733: inst_code => $inst_code,
8734: owner => $course_owner,
8735: type => $crstype,
1.1029 raeburn 8736: creator => $env{'user.name'}.':'.
8737: $env{'user.domain'},
8738: created => $now,
8739: context => $context,
1.918 raeburn 8740: },
8741: };
1.921 raeburn 8742: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 8743: # set toplevel url
1.271 www 8744: my $topurl=$url;
8745: unless ($nonstandard) {
8746: # ------------------------------------------ For standard courses, make top url
8747: my $mapurl=&clutter($url);
1.278 www 8748: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 8749: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 8750: <map>
8751: <resource id="1" type="start"></resource>
8752: <resource id="2" src="$mapurl"></resource>
8753: <resource id="3" type="finish"></resource>
8754: <link index="1" from="1" to="2"></link>
8755: <link index="2" from="2" to="3"></link>
8756: </map>
8757: ENDINITMAP
8758: $topurl=&declutter(
1.638 albertel 8759: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 8760: );
8761: }
8762: # ----------------------------------------------------------- Write preferences
1.84 www 8763: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 8764: ('description' => $description,
8765: 'url' => $topurl,
8766: 'internal.creator' => $env{'user.name'}.':'.
8767: $env{'user.domain'},
8768: 'internal.created' => $now,
8769: 'internal.creationcontext' => $context)
8770: );
1.84 www 8771: return '/'.$udom.'/'.$uname;
8772: }
8773:
1.1011 raeburn 8774: # ------------------------------------------------------------------- Create ID
8775: sub generate_coursenum {
1.1038 raeburn 8776: my ($udom,$crstype) = @_;
1.1011 raeburn 8777: my $domdesc = &domain($udom);
8778: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 8779: my $first;
8780: if ($crstype eq 'Community') {
8781: $first = '0';
8782: } else {
8783: $first = int(1+rand(9));
8784: }
8785: my $uname=$first.
1.1011 raeburn 8786: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
8787: substr($$.time,0,5).unpack("H8",pack("I32",time)).
8788: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
8789: # ----------------------------------------------- Make sure that does not exist
8790: my $uhome=&homeserver($uname,$udom,'true');
8791: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 8792: if ($crstype eq 'Community') {
8793: $first = '0';
8794: } else {
8795: $first = int(1+rand(9));
8796: }
8797: $uname=$first.
1.1011 raeburn 8798: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
8799: substr($$.time,0,5).unpack("H8",pack("I32",time)).
8800: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
8801: $uhome=&homeserver($uname,$udom,'true');
8802: unless (($uhome eq '') || ($uhome eq 'no_host')) {
8803: return 'error: unable to generate unique course-ID';
8804: }
8805: }
8806: return $uname;
8807: }
8808:
1.813 albertel 8809: sub is_course {
1.1167 droeschl 8810: my ($cdom, $cnum) = scalar(@_) == 1 ?
8811: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
8812:
8813: return unless $cdom and $cnum;
8814:
8815: my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
8816: '.');
8817:
1.1219 raeburn 8818: return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167 droeschl 8819: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813 albertel 8820: }
8821:
1.1015 raeburn 8822: sub store_userdata {
8823: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 8824: my $result;
1.1016 raeburn 8825: if ($datakey ne '') {
1.1013 raeburn 8826: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 8827: if ($udom eq '' || $uname eq '') {
8828: $udom = $env{'user.domain'};
8829: $uname = $env{'user.name'};
8830: }
8831: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 8832: if (($uhome eq '') || ($uhome eq 'no_host')) {
8833: $result = 'error: no_host';
8834: } else {
8835: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
8836: $storehash->{'host'} = $perlvar{'lonHostID'};
8837:
8838: my $namevalue='';
8839: foreach my $key (keys(%{$storehash})) {
8840: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
8841: }
8842: $namevalue=~s/\&$//;
1.1224 raeburn 8843: unless ($namespace eq 'courserequests') {
8844: $datakey = &escape($datakey);
8845: }
1.1105 raeburn 8846: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
8847: $namevalue,$uhome);
1.1013 raeburn 8848: }
8849: } else {
8850: $result = 'error: data to store was not a hash reference';
8851: }
8852: } else {
8853: $result= 'error: invalid requestkey';
8854: }
8855: return $result;
8856: }
8857:
1.21 www 8858: # ---------------------------------------------------------- Assign Custom Role
8859:
8860: sub assigncustomrole {
1.957 raeburn 8861: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 8862: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 8863: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 8864: }
8865:
8866: # ----------------------------------------------------------------- Revoke Role
8867:
8868: sub revokerole {
1.957 raeburn 8869: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 8870: my $now=time;
1.965 raeburn 8871: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 8872: }
8873:
8874: # ---------------------------------------------------------- Revoke Custom Role
8875:
8876: sub revokecustomrole {
1.957 raeburn 8877: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 8878: my $now=time;
1.357 www 8879: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 8880: $deleteflag,$selfenroll,$context);
1.17 www 8881: }
8882:
1.533 banghart 8883: # ------------------------------------------------------------ Disk usage
1.535 albertel 8884: sub diskusage {
1.955 raeburn 8885: my ($udom,$uname,$directorypath,$getpropath)=@_;
8886: $directorypath =~ s/\/$//;
8887: my $listing=&reply('du2:'.&escape($directorypath).':'
8888: .&escape($getpropath).':'.&escape($uname).':'
8889: .&escape($udom),homeserver($uname,$udom));
8890: if ($listing eq 'unknown_cmd') {
8891: if ($getpropath) {
8892: $directorypath = &propath($udom,$uname).'/'.$directorypath;
8893: }
8894: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
8895: }
1.514 albertel 8896: return $listing;
1.512 banghart 8897: }
8898:
1.566 banghart 8899: sub is_locked {
1.1096 raeburn 8900: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 8901: my @check;
8902: my $is_locked;
1.1093 raeburn 8903: push (@check,$file_name);
1.613 albertel 8904: my %locked = &get('file_permissions',\@check,
1.620 albertel 8905: $env{'user.domain'},$env{'user.name'});
1.615 albertel 8906: my ($tmp)=keys(%locked);
8907: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 8908:
1.566 banghart 8909: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 8910: $is_locked = 'false';
8911: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 8912: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 8913: $is_locked = 'true';
1.1096 raeburn 8914: if (ref($which) eq 'ARRAY') {
8915: push(@{$which},$entry);
8916: } else {
8917: last;
8918: }
1.745 raeburn 8919: }
8920: }
1.566 banghart 8921: } else {
8922: $is_locked = 'false';
8923: }
1.1093 raeburn 8924: return $is_locked;
1.566 banghart 8925: }
8926:
1.759 albertel 8927: sub declutter_portfile {
8928: my ($file) = @_;
1.833 albertel 8929: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 8930: return $file;
8931: }
8932:
1.559 banghart 8933: # ------------------------------------------------------------- Mark as Read Only
8934:
8935: sub mark_as_readonly {
8936: my ($domain,$user,$files,$what) = @_;
1.613 albertel 8937: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 8938: my ($tmp)=keys(%current_permissions);
8939: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 8940: foreach my $file (@{$files}) {
1.759 albertel 8941: $file = &declutter_portfile($file);
1.561 banghart 8942: push(@{$current_permissions{$file}},$what);
1.559 banghart 8943: }
1.613 albertel 8944: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 8945: return;
8946: }
8947:
1.572 banghart 8948: # ------------------------------------------------------------Save Selected Files
8949:
8950: sub save_selected_files {
8951: my ($user, $path, @files) = @_;
8952: my $filename = $user."savedfiles";
1.573 banghart 8953: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 8954: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 8955: foreach my $file (@files) {
1.620 albertel 8956: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 8957: }
8958: foreach my $file (@other_files) {
1.574 banghart 8959: print (OUT $file."\n");
1.572 banghart 8960: }
1.574 banghart 8961: close (OUT);
1.572 banghart 8962: return 'ok';
8963: }
8964:
1.574 banghart 8965: sub clear_selected_files {
8966: my ($user) = @_;
8967: my $filename = $user."savedfiles";
1.1117 foxr 8968: open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574 banghart 8969: print (OUT undef);
8970: close (OUT);
8971: return ("ok");
8972: }
8973:
1.572 banghart 8974: sub files_in_path {
8975: my ($user, $path) = @_;
8976: my $filename = $user."savedfiles";
8977: my %return_files;
1.1117 foxr 8978: open (IN, '<'.LONCAPA::tempdir().$filename);
1.573 banghart 8979: while (my $line_in = <IN>) {
1.574 banghart 8980: chomp ($line_in);
8981: my @paths_and_file = split (m!/!, $line_in);
8982: my $file_part = pop (@paths_and_file);
8983: my $path_part = join ('/', @paths_and_file);
1.573 banghart 8984: $path_part.='/';
8985: my $path_and_file = $path_part.$file_part;
8986: if ($path_part eq $path) {
8987: $return_files{$file_part}= 'selected';
8988: }
8989: }
1.574 banghart 8990: close (IN);
8991: return (\%return_files);
1.572 banghart 8992: }
8993:
8994: # called in portfolio select mode, to show files selected NOT in current directory
8995: sub files_not_in_path {
8996: my ($user, $path) = @_;
8997: my $filename = $user."savedfiles";
8998: my @return_files;
8999: my $path_part;
1.1117 foxr 9000: open(IN, '<'.LONCAPA::.$filename);
1.800 albertel 9001: while (my $line = <IN>) {
1.572 banghart 9002: #ok, I know it's clunky, but I want it to work
1.800 albertel 9003: my @paths_and_file = split(m|/|, $line);
9004: my $file_part = pop(@paths_and_file);
9005: chomp($file_part);
9006: my $path_part = join('/', @paths_and_file);
1.572 banghart 9007: $path_part .= '/';
9008: my $path_and_file = $path_part.$file_part;
9009: if ($path_part ne $path) {
1.800 albertel 9010: push(@return_files, ($path_and_file));
1.572 banghart 9011: }
9012: }
1.800 albertel 9013: close(OUT);
1.574 banghart 9014: return (@return_files);
1.572 banghart 9015: }
9016:
1.745 raeburn 9017: #----------------------------------------------Get portfolio file permissions
1.629 banghart 9018:
1.745 raeburn 9019: sub get_portfile_permissions {
9020: my ($domain,$user) = @_;
1.613 albertel 9021: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 9022: my ($tmp)=keys(%current_permissions);
9023: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 9024: return \%current_permissions;
9025: }
9026:
9027: #---------------------------------------------Get portfolio file access controls
9028:
1.749 raeburn 9029: sub get_access_controls {
1.745 raeburn 9030: my ($current_permissions,$group,$file) = @_;
1.769 albertel 9031: my %access;
9032: my $real_file = $file;
9033: $file =~ s/\.meta$//;
1.745 raeburn 9034: if (defined($file)) {
1.749 raeburn 9035: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
9036: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 9037: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 9038: }
9039: }
1.745 raeburn 9040: } else {
1.749 raeburn 9041: foreach my $key (keys(%{$current_permissions})) {
9042: if ($key =~ /\0accesscontrol$/) {
9043: if (defined($group)) {
9044: if ($key !~ m-^\Q$group\E/-) {
9045: next;
9046: }
9047: }
9048: my ($fullpath) = split(/\0/,$key);
9049: if (ref($$current_permissions{$key}) eq 'HASH') {
9050: foreach my $control (keys(%{$$current_permissions{$key}})) {
9051: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
9052: }
9053: }
9054: }
9055: }
9056: }
9057: return %access;
9058: }
9059:
9060: sub modify_access_controls {
9061: my ($file_name,$changes,$domain,$user)=@_;
9062: my ($outcome,$deloutcome);
9063: my %store_permissions;
9064: my %new_values;
9065: my %new_control;
9066: my %translation;
9067: my @deletions = ();
9068: my $now = time;
9069: if (exists($$changes{'activate'})) {
9070: if (ref($$changes{'activate'}) eq 'HASH') {
9071: my @newitems = sort(keys(%{$$changes{'activate'}}));
9072: my $numnew = scalar(@newitems);
9073: for (my $i=0; $i<$numnew; $i++) {
9074: my $newkey = $newitems[$i];
9075: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 9076: if ($newkey =~ /^\d+:/) {
9077: $newkey =~ s/^(\d+)/$newid/;
9078: $translation{$1} = $newid;
9079: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
9080: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
9081: $translation{$1} = $newid;
9082: }
1.749 raeburn 9083: $new_values{$file_name."\0".$newkey} =
9084: $$changes{'activate'}{$newitems[$i]};
9085: $new_control{$newkey} = $now;
9086: }
9087: }
9088: }
9089: my %todelete;
9090: my %changed_items;
9091: foreach my $action ('delete','update') {
9092: if (exists($$changes{$action})) {
9093: if (ref($$changes{$action}) eq 'HASH') {
9094: foreach my $key (keys(%{$$changes{$action}})) {
9095: my ($itemnum) = ($key =~ /^([^:]+):/);
9096: if ($action eq 'delete') {
9097: $todelete{$itemnum} = 1;
9098: } else {
9099: $changed_items{$itemnum} = $key;
9100: }
9101: }
1.745 raeburn 9102: }
9103: }
1.749 raeburn 9104: }
9105: # get lock on access controls for file.
9106: my $lockhash = {
9107: $file_name."\0".'locked_access_records' => $env{'user.name'}.
9108: ':'.$env{'user.domain'},
9109: };
9110: my $tries = 0;
9111: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9112:
9113: while (($gotlock ne 'ok') && $tries <3) {
9114: $tries ++;
9115: sleep 1;
9116: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9117: }
9118: if ($gotlock eq 'ok') {
9119: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
9120: my ($tmp)=keys(%curr_permissions);
9121: if ($tmp=~/^error:/) { undef(%curr_permissions); }
9122: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
9123: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
9124: if (ref($curr_controls) eq 'HASH') {
9125: foreach my $control_item (keys(%{$curr_controls})) {
9126: my ($itemnum) = ($control_item =~ /^([^:]+):/);
9127: if (defined($todelete{$itemnum})) {
9128: push(@deletions,$file_name."\0".$control_item);
9129: } else {
9130: if (defined($changed_items{$itemnum})) {
9131: $new_control{$changed_items{$itemnum}} = $now;
9132: push(@deletions,$file_name."\0".$control_item);
9133: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
9134: } else {
9135: $new_control{$control_item} = $$curr_controls{$control_item};
9136: }
9137: }
1.745 raeburn 9138: }
9139: }
9140: }
1.970 raeburn 9141: my ($group);
9142: if (&is_course($domain,$user)) {
9143: ($group,my $file) = split(/\//,$file_name,2);
9144: }
1.749 raeburn 9145: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
9146: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
9147: $outcome = &put('file_permissions',\%new_values,$domain,$user);
9148: # remove lock
9149: my @del_lock = ($file_name."\0".'locked_access_records');
9150: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 9151: my $sqlresult =
1.970 raeburn 9152: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 9153: $group);
1.749 raeburn 9154: } else {
9155: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 9156: }
1.749 raeburn 9157: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 9158: }
9159:
1.827 raeburn 9160: sub make_public_indefinitely {
9161: my ($requrl) = @_;
9162: my $now = time;
9163: my $action = 'activate';
9164: my $aclnum = 0;
9165: if (&is_portfolio_url($requrl)) {
9166: my (undef,$udom,$unum,$file_name,$group) =
9167: &parse_portfolio_url($requrl);
9168: my $current_perms = &get_portfile_permissions($udom,$unum);
9169: my %access_controls = &get_access_controls($current_perms,
9170: $group,$file_name);
9171: foreach my $key (keys(%{$access_controls{$file_name}})) {
9172: my ($num,$scope,$end,$start) =
9173: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
9174: if ($scope eq 'public') {
9175: if ($start <= $now && $end == 0) {
9176: $action = 'none';
9177: } else {
9178: $action = 'update';
9179: $aclnum = $num;
9180: }
9181: last;
9182: }
9183: }
9184: if ($action eq 'none') {
9185: return 'ok';
9186: } else {
9187: my %changes;
9188: my $newend = 0;
9189: my $newstart = $now;
9190: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
9191: $changes{$action}{$newkey} = {
9192: type => 'public',
9193: time => {
9194: start => $newstart,
9195: end => $newend,
9196: },
9197: };
9198: my ($outcome,$deloutcome,$new_values,$translation) =
9199: &modify_access_controls($file_name,\%changes,$udom,$unum);
9200: return $outcome;
9201: }
9202: } else {
9203: return 'invalid';
9204: }
9205: }
9206:
1.745 raeburn 9207: #------------------------------------------------------Get Marked as Read Only
9208:
9209: sub get_marked_as_readonly {
9210: my ($domain,$user,$what,$group) = @_;
9211: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 9212: my @readonly_files;
1.629 banghart 9213: my $cmp1=$what;
9214: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 9215: while (my ($file_name,$value) = each(%{$current_permissions})) {
9216: if (defined($group)) {
9217: if ($file_name !~ m-^\Q$group\E/-) {
9218: next;
9219: }
9220: }
1.561 banghart 9221: if (ref($value) eq "ARRAY"){
9222: foreach my $stored_what (@{$value}) {
1.629 banghart 9223: my $cmp2=$stored_what;
1.759 albertel 9224: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 9225: $cmp2=join('',@{$stored_what});
1.745 raeburn 9226: }
1.629 banghart 9227: if ($cmp1 eq $cmp2) {
1.561 banghart 9228: push(@readonly_files, $file_name);
1.745 raeburn 9229: last;
1.563 banghart 9230: } elsif (!defined($what)) {
9231: push(@readonly_files, $file_name);
1.745 raeburn 9232: last;
1.561 banghart 9233: }
9234: }
1.745 raeburn 9235: }
1.561 banghart 9236: }
9237: return @readonly_files;
9238: }
1.577 banghart 9239: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 9240:
1.577 banghart 9241: sub get_marked_as_readonly_hash {
1.745 raeburn 9242: my ($current_permissions,$group,$what) = @_;
1.577 banghart 9243: my %readonly_files;
1.745 raeburn 9244: while (my ($file_name,$value) = each(%{$current_permissions})) {
9245: if (defined($group)) {
9246: if ($file_name !~ m-^\Q$group\E/-) {
9247: next;
9248: }
9249: }
1.577 banghart 9250: if (ref($value) eq "ARRAY"){
9251: foreach my $stored_what (@{$value}) {
1.745 raeburn 9252: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 9253: foreach my $lock_descriptor(@{$stored_what}) {
9254: if ($lock_descriptor eq 'graded') {
9255: $readonly_files{$file_name} = 'graded';
9256: } elsif ($lock_descriptor eq 'handback') {
9257: $readonly_files{$file_name} = 'handback';
9258: } else {
9259: if (!exists($readonly_files{$file_name})) {
9260: $readonly_files{$file_name} = 'locked';
9261: }
9262: }
1.745 raeburn 9263: }
1.750 banghart 9264: }
1.577 banghart 9265: }
9266: }
9267: }
9268: return %readonly_files;
9269: }
1.559 banghart 9270: # ------------------------------------------------------------ Unmark as Read Only
9271:
9272: sub unmark_as_readonly {
1.629 banghart 9273: # unmarks $file_name (if $file_name is defined), or all files locked by $what
9274: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 9275: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 9276: $file_name = &declutter_portfile($file_name);
1.634 albertel 9277: my $symb_crs = $what;
9278: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 9279: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 9280: my ($tmp)=keys(%current_permissions);
9281: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 9282: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 9283: foreach my $file (@readonly_files) {
1.759 albertel 9284: my $clean_file = &declutter_portfile($file);
9285: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 9286: my $current_locks = $current_permissions{$file};
1.563 banghart 9287: my @new_locks;
9288: my @del_keys;
9289: if (ref($current_locks) eq "ARRAY"){
9290: foreach my $locker (@{$current_locks}) {
1.632 albertel 9291: my $compare=$locker;
1.749 raeburn 9292: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 9293: $compare=join('',@{$locker});
1.746 raeburn 9294: if ($compare ne $symb_crs) {
9295: push(@new_locks, $locker);
9296: }
1.563 banghart 9297: }
9298: }
1.650 albertel 9299: if (scalar(@new_locks) > 0) {
1.563 banghart 9300: $current_permissions{$file} = \@new_locks;
9301: } else {
9302: push(@del_keys, $file);
1.613 albertel 9303: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 9304: delete($current_permissions{$file});
1.563 banghart 9305: }
9306: }
1.561 banghart 9307: }
1.613 albertel 9308: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 9309: return;
9310: }
1.512 banghart 9311:
1.17 www 9312: # ------------------------------------------------------------ Directory lister
9313:
9314: sub dirlist {
1.955 raeburn 9315: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 9316: $uri=~s/^\///;
9317: $uri=~s/\/$//;
1.253 stredwic 9318: my ($udom, $uname);
1.955 raeburn 9319: if ($getuserdir) {
1.253 stredwic 9320: $udom = $userdomain;
9321: $uname = $username;
1.955 raeburn 9322: } else {
9323: (undef,$udom,$uname)=split(/\//,$uri);
9324: if(defined($userdomain)) {
9325: $udom = $userdomain;
9326: }
9327: if(defined($username)) {
9328: $uname = $username;
9329: }
1.253 stredwic 9330: }
1.955 raeburn 9331: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 9332:
1.955 raeburn 9333: $dirRoot = $perlvar{'lonDocRoot'};
9334: if (defined($getpropath)) {
9335: $dirRoot = &propath($udom,$uname);
1.253 stredwic 9336: $dirRoot =~ s/\/$//;
1.955 raeburn 9337: } elsif (defined($getuserdir)) {
9338: my $subdir=$uname.'__';
9339: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
9340: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
9341: ."/$udom/$subdir/$uname";
9342: } elsif (defined($alternateRoot)) {
9343: $dirRoot = $alternateRoot;
1.751 banghart 9344: }
1.253 stredwic 9345:
9346: if($udom) {
9347: if($uname) {
1.1135 raeburn 9348: my $uhome = &homeserver($uname,$udom);
1.1136 raeburn 9349: if ($uhome eq 'no_host') {
9350: return ([],'no_host');
9351: }
1.955 raeburn 9352: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 9353: .$getuserdir.':'.&escape($dirRoot)
1.1135 raeburn 9354: .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955 raeburn 9355: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 9356: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955 raeburn 9357: } else {
9358: @listing_results = map { &unescape($_); } split(/:/,$listing);
9359: }
1.605 matthew 9360: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 9361: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605 matthew 9362: @listing_results = split(/:/,$listing);
9363: } else {
9364: @listing_results = map { &unescape($_); } split(/:/,$listing);
9365: }
1.1135 raeburn 9366: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
1.1136 raeburn 9367: ($listing eq 'rejected') || ($listing eq 'refused') ||
9368: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
9369: return ([],$listing);
9370: } else {
9371: return (\@listing_results);
1.1135 raeburn 9372: }
1.955 raeburn 9373: } elsif(!$alternateRoot) {
1.1136 raeburn 9374: my (%allusers,%listerror);
1.841 albertel 9375: my %servers = &get_servers($udom,'library');
1.955 raeburn 9376: foreach my $tryserver (keys(%servers)) {
9377: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
9378: &escape($udom),$tryserver);
9379: if ($listing eq 'unknown_cmd') {
9380: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
9381: $udom, $tryserver);
9382: } else {
9383: @listing_results = map { &unescape($_); } split(/:/,$listing);
9384: }
1.841 albertel 9385: if ($listing eq 'unknown_cmd') {
9386: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
9387: $udom, $tryserver);
9388: @listing_results = split(/:/,$listing);
9389: } else {
9390: @listing_results =
9391: map { &unescape($_); } split(/:/,$listing);
9392: }
1.1136 raeburn 9393: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
9394: ($listing eq 'rejected') || ($listing eq 'refused') ||
9395: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
9396: $listerror{$tryserver} = $listing;
9397: } else {
1.841 albertel 9398: foreach my $line (@listing_results) {
9399: my ($entry) = split(/&/,$line,2);
9400: $allusers{$entry} = 1;
9401: }
9402: }
1.253 stredwic 9403: }
1.1136 raeburn 9404: my @alluserslist=();
1.800 albertel 9405: foreach my $user (sort(keys(%allusers))) {
1.1136 raeburn 9406: push(@alluserslist,$user.'&user');
1.253 stredwic 9407: }
1.1136 raeburn 9408: return (\@alluserslist);
1.253 stredwic 9409: } else {
1.1136 raeburn 9410: return ([],'missing username');
1.253 stredwic 9411: }
1.955 raeburn 9412: } elsif(!defined($getpropath)) {
1.1136 raeburn 9413: my $path = $perlvar{'lonDocRoot'}.'/res/';
9414: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
9415: return (\@all_domains);
1.955 raeburn 9416: } else {
1.1136 raeburn 9417: return ([],'missing domain');
1.275 stredwic 9418: }
9419: }
9420:
9421: # --------------------------------------------- GetFileTimestamp
9422: # This function utilizes dirlist and returns the date stamp for
9423: # when it was last modified. It will also return an error of -1
9424: # if an error occurs
9425:
9426: sub GetFileTimestamp {
1.955 raeburn 9427: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 9428: $studentDomain = &LONCAPA::clean_domain($studentDomain);
9429: $studentName = &LONCAPA::clean_username($studentName);
1.1136 raeburn 9430: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
9431: undef,$getuserdir);
9432: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
9433: return -1;
9434: }
9435: if (ref($fileref) eq 'ARRAY') {
9436: my @stats = split('&',$fileref->[0]);
1.375 matthew 9437: # @stats contains first the filename, then the stat output
9438: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 9439: } else {
9440: return -1;
1.253 stredwic 9441: }
1.26 www 9442: }
9443:
1.712 albertel 9444: sub stat_file {
9445: my ($uri) = @_;
1.787 albertel 9446: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 9447:
1.955 raeburn 9448: my ($udom,$uname,$file);
1.712 albertel 9449: if ($uri =~ m-^/(uploaded|editupload)/-) {
9450: ($udom,$uname,$file) =
1.811 albertel 9451: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 9452: $file = 'userfiles/'.$file;
9453: }
9454: if ($uri =~ m-^/res/-) {
9455: ($udom,$uname) =
1.807 albertel 9456: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 9457: $file = $uri;
9458: }
9459:
9460: if (!$udom || !$uname || !$file) {
9461: # unable to handle the uri
9462: return ();
9463: }
1.956 raeburn 9464: my $getpropath;
9465: if ($file =~ /^userfiles\//) {
9466: $getpropath = 1;
9467: }
1.1136 raeburn 9468: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
9469: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
9470: return ();
9471: } else {
9472: if (ref($listref) eq 'ARRAY') {
9473: my @stats = split('&',$listref->[0]);
9474: shift(@stats); #filename is first
9475: return @stats;
9476: }
1.712 albertel 9477: }
9478: return ();
9479: }
9480:
1.26 www 9481: # -------------------------------------------------------- Value of a Condition
9482:
1.713 albertel 9483: # gets the value of a specific preevaluated condition
9484: # stored in the string $env{user.state.<cid>}
9485: # or looks up a condition reference in the bighash and if if hasn't
9486: # already been evaluated recurses into docondval to get the value of
9487: # the condition, then memoizing it to
9488: # $env{user.state.<cid>.<condition>}
1.40 www 9489: sub directcondval {
9490: my $number=shift;
1.620 albertel 9491: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 9492: &Apache::lonuserstate::evalstate();
9493: }
1.713 albertel 9494: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
9495: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
9496: } elsif ($number =~ /^_/) {
9497: my $sub_condition;
9498: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
9499: &GDBM_READER(),0640)) {
9500: $sub_condition=$bighash{'conditions'.$number};
9501: untie(%bighash);
9502: }
9503: my $value = &docondval($sub_condition);
1.949 raeburn 9504: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 9505: return $value;
9506: }
1.620 albertel 9507: if ($env{'user.state.'.$env{'request.course.id'}}) {
9508: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 9509: } else {
9510: return 2;
9511: }
9512: }
9513:
1.713 albertel 9514: # get the collection of conditions for this resource
1.26 www 9515: sub condval {
9516: my $condidx=shift;
1.54 www 9517: my $allpathcond='';
1.713 albertel 9518: foreach my $cond (split(/\|/,$condidx)) {
9519: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
9520: $allpathcond.=
9521: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
9522: }
1.191 harris41 9523: }
1.54 www 9524: $allpathcond=~s/\|$//;
1.713 albertel 9525: return &docondval($allpathcond);
9526: }
9527:
9528: #evaluates an expression of conditions
9529: sub docondval {
9530: my ($allpathcond) = @_;
9531: my $result=0;
9532: if ($env{'request.course.id'}
9533: && defined($allpathcond)) {
9534: my $operand='|';
9535: my @stack;
9536: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
9537: if ($chunk eq '(') {
9538: push @stack,($operand,$result);
9539: } elsif ($chunk eq ')') {
9540: my $before=pop @stack;
9541: if (pop @stack eq '&') {
9542: $result=$result>$before?$before:$result;
9543: } else {
9544: $result=$result>$before?$result:$before;
9545: }
9546: } elsif (($chunk eq '&') || ($chunk eq '|')) {
9547: $operand=$chunk;
9548: } else {
9549: my $new=directcondval($chunk);
9550: if ($operand eq '&') {
9551: $result=$result>$new?$new:$result;
9552: } else {
9553: $result=$result>$new?$result:$new;
9554: }
9555: }
9556: }
1.26 www 9557: }
9558: return $result;
1.421 albertel 9559: }
9560:
9561: # ---------------------------------------------------- Devalidate courseresdata
9562:
9563: sub devalidatecourseresdata {
9564: my ($coursenum,$coursedomain)=@_;
9565: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 9566: &devalidate_cache_new('courseres',$hashid);
1.28 www 9567: }
9568:
1.763 www 9569:
1.200 www 9570: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 9571: #
9572: # Parameters:
9573: # $coursenum - Number of the course.
9574: # $coursedomain - Domain at which the course was created.
9575: # Returns:
9576: # A hash of the course parameters along (I think) with timestamps
9577: # and version info.
1.877 foxr 9578:
1.624 albertel 9579: sub get_courseresdata {
9580: my ($coursenum,$coursedomain)=@_;
1.200 www 9581: my $coursehom=&homeserver($coursenum,$coursedomain);
9582: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 9583: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 9584: my %dumpreply;
1.417 albertel 9585: unless (defined($cached)) {
1.624 albertel 9586: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 9587: $result=\%dumpreply;
1.251 albertel 9588: my ($tmp) = keys(%dumpreply);
9589: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 9590: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 9591: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
9592: return $tmp;
1.416 albertel 9593: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 9594: $result=undef;
1.599 albertel 9595: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 9596: }
9597: }
1.624 albertel 9598: return $result;
9599: }
9600:
1.633 albertel 9601: sub devalidateuserresdata {
9602: my ($uname,$udom)=@_;
9603: my $hashid="$udom:$uname";
9604: &devalidate_cache_new('userres',$hashid);
9605: }
9606:
1.624 albertel 9607: sub get_userresdata {
9608: my ($uname,$udom)=@_;
9609: #most student don\'t have any data set, check if there is some data
9610: if (&EXT_cache_status($udom,$uname)) { return undef; }
9611:
9612: my $hashid="$udom:$uname";
9613: my ($result,$cached)=&is_cached_new('userres',$hashid);
9614: if (!defined($cached)) {
9615: my %resourcedata=&dump('resourcedata',$udom,$uname);
9616: $result=\%resourcedata;
9617: &do_cache_new('userres',$hashid,$result,600);
9618: }
9619: my ($tmp)=keys(%$result);
9620: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
9621: return $result;
9622: }
9623: #error 2 occurs when the .db doesn't exist
9624: if ($tmp!~/error: 2 /) {
1.672 albertel 9625: &logthis("<font color=\"blue\">WARNING:".
1.624 albertel 9626: " Trying to get resource data for ".
9627: $uname." at ".$udom.": ".
9628: $tmp."</font>");
9629: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 9630: #&EXT_cache_set($udom,$uname);
9631: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 9632: undef($tmp); # not really an error so don't send it back
1.624 albertel 9633: }
9634: return $tmp;
9635: }
1.879 foxr 9636: #----------------------------------------------- resdata - return resource data
9637: # Purpose:
9638: # Return resource data for either users or for a course.
9639: # Parameters:
9640: # $name - Course/user name.
9641: # $domain - Name of the domain the user/course is registered on.
9642: # $type - Type of thing $name is (must be 'course' or 'user'
9643: # @which - Array of names of resources desired.
9644: # Returns:
9645: # The value of the first reasource in @which that is found in the
9646: # resource hash.
9647: # Exceptional Conditions:
9648: # If the $type passed in is not valid (not the string 'course' or
9649: # 'user', an undefined reference is returned.
9650: # If none of the resources are found, an undef is returned
1.624 albertel 9651: sub resdata {
9652: my ($name,$domain,$type,@which)=@_;
9653: my $result;
9654: if ($type eq 'course') {
9655: $result=&get_courseresdata($name,$domain);
9656: } elsif ($type eq 'user') {
9657: $result=&get_userresdata($name,$domain);
9658: }
9659: if (!ref($result)) { return $result; }
1.251 albertel 9660: foreach my $item (@which) {
1.927 albertel 9661: if (defined($result->{$item->[0]})) {
9662: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 9663: }
1.250 albertel 9664: }
1.291 albertel 9665: return undef;
1.200 www 9666: }
9667:
1.1236 raeburn 9668: sub get_numsuppfiles {
9669: my ($cnum,$cdom,$ignorecache)=@_;
9670: my $hashid=$cnum.':'.$cdom;
9671: my ($suppcount,$cached);
9672: unless ($ignorecache) {
9673: ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
9674: }
9675: unless (defined($cached)) {
9676: my $chome=&homeserver($cnum,$cdom);
9677: unless ($chome eq 'no_host') {
9678: ($suppcount,my $errors) = (0,0);
9679: my $suppmap = 'supplemental.sequence';
9680: ($suppcount,$errors) =
9681: &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
9682: }
9683: &do_cache_new('suppcount',$hashid,$suppcount,600);
9684: }
9685: return $suppcount;
9686: }
9687:
1.379 matthew 9688: #
9689: # EXT resource caching routines
9690: #
9691:
9692: sub clear_EXT_cache_status {
1.383 albertel 9693: &delenv('cache.EXT.');
1.379 matthew 9694: }
9695:
9696: sub EXT_cache_status {
9697: my ($target_domain,$target_user) = @_;
1.383 albertel 9698: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 9699: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 9700: # We know already the user has no data
9701: return 1;
9702: } else {
9703: return 0;
9704: }
9705: }
9706:
9707: sub EXT_cache_set {
9708: my ($target_domain,$target_user) = @_;
1.383 albertel 9709: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 9710: #&appenv({$cachename => time});
1.379 matthew 9711: }
9712:
1.28 www 9713: # --------------------------------------------------------- Value of a Variable
1.58 www 9714: sub EXT {
1.715 albertel 9715:
1.1228 raeburn 9716: my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68 www 9717: unless ($varname) { return ''; }
1.218 albertel 9718: #get real user name/domain, courseid and symb
9719: my $courseid;
1.359 albertel 9720: my $publicuser;
1.427 www 9721: if ($symbparm) {
9722: $symbparm=&get_symb_from_alias($symbparm);
9723: }
1.218 albertel 9724: if (!($uname && $udom)) {
1.790 albertel 9725: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 9726: if (!$symbparm) { $symbparm=$cursymb; }
9727: } else {
1.620 albertel 9728: $courseid=$env{'request.course.id'};
1.218 albertel 9729: }
1.48 www 9730: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
9731: my $rest;
1.320 albertel 9732: if (defined($therest[0])) {
1.48 www 9733: $rest=join('.',@therest);
9734: } else {
9735: $rest='';
9736: }
1.320 albertel 9737:
1.57 www 9738: my $qualifierrest=$qualifier;
9739: if ($rest) { $qualifierrest.='.'.$rest; }
9740: my $spacequalifierrest=$space;
9741: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 9742: if ($realm eq 'user') {
1.48 www 9743: # --------------------------------------------------------------- user.resource
9744: if ($space eq 'resource') {
1.651 albertel 9745: if ( (defined($Apache::lonhomework::parsing_a_problem)
9746: || defined($Apache::lonhomework::parsing_a_task))
9747: &&
1.744 albertel 9748: ($symbparm eq &symbread()) ) {
9749: # if we are in the middle of processing the resource the
9750: # get the value we are planning on committing
9751: if (defined($Apache::lonhomework::results{$qualifierrest})) {
9752: return $Apache::lonhomework::results{$qualifierrest};
9753: } else {
9754: return $Apache::lonhomework::history{$qualifierrest};
9755: }
1.335 albertel 9756: } else {
1.359 albertel 9757: my %restored;
1.620 albertel 9758: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 9759: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
9760: } else {
9761: %restored=&restore($symbparm,$courseid,$udom,$uname);
9762: }
1.335 albertel 9763: return $restored{$qualifierrest};
9764: }
1.48 www 9765: # ----------------------------------------------------------------- user.access
9766: } elsif ($space eq 'access') {
1.218 albertel 9767: # FIXME - not supporting calls for a specific user
1.48 www 9768: return &allowed($qualifier,$rest);
9769: # ------------------------------------------ user.preferences, user.environment
9770: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 9771: if (($uname eq $env{'user.name'}) &&
9772: ($udom eq $env{'user.domain'})) {
9773: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 9774: } else {
1.359 albertel 9775: my %returnhash;
9776: if (!$publicuser) {
9777: %returnhash=&userenvironment($udom,$uname,
9778: $qualifierrest);
9779: }
1.218 albertel 9780: return $returnhash{$qualifierrest};
9781: }
1.48 www 9782: # ----------------------------------------------------------------- user.course
9783: } elsif ($space eq 'course') {
1.218 albertel 9784: # FIXME - not supporting calls for a specific user
1.620 albertel 9785: return $env{join('.',('request.course',$qualifier))};
1.48 www 9786: # ------------------------------------------------------------------- user.role
9787: } elsif ($space eq 'role') {
1.218 albertel 9788: # FIXME - not supporting calls for a specific user
1.620 albertel 9789: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 9790: if ($qualifier eq 'value') {
9791: return $role;
9792: } elsif ($qualifier eq 'extent') {
9793: return $where;
9794: }
9795: # ----------------------------------------------------------------- user.domain
9796: } elsif ($space eq 'domain') {
1.218 albertel 9797: return $udom;
1.48 www 9798: # ------------------------------------------------------------------- user.name
9799: } elsif ($space eq 'name') {
1.218 albertel 9800: return $uname;
1.48 www 9801: # ---------------------------------------------------- Any other user namespace
1.29 www 9802: } else {
1.359 albertel 9803: my %reply;
9804: if (!$publicuser) {
9805: %reply=&get($space,[$qualifierrest],$udom,$uname);
9806: }
9807: return $reply{$qualifierrest};
1.48 www 9808: }
1.236 www 9809: } elsif ($realm eq 'query') {
9810: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 9811: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
9812: [$spacequalifierrest]);
1.620 albertel 9813: return $env{'form.'.$spacequalifierrest};
1.236 www 9814: } elsif ($realm eq 'request') {
1.48 www 9815: # ------------------------------------------------------------- request.browser
9816: if ($space eq 'browser') {
1.1145 bisitz 9817: return $env{'browser.'.$qualifier};
1.57 www 9818: # ------------------------------------------------------------ request.filename
9819: } else {
1.620 albertel 9820: return $env{'request.'.$spacequalifierrest};
1.29 www 9821: }
1.28 www 9822: } elsif ($realm eq 'course') {
1.48 www 9823: # ---------------------------------------------------------- course.description
1.620 albertel 9824: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 9825: } elsif ($realm eq 'resource') {
1.165 www 9826:
1.620 albertel 9827: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 9828: if (!$symbparm) { $symbparm=&symbread(); }
9829: }
1.693 albertel 9830:
1.1232 raeburn 9831: if ($qualifier eq '') {
9832: if ($space eq 'title') {
9833: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
9834: return &gettitle($symbparm);
9835: }
1.693 albertel 9836:
1.1232 raeburn 9837: if ($space eq 'map') {
9838: my ($map) = &decode_symb($symbparm);
9839: return &symbread($map);
9840: }
9841: if ($space eq 'maptitle') {
9842: my ($map) = &decode_symb($symbparm);
9843: return &gettitle($map);
9844: }
9845: if ($space eq 'filename') {
9846: if ($symbparm) {
9847: return &clutter((&decode_symb($symbparm))[2]);
9848: }
9849: return &hreflocation('',$env{'request.filename'});
1.905 albertel 9850: }
1.1232 raeburn 9851:
1.1233 raeburn 9852: if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
9853: if ($space eq 'visibleparts') {
9854: my $navmap = Apache::lonnavmaps::navmap->new();
9855: my $item;
9856: if (ref($navmap)) {
9857: my $res = $navmap->getBySymb($symbparm);
9858: my $parts = $res->parts();
9859: if (ref($parts) eq 'ARRAY') {
9860: $item = join(',',@{$parts});
9861: }
9862: undef($navmap);
1.1232 raeburn 9863: }
1.1233 raeburn 9864: return $item;
1.1232 raeburn 9865: }
9866: }
9867: }
1.693 albertel 9868:
9869: my ($section, $group, @groups);
1.593 albertel 9870: my ($courselevelm,$courselevel);
1.1228 raeburn 9871: if (($courseid eq '') && ($cid)) {
9872: $courseid = $cid;
9873: }
9874: if (($symbparm && $courseid) &&
9875: (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165 www 9876:
1.218 albertel 9877: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 9878:
1.60 www 9879: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 9880: my $symbp=$symbparm;
1.735 albertel 9881: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 9882:
9883: my $symbparm=$symbp.'.'.$spacequalifierrest;
9884: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
9885:
1.620 albertel 9886: if (($env{'user.name'} eq $uname) &&
9887: ($env{'user.domain'} eq $udom)) {
9888: $section=$env{'request.course.sec'};
1.733 raeburn 9889: @groups = split(/:/,$env{'request.course.groups'});
9890: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 9891: } else {
1.539 albertel 9892: if (! defined($usection)) {
1.551 albertel 9893: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 9894: } else {
9895: $section = $usection;
9896: }
1.733 raeburn 9897: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 9898: }
9899:
9900: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
9901: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
9902: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
9903:
1.593 albertel 9904: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 9905: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 9906: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 9907:
1.60 www 9908: # ----------------------------------------------------------- first, check user
1.624 albertel 9909:
9910: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 9911: ([$courselevelr,'resource'],
9912: [$courselevelm,'map' ],
9913: [$courselevel, 'course' ]));
1.931 albertel 9914: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 9915:
1.594 albertel 9916: # ------------------------------------------------ second, check some of course
1.684 raeburn 9917: my $coursereply;
1.691 raeburn 9918: if (@groups > 0) {
9919: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
9920: $mapparm,$spacequalifierrest);
1.927 albertel 9921: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 9922: }
1.96 www 9923:
1.684 raeburn 9924: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 9925: $env{'course.'.$courseid.'.domain'},
9926: 'course',
9927: ([$seclevelr, 'resource'],
9928: [$seclevelm, 'map' ],
9929: [$seclevel, 'course' ],
9930: [$courselevelr,'resource']));
9931: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 9932:
1.60 www 9933: # ------------------------------------------------------ third, check map parms
1.218 albertel 9934: my %parmhash=();
9935: my $thisparm='';
9936: if (tie(%parmhash,'GDBM_File',
1.620 albertel 9937: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 9938: &GDBM_READER(),0640)) {
1.218 albertel 9939: $thisparm=$parmhash{$symbparm};
9940: untie(%parmhash);
9941: }
1.927 albertel 9942: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 9943: }
1.594 albertel 9944: # ------------------------------------------ fourth, look in resource metadata
1.71 www 9945:
1.218 albertel 9946: $spacequalifierrest=~s/\./\_/;
1.282 albertel 9947: my $filename;
9948: if (!$symbparm) { $symbparm=&symbread(); }
9949: if ($symbparm) {
1.409 www 9950: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 9951: } else {
1.620 albertel 9952: $filename=$env{'request.filename'};
1.282 albertel 9953: }
9954: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 9955: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 9956: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 9957: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 9958:
1.927 albertel 9959: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 9960: if ($symbparm && defined($courseid) &&
1.620 albertel 9961: $courseid eq $env{'request.course.id'}) {
1.624 albertel 9962: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
9963: $env{'course.'.$courseid.'.domain'},
9964: 'course',
1.927 albertel 9965: ([$courselevelm,'map' ],
9966: [$courselevel, 'course']));
9967: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 9968: }
1.145 www 9969: # ------------------------------------------------------------------ Cascade up
1.218 albertel 9970: unless ($space eq '0') {
1.336 albertel 9971: my @parts=split(/_/,$space);
9972: my $id=pop(@parts);
9973: my $part=join('_',@parts);
9974: if ($part eq '') { $part='0'; }
1.927 albertel 9975: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 9976: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 9977: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 9978: }
1.395 albertel 9979: if ($recurse) { return undef; }
9980: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 9981: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 9982: # ---------------------------------------------------- Any other user namespace
9983: } elsif ($realm eq 'environment') {
9984: # ----------------------------------------------------------------- environment
1.620 albertel 9985: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
9986: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 9987: } else {
1.770 albertel 9988: if ($uname eq 'anonymous' && $udom eq '') {
9989: return '';
9990: }
1.219 albertel 9991: my %returnhash=&userenvironment($udom,$uname,
9992: $spacequalifierrest);
9993: return $returnhash{$spacequalifierrest};
9994: }
1.28 www 9995: } elsif ($realm eq 'system') {
1.48 www 9996: # ----------------------------------------------------------------- system.time
9997: if ($space eq 'time') {
9998: return time;
9999: }
1.696 albertel 10000: } elsif ($realm eq 'server') {
10001: # ----------------------------------------------------------------- system.time
10002: if ($space eq 'name') {
10003: return $ENV{'SERVER_NAME'};
10004: }
1.28 www 10005: }
1.48 www 10006: return '';
1.61 www 10007: }
10008:
1.927 albertel 10009: sub get_reply {
10010: my ($reply_value) = @_;
1.940 raeburn 10011: if (ref($reply_value) eq 'ARRAY') {
10012: if (wantarray) {
10013: return @$reply_value;
10014: }
10015: return $reply_value->[0];
10016: } else {
10017: return $reply_value;
1.927 albertel 10018: }
10019: }
10020:
1.691 raeburn 10021: sub check_group_parms {
10022: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
10023: my @groupitems = ();
10024: my $resultitem;
1.927 albertel 10025: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 10026: foreach my $group (@{$groups}) {
10027: foreach my $level (@levels) {
1.927 albertel 10028: my $item = $courseid.'.['.$group.'].'.$level->[0];
10029: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 10030: }
10031: }
10032: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
10033: $env{'course.'.$courseid.'.domain'},
10034: 'course',@groupitems);
10035: return $coursereply;
10036: }
10037:
10038: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 10039: my ($courseid,@groups) = @_;
10040: @groups = sort(@groups);
1.691 raeburn 10041: return @groups;
10042: }
10043:
1.395 albertel 10044: sub packages_tab_default {
10045: my ($uri,$varname)=@_;
10046: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 10047:
10048: my (@extension,@specifics,$do_default);
10049: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 10050: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 10051: if ($pack_type eq 'default') {
10052: $do_default=1;
10053: } elsif ($pack_type eq 'extension') {
10054: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 10055: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 10056: # only look at packages defaults for packages that this id is
1.738 albertel 10057: push(@specifics,[$package,$pack_type,$pack_part]);
10058: }
10059: }
10060: # first look for a package that matches the requested part id
10061: foreach my $package (@specifics) {
10062: my (undef,$pack_type,$pack_part)=@{$package};
10063: next if ($pack_part ne $part);
10064: if (defined($packagetab{"$pack_type&$name&default"})) {
10065: return $packagetab{"$pack_type&$name&default"};
10066: }
10067: }
10068: # look for any possible matching non extension_ package
10069: foreach my $package (@specifics) {
10070: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 10071: if (defined($packagetab{"$pack_type&$name&default"})) {
10072: return $packagetab{"$pack_type&$name&default"};
10073: }
1.585 albertel 10074: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 10075: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
10076: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 10077: }
10078: }
1.738 albertel 10079: # look for any posible extension_ match
10080: foreach my $package (@extension) {
10081: my ($package,$pack_type)=@{$package};
10082: if (defined($packagetab{"$pack_type&$name&default"})) {
10083: return $packagetab{"$pack_type&$name&default"};
10084: }
10085: if (defined($packagetab{$package."&$name&default"})) {
10086: return $packagetab{$package."&$name&default"};
10087: }
10088: }
10089: # look for a global default setting
10090: if ($do_default && defined($packagetab{"default&$name&default"})) {
10091: return $packagetab{"default&$name&default"};
10092: }
1.395 albertel 10093: return undef;
10094: }
10095:
1.334 albertel 10096: sub add_prefix_and_part {
10097: my ($prefix,$part)=@_;
10098: my $keyroot;
10099: if (defined($prefix) && $prefix !~ /^__/) {
10100: # prefix that has a part already
10101: $keyroot=$prefix;
10102: } elsif (defined($prefix)) {
10103: # prefix that is missing a part
10104: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
10105: } else {
10106: # no prefix at all
10107: if (defined($part)) { $keyroot='_'.$part; }
10108: }
10109: return $keyroot;
10110: }
10111:
1.71 www 10112: # ---------------------------------------------------------------- Get metadata
10113:
1.599 albertel 10114: my %metaentry;
1.1070 www 10115: my %importedpartids;
1.71 www 10116: sub metadata {
1.176 www 10117: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 10118: $uri=&declutter($uri);
1.288 albertel 10119: # if it is a non metadata possible uri return quickly
1.529 albertel 10120: if (($uri eq '') ||
10121: (($uri =~ m|^/*adm/|) &&
1.1217 raeburn 10122: ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108 raeburn 10123: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 10124: return undef;
10125: }
1.1140 www 10126: if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/)
1.924 albertel 10127: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 10128: return undef;
1.288 albertel 10129: }
1.73 www 10130: my $filename=$uri;
10131: $uri=~s/\.meta$//;
1.172 www 10132: #
10133: # Is the metadata already cached?
1.177 www 10134: # Look at timestamp of caching
1.172 www 10135: # Everything is cached by the main uri, libraries are never directly cached
10136: #
1.428 albertel 10137: if (!defined($liburi)) {
1.599 albertel 10138: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 10139: if (defined($cached)) { return $result->{':'.$what}; }
10140: }
10141: {
1.1069 www 10142: # Imported parts would go here
1.1070 www 10143: my %importedids=();
10144: my @origfileimportpartids=();
1.1069 www 10145: my $importedparts=0;
1.172 www 10146: #
10147: # Is this a recursive call for a library?
10148: #
1.599 albertel 10149: # if (! exists($metacache{$uri})) {
10150: # $metacache{$uri}={};
10151: # }
1.924 albertel 10152: my $cachetime = 60*60;
1.171 www 10153: if ($liburi) {
10154: $liburi=&declutter($liburi);
10155: $filename=$liburi;
1.401 bowersj2 10156: } else {
1.599 albertel 10157: &devalidate_cache_new('meta',$uri);
10158: undef(%metaentry);
1.401 bowersj2 10159: }
1.140 www 10160: my %metathesekeys=();
1.73 www 10161: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 10162: my $metastring;
1.1140 www 10163: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929 albertel 10164: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 10165: $metastring =
1.929 albertel 10166: &Apache::lonnet::ssi_body($which,
1.924 albertel 10167: ('grade_target' => 'meta'));
10168: $cachetime = 1; # only want this cached in the child not long term
1.1108 raeburn 10169: } elsif (($uri !~ m -^(editupload)/-) &&
10170: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 10171: my $file=&filelocation('',&clutter($filename));
1.599 albertel 10172: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 10173: $metastring=&getfile($file);
1.489 albertel 10174: }
1.208 albertel 10175: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 10176: my $token;
1.140 www 10177: undef %metathesekeys;
1.71 www 10178: while ($token=$parser->get_token) {
1.339 albertel 10179: if ($token->[0] eq 'S') {
10180: if (defined($token->[2]->{'package'})) {
1.172 www 10181: #
10182: # This is a package - get package info
10183: #
1.339 albertel 10184: my $package=$token->[2]->{'package'};
10185: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10186: if (defined($token->[2]->{'id'})) {
10187: $keyroot.='_'.$token->[2]->{'id'};
10188: }
1.599 albertel 10189: if ($metaentry{':packages'}) {
10190: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 10191: } else {
1.599 albertel 10192: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 10193: }
1.736 albertel 10194: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 10195: my $part=$keyroot;
10196: $part=~s/^\_//;
1.736 albertel 10197: if ($pack_entry=~/^\Q$package\E\&/ ||
10198: $pack_entry=~/^\Q$package\E_0\&/) {
10199: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 10200: # ignore package.tab specified default values
10201: # here &package_tab_default() will fetch those
10202: if ($subp eq 'default') { next; }
1.736 albertel 10203: my $value=$packagetab{$pack_entry};
1.432 albertel 10204: my $unikey;
10205: if ($pack =~ /_0$/) {
10206: $unikey='parameter_0_'.$name;
10207: $part=0;
10208: } else {
10209: $unikey='parameter'.$keyroot.'_'.$name;
10210: }
1.339 albertel 10211: if ($subp eq 'display') {
10212: $value.=' [Part: '.$part.']';
10213: }
1.599 albertel 10214: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 10215: $metathesekeys{$unikey}=1;
1.599 albertel 10216: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10217: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 10218: }
1.599 albertel 10219: if (defined($metaentry{':'.$unikey.'.default'})) {
10220: $metaentry{':'.$unikey}=
10221: $metaentry{':'.$unikey.'.default'};
1.356 albertel 10222: }
1.339 albertel 10223: }
10224: }
10225: } else {
1.172 www 10226: #
10227: # This is not a package - some other kind of start tag
1.339 albertel 10228: #
10229: my $entry=$token->[1];
1.1068 www 10230: my $unikey='';
1.175 www 10231:
1.339 albertel 10232: if ($entry eq 'import') {
1.175 www 10233: #
10234: # Importing a library here
1.339 albertel 10235: #
1.1067 www 10236: my $location=$parser->get_text('/import');
10237: my $dir=$filename;
10238: $dir=~s|[^/]*$||;
10239: $location=&filelocation($dir,$location);
1.1069 www 10240:
1.1068 www 10241: my $importmode=$token->[2]->{'importmode'};
10242: if ($importmode eq 'problem') {
1.1069 www 10243: # Import as problem/response
1.1068 www 10244: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10245: } elsif ($importmode eq 'part') {
10246: # Import as part(s)
1.1069 www 10247: $importedparts=1;
10248: # We need to get the original file and the imported file to get the part order correct
10249: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
10250: # Load and inspect original file
1.1070 www 10251: if ($#origfileimportpartids<0) {
10252: undef(%importedpartids);
10253: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
10254: my $origfile=&getfile($origfilelocation);
10255: @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10256: }
10257:
1.1069 www 10258: # Load and inspect imported file
10259: my $impfile=&getfile($location);
10260: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10261: if ($#impfilepartids>=0) {
10262: # This problem had parts
1.1070 www 10263: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 10264: } else {
10265: # Importing by turning a single problem into a problem part
10266: # It gets the import-tags ID as part-ID
10267: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 10268: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 10269: }
1.1068 www 10270: } else {
10271: # Normal import
10272: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10273: if (defined($token->[2]->{'id'})) {
10274: $unikey.='_'.$token->[2]->{'id'};
10275: }
1.1067 www 10276: }
10277:
1.339 albertel 10278: if ($depthcount<20) {
1.736 albertel 10279: my $metadata =
10280: &metadata($uri,'keys', $location,$unikey,
10281: $depthcount+1);
10282: foreach my $meta (split(',',$metadata)) {
10283: $metaentry{':'.$meta}=$metaentry{':'.$meta};
10284: $metathesekeys{$meta}=1;
1.339 albertel 10285: }
1.1068 www 10286:
10287: }
1.1067 www 10288: } else {
10289: #
10290: # Not importing, some other kind of non-package, non-library start tag
10291: #
10292: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
10293: if (defined($token->[2]->{'id'})) {
10294: $unikey.='_'.$token->[2]->{'id'};
10295: }
1.339 albertel 10296: if (defined($token->[2]->{'name'})) {
10297: $unikey.='_'.$token->[2]->{'name'};
10298: }
10299: $metathesekeys{$unikey}=1;
1.736 albertel 10300: foreach my $param (@{$token->[3]}) {
10301: $metaentry{':'.$unikey.'.'.$param} =
10302: $token->[2]->{$param};
1.339 albertel 10303: }
10304: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 10305: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 10306: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
10307: # only ws inside the tag, and not in default, so use default
10308: # as value
1.599 albertel 10309: $metaentry{':'.$unikey}=$default;
1.908 albertel 10310: } elsif ( $internaltext =~ /\S/ ) {
10311: # something interesting inside the tag
10312: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 10313: } else {
1.908 albertel 10314: # no interesting values, don't set a default
1.339 albertel 10315: }
1.172 www 10316: # end of not-a-package not-a-library import
1.339 albertel 10317: }
1.172 www 10318: # end of not-a-package start tag
1.339 albertel 10319: }
1.172 www 10320: # the next is the end of "start tag"
1.339 albertel 10321: }
10322: }
1.483 albertel 10323: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 10324: $extension = lc($extension);
10325: if ($extension eq 'htm') { $extension='html'; }
10326:
1.737 albertel 10327: foreach my $key (keys(%packagetab)) {
1.483 albertel 10328: #no specific packages #how's our extension
10329: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 10330: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 10331: \%metathesekeys);
10332: }
1.883 albertel 10333:
10334: if (!exists($metaentry{':packages'})
10335: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 10336: foreach my $key (keys(%packagetab)) {
1.483 albertel 10337: #no specific packages well let's get default then
10338: if ($key!~/^default&/) { next; }
1.488 albertel 10339: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 10340: \%metathesekeys);
10341: }
10342: }
1.338 www 10343: # are there custom rights to evaluate
1.599 albertel 10344: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 10345:
1.338 www 10346: #
10347: # Importing a rights file here
1.339 albertel 10348: #
10349: unless ($depthcount) {
1.599 albertel 10350: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 10351: my $dir=$filename;
10352: $dir=~s|[^/]*$||;
10353: $location=&filelocation($dir,$location);
1.736 albertel 10354: my $rights_metadata =
10355: &metadata($uri,'keys',$location,'_rights',
10356: $depthcount+1);
10357: foreach my $rights (split(',',$rights_metadata)) {
10358: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
10359: $metathesekeys{$rights}=1;
1.339 albertel 10360: }
10361: }
10362: }
1.737 albertel 10363: # uniqifiy package listing
10364: my %seen;
10365: my @uniq_packages =
10366: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
10367: $metaentry{':packages'} = join(',',@uniq_packages);
10368:
1.1070 www 10369: if ($importedparts) {
10370: # We had imported parts and need to rebuild partorder
10371: $metaentry{':partorder'}='';
10372: $metathesekeys{'partorder'}=1;
10373: for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
10374: if ($origfileimportpartids[$index] eq 'part') {
10375: # original part, part of the problem
10376: $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
10377: } else {
10378: # we have imported parts at this position
10379: $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
10380: }
10381: }
10382: $metaentry{':partorder'}=~s/^\,//;
10383: }
10384:
1.737 albertel 10385: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 10386: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
10387: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924 albertel 10388: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 10389: # this is the end of "was not already recently cached
1.71 www 10390: }
1.599 albertel 10391: return $metaentry{':'.$what};
1.261 albertel 10392: }
10393:
1.488 albertel 10394: sub metadata_create_package_def {
1.483 albertel 10395: my ($uri,$key,$package,$metathesekeys)=@_;
10396: my ($pack,$name,$subp)=split(/\&/,$key);
10397: if ($subp eq 'default') { next; }
10398:
1.599 albertel 10399: if (defined($metaentry{':packages'})) {
10400: $metaentry{':packages'}.=','.$package;
1.483 albertel 10401: } else {
1.599 albertel 10402: $metaentry{':packages'}=$package;
1.483 albertel 10403: }
10404: my $value=$packagetab{$key};
10405: my $unikey;
10406: $unikey='parameter_0_'.$name;
1.599 albertel 10407: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 10408: $$metathesekeys{$unikey}=1;
1.599 albertel 10409: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10410: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 10411: }
1.599 albertel 10412: if (defined($metaentry{':'.$unikey.'.default'})) {
10413: $metaentry{':'.$unikey}=
10414: $metaentry{':'.$unikey.'.default'};
1.483 albertel 10415: }
10416: }
10417:
1.261 albertel 10418: sub metadata_generate_part0 {
10419: my ($metadata,$metacache,$uri) = @_;
10420: my %allnames;
1.737 albertel 10421: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 10422: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 10423: my $part=$$metacache{':'.$metakey.'.part'};
10424: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 10425: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 10426: $allnames{$name}=$part;
10427: }
10428: }
10429: }
10430: foreach my $name (keys(%allnames)) {
10431: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 10432: my $key=":parameter_0_$name";
1.261 albertel 10433: $$metacache{"$key.part"}='0';
10434: $$metacache{"$key.name"}=$name;
1.428 albertel 10435: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 10436: $allnames{$name}.'_'.$name.
10437: '.type'};
1.428 albertel 10438: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 10439: '.display'};
1.644 www 10440: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 10441: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 10442: $$metacache{"$key.display"}=$olddis;
10443: }
1.71 www 10444: }
10445:
1.764 albertel 10446: # ------------------------------------------------------ Devalidate title cache
10447:
10448: sub devalidate_title_cache {
10449: my ($url)=@_;
10450: if (!$env{'request.course.id'}) { return; }
10451: my $symb=&symbread($url);
10452: if (!$symb) { return; }
10453: my $key=$env{'request.course.id'}."\0".$symb;
10454: &devalidate_cache_new('title',$key);
10455: }
10456:
1.1014 droeschl 10457: # ------------------------------------------------- Get the title of a course
10458:
10459: sub current_course_title {
10460: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
10461: }
1.301 www 10462: # ------------------------------------------------- Get the title of a resource
10463:
10464: sub gettitle {
10465: my $urlsymb=shift;
10466: my $symb=&symbread($urlsymb);
1.534 albertel 10467: if ($symb) {
1.620 albertel 10468: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 10469: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 10470: if (defined($cached)) {
10471: return $result;
10472: }
1.534 albertel 10473: my ($map,$resid,$url)=&decode_symb($symb);
10474: my $title='';
1.907 albertel 10475: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
10476: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
10477: } else {
10478: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10479: &GDBM_READER(),0640)) {
10480: my $mapid=$bighash{'map_pc_'.&clutter($map)};
10481: $title=$bighash{'title_'.$mapid.'.'.$resid};
10482: untie(%bighash);
10483: }
1.534 albertel 10484: }
10485: $title=~s/\&colon\;/\:/gs;
10486: if ($title) {
1.1159 www 10487: # Remember both $symb and $title for dynamic metadata
10488: $accesshash{$symb.'___crstitle'}=$title;
1.1161 www 10489: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159 www 10490: # Cache this title and then return it
1.599 albertel 10491: return &do_cache_new('title',$key,$title,600);
1.534 albertel 10492: }
10493: $urlsymb=$url;
10494: }
10495: my $title=&metadata($urlsymb,'title');
10496: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
10497: return $title;
1.301 www 10498: }
1.613 albertel 10499:
1.614 albertel 10500: sub get_slot {
10501: my ($which,$cnum,$cdom)=@_;
10502: if (!$cnum || !$cdom) {
1.790 albertel 10503: (undef,my $courseid)=&whichuser();
1.620 albertel 10504: $cdom=$env{'course.'.$courseid.'.domain'};
10505: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 10506: }
1.703 albertel 10507: my $key=join("\0",'slots',$cdom,$cnum,$which);
10508: my %slotinfo;
10509: if (exists($remembered{$key})) {
10510: $slotinfo{$which} = $remembered{$key};
10511: } else {
10512: %slotinfo=&get('slots',[$which],$cdom,$cnum);
10513: &Apache::lonhomework::showhash(%slotinfo);
10514: my ($tmp)=keys(%slotinfo);
10515: if ($tmp=~/^error:/) { return (); }
10516: $remembered{$key} = $slotinfo{$which};
10517: }
1.616 albertel 10518: if (ref($slotinfo{$which}) eq 'HASH') {
10519: return %{$slotinfo{$which}};
10520: }
10521: return $slotinfo{$which};
1.614 albertel 10522: }
1.1150 raeburn 10523:
10524: sub get_reservable_slots {
10525: my ($cnum,$cdom,$uname,$udom) = @_;
10526: my $now = time;
10527: my $reservable_info;
10528: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
10529: if (exists($remembered{$key})) {
10530: $reservable_info = $remembered{$key};
10531: } else {
10532: my %resv;
10533: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
10534: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
10535: $reservable_info = \%resv;
10536: $remembered{$key} = $reservable_info;
10537: }
10538: return $reservable_info;
10539: }
10540:
10541: sub get_course_slots {
10542: my ($cnum,$cdom) = @_;
10543: my $hashid=$cnum.':'.$cdom;
10544: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
10545: if (defined($cached)) {
10546: if (ref($result) eq 'HASH') {
10547: return %{$result};
10548: }
10549: } else {
10550: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
10551: my ($tmp) = keys(%slots);
10552: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1219 raeburn 10553: &do_cache_new('allslots',$hashid,\%slots,600);
1.1150 raeburn 10554: return %slots;
10555: }
10556: }
10557: return;
10558: }
10559:
10560: sub devalidate_slots_cache {
10561: my ($cnum,$cdom)=@_;
10562: my $hashid=$cnum.':'.$cdom;
10563: &devalidate_cache_new('allslots',$hashid);
10564: }
10565:
1.1181 raeburn 10566: sub get_coursechange {
10567: my ($cdom,$cnum) = @_;
10568: if ($cdom eq '' || $cnum eq '') {
10569: return unless ($env{'request.course.id'});
10570: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10571: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10572: }
10573: my $hashid=$cdom.'_'.$cnum;
10574: my ($change,$cached)=&is_cached_new('crschange',$hashid);
10575: if ((defined($cached)) && ($change ne '')) {
10576: return $change;
10577: } else {
10578: my %crshash;
10579: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
10580: if ($crshash{'internal.contentchange'} eq '') {
10581: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
10582: if ($change eq '') {
10583: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
10584: $change = $crshash{'internal.created'};
10585: }
10586: } else {
10587: $change = $crshash{'internal.contentchange'};
10588: }
10589: my $cachetime = 600;
10590: &do_cache_new('crschange',$hashid,$change,$cachetime);
10591: }
10592: return $change;
10593: }
10594:
10595: sub devalidate_coursechange_cache {
10596: my ($cnum,$cdom)=@_;
10597: my $hashid=$cnum.':'.$cdom;
10598: &devalidate_cache_new('crschange',$hashid);
10599: }
10600:
1.31 www 10601: # ------------------------------------------------- Update symbolic store links
10602:
10603: sub symblist {
10604: my ($mapname,%newhash)=@_;
1.438 www 10605: $mapname=&deversion(&declutter($mapname));
1.31 www 10606: my %hash;
1.620 albertel 10607: if (($env{'request.course.fn'}) && (%newhash)) {
10608: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 10609: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 10610: foreach my $url (keys(%newhash)) {
1.711 albertel 10611: next if ($url eq 'last_known'
10612: && $env{'form.no_update_last_known'});
10613: $hash{declutter($url)}=&encode_symb($mapname,
10614: $newhash{$url}->[1],
10615: $newhash{$url}->[0]);
1.191 harris41 10616: }
1.31 www 10617: if (untie(%hash)) {
10618: return 'ok';
10619: }
10620: }
10621: }
10622: return 'error';
1.212 www 10623: }
10624:
10625: # --------------------------------------------------------------- Verify a symb
10626:
10627: sub symbverify {
1.1190 raeburn 10628: my ($symb,$thisurl,$encstate)=@_;
1.510 www 10629: my $thisfn=$thisurl;
1.439 www 10630: $thisfn=&declutter($thisfn);
1.215 www 10631: # direct jump to resource in page or to a sequence - will construct own symbs
10632: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
10633: # check URL part
1.409 www 10634: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 10635:
1.431 www 10636: unless ($url eq $thisfn) { return 0; }
1.213 www 10637:
1.216 www 10638: $symb=&symbclean($symb);
1.510 www 10639: $thisurl=&deversion($thisurl);
1.439 www 10640: $thisfn=&deversion($thisfn);
1.213 www 10641:
10642: my %bighash;
10643: my $okay=0;
1.431 www 10644:
1.620 albertel 10645: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 10646: &GDBM_READER(),0640)) {
1.1204 raeburn 10647: my $noclutter;
1.1032 raeburn 10648: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
10649: $thisurl =~ s/\?.+$//;
1.1204 raeburn 10650: if ($map =~ m{^uploaded/.+\.page$}) {
10651: $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
10652: $thisurl =~ s{^\Qhttp://https://\E}{https://};
10653: $noclutter = 1;
10654: }
10655: }
10656: my $ids;
10657: if ($noclutter) {
10658: $ids=$bighash{'ids_'.$thisurl};
10659: } else {
10660: $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032 raeburn 10661: }
1.1102 raeburn 10662: unless ($ids) {
10663: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
10664: $ids=$bighash{$idkey};
1.216 www 10665: }
10666: if ($ids) {
10667: # ------------------------------------------------------------------- Has ID(s)
1.1202 raeburn 10668: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
1.1203 raeburn 10669: $symb =~ s/\?.+$//;
1.1202 raeburn 10670: }
1.800 albertel 10671: foreach my $id (split(/\,/,$ids)) {
10672: my ($mapid,$resid)=split(/\./,$id);
1.216 www 10673: if (
10674: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190 raeburn 10675: eq $symb) {
10676: if (ref($encstate)) {
10677: $$encstate = $bighash{'encrypted_'.$id};
10678: }
1.620 albertel 10679: if (($env{'request.role.adv'}) ||
1.1101 raeburn 10680: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
10681: ($thisurl eq '/adm/navmaps')) {
1.1190 raeburn 10682: $okay=1;
1.1202 raeburn 10683: last;
1.582 albertel 10684: }
10685: }
1.216 www 10686: }
10687: }
1.213 www 10688: untie(%bighash);
10689: }
10690: return $okay;
1.31 www 10691: }
10692:
1.210 www 10693: # --------------------------------------------------------------- Clean-up symb
10694:
10695: sub symbclean {
10696: my $symb=shift;
1.568 albertel 10697: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 10698: # remove version from map
10699: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 10700:
1.210 www 10701: # remove version from URL
10702: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 10703:
1.507 www 10704: # remove wrapper
10705:
1.510 www 10706: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 10707: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 10708: return $symb;
1.409 www 10709: }
10710:
10711: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 10712:
10713: sub encode_symb {
10714: my ($map,$resid,$url)=@_;
10715: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
10716: }
1.409 www 10717:
10718: sub decode_symb {
1.568 albertel 10719: my $symb=shift;
10720: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
10721: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 10722: return (&fixversion($map),$resid,&fixversion($url));
10723: }
10724:
10725: sub fixversion {
10726: my $fn=shift;
1.609 banghart 10727: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 10728: my %bighash;
10729: my $uri=&clutter($fn);
1.620 albertel 10730: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 10731: # is this cached?
1.599 albertel 10732: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 10733: if (defined($cached)) { return $result; }
10734: # unfortunately not cached, or expired
1.620 albertel 10735: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 10736: &GDBM_READER(),0640)) {
10737: if ($bighash{'version_'.$uri}) {
10738: my $version=$bighash{'version_'.$uri};
1.444 www 10739: unless (($version eq 'mostrecent') ||
10740: ($version==&getversion($uri))) {
1.440 www 10741: $uri=~s/\.(\w+)$/\.$version\.$1/;
10742: }
10743: }
10744: untie %bighash;
1.413 www 10745: }
1.599 albertel 10746: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 10747: }
10748:
10749: sub deversion {
10750: my $url=shift;
10751: $url=~s/\.\d+\.(\w+)$/\.$1/;
10752: return $url;
1.210 www 10753: }
10754:
1.31 www 10755: # ------------------------------------------------------ Return symb list entry
10756:
10757: sub symbread {
1.249 www 10758: my ($thisfn,$donotrecurse)=@_;
1.1206 raeburn 10759: my $cache_str;
10760: if ($thisfn ne '') {
10761: $cache_str='request.symbread.cached.'.$thisfn;
10762: if ($env{$cache_str} ne '') {
1.1179 raeburn 10763: return $env{$cache_str};
10764: }
1.1206 raeburn 10765: } else {
1.242 www 10766: # no filename provided? try from environment
1.620 albertel 10767: if ($env{'request.symb'}) {
10768: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 10769: }
1.620 albertel 10770: $thisfn=$env{'request.filename'};
1.44 www 10771: }
1.569 albertel 10772: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 10773: # is that filename actually a symb? Verify, clean, and return
10774: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 10775: if (&symbverify($thisfn,$1)) {
1.620 albertel 10776: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 10777: }
1.242 www 10778: }
1.44 www 10779: $thisfn=declutter($thisfn);
1.31 www 10780: my %hash;
1.37 www 10781: my %bighash;
10782: my $syval='';
1.620 albertel 10783: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 10784: my $targetfn = $thisfn;
1.609 banghart 10785: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 10786: $targetfn = 'adm/wrapper/'.$thisfn;
10787: }
1.687 albertel 10788: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
10789: $targetfn=$1;
10790: }
1.620 albertel 10791: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 10792: &GDBM_READER(),0640)) {
1.481 raeburn 10793: $syval=$hash{$targetfn};
1.37 www 10794: untie(%hash);
10795: }
10796: # ---------------------------------------------------------- There was an entry
10797: if ($syval) {
1.601 albertel 10798: #unless ($syval=~/\_\d+$/) {
1.620 albertel 10799: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 10800: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 10801: #return $env{$cache_str}='';
1.601 albertel 10802: #}
10803: #$syval.=$1;
10804: #}
1.37 www 10805: } else {
10806: # ------------------------------------------------------- Was not in symb table
1.620 albertel 10807: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 10808: &GDBM_READER(),0640)) {
1.37 www 10809: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 10810: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 10811: unless ($ids) {
10812: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 10813: }
10814: unless ($ids) {
10815: # alias?
10816: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 10817: }
1.37 www 10818: if ($ids) {
10819: # ------------------------------------------------------------------- Has ID(s)
10820: my @possibilities=split(/\,/,$ids);
1.39 www 10821: if ($#possibilities==0) {
10822: # ----------------------------------------------- There is only one possibility
1.37 www 10823: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 10824: $syval=&encode_symb($bighash{'map_id_'.$mapid},
10825: $resid,$thisfn);
1.249 www 10826: } elsif (!$donotrecurse) {
1.39 www 10827: # ------------------------------------------ There is more than one possibility
10828: my $realpossible=0;
1.800 albertel 10829: foreach my $id (@possibilities) {
10830: my $file=$bighash{'src_'.$id};
1.39 www 10831: if (&allowed('bre',$file)) {
1.800 albertel 10832: my ($mapid,$resid)=split(/\./,$id);
1.39 www 10833: if ($bighash{'map_type_'.$mapid} ne 'page') {
10834: $realpossible++;
1.626 albertel 10835: $syval=&encode_symb($bighash{'map_id_'.$mapid},
10836: $resid,$thisfn);
1.39 www 10837: }
10838: }
1.191 harris41 10839: }
1.39 www 10840: if ($realpossible!=1) { $syval=''; }
1.249 www 10841: } else {
10842: $syval='';
1.37 www 10843: }
10844: }
10845: untie(%bighash)
1.481 raeburn 10846: }
1.31 www 10847: }
1.62 www 10848: if ($syval) {
1.620 albertel 10849: return $env{$cache_str}=$syval;
1.62 www 10850: }
1.31 www 10851: }
1.949 raeburn 10852: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 10853: return $env{$cache_str}='';
1.31 www 10854: }
10855:
10856: # ---------------------------------------------------------- Return random seed
10857:
1.32 www 10858: sub numval {
10859: my $txt=shift;
10860: $txt=~tr/A-J/0-9/;
10861: $txt=~tr/a-j/0-9/;
10862: $txt=~tr/K-T/0-9/;
10863: $txt=~tr/k-t/0-9/;
10864: $txt=~tr/U-Z/0-5/;
10865: $txt=~tr/u-z/0-5/;
10866: $txt=~s/\D//g;
1.564 albertel 10867: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 10868: return int($txt);
1.368 albertel 10869: }
10870:
1.484 albertel 10871: sub numval2 {
10872: my $txt=shift;
10873: $txt=~tr/A-J/0-9/;
10874: $txt=~tr/a-j/0-9/;
10875: $txt=~tr/K-T/0-9/;
10876: $txt=~tr/k-t/0-9/;
10877: $txt=~tr/U-Z/0-5/;
10878: $txt=~tr/u-z/0-5/;
10879: $txt=~s/\D//g;
10880: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10881: my $total;
10882: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 10883: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 10884: return int($total);
10885: }
10886:
1.575 albertel 10887: sub numval3 {
10888: use integer;
10889: my $txt=shift;
10890: $txt=~tr/A-J/0-9/;
10891: $txt=~tr/a-j/0-9/;
10892: $txt=~tr/K-T/0-9/;
10893: $txt=~tr/k-t/0-9/;
10894: $txt=~tr/U-Z/0-5/;
10895: $txt=~tr/u-z/0-5/;
10896: $txt=~s/\D//g;
10897: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10898: my $total;
10899: foreach my $val (@txts) { $total+=$val; }
10900: if ($_64bit) { $total=(($total<<32)>>32); }
10901: return $total;
10902: }
10903:
1.675 albertel 10904: sub digest {
10905: my ($data)=@_;
10906: my $digest=&Digest::MD5::md5($data);
10907: my ($a,$b,$c,$d)=unpack("iiii",$digest);
10908: my ($e,$f);
10909: {
10910: use integer;
10911: $e=($a+$b);
10912: $f=($c+$d);
10913: if ($_64bit) {
10914: $e=(($e<<32)>>32);
10915: $f=(($f<<32)>>32);
10916: }
10917: }
10918: if (wantarray) {
10919: return ($e,$f);
10920: } else {
10921: my $g;
10922: {
10923: use integer;
10924: $g=($e+$f);
10925: if ($_64bit) {
10926: $g=(($g<<32)>>32);
10927: }
10928: }
10929: return $g;
10930: }
10931: }
10932:
1.368 albertel 10933: sub latest_rnd_algorithm_id {
1.675 albertel 10934: return '64bit5';
1.366 albertel 10935: }
1.32 www 10936:
1.503 albertel 10937: sub get_rand_alg {
10938: my ($courseid)=@_;
1.790 albertel 10939: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 10940: if ($courseid) {
1.620 albertel 10941: return $env{"course.$courseid.rndseed"};
1.503 albertel 10942: }
10943: return &latest_rnd_algorithm_id();
10944: }
10945:
1.562 albertel 10946: sub validCODE {
10947: my ($CODE)=@_;
10948: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
10949: return 0;
10950: }
10951:
1.491 albertel 10952: sub getCODE {
1.620 albertel 10953: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 10954: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
10955: defined($Apache::lonhomework::parsing_a_task) ) &&
10956: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 10957: return $Apache::lonhomework::history{'resource.CODE'};
10958: }
10959: return undef;
10960: }
1.1133 foxr 10961: #
10962: # Determines the random seed for a specific context:
10963: #
10964: # parameters:
10965: # symb - in course context the symb for the seed.
10966: # course_id - The course id of the form domain_coursenum.
10967: # domain - Domain for the user.
10968: # course - Course for the user.
10969: # cenv - environment of the course.
10970: #
10971: # NOTE:
10972: # All parameters are picked out of the environment if missing
10973: # or not defined.
10974: # If a symb cannot be determined the current time is used instead.
10975: #
10976: # For a given well defined symb, courside, domain, username,
10977: # and course environment, the seed is reproducible.
10978: #
1.31 www 10979: sub rndseed {
1.1133 foxr 10980: my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790 albertel 10981: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 10982: if (!defined($symb)) {
1.366 albertel 10983: unless ($symb=$wsymb) { return time; }
10984: }
1.1146 foxr 10985: if (!defined $courseid) {
10986: $courseid=$wcourseid;
10987: }
10988: if (!defined $domain) { $domain=$wdomain; }
10989: if (!defined $username) { $username=$wusername }
1.1133 foxr 10990:
10991: my $which;
10992: if (defined($cenv->{'rndseed'})) {
10993: $which = $cenv->{'rndseed'};
10994: } else {
10995: $which =&get_rand_alg($courseid);
10996: }
1.491 albertel 10997: if (defined(&getCODE())) {
1.1133 foxr 10998:
1.675 albertel 10999: if ($which eq '64bit5') {
11000: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
11001: } elsif ($which eq '64bit4') {
1.575 albertel 11002: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
11003: } else {
11004: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
11005: }
1.675 albertel 11006: } elsif ($which eq '64bit5') {
11007: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 11008: } elsif ($which eq '64bit4') {
11009: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 11010: } elsif ($which eq '64bit3') {
11011: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 11012: } elsif ($which eq '64bit2') {
11013: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 11014: } elsif ($which eq '64bit') {
11015: return &rndseed_64bit($symb,$courseid,$domain,$username);
11016: }
11017: return &rndseed_32bit($symb,$courseid,$domain,$username);
11018: }
11019:
11020: sub rndseed_32bit {
11021: my ($symb,$courseid,$domain,$username)=@_;
11022: {
11023: use integer;
11024: my $symbchck=unpack("%32C*",$symb) << 27;
11025: my $symbseed=numval($symb) << 22;
11026: my $namechck=unpack("%32C*",$username) << 17;
11027: my $nameseed=numval($username) << 12;
11028: my $domainseed=unpack("%32C*",$domain) << 7;
11029: my $courseseed=unpack("%32C*",$courseid);
11030: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 11031: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11032: #&logthis("rndseed :$num:$symb");
1.564 albertel 11033: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 11034: return $num;
11035: }
11036: }
11037:
11038: sub rndseed_64bit {
11039: my ($symb,$courseid,$domain,$username)=@_;
11040: {
11041: use integer;
11042: my $symbchck=unpack("%32S*",$symb) << 21;
11043: my $symbseed=numval($symb) << 10;
11044: my $namechck=unpack("%32S*",$username);
11045:
11046: my $nameseed=numval($username) << 21;
11047: my $domainseed=unpack("%32S*",$domain) << 10;
11048: my $courseseed=unpack("%32S*",$courseid);
11049:
11050: my $num1=$symbchck+$symbseed+$namechck;
11051: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11052: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11053: #&logthis("rndseed :$num:$symb");
1.564 albertel 11054: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 11055: return "$num1,$num2";
1.155 albertel 11056: }
1.366 albertel 11057: }
11058:
1.443 albertel 11059: sub rndseed_64bit2 {
11060: my ($symb,$courseid,$domain,$username)=@_;
11061: {
11062: use integer;
11063: # strings need to be an even # of cahracters long, it it is odd the
11064: # last characters gets thrown away
11065: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11066: my $symbseed=numval($symb) << 10;
11067: my $namechck=unpack("%32S*",$username.' ');
11068:
11069: my $nameseed=numval($username) << 21;
1.501 albertel 11070: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11071: my $courseseed=unpack("%32S*",$courseid.' ');
11072:
11073: my $num1=$symbchck+$symbseed+$namechck;
11074: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11075: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11076: #&logthis("rndseed :$num:$symb");
1.803 albertel 11077: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 11078: return "$num1,$num2";
11079: }
11080: }
11081:
11082: sub rndseed_64bit3 {
11083: my ($symb,$courseid,$domain,$username)=@_;
11084: {
11085: use integer;
11086: # strings need to be an even # of cahracters long, it it is odd the
11087: # last characters gets thrown away
11088: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11089: my $symbseed=numval2($symb) << 10;
11090: my $namechck=unpack("%32S*",$username.' ');
11091:
11092: my $nameseed=numval2($username) << 21;
1.443 albertel 11093: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11094: my $courseseed=unpack("%32S*",$courseid.' ');
11095:
11096: my $num1=$symbchck+$symbseed+$namechck;
11097: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11098: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11099: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 11100: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 11101:
1.503 albertel 11102: return "$num1:$num2";
1.443 albertel 11103: }
11104: }
11105:
1.575 albertel 11106: sub rndseed_64bit4 {
11107: my ($symb,$courseid,$domain,$username)=@_;
11108: {
11109: use integer;
11110: # strings need to be an even # of cahracters long, it it is odd the
11111: # last characters gets thrown away
11112: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11113: my $symbseed=numval3($symb) << 10;
11114: my $namechck=unpack("%32S*",$username.' ');
11115:
11116: my $nameseed=numval3($username) << 21;
11117: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11118: my $courseseed=unpack("%32S*",$courseid.' ');
11119:
11120: my $num1=$symbchck+$symbseed+$namechck;
11121: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11122: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11123: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 11124: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 11125:
1.575 albertel 11126: return "$num1:$num2";
11127: }
11128: }
11129:
1.675 albertel 11130: sub rndseed_64bit5 {
11131: my ($symb,$courseid,$domain,$username)=@_;
11132: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
11133: return "$num1:$num2";
11134: }
11135:
1.366 albertel 11136: sub rndseed_CODE_64bit {
11137: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 11138: {
1.366 albertel 11139: use integer;
1.443 albertel 11140: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 11141: my $symbseed=numval2($symb);
1.491 albertel 11142: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11143: my $CODEseed=numval(&getCODE());
1.443 albertel 11144: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 11145: my $num1=$symbseed+$CODEchck;
11146: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 11147: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11148: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 11149: if ($_64bit) { $num1=(($num1<<32)>>32); }
11150: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 11151: return "$num1:$num2";
1.366 albertel 11152: }
11153: }
11154:
1.575 albertel 11155: sub rndseed_CODE_64bit4 {
11156: my ($symb,$courseid,$domain,$username)=@_;
11157: {
11158: use integer;
11159: my $symbchck=unpack("%32S*",$symb.' ') << 16;
11160: my $symbseed=numval3($symb);
11161: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11162: my $CODEseed=numval3(&getCODE());
11163: my $courseseed=unpack("%32S*",$courseid.' ');
11164: my $num1=$symbseed+$CODEchck;
11165: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 11166: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11167: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 11168: if ($_64bit) { $num1=(($num1<<32)>>32); }
11169: if ($_64bit) { $num2=(($num2<<32)>>32); }
11170: return "$num1:$num2";
11171: }
11172: }
11173:
1.675 albertel 11174: sub rndseed_CODE_64bit5 {
11175: my ($symb,$courseid,$domain,$username)=@_;
11176: my $code = &getCODE();
11177: my ($num1,$num2)=&digest("$symb,$courseid,$code");
11178: return "$num1:$num2";
11179: }
11180:
1.366 albertel 11181: sub setup_random_from_rndseed {
11182: my ($rndseed)=@_;
1.503 albertel 11183: if ($rndseed =~/([,:])/) {
11184: my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366 albertel 11185: &Math::Random::random_set_seed(abs($num1),abs($num2));
11186: } else {
11187: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 11188: }
1.36 albertel 11189: }
11190:
1.474 albertel 11191: sub latest_receipt_algorithm_id {
1.835 albertel 11192: return 'receipt3';
1.474 albertel 11193: }
11194:
1.480 www 11195: sub recunique {
11196: my $fucourseid=shift;
11197: my $unique;
1.835 albertel 11198: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
11199: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 11200: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 11201: } else {
11202: $unique=$perlvar{'lonReceipt'};
11203: }
11204: return unpack("%32C*",$unique);
11205: }
11206:
11207: sub recprefix {
11208: my $fucourseid=shift;
11209: my $prefix;
1.835 albertel 11210: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
11211: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 11212: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 11213: } else {
11214: $prefix=$perlvar{'lonHostID'};
11215: }
11216: return unpack("%32C*",$prefix);
11217: }
11218:
1.76 www 11219: sub ireceipt {
1.474 albertel 11220: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 11221:
11222: my $return =&recprefix($fucourseid).'-';
11223:
11224: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
11225: $env{'request.state'} eq 'construct') {
11226: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
11227: return $return;
11228: }
11229:
1.76 www 11230: my $cuname=unpack("%32C*",$funame);
11231: my $cudom=unpack("%32C*",$fudom);
11232: my $cucourseid=unpack("%32C*",$fucourseid);
11233: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 11234: my $cunique=&recunique($fucourseid);
1.474 albertel 11235: my $cpart=unpack("%32S*",$part);
1.835 albertel 11236: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
11237:
1.790 albertel 11238: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 11239:
11240: $return.= ($cunique%$cuname+
11241: $cunique%$cudom+
11242: $cusymb%$cuname+
11243: $cusymb%$cudom+
11244: $cucourseid%$cuname+
11245: $cucourseid%$cudom+
11246: $cpart%$cuname+
11247: $cpart%$cudom);
11248: } else {
11249: $return.= ($cunique%$cuname+
11250: $cunique%$cudom+
11251: $cusymb%$cuname+
11252: $cusymb%$cudom+
11253: $cucourseid%$cuname+
11254: $cucourseid%$cudom);
11255: }
11256: return $return;
1.76 www 11257: }
11258:
11259: sub receipt {
1.474 albertel 11260: my ($part)=@_;
1.790 albertel 11261: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 11262: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 11263: }
1.260 ng 11264:
1.790 albertel 11265: sub whichuser {
11266: my ($passedsymb)=@_;
11267: my ($symb,$courseid,$domain,$name,$publicuser);
11268: if (defined($env{'form.grade_symb'})) {
11269: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
11270: my $allowed=&allowed('vgr',$tmp_courseid);
11271: if (!$allowed &&
11272: exists($env{'request.course.sec'}) &&
11273: $env{'request.course.sec'} !~ /^\s*$/) {
11274: $allowed=&allowed('vgr',$tmp_courseid.
11275: '/'.$env{'request.course.sec'});
11276: }
11277: if ($allowed) {
11278: ($symb)=&get_env_multiple('form.grade_symb');
11279: $courseid=$tmp_courseid;
11280: ($domain)=&get_env_multiple('form.grade_domain');
11281: ($name)=&get_env_multiple('form.grade_username');
11282: return ($symb,$courseid,$domain,$name,$publicuser);
11283: }
11284: }
11285: if (!$passedsymb) {
11286: $symb=&symbread();
11287: } else {
11288: $symb=$passedsymb;
11289: }
11290: $courseid=$env{'request.course.id'};
11291: $domain=$env{'user.domain'};
11292: $name=$env{'user.name'};
11293: if ($name eq 'public' && $domain eq 'public') {
11294: if (!defined($env{'form.username'})) {
11295: $env{'form.username'}.=time.rand(10000000);
11296: }
11297: $name.=$env{'form.username'};
11298: }
11299: return ($symb,$courseid,$domain,$name,$publicuser);
11300:
11301: }
11302:
1.36 albertel 11303: # ------------------------------------------------------------ Serves up a file
1.472 albertel 11304: # returns either the contents of the file or
11305: # -1 if the file doesn't exist
1.481 raeburn 11306: #
11307: # if the target is a file that was uploaded via DOCS,
11308: # a check will be made to see if a current copy exists on the local server,
11309: # if it does this will be served, otherwise a copy will be retrieved from
11310: # the home server for the course and stored in /home/httpd/html/userfiles on
11311: # the local server.
1.472 albertel 11312:
1.36 albertel 11313: sub getfile {
1.538 albertel 11314: my ($file) = @_;
1.609 banghart 11315: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 11316: &repcopy($file);
11317: return &readfile($file);
11318: }
11319:
11320: sub repcopy_userfile {
11321: my ($file)=@_;
1.1142 raeburn 11322: my $londocroot = $perlvar{'lonDocRoot'};
11323: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164 raeburn 11324: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538 albertel 11325: my ($cdom,$cnum,$filename) =
1.811 albertel 11326: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 11327: my $uri="/uploaded/$cdom/$cnum/$filename";
11328: if (-e "$file") {
1.828 www 11329: # we already have a local copy, check it out
1.538 albertel 11330: my @fileinfo = stat($file);
1.828 www 11331: my $rtncode;
11332: my $info;
1.538 albertel 11333: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 11334: if ($lwpresp ne 'ok') {
1.828 www 11335: # there is no such file anymore, even though we had a local copy
1.482 albertel 11336: if ($rtncode eq '404') {
1.538 albertel 11337: unlink($file);
1.482 albertel 11338: }
11339: return -1;
11340: }
11341: if ($info < $fileinfo[9]) {
1.828 www 11342: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 11343: return 'ok';
1.828 www 11344: } else {
11345: # the file is outdated, get rid of it
11346: unlink($file);
1.482 albertel 11347: }
1.828 www 11348: }
11349: # one way or the other, at this point, we don't have the file
11350: # construct the correct path for the file
11351: my @parts = ($cdom,$cnum);
11352: if ($filename =~ m|^(.+)/[^/]+$|) {
11353: push @parts, split(/\//,$1);
11354: }
11355: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
11356: foreach my $part (@parts) {
11357: $path .= '/'.$part;
11358: if (!-e $path) {
11359: mkdir($path,0770);
1.482 albertel 11360: }
11361: }
1.828 www 11362: # now the path exists for sure
11363: # get a user agent
11364: my $ua=new LWP::UserAgent;
11365: my $transferfile=$file.'.in.transfer';
11366: # FIXME: this should flock
11367: if (-e $transferfile) { return 'ok'; }
11368: my $request;
11369: $uri=~s/^\///;
1.980 raeburn 11370: my $homeserver = &homeserver($cnum,$cdom);
11371: my $protocol = $protocol{$homeserver};
11372: $protocol = 'http' if ($protocol ne 'https');
11373: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 11374: my $response=$ua->request($request,$transferfile);
11375: # did it work?
11376: if ($response->is_error()) {
11377: unlink($transferfile);
11378: &logthis("Userfile repcopy failed for $uri");
11379: return -1;
11380: }
11381: # worked, rename the transfer file
11382: rename($transferfile,$file);
1.607 raeburn 11383: return 'ok';
1.481 raeburn 11384: }
11385:
1.517 albertel 11386: sub tokenwrapper {
11387: my $uri=shift;
1.980 raeburn 11388: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 11389: $uri=~s|^/||;
1.620 albertel 11390: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 11391: my $token=$1;
1.552 albertel 11392: my (undef,$udom,$uname,$file)=split('/',$uri,4);
11393: if ($udom && $uname && $file) {
11394: $file=~s|(\?\.*)*$||;
1.949 raeburn 11395: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 11396: my $homeserver = &homeserver($uname,$udom);
11397: my $protocol = $protocol{$homeserver};
11398: $protocol = 'http' if ($protocol ne 'https');
11399: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 11400: (($uri=~/\?/)?'&':'?').'token='.$token.
11401: '&tokenissued='.$perlvar{'lonHostID'};
11402: } else {
11403: return '/adm/notfound.html';
11404: }
11405: }
11406:
1.828 www 11407: # call with reqtype HEAD: get last modification time
11408: # call with reqtype GET: get the file contents
11409: # Do not call this with reqtype GET for large files! It loads everything into memory
11410: #
1.481 raeburn 11411: sub getuploaded {
11412: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
11413: $uri=~s/^\///;
1.980 raeburn 11414: my $homeserver = &homeserver($cnum,$cdom);
11415: my $protocol = $protocol{$homeserver};
11416: $protocol = 'http' if ($protocol ne 'https');
11417: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 11418: my $ua=new LWP::UserAgent;
11419: my $request=new HTTP::Request($reqtype,$uri);
11420: my $response=$ua->request($request);
11421: $$rtncode = $response->code;
1.482 albertel 11422: if (! $response->is_success()) {
11423: return 'failed';
11424: }
11425: if ($reqtype eq 'HEAD') {
1.486 www 11426: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 11427: } elsif ($reqtype eq 'GET') {
11428: $$info = $response->content;
1.472 albertel 11429: }
1.482 albertel 11430: return 'ok';
1.36 albertel 11431: }
11432:
1.481 raeburn 11433: sub readfile {
11434: my $file = shift;
11435: if ( (! -e $file ) || ($file eq '') ) { return -1; };
11436: my $fh;
11437: open($fh,"<$file");
11438: my $a='';
1.800 albertel 11439: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 11440: return $a;
11441: }
11442:
1.36 albertel 11443: sub filelocation {
1.590 banghart 11444: my ($dir,$file) = @_;
11445: my $location;
11446: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 11447:
11448: if ($file =~ m-^/adm/-) {
11449: $file=~s-^/adm/wrapper/-/-;
11450: $file=~s-^/adm/coursedocs/showdoc/-/-;
11451: }
1.882 albertel 11452:
1.1139 www 11453: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956 raeburn 11454: $location = $file;
1.609 banghart 11455: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 11456: my ($udom,$uname,$filename)=
1.811 albertel 11457: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 11458: my $home=&homeserver($uname,$udom);
11459: my $is_me=0;
11460: my @ids=¤t_machine_ids();
11461: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
11462: if ($is_me) {
1.1117 foxr 11463: $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 11464: } else {
11465: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
11466: $udom.'/'.$uname.'/'.$filename;
11467: }
1.882 albertel 11468: } elsif ($file =~ m-^/adm/-) {
11469: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 11470: } else {
11471: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139 www 11472: $file=~s:^/(res|priv)/:/:;
11473: my $space=$1;
1.590 banghart 11474: if ( !( $file =~ m:^/:) ) {
11475: $location = $dir. '/'.$file;
11476: } else {
1.1142 raeburn 11477: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590 banghart 11478: }
1.59 albertel 11479: }
1.590 banghart 11480: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 11481: while ($location=~m{/\.\./}) {
11482: if ($location =~ m{/[^/]+/\.\./}) {
11483: $location=~ s{/[^/]+/\.\./}{/}g;
11484: } else {
11485: $location=~ s{/\.\./}{/}g;
11486: }
11487: } #remove dir/..
1.590 banghart 11488: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
11489: return $location;
1.46 www 11490: }
1.36 albertel 11491:
1.46 www 11492: sub hreflocation {
11493: my ($dir,$file)=@_;
1.980 raeburn 11494: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 11495: $file=filelocation($dir,$file);
1.700 albertel 11496: } elsif ($file=~m-^/adm/-) {
11497: $file=~s-^/adm/wrapper/-/-;
11498: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 11499: }
11500: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
11501: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
11502: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143 raeburn 11503: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
11504: {/uploaded/$1/$2/}x;
1.46 www 11505: }
1.913 albertel 11506: if ($file=~ m{^/userfiles/}) {
11507: $file =~ s{^/userfiles/}{/uploaded/};
11508: }
1.462 albertel 11509: return $file;
1.465 albertel 11510: }
11511:
1.1139 www 11512:
11513:
11514:
11515:
1.465 albertel 11516: sub current_machine_domains {
1.853 albertel 11517: return &machine_domains(&hostname($perlvar{'lonHostID'}));
11518: }
11519:
11520: sub machine_domains {
11521: my ($hostname) = @_;
1.465 albertel 11522: my @domains;
1.838 albertel 11523: my %hostname = &all_hostnames();
1.465 albertel 11524: while( my($id, $name) = each(%hostname)) {
1.467 matthew 11525: # &logthis("-$id-$name-$hostname-");
1.465 albertel 11526: if ($hostname eq $name) {
1.844 albertel 11527: push(@domains,&host_domain($id));
1.465 albertel 11528: }
11529: }
11530: return @domains;
11531: }
11532:
11533: sub current_machine_ids {
1.853 albertel 11534: return &machine_ids(&hostname($perlvar{'lonHostID'}));
11535: }
11536:
11537: sub machine_ids {
11538: my ($hostname) = @_;
11539: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 11540: my @ids;
1.888 albertel 11541: my %name_to_host = &all_names();
1.889 albertel 11542: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
11543: return @{ $name_to_host{$hostname} };
11544: }
11545: return;
1.31 www 11546: }
11547:
1.824 raeburn 11548: sub additional_machine_domains {
11549: my @domains;
11550: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
11551: while( my $line = <$fh>) {
11552: $line =~ s/\s//g;
11553: push(@domains,$line);
11554: }
11555: return @domains;
11556: }
11557:
11558: sub default_login_domain {
11559: my $domain = $perlvar{'lonDefDomain'};
11560: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
11561: foreach my $posdom (¤t_machine_domains(),
11562: &additional_machine_domains()) {
11563: if (lc($posdom) eq lc($testdomain)) {
11564: $domain=$posdom;
11565: last;
11566: }
11567: }
11568: return $domain;
11569: }
11570:
1.31 www 11571: # ------------------------------------------------------------- Declutters URLs
11572:
11573: sub declutter {
11574: my $thisfn=shift;
1.569 albertel 11575: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479 albertel 11576: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31 www 11577: $thisfn=~s/^\///;
1.697 albertel 11578: $thisfn=~s|^adm/wrapper/||;
11579: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 11580: $thisfn=~s/^res\///;
1.1172 bisitz 11581: $thisfn=~s/^priv\///;
1.1032 raeburn 11582: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
11583: $thisfn=~s/\?.+$//;
11584: }
1.268 www 11585: return $thisfn;
11586: }
11587:
11588: # ------------------------------------------------------------- Clutter up URLs
11589:
11590: sub clutter {
11591: my $thisfn='/'.&declutter(shift);
1.887 albertel 11592: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 11593: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 11594: $thisfn='/res'.$thisfn;
11595: }
1.1031 raeburn 11596: if ($thisfn !~m|^/adm|) {
11597: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 11598: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 11599: } else {
11600: my ($ext) = ($thisfn =~ /\.(\w+)$/);
11601: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 11602: if ($embstyle eq 'ssi'
11603: || ($embstyle eq 'hdn')
11604: || ($embstyle eq 'rat')
11605: || ($embstyle eq 'prv')
11606: || ($embstyle eq 'ign')) {
11607: #do nothing with these
11608: } elsif (($embstyle eq 'img')
1.695 albertel 11609: || ($embstyle eq 'emb')
11610: || ($embstyle eq 'wrp')) {
11611: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 11612: } elsif ($embstyle eq 'unk'
11613: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 11614: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 11615: } else {
1.718 www 11616: # &logthis("Got a blank emb style");
1.695 albertel 11617: }
1.694 albertel 11618: }
11619: }
1.31 www 11620: return $thisfn;
1.12 www 11621: }
11622:
1.787 albertel 11623: sub clutter_with_no_wrapper {
11624: my $uri = &clutter(shift);
11625: if ($uri =~ m-^/adm/-) {
11626: $uri =~ s-^/adm/wrapper/-/-;
11627: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
11628: }
11629: return $uri;
11630: }
11631:
1.557 albertel 11632: sub freeze_escape {
11633: my ($value)=@_;
11634: if (ref($value)) {
11635: $value=&nfreeze($value);
11636: return '__FROZEN__'.&escape($value);
11637: }
11638: return &escape($value);
11639: }
11640:
1.11 www 11641:
1.557 albertel 11642: sub thaw_unescape {
11643: my ($value)=@_;
11644: if ($value =~ /^__FROZEN__/) {
11645: substr($value,0,10,undef);
11646: $value=&unescape($value);
11647: return &thaw($value);
11648: }
11649: return &unescape($value);
11650: }
11651:
1.436 albertel 11652: sub correct_line_ends {
11653: my ($result)=@_;
11654: $$result =~s/\r\n/\n/mg;
11655: $$result =~s/\r/\n/mg;
1.415 albertel 11656: }
1.1 albertel 11657: # ================================================================ Main Program
11658:
1.184 www 11659: sub goodbye {
1.204 albertel 11660: &logthis("Starting Shut down");
1.443 albertel 11661: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 11662: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 11663: #converted
1.599 albertel 11664: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 11665: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
11666: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
11667: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 11668: #1.1 only
1.870 albertel 11669: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
11670: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
11671: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
11672: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
11673: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 11674: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
11675: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 11676: &flushcourselogs();
11677: &logthis("Shutting down");
11678: }
11679:
1.852 albertel 11680: sub get_dns {
1.1210 raeburn 11681: my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869 albertel 11682: if (!$ignore_cache) {
11683: my ($content,$cached)=
11684: &Apache::lonnet::is_cached_new('dns',$url);
11685: if ($cached) {
1.1210 raeburn 11686: &$func($content,$hashref);
1.869 albertel 11687: return;
11688: }
11689: }
11690:
11691: my %alldns;
1.852 albertel 11692: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11693: foreach my $dns (<$config>) {
11694: next if ($dns !~ /^\^(\S*)/x);
1.979 raeburn 11695: my $line = $1;
11696: my ($host,$protocol) = split(/:/,$line);
11697: if ($protocol ne 'https') {
11698: $protocol = 'http';
11699: }
11700: $alldns{$host} = $protocol;
1.869 albertel 11701: }
11702: while (%alldns) {
11703: my ($dns) = keys(%alldns);
1.852 albertel 11704: my $ua=new LWP::UserAgent;
1.1134 raeburn 11705: $ua->timeout(30);
1.979 raeburn 11706: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 11707: my $response=$ua->request($request);
1.979 raeburn 11708: delete($alldns{$dns});
1.852 albertel 11709: next if ($response->is_error());
11710: my @content = split("\n",$response->content);
1.1210 raeburn 11711: unless ($nocache) {
1.1219 raeburn 11712: &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1210 raeburn 11713: }
11714: &$func(\@content,$hashref);
1.869 albertel 11715: return;
1.852 albertel 11716: }
11717: close($config);
1.871 albertel 11718: my $which = (split('/',$url))[3];
11719: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
11720: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 11721: my @content = <$config>;
1.1210 raeburn 11722: &$func(\@content,$hashref);
11723: return;
11724: }
11725:
11726: # ------------------------------------------------------Get DNS checksums file
1.1211 raeburn 11727: sub parse_dns_checksums_tab {
1.1210 raeburn 11728: my ($lines,$hashref) = @_;
11729: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
11730: my $loncaparev = &get_server_loncaparev($machine_dom);
11731: my ($release,$timestamp) = split(/\-/,$loncaparev);
11732: my (%chksum,%revnum);
11733: if (ref($lines) eq 'ARRAY') {
11734: chomp(@{$lines});
1.1238 raeburn 11735: my $version = shift(@{$lines});
11736: if ($version eq $release) {
1.1210 raeburn 11737: foreach my $line (@{$lines}) {
1.1238 raeburn 11738: my ($file,$version,$shasum) = split(/,/,$line);
11739: $chksum{$file} = $shasum;
11740: $revnum{$file} = $version;
1.1210 raeburn 11741: }
11742: if (ref($hashref) eq 'HASH') {
11743: %{$hashref} = (
11744: sums => \%chksum,
11745: versions => \%revnum,
11746: );
11747: }
11748: }
11749: }
1.869 albertel 11750: return;
1.852 albertel 11751: }
1.1210 raeburn 11752:
11753: sub fetch_dns_checksums {
1.1238 raeburn 11754: my %checksums;
11755: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
11756: my $loncaparev = &get_server_loncaparev($machine_dom);
11757: my ($release,$timestamp) = split(/\-/,$loncaparev);
11758: &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1211 raeburn 11759: \%checksums);
1.1210 raeburn 11760: return \%checksums;
11761: }
11762:
1.327 albertel 11763: # ------------------------------------------------------------ Read domain file
11764: {
1.852 albertel 11765: my $loaded;
1.846 albertel 11766: my %domain;
11767:
1.852 albertel 11768: sub parse_domain_tab {
11769: my ($lines) = @_;
11770: foreach my $line (@$lines) {
11771: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 11772:
1.846 albertel 11773: chomp($line);
1.852 albertel 11774: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 11775: my %this_domain;
11776: foreach my $field ('description', 'auth_def', 'auth_arg_def',
11777: 'lang_def', 'city', 'longi', 'lati',
11778: 'primary') {
11779: $this_domain{$field} = shift(@elements);
11780: }
11781: $domain{$name} = \%this_domain;
1.852 albertel 11782: }
11783: }
1.864 albertel 11784:
11785: sub reset_domain_info {
11786: undef($loaded);
11787: undef(%domain);
11788: }
11789:
1.852 albertel 11790: sub load_domain_tab {
1.869 albertel 11791: my ($ignore_cache) = @_;
11792: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852 albertel 11793: my $fh;
11794: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
11795: my @lines = <$fh>;
11796: &parse_domain_tab(\@lines);
1.448 albertel 11797: }
1.852 albertel 11798: close($fh);
11799: $loaded = 1;
1.327 albertel 11800: }
1.846 albertel 11801:
11802: sub domain {
1.852 albertel 11803: &load_domain_tab() if (!$loaded);
11804:
1.846 albertel 11805: my ($name,$what) = @_;
11806: return if ( !exists($domain{$name}) );
11807:
11808: if (!$what) {
11809: return $domain{$name}{'description'};
11810: }
11811: return $domain{$name}{$what};
11812: }
1.974 raeburn 11813:
11814: sub domain_info {
11815: &load_domain_tab() if (!$loaded);
11816: return %domain;
11817: }
11818:
1.327 albertel 11819: }
11820:
11821:
1.1 albertel 11822: # ------------------------------------------------------------- Read hosts file
11823: {
1.838 albertel 11824: my %hostname;
1.844 albertel 11825: my %hostdom;
1.845 albertel 11826: my %libserv;
1.852 albertel 11827: my $loaded;
1.888 albertel 11828: my %name_to_host;
1.1074 raeburn 11829: my %internetdom;
1.1107 raeburn 11830: my %LC_dns_serv;
1.852 albertel 11831:
11832: sub parse_hosts_tab {
11833: my ($file) = @_;
11834: foreach my $configline (@$file) {
11835: next if ($configline =~ /^(\#|\s*$ )/x);
1.1107 raeburn 11836: chomp($configline);
11837: if ($configline =~ /^\^/) {
11838: if ($configline =~ /^\^([\w.\-]+)/) {
11839: $LC_dns_serv{$1} = 1;
11840: }
11841: next;
11842: }
1.1074 raeburn 11843: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 11844: $name=~s/\s//g;
11845: if ($id && $domain && $role && $name) {
11846: $hostname{$id}=$name;
1.888 albertel 11847: push(@{$name_to_host{$name}}, $id);
1.852 albertel 11848: $hostdom{$id}=$domain;
11849: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 11850: if (defined($protocol)) {
11851: if ($protocol eq 'https') {
11852: $protocol{$id} = $protocol;
11853: } else {
11854: $protocol{$id} = 'http';
11855: }
1.968 raeburn 11856: } else {
1.969 raeburn 11857: $protocol{$id} = 'http';
1.968 raeburn 11858: }
1.1074 raeburn 11859: if (defined($intdom)) {
11860: $internetdom{$id} = $intdom;
11861: }
1.852 albertel 11862: }
11863: }
11864: }
1.864 albertel 11865:
11866: sub reset_hosts_info {
1.897 albertel 11867: &purge_remembered();
1.864 albertel 11868: &reset_domain_info();
11869: &reset_hosts_ip_info();
1.892 albertel 11870: undef(%name_to_host);
1.864 albertel 11871: undef(%hostname);
11872: undef(%hostdom);
11873: undef(%libserv);
11874: undef($loaded);
11875: }
1.1 albertel 11876:
1.852 albertel 11877: sub load_hosts_tab {
1.869 albertel 11878: my ($ignore_cache) = @_;
11879: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852 albertel 11880: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11881: my @config = <$config>;
11882: &parse_hosts_tab(\@config);
11883: close($config);
11884: $loaded=1;
1.1 albertel 11885: }
1.852 albertel 11886:
1.838 albertel 11887: sub hostname {
1.852 albertel 11888: &load_hosts_tab() if (!$loaded);
11889:
1.838 albertel 11890: my ($lonid) = @_;
11891: return $hostname{$lonid};
11892: }
1.845 albertel 11893:
1.838 albertel 11894: sub all_hostnames {
1.852 albertel 11895: &load_hosts_tab() if (!$loaded);
11896:
1.838 albertel 11897: return %hostname;
11898: }
1.845 albertel 11899:
1.888 albertel 11900: sub all_names {
11901: &load_hosts_tab() if (!$loaded);
11902:
11903: return %name_to_host;
11904: }
11905:
1.974 raeburn 11906: sub all_host_domain {
11907: &load_hosts_tab() if (!$loaded);
11908: return %hostdom;
11909: }
11910:
1.845 albertel 11911: sub is_library {
1.852 albertel 11912: &load_hosts_tab() if (!$loaded);
11913:
1.845 albertel 11914: return exists($libserv{$_[0]});
11915: }
11916:
11917: sub all_library {
1.852 albertel 11918: &load_hosts_tab() if (!$loaded);
11919:
1.845 albertel 11920: return %libserv;
11921: }
11922:
1.1062 droeschl 11923: sub unique_library {
11924: #2x reverse removes all hostnames that appear more than once
11925: my %unique = reverse &all_library();
11926: return reverse %unique;
11927: }
11928:
1.841 albertel 11929: sub get_servers {
1.852 albertel 11930: &load_hosts_tab() if (!$loaded);
11931:
1.841 albertel 11932: my ($domain,$type) = @_;
11933: my %possible_hosts = ($type eq 'library') ? %libserv
11934: : %hostname;
11935: my %result;
1.842 albertel 11936: if (ref($domain) eq 'ARRAY') {
11937: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 11938: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 11939: $result{$host} = $hostname;
11940: }
11941: }
11942: } else {
11943: while ( my ($host,$hostname) = each(%possible_hosts)) {
11944: if ($hostdom{$host} eq $domain) {
11945: $result{$host} = $hostname;
11946: }
1.841 albertel 11947: }
11948: }
11949: return %result;
11950: }
1.845 albertel 11951:
1.1062 droeschl 11952: sub get_unique_servers {
11953: my %unique = reverse &get_servers(@_);
11954: return reverse %unique;
11955: }
11956:
1.844 albertel 11957: sub host_domain {
1.852 albertel 11958: &load_hosts_tab() if (!$loaded);
11959:
1.844 albertel 11960: my ($lonid) = @_;
11961: return $hostdom{$lonid};
11962: }
11963:
1.841 albertel 11964: sub all_domains {
1.852 albertel 11965: &load_hosts_tab() if (!$loaded);
11966:
1.841 albertel 11967: my %seen;
11968: my @uniq = grep(!$seen{$_}++, values(%hostdom));
11969: return @uniq;
11970: }
1.1074 raeburn 11971:
11972: sub internet_dom {
11973: &load_hosts_tab() if (!$loaded);
11974:
11975: my ($lonid) = @_;
11976: return $internetdom{$lonid};
11977: }
1.1107 raeburn 11978:
11979: sub is_LC_dns {
11980: &load_hosts_tab() if (!$loaded);
11981:
11982: my ($hostname) = @_;
11983: return exists($LC_dns_serv{$hostname});
11984: }
11985:
1.1 albertel 11986: }
11987:
1.847 albertel 11988: {
11989: my %iphost;
1.856 albertel 11990: my %name_to_ip;
11991: my %lonid_to_ip;
1.869 albertel 11992:
1.847 albertel 11993: sub get_hosts_from_ip {
11994: my ($ip) = @_;
11995: my %iphosts = &get_iphost();
11996: if (ref($iphosts{$ip})) {
11997: return @{$iphosts{$ip}};
11998: }
11999: return;
1.839 albertel 12000: }
1.864 albertel 12001:
12002: sub reset_hosts_ip_info {
12003: undef(%iphost);
12004: undef(%name_to_ip);
12005: undef(%lonid_to_ip);
12006: }
1.856 albertel 12007:
12008: sub get_host_ip {
12009: my ($lonid) = @_;
12010: if (exists($lonid_to_ip{$lonid})) {
12011: return $lonid_to_ip{$lonid};
12012: }
12013: my $name=&hostname($lonid);
12014: my $ip = gethostbyname($name);
12015: return if (!$ip || length($ip) ne 4);
12016: $ip=inet_ntoa($ip);
12017: $name_to_ip{$name} = $ip;
12018: $lonid_to_ip{$lonid} = $ip;
12019: return $ip;
12020: }
1.847 albertel 12021:
12022: sub get_iphost {
1.869 albertel 12023: my ($ignore_cache) = @_;
1.894 albertel 12024:
1.869 albertel 12025: if (!$ignore_cache) {
12026: if (%iphost) {
12027: return %iphost;
12028: }
12029: my ($ip_info,$cached)=
12030: &Apache::lonnet::is_cached_new('iphost','iphost');
12031: if ($cached) {
12032: %iphost = %{$ip_info->[0]};
12033: %name_to_ip = %{$ip_info->[1]};
12034: %lonid_to_ip = %{$ip_info->[2]};
12035: return %iphost;
12036: }
12037: }
1.894 albertel 12038:
12039: # get yesterday's info for fallback
12040: my %old_name_to_ip;
12041: my ($ip_info,$cached)=
12042: &Apache::lonnet::is_cached_new('iphost','iphost');
12043: if ($cached) {
12044: %old_name_to_ip = %{$ip_info->[1]};
12045: }
12046:
1.888 albertel 12047: my %name_to_host = &all_names();
12048: foreach my $name (keys(%name_to_host)) {
1.847 albertel 12049: my $ip;
12050: if (!exists($name_to_ip{$name})) {
12051: $ip = gethostbyname($name);
12052: if (!$ip || length($ip) ne 4) {
1.894 albertel 12053: if (defined($old_name_to_ip{$name})) {
12054: $ip = $old_name_to_ip{$name};
12055: &logthis("Can't find $name defaulting to old $ip");
12056: } else {
12057: &logthis("Name $name no IP found");
12058: next;
12059: }
12060: } else {
12061: $ip=inet_ntoa($ip);
1.847 albertel 12062: }
12063: $name_to_ip{$name} = $ip;
12064: } else {
12065: $ip = $name_to_ip{$name};
1.653 albertel 12066: }
1.888 albertel 12067: foreach my $id (@{ $name_to_host{$name} }) {
12068: $lonid_to_ip{$id} = $ip;
12069: }
12070: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 12071: }
1.1219 raeburn 12072: &do_cache_new('iphost','iphost',
12073: [\%iphost,\%name_to_ip,\%lonid_to_ip],
12074: 48*60*60);
1.869 albertel 12075:
1.847 albertel 12076: return %iphost;
1.598 albertel 12077: }
12078:
1.992 raeburn 12079: #
12080: # Given a DNS returns the loncapa host name for that DNS
12081: #
12082: sub host_from_dns {
12083: my ($dns) = @_;
12084: my @hosts;
12085: my $ip;
12086:
1.993 raeburn 12087: if (exists($name_to_ip{$dns})) {
1.992 raeburn 12088: $ip = $name_to_ip{$dns};
12089: }
12090: if (!$ip) {
12091: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
12092: if (length($ip) == 4) {
12093: $ip = &IO::Socket::inet_ntoa($ip);
12094: }
12095: }
12096: if ($ip) {
12097: @hosts = get_hosts_from_ip($ip);
12098: return $hosts[0];
12099: }
12100: return undef;
1.986 foxr 12101: }
1.992 raeburn 12102:
1.1074 raeburn 12103: sub get_internet_names {
12104: my ($lonid) = @_;
12105: return if ($lonid eq '');
12106: my ($idnref,$cached)=
12107: &Apache::lonnet::is_cached_new('internetnames',$lonid);
12108: if ($cached) {
12109: return $idnref;
12110: }
12111: my $ip = &get_host_ip($lonid);
12112: my @hosts = &get_hosts_from_ip($ip);
12113: my %iphost = &get_iphost();
12114: my (@idns,%seen);
12115: foreach my $id (@hosts) {
12116: my $dom = &host_domain($id);
12117: my $prim_id = &domain($dom,'primary');
12118: my $prim_ip = &get_host_ip($prim_id);
12119: next if ($seen{$prim_ip});
12120: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
12121: foreach my $id (@{$iphost{$prim_ip}}) {
12122: my $intdom = &internet_dom($id);
12123: unless (grep(/^\Q$intdom\E$/,@idns)) {
12124: push(@idns,$intdom);
12125: }
12126: }
12127: }
12128: $seen{$prim_ip} = 1;
12129: }
1.1219 raeburn 12130: return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074 raeburn 12131: }
12132:
1.986 foxr 12133: }
12134:
1.1079 raeburn 12135: sub all_loncaparevs {
12136: 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);
12137: }
12138:
1.1227 raeburn 12139: # ---------------------------------------------------------- Read loncaparev table
12140: {
12141: sub load_loncaparevs {
12142: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
12143: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
12144: while (my $configline=<$config>) {
12145: chomp($configline);
12146: my ($hostid,$loncaparev)=split(/:/,$configline);
12147: $loncaparevs{$hostid}=$loncaparev;
12148: }
12149: close($config);
12150: }
12151: }
12152: }
12153: }
12154:
12155: # ---------------------------------------------------------- Read serverhostID table
12156: {
12157: sub load_serverhomeIDs {
12158: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
12159: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
12160: while (my $configline=<$config>) {
12161: chomp($configline);
12162: my ($name,$id)=split(/:/,$configline);
12163: $serverhomeIDs{$name}=$id;
12164: }
12165: close($config);
12166: }
12167: }
12168: }
12169: }
12170:
12171:
1.862 albertel 12172: BEGIN {
12173:
12174: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
12175: unless ($readit) {
12176: {
12177: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
12178: %perlvar = (%perlvar,%{$configvars});
12179: }
12180:
12181:
1.1 albertel 12182: # ------------------------------------------------------ Read spare server file
12183: {
1.448 albertel 12184: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 12185:
12186: while (my $configline=<$config>) {
12187: chomp($configline);
1.284 matthew 12188: if ($configline) {
1.784 albertel 12189: my ($host,$type) = split(':',$configline,2);
1.785 albertel 12190: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 12191: push(@{ $spareid{$type} }, $host);
1.1 albertel 12192: }
12193: }
1.448 albertel 12194: close($config);
1.1 albertel 12195: }
1.11 www 12196: # ------------------------------------------------------------ Read permissions
12197: {
1.448 albertel 12198: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 12199:
12200: while (my $configline=<$config>) {
1.448 albertel 12201: chomp($configline);
12202: if ($configline) {
12203: my ($role,$perm)=split(/ /,$configline);
12204: if ($perm ne '') { $pr{$role}=$perm; }
12205: }
1.11 www 12206: }
1.448 albertel 12207: close($config);
1.11 www 12208: }
12209:
12210: # -------------------------------------------- Read plain texts for permissions
12211: {
1.448 albertel 12212: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 12213:
12214: while (my $configline=<$config>) {
1.448 albertel 12215: chomp($configline);
12216: if ($configline) {
1.742 raeburn 12217: my ($short,@plain)=split(/:/,$configline);
12218: %{$prp{$short}} = ();
12219: if (@plain > 0) {
12220: $prp{$short}{'std'} = $plain[0];
12221: for (my $i=1; $i<@plain; $i++) {
12222: $prp{$short}{'alt'.$i} = $plain[$i];
12223: }
12224: }
1.448 albertel 12225: }
1.135 www 12226: }
1.448 albertel 12227: close($config);
1.135 www 12228: }
12229:
12230: # ---------------------------------------------------------- Read package table
12231: {
1.448 albertel 12232: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 12233:
12234: while (my $configline=<$config>) {
1.483 albertel 12235: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 12236: chomp($configline);
12237: my ($short,$plain)=split(/:/,$configline);
12238: my ($pack,$name)=split(/\&/,$short);
12239: if ($plain ne '') {
12240: $packagetab{$pack.'&'.$name.'&name'}=$name;
12241: $packagetab{$short}=$plain;
12242: }
1.11 www 12243: }
1.448 albertel 12244: close($config);
1.329 matthew 12245: }
12246:
1.1073 raeburn 12247: # ---------------------------------------------------------- Read loncaparev table
1.1227 raeburn 12248:
12249: &load_loncaparevs();
1.1073 raeburn 12250:
1.1074 raeburn 12251: # ---------------------------------------------------------- Read serverhostID table
12252:
1.1227 raeburn 12253: &load_serverhomeIDs();
12254:
12255: # ---------------------------------------------------------- Read releaseslist XML
1.1079 raeburn 12256: {
12257: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
12258: if (-e $file) {
12259: my $parser = HTML::LCParser->new($file);
12260: while (my $token = $parser->get_token()) {
12261: if ($token->[0] eq 'S') {
12262: my $item = $token->[1];
12263: my $name = $token->[2]{'name'};
12264: my $value = $token->[2]{'value'};
12265: if ($item ne '' && $name ne '' && $value ne '') {
12266: my $release = $parser->get_text();
12267: $release =~ s/(^\s*|\s*$ )//gx;
12268: $needsrelease{$item.':'.$name.':'.$value} = $release;
12269: }
12270: }
12271: }
12272: }
1.1073 raeburn 12273: }
12274:
1.1138 raeburn 12275: # ---------------------------------------------------------- Read managers table
12276: {
12277: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
12278: if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
12279: while (my $configline=<$config>) {
12280: chomp($configline);
12281: next if ($configline =~ /^\#/);
12282: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
12283: $managerstab{$configline} = 1;
12284: }
12285: }
12286: close($config);
12287: }
12288: }
12289: }
12290:
1.329 matthew 12291: # ------------- set up temporary directory
12292: {
1.1117 foxr 12293: $tmpdir = LONCAPA::tempdir();
1.329 matthew 12294:
1.11 www 12295: }
12296:
1.794 albertel 12297: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
12298: 'compress_threshold'=> 20_000,
12299: });
1.185 www 12300:
1.281 www 12301: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 12302: $dumpcount=0;
1.958 www 12303: $locknum=0;
1.22 www 12304:
1.163 harris41 12305: &logtouch();
1.672 albertel 12306: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 12307: $readit=1;
1.564 albertel 12308: {
12309: use integer;
12310: my $test=(2**32)+1;
1.568 albertel 12311: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 12312: &logthis(" Detected 64bit platform ($_64bit)");
12313: }
1.1214 raeburn 12314:
12315: {
12316: eval {
12317: ($apache) =
12318: (Apache2::ServerUtil::get_server_version() =~ m{Apache/(\d+\.\d+)});
12319: };
12320: if ($@) {
12321: $apache = 1.3;
1.1213 raeburn 12322: }
12323: }
1.1214 raeburn 12324:
1.195 www 12325: }
1.1 albertel 12326: }
1.179 www 12327:
1.1 albertel 12328: 1;
1.191 harris41 12329: __END__
12330:
1.243 albertel 12331: =pod
12332:
1.191 harris41 12333: =head1 NAME
12334:
1.243 albertel 12335: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 12336:
12337: =head1 SYNOPSIS
12338:
1.243 albertel 12339: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 12340:
12341: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
12342:
1.243 albertel 12343: Common parameters:
12344:
12345: =over 4
12346:
12347: =item *
12348:
12349: $uname : an internal username (if $cname expecting a course Id specifically)
12350:
12351: =item *
12352:
12353: $udom : a domain (if $cdom expecting a course's domain specifically)
12354:
12355: =item *
12356:
12357: $symb : a resource instance identifier
12358:
12359: =item *
12360:
12361: $namespace : the name of a .db file that contains the data needed or
12362: being set.
12363:
12364: =back
12365:
1.394 bowersj2 12366: =head1 OVERVIEW
1.191 harris41 12367:
1.394 bowersj2 12368: lonnet provides subroutines which interact with the
12369: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
12370: about classes, users, and resources.
1.243 albertel 12371:
12372: For many of these objects you can also use this to store data about
12373: them or modify them in various ways.
1.191 harris41 12374:
1.394 bowersj2 12375: =head2 Symbs
1.191 harris41 12376:
1.394 bowersj2 12377: To identify a specific instance of a resource, LON-CAPA uses symbols
12378: or "symbs"X<symb>. These identifiers are built from the URL of the
12379: map, the resource number of the resource in the map, and the URL of
12380: the resource itself. The latter is somewhat redundant, but might help
12381: if maps change.
12382:
12383: An example is
12384:
12385: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
12386:
12387: The respective map entry is
12388:
12389: <resource id="19" src="/res/msu/korte/tests/part12.problem"
12390: title="Problem 2">
12391: </resource>
12392:
12393: Symbs are used by the random number generator, as well as to store and
12394: restore data specific to a certain instance of for example a problem.
12395:
12396: =head2 Storing And Retrieving Data
12397:
12398: X<store()>X<cstore()>X<restore()>Three of the most important functions
12399: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
12400: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
12401: is is the non-critical message twin of cstore. These functions are for
12402: handlers to store a perl hash to a user's permanent data space in an
12403: easy manner, and to retrieve it again on another call. It is expected
12404: that a handler would use this once at the beginning to retrieve data,
12405: and then again once at the end to send only the new data back.
12406:
12407: The data is stored in the user's data directory on the user's
12408: homeserver under the ID of the course.
12409:
12410: The hash that is returned by restore will have all of the previous
12411: value for all of the elements of the hash.
12412:
12413: Example:
12414:
12415: #creating a hash
12416: my %hash;
12417: $hash{'foo'}='bar';
12418:
12419: #storing it
12420: &Apache::lonnet::cstore(\%hash);
12421:
12422: #changing a value
12423: $hash{'foo'}='notbar';
12424:
12425: #adding a new value
12426: $hash{'bar'}='foo';
12427: &Apache::lonnet::cstore(\%hash);
12428:
12429: #retrieving the hash
12430: my %history=&Apache::lonnet::restore();
12431:
12432: #print the hash
12433: foreach my $key (sort(keys(%history))) {
12434: print("\%history{$key} = $history{$key}");
12435: }
12436:
12437: Will print out:
1.191 harris41 12438:
1.394 bowersj2 12439: %history{1:foo} = bar
12440: %history{1:keys} = foo:timestamp
12441: %history{1:timestamp} = 990455579
12442: %history{2:bar} = foo
12443: %history{2:foo} = notbar
12444: %history{2:keys} = foo:bar:timestamp
12445: %history{2:timestamp} = 990455580
12446: %history{bar} = foo
12447: %history{foo} = notbar
12448: %history{timestamp} = 990455580
12449: %history{version} = 2
12450:
12451: Note that the special hash entries C<keys>, C<version> and
12452: C<timestamp> were added to the hash. C<version> will be equal to the
12453: total number of versions of the data that have been stored. The
12454: C<timestamp> attribute will be the UNIX time the hash was
12455: stored. C<keys> is available in every historical section to list which
12456: keys were added or changed at a specific historical revision of a
12457: hash.
12458:
12459: B<Warning>: do not store the hash that restore returns directly. This
12460: will cause a mess since it will restore the historical keys as if the
12461: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 12462:
1.394 bowersj2 12463: Calling convention:
1.191 harris41 12464:
1.1225 raeburn 12465: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
12466: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname);
1.191 harris41 12467:
1.394 bowersj2 12468: For more detailed information, see lonnet specific documentation.
1.191 harris41 12469:
1.394 bowersj2 12470: =head1 RETURN MESSAGES
1.191 harris41 12471:
1.394 bowersj2 12472: =over 4
1.191 harris41 12473:
1.394 bowersj2 12474: =item * B<con_lost>: unable to contact remote host
1.191 harris41 12475:
1.394 bowersj2 12476: =item * B<con_delayed>: unable to contact remote host, message will be delivered
12477: when the connection is brought back up
1.191 harris41 12478:
1.394 bowersj2 12479: =item * B<con_failed>: unable to contact remote host and unable to save message
12480: for later delivery
1.191 harris41 12481:
1.967 bisitz 12482: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 12483:
1.394 bowersj2 12484: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 12485: that was requested
1.191 harris41 12486:
1.243 albertel 12487: =back
1.191 harris41 12488:
1.243 albertel 12489: =head1 PUBLIC SUBROUTINES
1.191 harris41 12490:
1.243 albertel 12491: =head2 Session Environment Functions
1.191 harris41 12492:
1.243 albertel 12493: =over 4
1.191 harris41 12494:
1.394 bowersj2 12495: =item *
12496: X<appenv()>
1.949 raeburn 12497: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 12498: the user envirnoment file, and will be restored for each access this
1.620 albertel 12499: user makes during this session, also modifies the %env for the current
1.949 raeburn 12500: process. Optional rolesarrayref - if defined contains a reference to an array
12501: of roles which are exempt from the restriction on modifying user.role entries
12502: in the user's environment.db and in %env.
1.191 harris41 12503:
12504: =item *
1.394 bowersj2 12505: X<delenv()>
1.987 raeburn 12506: B<delenv($delthis,$regexp)>: removes all items from the session
12507: environment file that begin with $delthis. If the
12508: optional second arg - $regexp - is true, $delthis is treated as a
12509: regular expression, otherwise \Q$delthis\E is used.
12510: The values are also deleted from the current processes %env.
1.191 harris41 12511:
1.795 albertel 12512: =item * get_env_multiple($name)
12513:
12514: gets $name from the %env hash, it seemlessly handles the cases where multiple
12515: values may be defined and end up as an array ref.
12516:
12517: returns an array of values
12518:
1.243 albertel 12519: =back
12520:
12521: =head2 User Information
1.191 harris41 12522:
1.243 albertel 12523: =over 4
1.191 harris41 12524:
12525: =item *
1.394 bowersj2 12526: X<queryauthenticate()>
12527: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 12528: authentication scheme
12529:
12530: =item *
1.394 bowersj2 12531: X<authenticate()>
1.1073 raeburn 12532: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 12533: authenticate user from domain's lib servers (first use the current
12534: one). C<$upass> should be the users password.
1.1073 raeburn 12535: $checkdefauth is optional (value is 1 if a check should be made to
12536: authenticate user using default authentication method, and allow
12537: account creation if username does not have account in the domain).
12538: $clientcancheckhost is optional (value is 1 if checking whether the
12539: server can host will occur on the client side in lonauth.pm).
1.191 harris41 12540:
12541: =item *
1.394 bowersj2 12542: X<homeserver()>
12543: B<homeserver($uname,$udom)>: find the server which has
12544: the user's directory and files (there must be only one), this caches
12545: the answer, and also caches if there is a borken connection.
1.191 harris41 12546:
12547: =item *
1.394 bowersj2 12548: X<idget()>
12549: B<idget($udom,@ids)>: find the usernames behind a list of IDs
12550: (IDs are a unique resource in a domain, there must be only 1 ID per
12551: username, and only 1 username per ID in a specific domain) (returns
12552: hash: id=>name,id=>name)
1.191 harris41 12553:
12554: =item *
1.394 bowersj2 12555: X<idrget()>
12556: B<idrget($udom,@unames)>: find the IDs behind a list of
12557: usernames (returns hash: name=>id,name=>id)
1.191 harris41 12558:
12559: =item *
1.394 bowersj2 12560: X<idput()>
12561: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 12562:
12563: =item *
1.394 bowersj2 12564: X<rolesinit()>
1.1169 droeschl 12565: B<rolesinit($udom,$username)>: get user privileges.
12566: returns user role, first access and timer interval hashes
1.243 albertel 12567:
12568: =item *
1.1171 droeschl 12569: X<privileged()>
12570: B<privileged($username,$domain)>: returns a true if user has a
12571: privileged and active role (i.e. su or dc), false otherwise.
12572:
12573: =item *
1.551 albertel 12574: X<getsection()>
12575: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 12576: course $cname, return section name/number or '' for "not in course"
12577: and '-1' for "no section"
12578:
12579: =item *
1.394 bowersj2 12580: X<userenvironment()>
12581: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 12582: passed in @what from the requested user's environment, returns a hash
12583:
1.858 raeburn 12584: =item *
12585: X<userlog_query()>
1.859 albertel 12586: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
12587: activity.log file. %filters defines filters applied when parsing the
12588: log file. These can be start or end timestamps, or the type of action
12589: - log to look for Login or Logout events, check for Checkin or
12590: Checkout, role for role selection. The response is in the form
12591: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
12592: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 12593:
1.243 albertel 12594: =back
12595:
12596: =head2 User Roles
12597:
12598: =over 4
12599:
12600: =item *
12601:
1.810 raeburn 12602: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243 albertel 12603: F: full access
12604: U,I,K: authentication modes (cxx only)
12605: '': forbidden
12606: 1: user needs to choose course
12607: 2: browse allowed
1.766 albertel 12608: A: passphrase authentication needed
1.243 albertel 12609:
12610: =item *
12611:
1.1192 raeburn 12612: constructaccess($url,$setpriv) : check for access to construction space URL
12613:
12614: See if the owner domain and name in the URL match those in the
12615: expected environment. If so, return three element list
12616: ($ownername,$ownerdomain,$ownerhome).
12617:
12618: Otherwise return the null string.
12619:
12620: If second argument 'setpriv' is true, it assigns the privileges,
12621: and returns the same three element list, unless the owner has
12622: blocked "ad hoc" Domain Coordinator access to the Author Space,
12623: in which case the null string is returned.
12624:
12625: =item *
12626:
1.243 albertel 12627: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
12628: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
12629: and course level
12630:
12631: =item *
12632:
1.988 raeburn 12633: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
12634: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 12635: $type is Course (default) or Community.
1.988 raeburn 12636: If $forcedefault evaluates to true, text returned will be default
12637: text for $type. Otherwise, if this is a course, the text returned
12638: will be a custom name for the role (if defined in the course's
12639: environment). If no custom name is defined the default is returned.
12640:
1.832 raeburn 12641: =item *
12642:
1.1219 raeburn 12643: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858 raeburn 12644: All arguments are optional. Returns a hash of a roles, either for
12645: co-author/assistant author roles for a user's Construction Space
1.906 albertel 12646: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 12647: In the hash, keys are set to colon-separated $uname,$udom,$role, and
12648: (optionally) if $withsec is true, a fourth colon-separated item - $section.
12649: For each key, value is set to colon-separated start and end times for
12650: the role. If no username and domain are specified, will default to
1.934 raeburn 12651: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 12652: of role statuses (active, future or previous), roles
12653: (e.g., cc,in, st etc.) and domains of the roles which can be used
12654: to restrict the list of roles reported. If no array ref is
12655: provided for types, will default to return only active roles.
1.834 albertel 12656:
1.1195 raeburn 12657: =item *
12658:
12659: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196 raeburn 12660: user: $uname:$udom has a role in the course: $cdom_$cnum.
12661:
12662: Additional optional arguments are: $type (if role checking is to be restricted
12663: to certain user status types -- previous (expired roles), active (currently
1.1195 raeburn 12664: available roles) or future (roles available in the future), and
12665: $hideprivileged -- if true will not report course roles for users who
1.1219 raeburn 12666: have active Domain Coordinator role in course's domain or in additional
12667: domains (specified in 'Domains to check for privileged users' in course
12668: environment -- set via: Course Settings -> Classlists and staff listing).
12669:
12670: =item *
12671:
12672: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
12673: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
12674: $possdomains and $possroles are optional array refs -- to domains to check and
12675: roles to check. If $possdomains is not specified, a dump will be done of the
12676: users' roles.db to check for a dc or su role in any domain. This can be
12677: time consuming if &privileged is called repeatedly (e.g., when displaying a
12678: classlist), so in such cases, supplying a $possdomains array is preferred, as
12679: this then allows &privileged_by_domain() to be used, which caches the identity
12680: of privileged users, eliminating the need for repeated calls to &dump().
12681:
12682: =item *
12683:
12684: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
12685: where the outer hash keys are domains specified in the $possdomains array ref,
12686: next inner hash keys are privileged roles specified in the $roles array ref,
12687: and the innermost hash contains key = value pairs for username:domain = end:start
12688: for active or future "privileged" users with that role in that domain. To avoid
12689: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
12690: innerhash are cached using priv_$role and $dom as the identifiers.
1.1195 raeburn 12691:
1.243 albertel 12692: =back
12693:
12694: =head2 User Modification
12695:
12696: =over 4
12697:
12698: =item *
12699:
1.957 raeburn 12700: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 12701: user for the level given by URL. Optional start and end dates (leave empty
12702: string or zero for "no date")
1.191 harris41 12703:
12704: =item *
12705:
1.243 albertel 12706: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
12707: change a users, password, possible return values are: ok,
12708: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
12709: refused
1.191 harris41 12710:
12711: =item *
12712:
1.243 albertel 12713: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 12714:
12715: =item *
12716:
1.1058 raeburn 12717: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
12718: $forceid,$desiredhome,$email,$inststatus,$candelete) :
12719:
12720: will update user information (firstname,middlename,lastname,generation,
12721: permanentemail), and if forceid is true, student/employee ID also.
12722: A user's institutional affiliation(s) can also be updated.
12723: User information fields will not be overwritten with empty entries
12724: unless the field is included in the $candelete array reference.
12725: This array is included when a single user is modified via "Manage Users",
12726: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 12727:
12728: =item *
12729:
1.286 matthew 12730: modifystudent
12731:
1.957 raeburn 12732: modify a student's enrollment and identification information.
1.1235 raeburn 12733: The course id is resolved based on the current user's environment.
12734: This means the invoking user must be a course coordinator or otherwise
1.286 matthew 12735: associated with a course.
12736:
1.297 matthew 12737: This call is essentially a wrapper for lonnet::modifyuser and
12738: lonnet::modify_student_enrollment
1.286 matthew 12739:
12740: Inputs:
12741:
12742: =over 4
12743:
1.957 raeburn 12744: =item B<$udom> Student's loncapa domain
1.286 matthew 12745:
1.957 raeburn 12746: =item B<$uname> Student's loncapa login name
1.286 matthew 12747:
1.964 bisitz 12748: =item B<$uid> Student/Employee ID
1.286 matthew 12749:
1.957 raeburn 12750: =item B<$umode> Student's authentication mode
1.286 matthew 12751:
1.957 raeburn 12752: =item B<$upass> Student's password
1.286 matthew 12753:
1.957 raeburn 12754: =item B<$first> Student's first name
1.286 matthew 12755:
1.957 raeburn 12756: =item B<$middle> Student's middle name
1.286 matthew 12757:
1.957 raeburn 12758: =item B<$last> Student's last name
1.286 matthew 12759:
1.957 raeburn 12760: =item B<$gene> Student's generation
1.286 matthew 12761:
1.957 raeburn 12762: =item B<$usec> Student's section in course
1.286 matthew 12763:
12764: =item B<$end> Unix time of the roles expiration
12765:
12766: =item B<$start> Unix time of the roles start date
12767:
12768: =item B<$forceid> If defined, allow $uid to be changed
12769:
12770: =item B<$desiredhome> server to use as home server for student
12771:
1.957 raeburn 12772: =item B<$email> Student's permanent e-mail address
12773:
12774: =item B<$type> Type of enrollment (auto or manual)
12775:
1.963 raeburn 12776: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
12777:
12778: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 12779:
1.963 raeburn 12780: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 12781:
1.963 raeburn 12782: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 12783:
1.1216 raeburn 12784: =item B<$inststatus> institutional status of user - : separated string of escaped status types
12785:
12786: =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 12787:
1.286 matthew 12788: =back
1.297 matthew 12789:
12790: =item *
12791:
12792: modify_student_enrollment
12793:
1.1235 raeburn 12794: Change a student's enrollment status in a class. The environment variable
1.297 matthew 12795: 'role.request.course' must be defined for this function to proceed.
12796:
12797: Inputs:
12798:
12799: =over 4
12800:
1.1235 raeburn 12801: =item $udom, student's domain
1.297 matthew 12802:
1.1235 raeburn 12803: =item $uname, student's name
1.297 matthew 12804:
1.1235 raeburn 12805: =item $uid, student's user id
1.297 matthew 12806:
1.1235 raeburn 12807: =item $first, student's first name
1.297 matthew 12808:
12809: =item $middle
12810:
12811: =item $last
12812:
12813: =item $gene
12814:
12815: =item $usec
12816:
12817: =item $end
12818:
12819: =item $start
12820:
1.957 raeburn 12821: =item $type
12822:
12823: =item $locktype
12824:
12825: =item $cid
12826:
12827: =item $selfenroll
12828:
12829: =item $context
12830:
1.1216 raeburn 12831: =item $credits, number of credits student will earn from this class
12832:
1.297 matthew 12833: =back
12834:
1.191 harris41 12835:
12836: =item *
12837:
1.243 albertel 12838: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
12839: custom role; give a custom role to a user for the level given by URL. Specify
12840: name and domain of role author, and role name
1.191 harris41 12841:
12842: =item *
12843:
1.243 albertel 12844: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 12845:
12846: =item *
12847:
1.243 albertel 12848: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
12849:
12850: =back
12851:
12852: =head2 Course Infomation
12853:
12854: =over 4
1.191 harris41 12855:
12856: =item *
12857:
1.1118 foxr 12858: coursedescription($courseid,$options) : returns a hash of information about the
1.631 albertel 12859: specified course id, including all environment settings for the
12860: course, the description of the course will be in the hash under the
12861: key 'description'
1.191 harris41 12862:
1.1118 foxr 12863: $options is an optional parameter that if supplied is a hash reference that controls
12864: what how this function works. It has the following key/values:
12865:
12866: =over 4
12867:
12868: =item freshen_cache
12869:
12870: If defined, and the environment cache for the course is valid, it is
12871: returned in the returned hash.
12872:
12873: =item one_time
12874:
12875: If defined, the last cache time is set to _now_
12876:
12877: =item user
12878:
12879: If defined, the supplied username is used instead of the current user.
12880:
12881:
12882: =back
12883:
1.191 harris41 12884: =item *
12885:
1.624 albertel 12886: resdata($name,$domain,$type,@which) : request for current parameter
12887: setting for a specific $type, where $type is either 'course' or 'user',
12888: @what should be a list of parameters to ask about. This routine caches
1.1235 raeburn 12889: answers for 10 minutes.
1.243 albertel 12890:
1.877 foxr 12891: =item *
12892:
12893: get_courseresdata($courseid, $domain) : dump the entire course resource
12894: data base, returning a hash that is keyed by the resource name and has
12895: values that are the resource value. I believe that the timestamps and
12896: versions are also returned.
12897:
1.1236 raeburn 12898: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
12899: supplemental content area. This routine caches the number of files for
12900: 10 minutes.
12901:
1.243 albertel 12902: =back
12903:
12904: =head2 Course Modification
12905:
12906: =over 4
1.191 harris41 12907:
12908: =item *
12909:
1.243 albertel 12910: writecoursepref($courseid,%prefs) : write preferences (environment
12911: database) for a course
1.191 harris41 12912:
12913: =item *
12914:
1.1011 raeburn 12915: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
12916:
12917: =item *
12918:
1.1038 raeburn 12919: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 12920:
1.1167 droeschl 12921: =item *
12922:
12923: is_course($courseid), is_course($cdom, $cnum)
12924:
12925: Accepts either a combined $courseid (in the form of domain_courseid) or the
12926: two component version $cdom, $cnum. It checks if the specified course exists.
12927:
12928: Returns:
12929: undef if the course doesn't exist, otherwise
12930: in scalar context the combined courseid.
12931: in list context the two components of the course identifier, domain and
12932: courseid.
12933:
1.243 albertel 12934: =back
12935:
12936: =head2 Resource Subroutines
12937:
12938: =over 4
1.191 harris41 12939:
12940: =item *
12941:
1.243 albertel 12942: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 12943:
12944: =item *
12945:
1.243 albertel 12946: repcopy($filename) : subscribes to the requested file, and attempts to
12947: replicate from the owning library server, Might return
1.607 raeburn 12948: 'unavailable', 'not_found', 'forbidden', 'ok', or
12949: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 12950: resource. Expects the local filesystem pathname
12951: (/home/httpd/html/res/....)
12952:
12953: =back
12954:
12955: =head2 Resource Information
12956:
12957: =over 4
1.191 harris41 12958:
12959: =item *
12960:
1.1228 raeburn 12961: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates
12962: and returns the value of a variety of different possible values,
12963: $varname should be a request string, and the other parameters can be
12964: used to specify who and what one is asking about. Ordinarily, $cid
12965: does not need to be specified, as it is retrived from
12966: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
12967: within lonuserstate::loadmap() when initializing a course, before
12968: $env{'request.course.id'} has been set, so it needs to be provided
12969: in that one case.
1.243 albertel 12970:
12971: Possible values for $varname are environment.lastname (or other item
12972: from the envirnment hash), user.name (or someother aspect about the
12973: user), resource.0.maxtries (or some other part and parameter of a
12974: resource)
1.204 albertel 12975:
12976: =item *
12977:
1.243 albertel 12978: directcondval($number) : get current value of a condition; reads from a state
12979: string
1.204 albertel 12980:
12981: =item *
12982:
1.243 albertel 12983: condval($condidx) : value of condition index based on state
1.204 albertel 12984:
12985: =item *
12986:
1.243 albertel 12987: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
12988: resource's metadata, $what should be either a specific key, or either
12989: 'keys' (to get a list of possible keys) or 'packages' to get a list of
12990: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
12991:
12992: this function automatically caches all requests
1.191 harris41 12993:
12994: =item *
12995:
1.243 albertel 12996: metadata_query($query,$custom,$customshow) : make a metadata query against the
12997: network of library servers; returns file handle of where SQL and regex results
12998: will be stored for query
1.191 harris41 12999:
13000: =item *
13001:
1.243 albertel 13002: symbread($filename) : return symbolic list entry (filename argument optional);
13003: returns the data handle
1.191 harris41 13004:
13005: =item *
13006:
1.1190 raeburn 13007: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
13008: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582 albertel 13009: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190 raeburn 13010: on failure, user must be in a course, as it assumes the existence of
13011: the course initial hash, and uses $env('request.course.id'}. The third
13012: arg is an optional reference to a scalar. If this arg is passed in the
13013: call to symbverify, it will be set to 1 if the symb has been set to be
13014: encrypted; otherwise it will be null.
1.191 harris41 13015:
13016: =item *
13017:
1.243 albertel 13018: symbclean($symb) : removes versions numbers from a symb, returns the
13019: cleaned symb
1.191 harris41 13020:
13021: =item *
13022:
1.243 albertel 13023: is_on_map($uri) : checks if the $uri is somewhere on the current
13024: course map, user must be in a course for it to work.
1.191 harris41 13025:
13026: =item *
13027:
1.243 albertel 13028: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 13029:
13030: =item *
13031:
1.243 albertel 13032: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
13033: a random seed, all arguments are optional, if they aren't sent it uses the
13034: environment to derive them. Note: if symb isn't sent and it can't get one
13035: from &symbread it will use the current time as its return value
1.191 harris41 13036:
13037: =item *
13038:
1.243 albertel 13039: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
13040: unfakeable, receipt
1.191 harris41 13041:
13042: =item *
13043:
1.620 albertel 13044: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 13045:
13046: =item *
13047:
1.243 albertel 13048: countacc($url) : count the number of accesses to a given URL
1.191 harris41 13049:
13050: =item *
13051:
1.243 albertel 13052: 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 13053:
13054: =item *
13055:
1.243 albertel 13056: 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 13057:
13058: =item *
13059:
1.243 albertel 13060: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 13061:
13062: =item *
13063:
1.243 albertel 13064: devalidate($symb) : devalidate temporary spreadsheet calculations,
13065: forcing spreadsheet to reevaluate the resource scores next time.
13066:
1.1195 raeburn 13067: =item *
13068:
1.1196 raeburn 13069: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
13070: when viewing in course context.
1.1195 raeburn 13071:
1.1196 raeburn 13072: input: six args -- filename (decluttered), course number, course domain,
13073: url, symb (if registered) and group (if this is a
13074: group item -- e.g., bulletin board, group page etc.).
1.1195 raeburn 13075:
1.1196 raeburn 13076: output: array of five scalars --
1.1195 raeburn 13077: $cfile -- url for file editing if editable on current server
13078: $home -- homeserver of resource (i.e., for author if published,
13079: or course if uploaded.).
13080: $switchserver -- 1 if server switch will be needed.
1.1196 raeburn 13081: $forceedit -- 1 if icon/link should be to go to edit mode
13082: $forceview -- 1 if icon/link should be to go to view mode
1.1195 raeburn 13083:
13084: =item *
13085:
13086: is_course_upload($file,$cnum,$cdom)
13087:
13088: Used in course context to determine if current file was uploaded to
13089: the course (i.e., would be found in /userfiles/docs on the course's
13090: homeserver.
13091:
13092: input: 3 args -- filename (decluttered), course number and course domain.
13093: output: boolean -- 1 if file was uploaded.
13094:
1.243 albertel 13095: =back
13096:
13097: =head2 Storing/Retreiving Data
13098:
13099: =over 4
1.191 harris41 13100:
13101: =item *
13102:
1.243 albertel 13103: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
13104: for this url; hashref needs to be given and should be a \%hashname; the
13105: remaining args aren't required and if they aren't passed or are '' they will
1.620 albertel 13106: be derived from the env
1.191 harris41 13107:
13108: =item *
13109:
1.243 albertel 13110: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
13111: uses critical subroutine
1.191 harris41 13112:
13113: =item *
13114:
1.243 albertel 13115: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
13116: all args are optional
1.191 harris41 13117:
13118: =item *
13119:
1.717 albertel 13120: dumpstore($namespace,$udom,$uname,$regexp,$range) :
13121: dumps the complete (or key matching regexp) namespace into a hash
13122: ($udom, $uname, $regexp, $range are optional) for a namespace that is
13123: normally &store()ed into
13124:
13125: $range should be either an integer '100' (give me the first 100
13126: matching records)
13127: or be two integers sperated by a - with no spaces
13128: '30-50' (give me the 30th through the 50th matching
13129: records)
13130:
13131:
13132: =item *
13133:
13134: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
13135: replaces a &store() version of data with a replacement set of data
13136: for a particular resource in a namespace passed in the $storehash hash
13137: reference
13138:
13139: =item *
13140:
1.243 albertel 13141: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
13142: works very similar to store/cstore, but all data is stored in a
13143: temporary location and can be reset using tmpreset, $storehash should
13144: be a hash reference, returns nothing on success
1.191 harris41 13145:
13146: =item *
13147:
1.243 albertel 13148: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
13149: similar to restore, but all data is stored in a temporary location and
13150: can be reset using tmpreset. Returns a hash of values on success,
13151: error string otherwise.
1.191 harris41 13152:
13153: =item *
13154:
1.243 albertel 13155: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
13156: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 13157:
13158: =item *
13159:
1.243 albertel 13160: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13161: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 13162:
13163: =item *
13164:
1.243 albertel 13165: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
13166: namesp ($udom and $uname are optional)
1.191 harris41 13167:
13168: =item *
13169:
1.702 albertel 13170: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 13171: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 13172: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 13173:
1.702 albertel 13174: $range should be either an integer '100' (give me the first 100
13175: matching records)
13176: or be two integers sperated by a - with no spaces
13177: '30-50' (give me the 30th through the 50th matching
13178: records)
1.449 matthew 13179: =item *
13180:
13181: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
13182: $store can be a scalar, an array reference, or if the amount to be
13183: incremented is > 1, a hash reference.
13184:
13185: ($udom and $uname are optional)
1.191 harris41 13186:
13187: =item *
13188:
1.243 albertel 13189: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
13190: ($udom and $uname are optional)
1.191 harris41 13191:
13192: =item *
13193:
1.243 albertel 13194: cput($namespace,$storehash,$udom,$uname) : critical put
13195: ($udom and $uname are optional)
1.191 harris41 13196:
13197: =item *
13198:
1.748 albertel 13199: newput($namespace,$storehash,$udom,$uname) :
13200:
13201: Attempts to store the items in the $storehash, but only if they don't
13202: currently exist, if this succeeds you can be certain that you have
13203: successfully created a new key value pair in the $namespace db.
13204:
13205:
13206: Args:
13207: $namespace: name of database to store values to
13208: $storehash: hashref to store to the db
13209: $udom: (optional) domain of user containing the db
13210: $uname: (optional) name of user caontaining the db
13211:
13212: Returns:
13213: 'ok' -> succeeded in storing all keys of $storehash
13214: 'key_exists: <key>' -> failed to anything out of $storehash, as at
13215: least <key> already existed in the db (other
13216: requested keys may also already exist)
1.967 bisitz 13217: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 13218: 'con_lost' -> unable to contact request server
13219: 'refused' -> action was not allowed by remote machine
13220:
13221:
13222: =item *
13223:
1.243 albertel 13224: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13225: reference filled in from namesp (encrypts the return communication)
13226: ($udom and $uname are optional)
1.191 harris41 13227:
13228: =item *
13229:
1.243 albertel 13230: log($udom,$name,$home,$message) : write to permanent log for user; use
13231: critical subroutine
13232:
1.806 raeburn 13233: =item *
13234:
1.860 raeburn 13235: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
13236: array reference filled in from namespace found in domain level on either
13237: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 13238:
13239: =item *
13240:
1.860 raeburn 13241: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
13242: domain level either on specified domain server ($uhome) or primary domain
13243: server ($udom and $uhome are optional)
1.806 raeburn 13244:
1.943 raeburn 13245: =item *
13246:
1.1240 raeburn 13247: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
13248: for: authentication, language, quotas, timezone, date locale, and portal URL in
13249: the target domain.
13250:
13251: May also include additional key => value pairs for the following groups:
13252:
13253: =over
13254:
13255: =item
13256: disk quotas (MB allocated by default to portfolios and authoring spaces).
13257:
13258: =over
13259:
13260: =item defaultquota, authorquota
13261:
13262: =back
13263:
13264: =item
13265: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
13266: portfolio for users).
13267:
13268: =over
13269:
13270: =item
13271: aboutme, blog, webdav, portfolio
13272:
13273: =back
13274:
13275: =item
13276: requestcourses: ability to request courses, and how requests are processed.
13277:
13278: =over
13279:
13280: =item
13281: official, unofficial, community
13282:
13283: =back
13284:
13285: =item
13286: inststatus: types of institutional affiliation, and order in which they are displayed.
13287:
13288: =over
13289:
13290: =item
13291: inststatustypes, inststatusorder
13292:
13293: =back
13294:
13295: =item
13296: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
13297: for course's uploaded content.
13298:
13299: =over
13300:
13301: =item
13302: canuse_pdfforms, officialcredits, unofficialcredits, officialquota, unofficialquota, communityquota
13303:
13304: =back
13305:
13306: =item
13307: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
13308: on your servers.
13309:
13310: =over
13311:
13312: =item
13313: remotesessions, hostedsessions
13314:
13315: =back
13316:
13317: =back
13318:
13319: In cases where a domain coordinator has never used the "Set Domain Configuration"
13320: utility to create a configuration.db file on a domain's primary library server
13321: only the following domain defaults: auth_def, auth_arg_def, lang_def
13322: -- corresponding values are authentication type (internal, krb4, krb5,
13323: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
13324: will be available. Values are retrieved from cache (if current), unless the
13325: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
13326: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
13327:
13328: Typical usage:
1.943 raeburn 13329:
1.1240 raeburn 13330: %domdefaults = &get_domain_defaults($target_domain);
1.943 raeburn 13331:
1.243 albertel 13332: =back
13333:
13334: =head2 Network Status Functions
13335:
13336: =over 4
1.191 harris41 13337:
13338: =item *
13339:
1.1137 raeburn 13340: dirlist() : return directory list based on URI (first arg).
13341:
13342: Inputs: 1 required, 5 optional.
13343:
13344: =over
13345:
13346: =item
13347: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
13348:
13349: =item
13350: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
13351:
13352: =item
13353: $username - username of user/course to be listed. Extracted from $uri if absent.
13354:
13355: =item
13356: $getpropath - boolean: 1 if prepend path using &propath().
13357:
13358: =item
13359: $getuserdir - boolean: 1 if prepend path for "userfiles".
13360:
13361: =item
13362: $alternateRoot - path to prepend in place of path from $uri.
13363:
13364: =back
13365:
13366: Returns: Array of up to two items.
13367:
13368: =over
13369:
13370: a reference to an array of files/subdirectories
13371:
13372: =over
13373:
13374: Each element in the array of files/subdirectories is a & separated list of
13375: item name and the result of running stat on the item. If dirlist was requested
13376: for a file instead of a directory, the item name will be ''. For a directory
13377: listing, if the item is a metadata file, the element will end &N&M
13378: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
13379: default copyright set (1).
13380:
13381: =back
13382:
13383: a scalar containing error condition (if encountered).
13384:
13385: =over
13386:
13387: =item
13388: no_host (no homeserver identified for $username:$domain).
13389:
13390: =item
13391: no_such_host (server contacted for listing not identified as valid host).
13392:
13393: =item
13394: con_lost (connection to remote server failed).
13395:
13396: =item
13397: refused (invalid $username:$domain received on lond side).
13398:
13399: =item
13400: no_such_dir (directory at specified path on lond side does not exist).
13401:
13402: =item
13403: empty (directory at specified path on lond side is empty).
13404:
13405: =over
13406:
13407: This is currently not encountered because the &ls3, &ls2,
13408: &ls (_handler) routines on the lond side do not filter out
13409: . and .. from a directory listing.
13410:
13411: =back
13412:
13413: =back
13414:
13415: =back
1.191 harris41 13416:
13417: =item *
13418:
1.243 albertel 13419: spareserver() : find server with least workload from spare.tab
13420:
1.986 foxr 13421:
13422: =item *
13423:
13424: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
13425: if there is no corresponding loncapa host.
13426:
1.243 albertel 13427: =back
13428:
1.986 foxr 13429:
1.243 albertel 13430: =head2 Apache Request
13431:
13432: =over 4
1.191 harris41 13433:
13434: =item *
13435:
1.243 albertel 13436: ssi($url,%hash) : server side include, does a complete request cycle on url to
13437: localhost, posts hash
13438:
13439: =back
13440:
13441: =head2 Data to String to Data
13442:
13443: =over 4
1.191 harris41 13444:
13445: =item *
13446:
1.243 albertel 13447: hash2str(%hash) : convert a hash into a string complete with escaping and '='
13448: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 13449:
13450: =item *
13451:
1.243 albertel 13452: hashref2str($hashref) : convert a hashref into a string complete with
13453: escaping and '=' and '&' separators, supports elements that are
13454: arrayrefs and hashrefs
1.191 harris41 13455:
13456: =item *
13457:
1.243 albertel 13458: arrayref2str($arrayref) : convert an arrayref into a string complete
13459: with escaping and '&' separators, supports elements that are arrayrefs
13460: and hashrefs
1.191 harris41 13461:
13462: =item *
13463:
1.243 albertel 13464: str2hash($string) : convert string to hash using unescaping and
13465: splitting on '=' and '&', supports elements that are arrayrefs and
13466: hashrefs
1.191 harris41 13467:
13468: =item *
13469:
1.243 albertel 13470: str2array($string) : convert string to hash using unescaping and
13471: splitting on '&', supports elements that are arrayrefs and hashrefs
13472:
13473: =back
13474:
13475: =head2 Logging Routines
13476:
13477:
13478: These routines allow one to make log messages in the lonnet.log and
13479: lonnet.perm logfiles.
1.191 harris41 13480:
1.1119 foxr 13481: =over 4
13482:
1.191 harris41 13483: =item *
13484:
1.243 albertel 13485: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 13486:
13487: =item *
13488:
1.243 albertel 13489: logthis() : append message to the normal lonnet.log file, it gets
13490: preiodically rolled over and deleted.
1.191 harris41 13491:
13492: =item *
13493:
1.243 albertel 13494: logperm() : append a permanent message to lonnet.perm.log, this log
13495: file never gets deleted by any automated portion of the system, only
13496: messages of critical importance should go in here.
13497:
1.1119 foxr 13498:
1.243 albertel 13499: =back
13500:
13501: =head2 General File Helper Routines
13502:
13503: =over 4
1.191 harris41 13504:
13505: =item *
13506:
1.481 raeburn 13507: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
13508: (a) files in /uploaded
13509: (i) If a local copy of the file exists -
13510: compares modification date of local copy with last-modified date for
13511: definitive version stored on home server for course. If local copy is
13512: stale, requests a new version from the home server and stores it.
13513: If the original has been removed from the home server, then local copy
13514: is unlinked.
13515: (ii) If local copy does not exist -
13516: requests the file from the home server and stores it.
13517:
13518: If $caller is 'uploadrep':
13519: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
13520: for request for files originally uploaded via DOCS.
13521: - returns 'ok' if fresh local copy now available, -1 otherwise.
13522:
13523: Otherwise:
13524: This indicates a call from the content generation phase of the request.
13525: - returns the entire contents of the file or -1.
13526:
13527: (b) files in /res
13528: - returns the entire contents of a file or -1;
13529: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 13530:
1.712 albertel 13531:
13532: =item *
13533:
13534: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
13535: reference
13536:
13537: returns either a stat() list of data about the file or an empty list
13538: if the file doesn't exist or couldn't find out about it (connection
13539: problems or user unknown)
13540:
1.191 harris41 13541: =item *
13542:
1.243 albertel 13543: filelocation($dir,$file) : returns file system location of a file
13544: based on URI; meant to be "fairly clean" absolute reference, $dir is a
13545: directory that relative $file lookups are to looked in ($dir of /a/dir
13546: and a file of ../bob will become /a/bob)
1.191 harris41 13547:
13548: =item *
13549:
13550: hreflocation($dir,$file) : returns file system location or a URL; same as
13551: filelocation except for hrefs
13552:
13553: =item *
13554:
13555: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
13556:
1.243 albertel 13557: =back
13558:
1.608 albertel 13559: =head2 Usererfile file routines (/uploaded*)
13560:
13561: =over 4
13562:
13563: =item *
13564:
13565: userfileupload(): main rotine for putting a file in a user or course's
13566: filespace, arguments are,
13567:
1.620 albertel 13568: formname - required - this is the name of the element in $env where the
1.608 albertel 13569: filename, and the contents of the file to create/modifed exist
1.620 albertel 13570: the filename is in $env{'form.'.$formname.'.filename'} and the
13571: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 13572: context - if coursedoc, store the file in the course of the active role
13573: of the current user;
13574: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
13575: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 13576: subdir - required - subdirectory to put the file in under ../userfiles/
13577: if undefined, it will be placed in "unknown"
13578:
13579: (This routine calls clean_filename() to remove any dangerous
13580: characters from the filename, and then calls finuserfileupload() to
13581: complete the transaction)
13582:
13583: returns either the url of the uploaded file (/uploaded/....) if successful
13584: and /adm/notfound.html if unsuccessful
13585:
13586: =item *
13587:
13588: clean_filename(): routine for cleaing a filename up for storage in
13589: userfile space, argument is:
13590:
13591: filename - proposed filename
13592:
13593: returns: the new clean filename
13594:
13595: =item *
13596:
1.1090 raeburn 13597: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 13598: userspace, probably shouldn't be called directly
13599:
13600: docuname: username or courseid of destination for the file
13601: docudom: domain of user/course of destination for the file
13602: formname: same as for userfileupload()
1.1090 raeburn 13603: fname: filename (including subdirectories) for the file
13604: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
13605: allfiles: reference to hash used to store objects found by parser
13606: codebase: reference to hash used for codebases of java objects found by parser
13607: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
13608: thumbheight: height (pixels) of thumbnail to be created for uploaded image
13609: resizewidth: width to be used to resize image using resizeImage from ImageMagick
13610: resizeheight: height to be used to resize image using resizeImage from ImageMagick
13611: context: if 'overwrite', will move the uploaded file from its temporary location to
13612: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 13613: mimetype: reference to scalar to accommodate mime type determined
13614: from File::MMagic if $parser = parse.
1.608 albertel 13615:
13616: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 13617: and /adm/notfound.html if unsuccessful (or an error message if context
13618: was 'overwrite').
13619:
1.608 albertel 13620:
13621: =item *
13622:
13623: renameuserfile(): renames an existing userfile to a new name
13624:
13625: Args:
13626: docuname: username or courseid of destination for the file
13627: docudom: domain of user/course of destination for the file
13628: old: current file name (including any subdirs under userfiles)
13629: new: desired file name (including any subdirs under userfiles)
13630:
13631: =item *
13632:
13633: mkdiruserfile(): creates a directory is a userfiles dir
13634:
13635: Args:
13636: docuname: username or courseid of destination for the file
13637: docudom: domain of user/course of destination for the file
13638: dir: dir to create (including any subdirs under userfiles)
13639:
13640: =item *
13641:
13642: removeuserfile(): removes a file that exists in userfiles
13643:
13644: Args:
13645: docuname: username or courseid of destination for the file
13646: docudom: domain of user/course of destination for the file
13647: fname: filname to delete (including any subdirs under userfiles)
13648:
13649: =item *
13650:
13651: removeuploadedurl(): convience function for removeuserfile()
13652:
13653: Args:
13654: url: a full /uploaded/... url to delete
13655:
1.747 albertel 13656: =item *
13657:
13658: get_portfile_permissions():
13659: Args:
13660: domain: domain of user or course contain the portfolio files
13661: user: name of user or num of course contain the portfolio files
13662: Returns:
13663: hashref of a dump of the proper file_permissions.db
13664:
13665:
13666: =item *
13667:
13668: get_access_controls():
13669:
13670: Args:
13671: current_permissions: the hash ref returned from get_portfile_permissions()
13672: group: (optional) the group you want the files associated with
13673: file: (optional) the file you want access info on
13674:
13675: Returns:
1.749 raeburn 13676: a hash (keys are file names) of hashes containing
13677: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
13678: values are XML containing access control settings (see below)
1.747 albertel 13679:
13680: Internal notes:
13681:
1.749 raeburn 13682: access controls are stored in file_permissions.db as key=value pairs.
13683: key -> path to file/file_name\0uniqueID:scope_end_start
13684: where scope -> public,guest,course,group,domains or users.
13685: end -> UNIX time for end of access (0 -> no end date)
13686: start -> UNIX time for start of access
13687:
13688: value -> XML description of access control
13689: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
13690: <start></start>
13691: <end></end>
13692:
13693: <password></password> for scope type = guest
13694:
13695: <domain></domain> for scope type = course or group
13696: <number></number>
13697: <roles id="">
13698: <role></role>
13699: <access></access>
13700: <section></section>
13701: <group></group>
13702: </roles>
13703:
13704: <dom></dom> for scope type = domains
13705:
13706: <users> for scope type = users
13707: <user>
13708: <uname></uname>
13709: <udom></udom>
13710: </user>
13711: </users>
13712: </scope>
13713:
13714: Access data is also aggregated for each file in an additional key=value pair:
13715: key -> path to file/file_name\0accesscontrol
13716: value -> reference to hash
13717: hash contains key = value pairs
13718: where key = uniqueID:scope_end_start
13719: value = UNIX time record was last updated
13720:
13721: Used to improve speed of look-ups of access controls for each file.
13722:
13723: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
13724:
1.1198 raeburn 13725: =item *
13726:
1.749 raeburn 13727: modify_access_controls():
13728:
13729: Modifies access controls for a portfolio file
13730: Args
13731: 1. file name
13732: 2. reference to hash of required changes,
13733: 3. domain
13734: 4. username
13735: where domain,username are the domain of the portfolio owner
13736: (either a user or a course)
13737:
13738: Returns:
13739: 1. result of additions or updates ('ok' or 'error', with error message).
13740: 2. result of deletions ('ok' or 'error', with error message).
13741: 3. reference to hash of any new or updated access controls.
13742: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
13743: key = integer (inbound ID)
1.1198 raeburn 13744: value = uniqueID
13745:
13746: =item *
13747:
13748: get_timebased_id():
13749:
13750: Attempts to get a unique timestamp-based suffix for use with items added to a
13751: course via the Course Editor (e.g., folders, composite pages,
13752: group bulletin boards).
13753:
13754: Args: (first three required; six others optional)
13755:
13756: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
13757: docssequence, or name of group
13758:
13759: 2. keyid (alphanumeric): name of temporary locking key in hash,
13760: e.g., num, boardids
13761:
13762: 3. namespace: name of gdbm file used to store suffixes already assigned;
13763: file will be named nohist_namespace.db
13764:
13765: 4. cdom: domain of course; default is current course domain from %env
13766:
13767: 5. cnum: course number; default is current course number from %env
13768:
13769: 6. idtype: set to concat if an additional digit is to be appended to the
13770: unix timestamp to form the suffix, if the plain timestamp is already
13771: in use. Default is to not do this, but simply increment the unix
13772: timestamp by 1 until a unique key is obtained.
13773:
13774: 7. who: holder of locking key; defaults to user:domain for user.
13775:
13776: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
13777: retrying); default is 3.
13778:
13779: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
13780:
13781: Returns:
13782:
13783: 1. suffix obtained (numeric)
13784:
13785: 2. result of deleting locking key (ok if deleted, or lock never obtained)
13786:
13787: 3. error: contains (localized) error message if an error occurred.
13788:
1.747 albertel 13789:
1.608 albertel 13790: =back
13791:
1.243 albertel 13792: =head2 HTTP Helper Routines
13793:
13794: =over 4
13795:
1.191 harris41 13796: =item *
13797:
13798: escape() : unpack non-word characters into CGI-compatible hex codes
13799:
13800: =item *
13801:
13802: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
13803:
1.243 albertel 13804: =back
13805:
13806: =head1 PRIVATE SUBROUTINES
13807:
13808: =head2 Underlying communication routines (Shouldn't call)
13809:
13810: =over 4
13811:
13812: =item *
13813:
13814: subreply() : tries to pass a message to lonc, returns con_lost if incapable
13815:
13816: =item *
13817:
13818: reply() : uses subreply to send a message to remote machine, logs all failures
13819:
13820: =item *
13821:
13822: critical() : passes a critical message to another server; if cannot
13823: get through then place message in connection buffer directory and
13824: returns con_delayed, if incapable of saving message, returns
13825: con_failed
13826:
13827: =item *
13828:
13829: reconlonc() : tries to reconnect lonc client processes.
13830:
13831: =back
13832:
13833: =head2 Resource Access Logging
13834:
13835: =over 4
13836:
13837: =item *
13838:
13839: flushcourselogs() : flush (save) buffer logs and access logs
13840:
13841: =item *
13842:
13843: courselog($what) : save message for course in hash
13844:
13845: =item *
13846:
13847: courseacclog($what) : save message for course using &courselog(). Perform
13848: special processing for specific resource types (problems, exams, quizzes, etc).
13849:
1.191 harris41 13850: =item *
13851:
13852: goodbye() : flush course logs and log shutting down; it is called in srm.conf
13853: as a PerlChildExitHandler
1.243 albertel 13854:
13855: =back
13856:
13857: =head2 Other
13858:
13859: =over 4
13860:
13861: =item *
13862:
13863: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 13864:
13865: =back
13866:
13867: =cut
1.877 foxr 13868:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>