Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1256
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1256 ! raeburn 4: # $Id: lonnet.pm,v 1.1255 2014/04/16 14:40:05 raeburn Exp $
1.178 www 5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27: #
1.169 harris41 28: ###
29:
1.971 jms 30: =pod
31:
1.972 jms 32: =head1 NAME
33:
34: Apache::lonnet.pm
35:
36: =head1 SYNOPSIS
37:
38: This file is an interface to the lonc processes of
39: the LON-CAPA network as well as set of elaborated functions for handling information
40: necessary for navigating through a given cluster of LON-CAPA machines within a
41: domain. There are over 40 specialized functions in this module which handle the
42: reading and transmission of metadata, user information (ids, names, environments, roles,
43: logs), file information (storage, reading, directories, extensions, replication, embedded
44: styles and descriptors), educational resources (course descriptions, section names and
45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
46: and from more descriptive phrases or explanations.
47:
48: This is part of the LearningOnline Network with CAPA project
49: described at http://www.lon-capa.org.
50:
1.971 jms 51: =head1 Package Variables
52:
53: These are largely undocumented, so if you decipher one please note it here.
54:
55: =over 4
56:
57: =item $processmarker
58:
59: Contains the time this process was started and this servers host id.
60:
61: =item $dumpcount
62:
63: Counts the number of times a message log flush has been attempted (regardless
64: of success) by this process. Used as part of the filename when messages are
65: delayed.
66:
67: =back
68:
69: =cut
70:
1.1 albertel 71: package Apache::lonnet;
72:
73: use strict;
1.8 www 74: use LWP::UserAgent();
1.486 www 75: use HTTP::Date;
1.977 amueller 76: use Image::Magick;
77:
1.1182 foxr 78:
1.1173 foxr 79: use Encode;
80:
1.1245 raeburn 81: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.1138 raeburn 82: $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
83: %managerstab);
1.871 albertel 84:
85: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
86: %userrolehash, $processmarker, $dumpcount, %coursedombuf,
87: %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958 www 88: %courseownerbuf, %coursetypebuf,$locknum);
1.403 www 89:
1.1 albertel 90: use IO::Socket;
1.31 www 91: use GDBM_File;
1.208 albertel 92: use HTML::LCParser;
1.88 www 93: use Fcntl qw(:flock);
1.870 albertel 94: use Storable qw(thaw nfreeze);
1.539 albertel 95: use Time::HiRes qw( gettimeofday tv_interval );
1.599 albertel 96: use Cache::Memcached;
1.676 albertel 97: use Digest::MD5;
1.790 albertel 98: use Math::Random;
1.1024 raeburn 99: use File::MMagic;
1.807 albertel 100: use LONCAPA qw(:DEFAULT :match);
1.740 www 101: use LONCAPA::Configuration;
1.1160 www 102: use LONCAPA::lonmetadata;
1.1167 droeschl 103: use LONCAPA::Lond;
1.1117 foxr 104:
1.1090 raeburn 105: use File::Copy;
1.676 albertel 106:
1.195 www 107: my $readit;
1.550 foxr 108: my $max_connection_retries = 10; # Or some such value.
1.1 albertel 109:
1.619 albertel 110: require Exporter;
111:
112: our @ISA = qw (Exporter);
113: our @EXPORT = qw(%env);
114:
1.449 matthew 115:
1.1187 raeburn 116: # ------------------------------------ Logging (parameters, docs, slots, roles)
1.729 www 117: {
118: my $logid;
1.1187 raeburn 119: sub write_log {
1.1188 raeburn 120: my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
1.1184 raeburn 121: if ($context eq 'course') {
122: if (($cnum eq '') || ($cdom eq '')) {
123: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
124: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
125: }
1.957 raeburn 126: }
1.1184 raeburn 127: $logid ++;
1.957 raeburn 128: my $now = time();
129: my $id=$now.'00000'.$$.'00000'.$logid;
1.1184 raeburn 130: my $logentry = {
131: $id => {
132: 'exe_uname' => $env{'user.name'},
133: 'exe_udom' => $env{'user.domain'},
134: 'exe_time' => $now,
135: 'exe_ip' => $ENV{'REMOTE_ADDR'},
136: 'delflag' => $delflag,
137: 'logentry' => $storehash,
138: 'uname' => $uname,
139: 'udom' => $udom,
140: }
141: };
142: return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
1.729 www 143: }
144: }
1.1 albertel 145:
1.163 harris41 146: sub logtouch {
147: my $execdir=$perlvar{'lonDaemons'};
1.448 albertel 148: unless (-e "$execdir/logs/lonnet.log") {
149: open(my $fh,">>$execdir/logs/lonnet.log");
1.163 harris41 150: close $fh;
151: }
152: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
153: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
154: }
155:
1.1 albertel 156: sub logthis {
157: my $message=shift;
158: my $execdir=$perlvar{'lonDaemons'};
159: my $now=time;
160: my $local=localtime($now);
1.448 albertel 161: if (open(my $fh,">>$execdir/logs/lonnet.log")) {
1.986 foxr 162: my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
163: print $fh $logstring;
1.448 albertel 164: close($fh);
165: }
1.1 albertel 166: return 1;
167: }
168:
169: sub logperm {
170: my $message=shift;
171: my $execdir=$perlvar{'lonDaemons'};
172: my $now=time;
173: my $local=localtime($now);
1.448 albertel 174: if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
175: print $fh "$now:$message:$local\n";
176: close($fh);
177: }
1.1 albertel 178: return 1;
179: }
180:
1.850 albertel 181: sub create_connection {
1.853 albertel 182: my ($hostname,$lonid) = @_;
1.851 albertel 183: my $client=IO::Socket::UNIX->new(Peer => $perlvar{'lonSockCreate'},
1.850 albertel 184: Type => SOCK_STREAM,
185: Timeout => 10);
186: return 0 if (!$client);
1.890 albertel 187: print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850 albertel 188: my $result = <$client>;
189: chomp($result);
190: return 1 if ($result eq 'done');
191: return 0;
192: }
193:
1.983 raeburn 194: sub get_server_timezone {
195: my ($cnum,$cdom) = @_;
196: my $home=&homeserver($cnum,$cdom);
197: if ($home ne 'no_host') {
198: my $cachetime = 24*3600;
199: my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
200: if (defined($cached)) {
201: return $timezone;
202: } else {
203: my $timezone = &reply('servertimezone',$home);
204: return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
205: }
206: }
207: }
1.850 albertel 208:
1.1106 raeburn 209: sub get_server_distarch {
210: my ($lonhost,$ignore_cache) = @_;
211: if (defined($lonhost)) {
212: if (!defined(&hostname($lonhost))) {
213: return;
214: }
215: my $cachetime = 12*3600;
216: if (!$ignore_cache) {
217: my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
218: if (defined($cached)) {
219: return $distarch;
220: }
221: }
222: my $rep = &reply('serverdistarch',$lonhost);
223: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
224: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
225: $rep eq '') {
226: return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
227: }
228: }
229: return;
230: }
231:
1.993 raeburn 232: sub get_server_loncaparev {
1.1073 raeburn 233: my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993 raeburn 234: if (defined($lonhost)) {
235: if (!defined(&hostname($lonhost))) {
236: undef($lonhost);
237: }
238: }
239: if (!defined($lonhost)) {
240: if (defined(&domain($dom,'primary'))) {
241: $lonhost=&domain($dom,'primary');
242: if ($lonhost eq 'no_host') {
243: undef($lonhost);
244: }
245: }
246: }
247: if (defined($lonhost)) {
1.1073 raeburn 248: my $cachetime = 12*3600;
249: if (!$ignore_cache) {
250: my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
251: if (defined($cached)) {
252: return $loncaparev;
253: }
254: }
255: my ($answer,$loncaparev);
256: my @ids=¤t_machine_ids();
257: if (grep(/^\Q$lonhost\E$/,@ids)) {
258: $answer = $perlvar{'lonVersion'};
1.1081 raeburn 259: if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 260: $loncaparev = $1;
261: }
262: } else {
263: $answer = &reply('serverloncaparev',$lonhost);
264: if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
265: if ($caller eq 'loncron') {
266: my $ua=new LWP::UserAgent;
1.1082 raeburn 267: $ua->timeout(4);
1.1073 raeburn 268: my $protocol = $protocol{$lonhost};
269: $protocol = 'http' if ($protocol ne 'https');
270: my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
271: my $request=new HTTP::Request('GET',$url);
272: my $response=$ua->request($request);
273: unless ($response->is_error()) {
274: my $content = $response->content;
1.1081 raeburn 275: if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073 raeburn 276: $loncaparev = $1;
277: }
278: }
279: } else {
280: $loncaparev = $loncaparevs{$lonhost};
281: }
1.1081 raeburn 282: } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 283: $loncaparev = $1;
284: }
1.993 raeburn 285: }
1.1073 raeburn 286: return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993 raeburn 287: }
288: }
289:
1.1074 raeburn 290: sub get_server_homeID {
291: my ($hostname,$ignore_cache,$caller) = @_;
292: unless ($ignore_cache) {
293: my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
294: if (defined($cached)) {
295: return $serverhomeID;
296: }
297: }
298: my $cachetime = 12*3600;
299: my $serverhomeID;
300: if ($caller eq 'loncron') {
301: my @machine_ids = &machine_ids($hostname);
302: foreach my $id (@machine_ids) {
303: my $response = &reply('serverhomeID',$id);
304: unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
305: $serverhomeID = $response;
306: last;
307: }
308: }
309: if ($serverhomeID eq '') {
310: $serverhomeID = $machine_ids[-1];
311: }
312: } else {
313: $serverhomeID = $serverhomeIDs{$hostname};
314: }
315: return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
316: }
317:
1.1121 raeburn 318: sub get_remote_globals {
319: my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125 raeburn 320: my ($result,%returnhash,%whatneeded);
321: if (ref($whathash) eq 'HASH') {
1.1121 raeburn 322: foreach my $what (sort(keys(%{$whathash}))) {
323: my $hashid = $lonhost.'-'.$what;
1.1125 raeburn 324: my ($response,$cached);
1.1121 raeburn 325: unless ($ignore_cache) {
1.1125 raeburn 326: ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121 raeburn 327: }
328: if (defined($cached)) {
1.1125 raeburn 329: $returnhash{$what} = $response;
1.1121 raeburn 330: } else {
1.1125 raeburn 331: $whatneeded{$what} = 1;
1.1121 raeburn 332: }
333: }
1.1125 raeburn 334: if (keys(%whatneeded) == 0) {
335: $result = 'ok';
336: } else {
1.1121 raeburn 337: my $requested = &freeze_escape(\%whatneeded);
338: my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125 raeburn 339: if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
340: ($rep eq 'unknown_cmd')) {
341: $result = $rep;
342: } else {
343: $result = 'ok';
1.1121 raeburn 344: my @pairs=split(/\&/,$rep);
1.1125 raeburn 345: foreach my $item (@pairs) {
346: my ($key,$value)=split(/=/,$item,2);
347: my $what = &unescape($key);
348: my $hashid = $lonhost.'-'.$what;
349: $returnhash{$what}=&thaw_unescape($value);
350: &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121 raeburn 351: }
352: }
353: }
354: }
1.1125 raeburn 355: return ($result,\%returnhash);
1.1121 raeburn 356: }
357:
1.1124 raeburn 358: sub remote_devalidate_cache {
1.1241 raeburn 359: my ($lonhost,$cachekeys) = @_;
360: my $items;
361: return unless (ref($cachekeys) eq 'ARRAY');
362: my $cachestr = join('&',@{$cachekeys});
363: my $response = &reply('devalidatecache:'.&escape($cachestr),$lonhost);
1.1124 raeburn 364: return $response;
365: }
366:
1.1 albertel 367: # -------------------------------------------------- Non-critical communication
368: sub subreply {
369: my ($cmd,$server)=@_;
1.838 albertel 370: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549 foxr 371: #
372: # With loncnew process trimming, there's a timing hole between lonc server
373: # process exit and the master server picking up the listen on the AF_UNIX
374: # socket. In that time interval, a lock file will exist:
375:
376: my $lockfile=$peerfile.".lock";
377: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
378: sleep(1);
379: }
380: # At this point, either a loncnew parent is listening or an old lonc
1.550 foxr 381: # or loncnew child is listening so we can connect or everything's dead.
1.549 foxr 382: #
1.550 foxr 383: # We'll give the connection a few tries before abandoning it. If
384: # connection is not possible, we'll con_lost back to the client.
385: #
386: my $client;
387: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
388: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
389: Type => SOCK_STREAM,
390: Timeout => 10);
1.869 albertel 391: if ($client) {
1.550 foxr 392: last; # Connected!
1.850 albertel 393: } else {
1.853 albertel 394: &create_connection(&hostname($server),$server);
1.550 foxr 395: }
1.850 albertel 396: sleep(1); # Try again later if failed connection.
1.550 foxr 397: }
398: my $answer;
399: if ($client) {
1.704 albertel 400: print $client "sethost:$server:$cmd\n";
1.550 foxr 401: $answer=<$client>;
402: if (!$answer) { $answer="con_lost"; }
403: chomp($answer);
404: } else {
405: $answer = 'con_lost'; # Failed connection.
406: }
1.1 albertel 407: return $answer;
408: }
409:
410: sub reply {
411: my ($cmd,$server)=@_;
1.838 albertel 412: unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1 albertel 413: my $answer=subreply($cmd,$server);
1.65 www 414: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672 albertel 415: &logthis("<font color=\"blue\">WARNING:".
1.12 www 416: " $cmd to $server returned $answer</font>");
417: }
1.1 albertel 418: return $answer;
419: }
420:
421: # ----------------------------------------------------------- Send USR1 to lonc
422:
423: sub reconlonc {
1.891 albertel 424: my ($lonid) = @_;
425: my $hostname = &hostname($lonid);
426: if ($lonid) {
427: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
428: if ($hostname && -e $peerfile) {
429: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
430: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
431: Type => SOCK_STREAM,
432: Timeout => 10);
433: if ($client) {
434: print $client ("reset_retries\n");
435: my $answer=<$client>;
436: #reset just this one.
437: }
438: }
439: return;
440: }
441:
1.836 www 442: &logthis("Trying to reconnect lonc");
1.1 albertel 443: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448 albertel 444: if (open(my $fh,"<$loncfile")) {
1.1 albertel 445: my $loncpid=<$fh>;
446: chomp($loncpid);
447: if (kill 0 => $loncpid) {
448: &logthis("lonc at pid $loncpid responding, sending USR1");
449: kill USR1 => $loncpid;
450: sleep 1;
1.836 www 451: } else {
1.12 www 452: &logthis(
1.672 albertel 453: "<font color=\"blue\">WARNING:".
1.12 www 454: " lonc at pid $loncpid not responding, giving up</font>");
1.1 albertel 455: }
456: } else {
1.836 www 457: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1 albertel 458: }
459: }
460:
461: # ------------------------------------------------------ Critical communication
1.12 www 462:
1.1 albertel 463: sub critical {
464: my ($cmd,$server)=@_;
1.838 albertel 465: unless (&hostname($server)) {
1.672 albertel 466: &logthis("<font color=\"blue\">WARNING:".
1.89 www 467: " Critical message to unknown server ($server)</font>");
468: return 'no_such_host';
469: }
1.1 albertel 470: my $answer=reply($cmd,$server);
471: if ($answer eq 'con_lost') {
472: &reconlonc("$perlvar{'lonSockDir'}/$server");
1.589 albertel 473: my $answer=reply($cmd,$server);
1.1 albertel 474: if ($answer eq 'con_lost') {
475: my $now=time;
476: my $middlename=$cmd;
1.5 www 477: $middlename=substr($middlename,0,16);
1.1 albertel 478: $middlename=~s/\W//g;
479: my $dfilename=
1.305 www 480: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
481: $dumpcount++;
1.1 albertel 482: {
1.448 albertel 483: my $dfh;
484: if (open($dfh,">$dfilename")) {
485: print $dfh "$cmd\n";
486: close($dfh);
487: }
1.1 albertel 488: }
489: sleep 2;
490: my $wcmd='';
491: {
1.448 albertel 492: my $dfh;
493: if (open($dfh,"<$dfilename")) {
494: $wcmd=<$dfh>;
495: close($dfh);
496: }
1.1 albertel 497: }
498: chomp($wcmd);
1.7 www 499: if ($wcmd eq $cmd) {
1.672 albertel 500: &logthis("<font color=\"blue\">WARNING: ".
1.12 www 501: "Connection buffer $dfilename: $cmd</font>");
1.1 albertel 502: &logperm("D:$server:$cmd");
503: return 'con_delayed';
504: } else {
1.672 albertel 505: &logthis("<font color=\"red\">CRITICAL:"
1.12 www 506: ." Critical connection failed: $server $cmd</font>");
1.1 albertel 507: &logperm("F:$server:$cmd");
508: return 'con_failed';
509: }
510: }
511: }
512: return $answer;
1.405 albertel 513: }
514:
1.755 albertel 515: # ------------------------------------------- check if return value is an error
516:
517: sub error {
518: my ($result) = @_;
1.756 albertel 519: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755 albertel 520: if ($2 == 2) { return undef; }
521: return $1;
522: }
523: return undef;
524: }
525:
1.783 albertel 526: sub convert_and_load_session_env {
527: my ($lonidsdir,$handle)=@_;
528: my @profile;
529: {
1.917 albertel 530: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
531: if (!$opened) {
1.915 albertel 532: return 0;
533: }
1.783 albertel 534: flock($idf,LOCK_SH);
535: @profile=<$idf>;
536: close($idf);
537: }
538: my %temp_env;
539: foreach my $line (@profile) {
1.786 albertel 540: if ($line !~ m/=/) {
541: return 0;
542: }
1.783 albertel 543: chomp($line);
544: my ($envname,$envvalue)=split(/=/,$line,2);
545: $temp_env{&unescape($envname)} = &unescape($envvalue);
546: }
547: unlink("$lonidsdir/$handle.id");
548: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
549: 0640)) {
550: %disk_env = %temp_env;
551: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
552: untie(%disk_env);
553: }
1.786 albertel 554: return 1;
1.783 albertel 555: }
556:
1.374 www 557: # ------------------------------------------- Transfer profile into environment
1.780 albertel 558: my $env_loaded;
559: sub transfer_profile_to_env {
1.788 albertel 560: my ($lonidsdir,$handle,$force_transfer) = @_;
561: if (!$force_transfer && $env_loaded) { return; }
1.374 www 562:
1.720 albertel 563: if (!defined($lonidsdir)) {
564: $lonidsdir = $perlvar{'lonIDsDir'};
565: }
566: if (!defined($handle)) {
567: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
568: }
569:
1.786 albertel 570: my $convert;
571: {
1.917 albertel 572: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
573: if (!$opened) {
1.915 albertel 574: return;
575: }
1.786 albertel 576: flock($idf,LOCK_SH);
577: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
578: &GDBM_READER(),0640)) {
579: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
580: untie(%disk_env);
581: } else {
582: $convert = 1;
583: }
584: }
585: if ($convert) {
586: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
587: &logthis("Failed to load session, or convert session.");
588: }
1.374 www 589: }
1.783 albertel 590:
1.786 albertel 591: my %remove;
1.783 albertel 592: while ( my $envname = each(%env) ) {
1.433 matthew 593: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
594: if ($time < time-300) {
1.783 albertel 595: $remove{$key}++;
1.433 matthew 596: }
597: }
598: }
1.783 albertel 599:
1.619 albertel 600: $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780 albertel 601: $env_loaded=1;
1.783 albertel 602: foreach my $expired_key (keys(%remove)) {
1.433 matthew 603: &delenv($expired_key);
1.374 www 604: }
1.1 albertel 605: }
606:
1.916 albertel 607: # ---------------------------------------------------- Check for valid session
608: sub check_for_valid_session {
1.1245 raeburn 609: my ($r,$name,$userhashref) = @_;
1.916 albertel 610: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1155 raeburn 611: if ($name eq '') {
612: $name = 'lonID';
613: }
614: my $lonid=$cookies{$name};
1.916 albertel 615: return undef if (!$lonid);
616:
617: my $handle=&LONCAPA::clean_handle($lonid->value);
1.1155 raeburn 618: my $lonidsdir;
619: if ($name eq 'lonDAV') {
620: $lonidsdir=$r->dir_config('lonDAVsessDir');
621: } else {
622: $lonidsdir=$r->dir_config('lonIDsDir');
623: }
1.916 albertel 624: return undef if (!-e "$lonidsdir/$handle.id");
625:
1.917 albertel 626: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
627: return undef if (!$opened);
1.916 albertel 628:
629: flock($idf,LOCK_SH);
630: my %disk_env;
631: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
632: &GDBM_READER(),0640)) {
633: return undef;
634: }
635:
636: if (!defined($disk_env{'user.name'})
637: || !defined($disk_env{'user.domain'})) {
638: return undef;
639: }
1.1245 raeburn 640:
641: if (ref($userhashref) eq 'HASH') {
642: $userhashref->{'name'} = $disk_env{'user.name'};
643: $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1212 raeburn 644: }
1.1245 raeburn 645:
1.916 albertel 646: return $handle;
647: }
648:
1.830 albertel 649: sub timed_flock {
650: my ($file,$lock_type) = @_;
651: my $failed=0;
652: eval {
653: local $SIG{__DIE__}='DEFAULT';
654: local $SIG{ALRM}=sub {
655: $failed=1;
656: die("failed lock");
657: };
658: alarm(13);
659: flock($file,$lock_type);
660: alarm(0);
661: };
662: if ($failed) {
663: return undef;
664: } else {
665: return 1;
666: }
667: }
668:
1.5 www 669: # ---------------------------------------------------------- Append Environment
670:
671: sub appenv {
1.949 raeburn 672: my ($newenv,$roles) = @_;
673: if (ref($newenv) eq 'HASH') {
674: foreach my $key (keys(%{$newenv})) {
675: my $refused = 0;
676: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
677: $refused = 1;
678: if (ref($roles) eq 'ARRAY') {
1.1250 raeburn 679: my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949 raeburn 680: if (grep(/^\Q$role\E$/,@{$roles})) {
681: $refused = 0;
682: }
683: }
684: }
685: if ($refused) {
686: &logthis("<font color=\"blue\">WARNING: ".
687: "Attempt to modify environment ".$key." to ".$newenv->{$key}
688: .'</font>');
689: delete($newenv->{$key});
690: } else {
691: $env{$key}=$newenv->{$key};
692: }
693: }
694: my $opened = open(my $env_file,'+<',$env{'user.environment'});
695: if ($opened
696: && &timed_flock($env_file,LOCK_EX)
697: &&
698: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
699: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
700: while (my ($key,$value) = each(%{$newenv})) {
701: $disk_env{$key} = $value;
702: }
703: untie(%disk_env);
1.35 www 704: }
1.191 harris41 705: }
1.56 www 706: return 'ok';
707: }
708: # ----------------------------------------------------- Delete from Environment
709:
710: sub delenv {
1.1104 raeburn 711: my ($delthis,$regexp,$roles) = @_;
712: if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
713: my $refused = 1;
714: if (ref($roles) eq 'ARRAY') {
715: my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
716: if (grep(/^\Q$role\E$/,@{$roles})) {
717: $refused = 0;
718: }
719: }
720: if ($refused) {
721: &logthis("<font color=\"blue\">WARNING: ".
722: "Attempt to delete from environment ".$delthis);
723: return 'error';
724: }
1.56 www 725: }
1.917 albertel 726: my $opened = open(my $env_file,'+<',$env{'user.environment'});
727: if ($opened
1.915 albertel 728: && &timed_flock($env_file,LOCK_EX)
1.830 albertel 729: &&
730: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
731: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 732: foreach my $key (keys(%disk_env)) {
1.987 raeburn 733: if ($regexp) {
734: if ($key=~/^$delthis/) {
735: delete($env{$key});
736: delete($disk_env{$key});
737: }
738: } else {
739: if ($key=~/^\Q$delthis\E/) {
740: delete($env{$key});
741: delete($disk_env{$key});
742: }
743: }
1.448 albertel 744: }
1.783 albertel 745: untie(%disk_env);
1.5 www 746: }
747: return 'ok';
1.369 albertel 748: }
749:
1.790 albertel 750: sub get_env_multiple {
751: my ($name) = @_;
752: my @values;
753: if (defined($env{$name})) {
754: # exists is it an array
755: if (ref($env{$name})) {
756: @values=@{ $env{$name} };
757: } else {
758: $values[0]=$env{$name};
759: }
760: }
761: return(@values);
762: }
763:
1.958 www 764: # ------------------------------------------------------------------- Locking
765:
766: sub set_lock {
767: my ($text)=@_;
768: $locknum++;
769: my $id=$$.'-'.$locknum;
770: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
771: 'session.lock.'.$id => $text});
772: return $id;
773: }
774:
775: sub get_locks {
776: my $num=0;
777: my %texts=();
778: foreach my $lock (split(/\,/,$env{'session.locks'})) {
779: if ($lock=~/\w/) {
780: $num++;
781: $texts{$lock}=$env{'session.lock.'.$lock};
782: }
783: }
784: return ($num,%texts);
785: }
786:
787: sub remove_lock {
788: my ($id)=@_;
789: my $newlocks='';
790: foreach my $lock (split(/\,/,$env{'session.locks'})) {
791: if (($lock=~/\w/) && ($lock ne $id)) {
792: $newlocks.=','.$lock;
793: }
794: }
795: &appenv({'session.locks' => $newlocks});
796: &delenv('session.lock.'.$id);
797: }
798:
799: sub remove_all_locks {
800: my $activelocks=$env{'session.locks'};
801: foreach my $lock (split(/\,/,$env{'session.locks'})) {
802: if ($lock=~/\w/) {
803: &remove_lock($lock);
804: }
805: }
806: }
807:
808:
1.369 albertel 809: # ------------------------------------------ Find out current server userload
810: sub userload {
811: my $numusers=0;
812: {
813: opendir(LONIDS,$perlvar{'lonIDsDir'});
814: my $filename;
815: my $curtime=time;
816: while ($filename=readdir(LONIDS)) {
1.925 albertel 817: next if ($filename eq '.' || $filename eq '..');
818: next if ($filename =~ /publicuser_\d+\.id/);
1.404 albertel 819: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437 albertel 820: if ($curtime-$mtime < 1800) { $numusers++; }
1.369 albertel 821: }
822: closedir(LONIDS);
823: }
824: my $userloadpercent=0;
825: my $maxuserload=$perlvar{'lonUserLoadLim'};
826: if ($maxuserload) {
1.371 albertel 827: $userloadpercent=100*$numusers/$maxuserload;
1.369 albertel 828: }
1.372 albertel 829: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369 albertel 830: return $userloadpercent;
1.283 www 831: }
832:
1.1 albertel 833: # ------------------------------ Find server with least workload from spare.tab
1.11 www 834:
1.1 albertel 835: sub spareserver {
1.1083 raeburn 836: my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784 albertel 837: my $spare_server;
1.370 albertel 838: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784 albertel 839: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
840: : $userloadpercent;
1.1083 raeburn 841: my ($uint_dom,$remotesessions);
842: if (($udom ne '') && (&domain($udom) ne '')) {
843: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
844: $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
845: my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
846: $remotesessions = $udomdefaults{'remotesessions'};
847: }
1.1123 raeburn 848: my $spareshash = &this_host_spares($udom);
849: if (ref($spareshash) eq 'HASH') {
850: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
851: foreach my $try_server (@{ $spareshash->{'primary'} }) {
852: if ($uint_dom) {
853: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
854: $try_server));
855: }
856: ($spare_server, $lowest_load) =
857: &compare_server_load($try_server, $spare_server, $lowest_load);
858: }
1.1083 raeburn 859: }
1.784 albertel 860:
1.1123 raeburn 861: my $found_server = ($spare_server ne '' && $lowest_load < 100);
862:
863: if (!$found_server) {
864: if (ref($spareshash->{'default'}) eq 'ARRAY') {
865: foreach my $try_server (@{ $spareshash->{'default'} }) {
866: if ($uint_dom) {
867: next unless (&spare_can_host($udom,$uint_dom,
868: $remotesessions,$try_server));
869: }
870: ($spare_server, $lowest_load) =
871: &compare_server_load($try_server, $spare_server, $lowest_load);
872: }
873: }
874: }
1.784 albertel 875: }
876:
877: if (!$want_server_name) {
1.968 raeburn 878: my $protocol = 'http';
879: if ($protocol{$spare_server} eq 'https') {
880: $protocol = $protocol{$spare_server};
881: }
1.1001 raeburn 882: if (defined($spare_server)) {
883: my $hostname = &hostname($spare_server);
1.1083 raeburn 884: if (defined($hostname)) {
1.1001 raeburn 885: $spare_server = $protocol.'://'.$hostname;
886: }
887: }
1.784 albertel 888: }
889: return $spare_server;
890: }
891:
892: sub compare_server_load {
1.1253 raeburn 893: my ($try_server, $spare_server, $lowest_load, $required) = @_;
894:
895: if ($required) {
896: my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
897: my $remoterev = &get_server_loncaparev(undef,$try_server);
898: my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
899: if (($major eq '' && $minor eq '') ||
900: (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
901: return ($spare_server,$lowest_load);
902: }
903: }
1.784 albertel 904:
905: my $loadans = &reply('load', $try_server);
906: my $userloadans = &reply('userload',$try_server);
907:
908: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114 raeburn 909: return ($spare_server, $lowest_load); #didn't get a number from the server
1.784 albertel 910: }
911:
912: my $load;
913: if ($loadans =~ /\d/) {
914: if ($userloadans =~ /\d/) {
915: #both are numbers, pick the bigger one
916: $load = ($loadans > $userloadans) ? $loadans
917: : $userloadans;
1.411 albertel 918: } else {
1.784 albertel 919: $load = $loadans;
1.411 albertel 920: }
1.784 albertel 921: } else {
922: $load = $userloadans;
923: }
924:
925: if (($load =~ /\d/) && ($load < $lowest_load)) {
926: $spare_server = $try_server;
927: $lowest_load = $load;
1.370 albertel 928: }
1.784 albertel 929: return ($spare_server,$lowest_load);
1.202 matthew 930: }
1.914 albertel 931:
932: # --------------------------- ask offload servers if user already has a session
933: sub find_existing_session {
934: my ($udom,$uname) = @_;
1.1123 raeburn 935: my $spareshash = &this_host_spares($udom);
936: if (ref($spareshash) eq 'HASH') {
937: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
938: foreach my $try_server (@{ $spareshash->{'primary'} }) {
939: return $try_server if (&has_user_session($try_server, $udom, $uname));
940: }
941: }
942: if (ref($spareshash->{'default'}) eq 'ARRAY') {
943: foreach my $try_server (@{ $spareshash->{'default'} }) {
944: return $try_server if (&has_user_session($try_server, $udom, $uname));
945: }
946: }
1.914 albertel 947: }
948: return;
949: }
950:
951: # -------------------------------- ask if server already has a session for user
952: sub has_user_session {
953: my ($lonid,$udom,$uname) = @_;
954: my $result = &reply(join(':','userhassession',
955: map {&escape($_)} ($udom,$uname)),$lonid);
956: return 1 if ($result eq 'ok');
957:
958: return 0;
959: }
960:
1.1076 raeburn 961: # --------- determine least loaded server in a user's domain which allows login
962:
963: sub choose_server {
1.1253 raeburn 964: my ($udom,$checkloginvia,$required) = @_;
1.1076 raeburn 965: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077 raeburn 966: my %servers = &get_servers($udom);
1.1076 raeburn 967: my $lowest_load = 30000;
1.1151 raeburn 968: my ($login_host,$hostname,$portal_path,$isredirect);
1.1076 raeburn 969: foreach my $lonhost (keys(%servers)) {
1.1115 raeburn 970: my $loginvia;
971: if ($checkloginvia) {
972: $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116 raeburn 973: if ($loginvia) {
974: my ($server,$path) = split(/:/,$loginvia);
975: ($login_host, $lowest_load) =
1.1253 raeburn 976: &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116 raeburn 977: if ($login_host eq $server) {
978: $portal_path = $path;
1.1151 raeburn 979: $isredirect = 1;
1.1116 raeburn 980: }
981: } else {
982: ($login_host, $lowest_load) =
1.1253 raeburn 983: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116 raeburn 984: if ($login_host eq $lonhost) {
985: $portal_path = '';
1.1151 raeburn 986: $isredirect = '';
1.1116 raeburn 987: }
988: }
989: } else {
1.1076 raeburn 990: ($login_host, $lowest_load) =
1.1253 raeburn 991: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076 raeburn 992: }
993: }
994: if ($login_host ne '') {
1.1116 raeburn 995: $hostname = &hostname($login_host);
1.1076 raeburn 996: }
1.1151 raeburn 997: return ($login_host,$hostname,$portal_path,$isredirect);
1.1076 raeburn 998: }
999:
1.202 matthew 1000: # --------------------------------------------- Try to change a user's password
1001:
1002: sub changepass {
1.799 raeburn 1003: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 1004: $currentpass = &escape($currentpass);
1005: $newpass = &escape($newpass);
1.1030 raeburn 1006: my $lonhost = $perlvar{'lonHostID'};
1007: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202 matthew 1008: $server);
1009: if (! $answer) {
1010: &logthis("No reply on password change request to $server ".
1011: "by $uname in domain $udom.");
1012: } elsif ($answer =~ "^ok") {
1013: &logthis("$uname in $udom successfully changed their password ".
1014: "on $server.");
1015: } elsif ($answer =~ "^pwchange_failure") {
1016: &logthis("$uname in $udom was unable to change their password ".
1017: "on $server. The action was blocked by either lcpasswd ".
1018: "or pwchange");
1019: } elsif ($answer =~ "^non_authorized") {
1020: &logthis("$uname in $udom did not get their password correct when ".
1021: "attempting to change it on $server.");
1022: } elsif ($answer =~ "^auth_mode_error") {
1023: &logthis("$uname in $udom attempted to change their password despite ".
1024: "not being locally or internally authenticated on $server.");
1025: } elsif ($answer =~ "^unknown_user") {
1026: &logthis("$uname in $udom attempted to change their password ".
1027: "on $server but were unable to because $server is not ".
1028: "their home server.");
1029: } elsif ($answer =~ "^refused") {
1030: &logthis("$server refused to change $uname in $udom password because ".
1031: "it was sent an unencrypted request to change the password.");
1.1030 raeburn 1032: } elsif ($answer =~ "invalid_client") {
1033: &logthis("$server refused to change $uname in $udom password because ".
1034: "it was a reset by e-mail originating from an invalid server.");
1.202 matthew 1035: }
1036: return $answer;
1.1 albertel 1037: }
1038:
1.169 harris41 1039: # ----------------------- Try to determine user's current authentication scheme
1040:
1041: sub queryauthenticate {
1042: my ($uname,$udom)=@_;
1.456 albertel 1043: my $uhome=&homeserver($uname,$udom);
1044: if (!$uhome) {
1045: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
1046: return 'no_host';
1047: }
1048: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
1049: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
1050: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 1051: }
1.456 albertel 1052: return $answer;
1.169 harris41 1053: }
1054:
1.1 albertel 1055: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 1056:
1.1 albertel 1057: sub authenticate {
1.1073 raeburn 1058: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807 albertel 1059: $upass=&escape($upass);
1060: $uname= &LONCAPA::clean_username($uname);
1.836 www 1061: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 1062: my $newhome;
1.836 www 1063: if ((!$uhome) || ($uhome eq 'no_host')) {
1064: # Maybe the machine was offline and only re-appeared again recently?
1065: &reconlonc();
1066: # One more
1.952 raeburn 1067: $uhome=&homeserver($uname,$udom,1);
1068: if (($uhome eq 'no_host') && $checkdefauth) {
1069: if (defined(&domain($udom,'primary'))) {
1070: $newhome=&domain($udom,'primary');
1071: }
1072: if ($newhome ne '') {
1073: $uhome = $newhome;
1074: }
1075: }
1.836 www 1076: if ((!$uhome) || ($uhome eq 'no_host')) {
1077: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 1078: return 'no_host';
1079: }
1.1 albertel 1080: }
1.1073 raeburn 1081: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471 albertel 1082: if ($answer eq 'authorized') {
1.952 raeburn 1083: if ($newhome) {
1084: &logthis("User $uname at $udom authorized by $uhome, but needs account");
1085: return 'no_account_on_host';
1086: } else {
1087: &logthis("User $uname at $udom authorized by $uhome");
1088: return $uhome;
1089: }
1.471 albertel 1090: }
1091: if ($answer eq 'non_authorized') {
1092: &logthis("User $uname at $udom rejected by $uhome");
1093: return 'no_host';
1.9 www 1094: }
1.471 albertel 1095: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 1096: return 'no_host';
1097: }
1098:
1.1073 raeburn 1099: sub can_host_session {
1.1074 raeburn 1100: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073 raeburn 1101: my $canhost = 1;
1.1074 raeburn 1102: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073 raeburn 1103: if (ref($remotesessions) eq 'HASH') {
1104: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074 raeburn 1105: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073 raeburn 1106: $canhost = 0;
1107: } else {
1108: $canhost = 1;
1109: }
1110: }
1111: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074 raeburn 1112: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073 raeburn 1113: $canhost = 1;
1114: } else {
1115: $canhost = 0;
1116: }
1117: }
1118: if ($canhost) {
1119: if ($remotesessions->{'version'} ne '') {
1120: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1121: if ($reqmajor ne '' && $reqminor ne '') {
1122: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1123: my $major = $1;
1124: my $minor = $2;
1125: if (($major < $reqmajor ) ||
1126: (($major == $reqmajor) && ($minor < $reqminor))) {
1127: $canhost = 0;
1128: }
1129: } else {
1130: $canhost = 0;
1131: }
1132: }
1133: }
1134: }
1135: }
1136: if ($canhost) {
1137: if (ref($hostedsessions) eq 'HASH') {
1.1120 raeburn 1138: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1139: my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073 raeburn 1140: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120 raeburn 1141: if (($uint_dom ne '') &&
1142: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073 raeburn 1143: $canhost = 0;
1144: } else {
1145: $canhost = 1;
1146: }
1147: }
1148: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120 raeburn 1149: if (($uint_dom ne '') &&
1150: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073 raeburn 1151: $canhost = 1;
1152: } else {
1153: $canhost = 0;
1154: }
1155: }
1156: }
1157: }
1158: return $canhost;
1159: }
1160:
1.1083 raeburn 1161: sub spare_can_host {
1162: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1163: my $canhost=1;
1164: my @intdoms;
1165: my $internet_names = &Apache::lonnet::get_internet_names($try_server);
1166: if (ref($internet_names) eq 'ARRAY') {
1167: @intdoms = @{$internet_names};
1168: }
1169: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1170: my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
1171: my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
1172: my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
1173: my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
1174: $canhost = &can_host_session($udom,$try_server,$remoterev,
1175: $remotesessions,
1176: $defdomdefaults{'hostedsessions'});
1177: }
1178: return $canhost;
1179: }
1180:
1.1123 raeburn 1181: sub this_host_spares {
1182: my ($dom) = @_;
1.1126 raeburn 1183: my ($dom_in_use,$lonhost_in_use,$result);
1.1123 raeburn 1184: my @hosts = ¤t_machine_ids();
1185: foreach my $lonhost (@hosts) {
1186: if (&host_domain($lonhost) eq $dom) {
1.1126 raeburn 1187: $dom_in_use = $dom;
1188: $lonhost_in_use = $lonhost;
1.1123 raeburn 1189: last;
1190: }
1191: }
1.1126 raeburn 1192: if ($dom_in_use ne '') {
1193: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1194: }
1195: if (ref($result) ne 'HASH') {
1196: $lonhost_in_use = $perlvar{'lonHostID'};
1197: $dom_in_use = &host_domain($lonhost_in_use);
1198: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1199: if (ref($result) ne 'HASH') {
1200: $result = \%spareid;
1201: }
1202: }
1203: return $result;
1204: }
1205:
1206: sub spares_for_offload {
1207: my ($dom_in_use,$lonhost_in_use) = @_;
1208: my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123 raeburn 1209: if (defined($cached)) {
1210: return $result;
1211: } else {
1.1126 raeburn 1212: my $cachetime = 60*60*24;
1213: my %domconfig =
1214: &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
1215: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1216: if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
1217: if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
1218: return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123 raeburn 1219: }
1220: }
1221: }
1222: }
1.1126 raeburn 1223: return;
1.1123 raeburn 1224: }
1225:
1.1129 raeburn 1226: sub get_lonbalancer_config {
1227: my ($servers) = @_;
1228: my ($currbalancer,$currtargets);
1229: if (ref($servers) eq 'HASH') {
1230: foreach my $server (keys(%{$servers})) {
1231: my %what = (
1232: spareid => 1,
1233: perlvar => 1,
1234: );
1235: my ($result,$returnhash) = &get_remote_globals($server,\%what);
1236: if ($result eq 'ok') {
1237: if (ref($returnhash) eq 'HASH') {
1238: if (ref($returnhash->{'perlvar'}) eq 'HASH') {
1239: if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
1240: $currbalancer = $server;
1241: $currtargets = {};
1242: if (ref($returnhash->{'spareid'}) eq 'HASH') {
1243: if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
1244: $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
1245: }
1246: if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
1247: $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
1248: }
1249: }
1250: last;
1251: }
1252: }
1253: }
1254: }
1255: }
1256: }
1257: return ($currbalancer,$currtargets);
1258: }
1259:
1260: sub check_loadbalancing {
1261: my ($uname,$udom) = @_;
1.1191 raeburn 1262: my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1263: $rule_in_effect,$offloadto,$otherserver);
1.1129 raeburn 1264: my $lonhost = $perlvar{'lonHostID'};
1.1175 raeburn 1265: my @hosts = ¤t_machine_ids();
1.1129 raeburn 1266: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1267: my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
1268: my $intdom = &Apache::lonnet::internet_dom($lonhost);
1269: my $serverhomedom = &host_domain($lonhost);
1270:
1271: my $cachetime = 60*60*24;
1272:
1273: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1274: $dom_in_use = $udom;
1275: $homeintdom = 1;
1276: } else {
1277: $dom_in_use = $serverhomedom;
1278: }
1279: my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
1280: unless (defined($cached)) {
1281: my %domconfig =
1282: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
1283: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1284: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129 raeburn 1285: }
1286: }
1287: if (ref($result) eq 'HASH') {
1.1191 raeburn 1288: ($is_balancer,$currtargets,$currrules) =
1289: &check_balancer_result($result,@hosts);
1.1129 raeburn 1290: if ($is_balancer) {
1291: if (ref($currrules) eq 'HASH') {
1292: if ($homeintdom) {
1293: if ($uname ne '') {
1294: if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
1295: my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
1296: if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
1297: $rule_in_effect = $currrules->{'_LC_author'};
1298: } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
1299: $rule_in_effect = $currrules->{'_LC_adv'}
1300: }
1301: }
1302: if ($rule_in_effect eq '') {
1303: my %userenv = &userenvironment($udom,$uname,'inststatus');
1304: if ($userenv{'inststatus'} ne '') {
1305: my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
1306: my ($othertitle,$usertypes,$types) =
1307: &Apache::loncommon::sorted_inst_types($udom);
1308: if (ref($types) eq 'ARRAY') {
1309: foreach my $type (@{$types}) {
1310: if (grep(/^\Q$type\E$/,@statuses)) {
1311: if (exists($currrules->{$type})) {
1312: $rule_in_effect = $currrules->{$type};
1313: }
1314: }
1315: }
1316: }
1317: } else {
1318: if (exists($currrules->{'default'})) {
1319: $rule_in_effect = $currrules->{'default'};
1320: }
1321: }
1322: }
1323: } else {
1324: if (exists($currrules->{'default'})) {
1325: $rule_in_effect = $currrules->{'default'};
1326: }
1327: }
1328: } else {
1329: if ($currrules->{'_LC_external'} ne '') {
1330: $rule_in_effect = $currrules->{'_LC_external'};
1331: }
1332: }
1333: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1334: $uname,$udom);
1335: }
1336: }
1337: } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1239 raeburn 1338: ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129 raeburn 1339: unless (defined($cached)) {
1340: my %domconfig =
1341: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
1342: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1343: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129 raeburn 1344: }
1345: }
1346: if (ref($result) eq 'HASH') {
1.1191 raeburn 1347: ($is_balancer,$currtargets,$currrules) =
1348: &check_balancer_result($result,@hosts);
1349: if ($is_balancer) {
1.1129 raeburn 1350: if (ref($currrules) eq 'HASH') {
1351: if ($currrules->{'_LC_internetdom'} ne '') {
1352: $rule_in_effect = $currrules->{'_LC_internetdom'};
1353: }
1354: }
1355: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1356: $uname,$udom);
1357: }
1358: } else {
1359: if ($perlvar{'lonBalancer'} eq 'yes') {
1360: $is_balancer = 1;
1361: $offloadto = &this_host_spares($dom_in_use);
1362: }
1363: }
1364: } else {
1365: if ($perlvar{'lonBalancer'} eq 'yes') {
1366: $is_balancer = 1;
1367: $offloadto = &this_host_spares($dom_in_use);
1368: }
1369: }
1.1176 raeburn 1370: if ($is_balancer) {
1371: my $lowest_load = 30000;
1372: if (ref($offloadto) eq 'HASH') {
1373: if (ref($offloadto->{'primary'}) eq 'ARRAY') {
1374: foreach my $try_server (@{$offloadto->{'primary'}}) {
1375: ($otherserver,$lowest_load) =
1376: &compare_server_load($try_server,$otherserver,$lowest_load);
1377: }
1.1129 raeburn 1378: }
1.1176 raeburn 1379: my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129 raeburn 1380:
1.1176 raeburn 1381: if (!$found_server) {
1382: if (ref($offloadto->{'default'}) eq 'ARRAY') {
1383: foreach my $try_server (@{$offloadto->{'default'}}) {
1384: ($otherserver,$lowest_load) =
1385: &compare_server_load($try_server,$otherserver,$lowest_load);
1386: }
1387: }
1388: }
1389: } elsif (ref($offloadto) eq 'ARRAY') {
1390: if (@{$offloadto} == 1) {
1391: $otherserver = $offloadto->[0];
1392: } elsif (@{$offloadto} > 1) {
1393: foreach my $try_server (@{$offloadto}) {
1.1129 raeburn 1394: ($otherserver,$lowest_load) =
1395: &compare_server_load($try_server,$otherserver,$lowest_load);
1396: }
1397: }
1398: }
1.1176 raeburn 1399: if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
1400: $is_balancer = 0;
1401: if ($uname ne '' && $udom ne '') {
1402: if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1403:
1404: &appenv({'user.loadbalexempt' => $lonhost,
1405: 'user.loadbalcheck.time' => time});
1406: }
1.1129 raeburn 1407: }
1408: }
1409: }
1410: return ($is_balancer,$otherserver);
1411: }
1412:
1.1191 raeburn 1413: sub check_balancer_result {
1414: my ($result,@hosts) = @_;
1415: my ($is_balancer,$currtargets,$currrules);
1416: if (ref($result) eq 'HASH') {
1417: if ($result->{'lonhost'} ne '') {
1418: my $currbalancer = $result->{'lonhost'};
1419: if (grep(/^\Q$currbalancer\E$/,@hosts)) {
1420: $is_balancer = 1;
1421: $currtargets = $result->{'targets'};
1422: $currrules = $result->{'rules'};
1423: }
1424: } else {
1425: foreach my $key (keys(%{$result})) {
1426: if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
1427: (ref($result->{$key}) eq 'HASH')) {
1428: $is_balancer = 1;
1429: $currrules = $result->{$key}{'rules'};
1430: $currtargets = $result->{$key}{'targets'};
1431: last;
1432: }
1433: }
1434: }
1435: }
1436: return ($is_balancer,$currtargets,$currrules);
1437: }
1438:
1.1129 raeburn 1439: sub get_loadbalancer_targets {
1440: my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
1441: my $offloadto;
1.1175 raeburn 1442: if ($rule_in_effect eq 'none') {
1443: return [$perlvar{'lonHostID'}];
1444: } elsif ($rule_in_effect eq '') {
1.1129 raeburn 1445: $offloadto = $currtargets;
1446: } else {
1447: if ($rule_in_effect eq 'homeserver') {
1448: my $homeserver = &homeserver($uname,$udom);
1449: if ($homeserver ne 'no_host') {
1450: $offloadto = [$homeserver];
1451: }
1452: } elsif ($rule_in_effect eq 'externalbalancer') {
1453: my %domconfig =
1454: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1455: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1456: if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
1457: if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
1458: $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
1459: }
1460: }
1461: } else {
1.1178 raeburn 1462: my %servers = &internet_dom_servers($udom);
1.1129 raeburn 1463: my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
1464: if (&hostname($remotebalancer) ne '') {
1465: $offloadto = [$remotebalancer];
1466: }
1467: }
1468: } elsif (&hostname($rule_in_effect) ne '') {
1469: $offloadto = [$rule_in_effect];
1470: }
1471: }
1472: return $offloadto;
1473: }
1474:
1.1127 raeburn 1475: sub internet_dom_servers {
1476: my ($dom) = @_;
1477: my (%uniqservers,%servers);
1478: my $primaryserver = &hostname(&domain($dom,'primary'));
1479: my @machinedoms = &machine_domains($primaryserver);
1480: foreach my $mdom (@machinedoms) {
1481: my %currservers = %servers;
1482: my %server = &get_servers($mdom);
1483: %servers = (%currservers,%server);
1484: }
1485: my %by_hostname;
1486: foreach my $id (keys(%servers)) {
1487: push(@{$by_hostname{$servers{$id}}},$id);
1488: }
1489: foreach my $hostname (sort(keys(%by_hostname))) {
1490: if (@{$by_hostname{$hostname}} > 1) {
1491: my $match = 0;
1492: foreach my $id (@{$by_hostname{$hostname}}) {
1493: if (&host_domain($id) eq $dom) {
1494: $uniqservers{$id} = $hostname;
1495: $match = 1;
1496: }
1497: }
1498: unless ($match) {
1499: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1500: }
1501: } else {
1502: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1503: }
1504: }
1505: return %uniqservers;
1506: }
1507:
1.1 albertel 1508: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 1509:
1.599 albertel 1510: my %homecache;
1.1 albertel 1511: sub homeserver {
1.230 stredwic 1512: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 1513: my $index="$uname:$udom";
1.426 albertel 1514:
1.599 albertel 1515: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 1516:
1517: my %servers = &get_servers($udom,'library');
1518: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 1519: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 1520: exists($badServerCache{$tryserver}));
1.841 albertel 1521:
1522: my $answer=reply("home:$udom:$uname",$tryserver);
1523: if ($answer eq 'found') {
1524: delete($badServerCache{$tryserver});
1525: return $homecache{$index}=$tryserver;
1526: } elsif ($answer eq 'no_host') {
1527: $badServerCache{$tryserver}=1;
1528: }
1.1 albertel 1529: }
1530: return 'no_host';
1.70 www 1531: }
1532:
1533: # ------------------------------------- Find the usernames behind a list of IDs
1534:
1535: sub idget {
1536: my ($udom,@ids)=@_;
1537: my %returnhash=();
1538:
1.841 albertel 1539: my %servers = &get_servers($udom,'library');
1540: foreach my $tryserver (keys(%servers)) {
1541: my $idlist=join('&',@ids);
1542: $idlist=~tr/A-Z/a-z/;
1543: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
1544: my @answer=();
1545: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1546: @answer=split(/\&/,$reply);
1547: } ;
1548: my $i;
1549: for ($i=0;$i<=$#ids;$i++) {
1550: if ($answer[$i]) {
1551: $returnhash{$ids[$i]}=$answer[$i];
1552: }
1553: }
1554: }
1.70 www 1555: return %returnhash;
1556: }
1557:
1558: # ------------------------------------- Find the IDs behind a list of usernames
1559:
1560: sub idrget {
1561: my ($udom,@unames)=@_;
1562: my %returnhash=();
1.800 albertel 1563: foreach my $uname (@unames) {
1564: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 1565: }
1.70 www 1566: return %returnhash;
1567: }
1568:
1569: # ------------------------------- Store away a list of names and associated IDs
1570:
1571: sub idput {
1572: my ($udom,%ids)=@_;
1573: my %servers=();
1.800 albertel 1574: foreach my $uname (keys(%ids)) {
1575: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1576: my $uhom=&homeserver($uname,$udom);
1.70 www 1577: if ($uhom ne 'no_host') {
1.800 albertel 1578: my $id=&escape($ids{$uname});
1.70 www 1579: $id=~tr/A-Z/a-z/;
1.800 albertel 1580: my $esc_unam=&escape($uname);
1.70 www 1581: if ($servers{$uhom}) {
1.800 albertel 1582: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70 www 1583: } else {
1.800 albertel 1584: $servers{$uhom}=$id.'='.$esc_unam;
1.70 www 1585: }
1586: }
1.191 harris41 1587: }
1.800 albertel 1588: foreach my $server (keys(%servers)) {
1589: &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191 harris41 1590: }
1.344 www 1591: }
1592:
1.1231 raeburn 1593: # ---------------------------------------- Delete unwanted IDs from ids.db file
1594:
1595: sub iddel {
1596: my ($udom,$idshashref,$uhome)=@_;
1597: my %result=();
1598: unless (ref($idshashref) eq 'HASH') {
1599: return %result;
1600: }
1601: my %servers=();
1602: while (my ($id,$uname) = each(%{$idshashref})) {
1603: my $uhom;
1604: if ($uhome) {
1605: $uhom = $uhome;
1606: } else {
1607: $uhom=&homeserver($uname,$udom);
1608: }
1609: if ($uhom ne 'no_host') {
1610: if ($servers{$uhom}) {
1611: $servers{$uhom}.='&'.&escape($id);
1612: } else {
1613: $servers{$uhom}=&escape($id);
1614: }
1615: }
1616: }
1617: foreach my $server (keys(%servers)) {
1618: $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
1619: }
1620: return %result;
1621: }
1622:
1.1023 raeburn 1623: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 1624: sub dump_dom {
1.1165 droeschl 1625: my ($namespace, $udom, $regexp) = @_;
1626:
1627: $udom ||= $env{'user.domain'};
1628:
1629: return () unless $udom;
1630:
1631: return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012 raeburn 1632: }
1633:
1.1023 raeburn 1634: # ------------------------------------------ get items from domain db files
1.806 raeburn 1635:
1636: sub get_dom {
1.860 raeburn 1637: my ($namespace,$storearr,$udom,$uhome)=@_;
1.806 raeburn 1638: my $items='';
1639: foreach my $item (@$storearr) {
1640: $items.=&escape($item).'&';
1641: }
1642: $items=~s/\&$//;
1.860 raeburn 1643: if (!$udom) {
1644: $udom=$env{'user.domain'};
1645: if (defined(&domain($udom,'primary'))) {
1646: $uhome=&domain($udom,'primary');
1647: } else {
1.874 albertel 1648: undef($uhome);
1.860 raeburn 1649: }
1650: } else {
1651: if (!$uhome) {
1652: if (defined(&domain($udom,'primary'))) {
1653: $uhome=&domain($udom,'primary');
1654: }
1655: }
1656: }
1657: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1658: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866 raeburn 1659: my %returnhash;
1.875 albertel 1660: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 1661: return %returnhash;
1662: }
1.806 raeburn 1663: my @pairs=split(/\&/,$rep);
1664: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1665: return @pairs;
1666: }
1667: my $i=0;
1668: foreach my $item (@$storearr) {
1669: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1670: $i++;
1671: }
1672: return %returnhash;
1673: } else {
1.880 banghart 1674: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 1675: }
1676: }
1677:
1678: # -------------------------------------------- put items in domain db files
1679:
1680: sub put_dom {
1.860 raeburn 1681: my ($namespace,$storehash,$udom,$uhome)=@_;
1682: if (!$udom) {
1683: $udom=$env{'user.domain'};
1684: if (defined(&domain($udom,'primary'))) {
1685: $uhome=&domain($udom,'primary');
1686: } else {
1.874 albertel 1687: undef($uhome);
1.860 raeburn 1688: }
1689: } else {
1690: if (!$uhome) {
1691: if (defined(&domain($udom,'primary'))) {
1692: $uhome=&domain($udom,'primary');
1693: }
1694: }
1695: }
1696: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1697: my $items='';
1698: foreach my $item (keys(%$storehash)) {
1699: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1700: }
1701: $items=~s/\&$//;
1702: return &reply("putdom:$udom:$namespace:$items",$uhome);
1703: } else {
1.860 raeburn 1704: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 1705: }
1706: }
1707:
1.1023 raeburn 1708: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 1709: sub newput_dom {
1.1023 raeburn 1710: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 1711: my $result;
1712: if (!$udom) {
1713: $udom=$env{'user.domain'};
1714: }
1.1023 raeburn 1715: if ($udom) {
1716: my $uname = &get_domainconfiguser($udom);
1717: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 1718: }
1719: return $result;
1720: }
1721:
1.1023 raeburn 1722: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 1723: sub del_dom {
1.1023 raeburn 1724: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 1725: if (ref($storearr) eq 'ARRAY') {
1726: if (!$udom) {
1727: $udom=$env{'user.domain'};
1728: }
1.1023 raeburn 1729: if ($udom) {
1730: my $uname = &get_domainconfiguser($udom);
1731: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 1732: }
1733: }
1734: }
1735:
1.1023 raeburn 1736: # ----------------------------------construct domainconfig user for a domain
1737: sub get_domainconfiguser {
1738: my ($udom) = @_;
1739: return $udom.'-domainconfig';
1740: }
1741:
1.837 raeburn 1742: sub retrieve_inst_usertypes {
1743: my ($udom) = @_;
1744: my (%returnhash,@order);
1.989 raeburn 1745: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1746: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1747: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1256 ! raeburn 1748: return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989 raeburn 1749: } else {
1750: if (defined(&domain($udom,'primary'))) {
1751: my $uhome=&domain($udom,'primary');
1752: my $rep=&reply("inst_usertypes:$udom",$uhome);
1753: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1256 ! raeburn 1754: &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989 raeburn 1755: return (\%returnhash,\@order);
1756: }
1757: my ($hashitems,$orderitems) = split(/:/,$rep);
1758: my @pairs=split(/\&/,$hashitems);
1759: foreach my $item (@pairs) {
1760: my ($key,$value)=split(/=/,$item,2);
1761: $key = &unescape($key);
1762: next if ($key =~ /^error: 2 /);
1763: $returnhash{$key}=&thaw_unescape($value);
1764: }
1765: my @esc_order = split(/\&/,$orderitems);
1766: foreach my $item (@esc_order) {
1767: push(@order,&unescape($item));
1768: }
1769: } else {
1.1256 ! raeburn 1770: &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837 raeburn 1771: }
1.1256 ! raeburn 1772: return (\%returnhash,\@order);
1.837 raeburn 1773: }
1774: }
1775:
1.868 raeburn 1776: sub is_domainimage {
1777: my ($url) = @_;
1778: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
1779: if (&domain($1) ne '') {
1780: return '1';
1781: }
1782: }
1783: return;
1784: }
1785:
1.899 raeburn 1786: sub inst_directory_query {
1787: my ($srch) = @_;
1788: my $udom = $srch->{'srchdomain'};
1789: my %results;
1790: my $homeserver = &domain($udom,'primary');
1.909 raeburn 1791: my $outcome;
1.899 raeburn 1792: if ($homeserver ne '') {
1.904 albertel 1793: my $queryid=&reply("querysend:instdirsearch:".
1794: &escape($srch->{'srchby'}).':'.
1795: &escape($srch->{'srchterm'}).':'.
1796: &escape($srch->{'srchtype'}),$homeserver);
1797: my $host=&hostname($homeserver);
1798: if ($queryid !~/^\Q$host\E\_/) {
1799: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1800: return;
1801: }
1802: my $response = &get_query_reply($queryid);
1803: my $maxtries = 5;
1804: my $tries = 1;
1805: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1806: $response = &get_query_reply($queryid);
1807: $tries ++;
1808: }
1809:
1810: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 1811: if ($response eq 'unavailable') {
1812: $outcome = $response;
1813: } else {
1814: $outcome = 'ok';
1815: my @matches = split(/\n/,$response);
1816: foreach my $match (@matches) {
1817: my ($key,$value) = split(/=/,$match);
1818: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1819: }
1.899 raeburn 1820: }
1821: }
1822: }
1.909 raeburn 1823: return ($outcome,%results);
1.899 raeburn 1824: }
1825:
1826: sub usersearch {
1827: my ($srch) = @_;
1828: my $dom = $srch->{'srchdomain'};
1829: my %results;
1830: my %libserv = &all_library();
1831: my $query = 'usersearch';
1832: foreach my $tryserver (keys(%libserv)) {
1833: if (&host_domain($tryserver) eq $dom) {
1834: my $host=&hostname($tryserver);
1835: my $queryid=
1.911 raeburn 1836: &reply("querysend:".&escape($query).':'.
1837: &escape($srch->{'srchby'}).':'.
1.899 raeburn 1838: &escape($srch->{'srchtype'}).':'.
1839: &escape($srch->{'srchterm'}),$tryserver);
1840: if ($queryid !~/^\Q$host\E\_/) {
1841: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 1842: next;
1.899 raeburn 1843: }
1844: my $reply = &get_query_reply($queryid);
1845: my $maxtries = 1;
1846: my $tries = 1;
1847: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1848: $reply = &get_query_reply($queryid);
1849: $tries ++;
1850: }
1851: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1852: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1853: } else {
1.911 raeburn 1854: my @matches;
1855: if ($reply =~ /\n/) {
1856: @matches = split(/\n/,$reply);
1857: } else {
1858: @matches = split(/\&/,$reply);
1859: }
1.899 raeburn 1860: foreach my $match (@matches) {
1861: my ($uname,$udom,%userhash);
1.911 raeburn 1862: foreach my $entry (split(/:/,$match)) {
1863: my ($key,$value) =
1864: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 1865: $userhash{$key} = $value;
1866: if ($key eq 'username') {
1867: $uname = $value;
1868: } elsif ($key eq 'domain') {
1869: $udom = $value;
1.911 raeburn 1870: }
1.899 raeburn 1871: }
1872: $results{$uname.':'.$udom} = \%userhash;
1873: }
1874: }
1875: }
1876: }
1877: return %results;
1878: }
1879:
1.912 raeburn 1880: sub get_instuser {
1881: my ($udom,$uname,$id) = @_;
1882: my $homeserver = &domain($udom,'primary');
1883: my ($outcome,%results);
1884: if ($homeserver ne '') {
1885: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1886: &escape($id).':'.&escape($udom),$homeserver);
1887: my $host=&hostname($homeserver);
1888: if ($queryid !~/^\Q$host\E\_/) {
1889: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1890: return;
1891: }
1892: my $response = &get_query_reply($queryid);
1893: my $maxtries = 5;
1894: my $tries = 1;
1895: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1896: $response = &get_query_reply($queryid);
1897: $tries ++;
1898: }
1899: if (!&error($response) && $response ne 'refused') {
1900: if ($response eq 'unavailable') {
1901: $outcome = $response;
1902: } else {
1903: $outcome = 'ok';
1904: my @matches = split(/\n/,$response);
1905: foreach my $match (@matches) {
1906: my ($key,$value) = split(/=/,$match);
1907: $results{&unescape($key)} = &thaw_unescape($value);
1908: }
1909: }
1910: }
1911: }
1912: my %userinfo;
1913: if (ref($results{$uname}) eq 'HASH') {
1914: %userinfo = %{$results{$uname}};
1915: }
1916: return ($outcome,%userinfo);
1917: }
1918:
1919: sub inst_rulecheck {
1.923 raeburn 1920: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 1921: my %returnhash;
1922: if ($udom ne '') {
1923: if (ref($rules) eq 'ARRAY') {
1924: @{$rules} = map {&escape($_);} (@{$rules});
1925: my $rulestr = join(':',@{$rules});
1926: my $homeserver=&domain($udom,'primary');
1927: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1928: my $response;
1929: if ($item eq 'username') {
1930: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
1931: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 1932: $homeserver));
1.923 raeburn 1933: } elsif ($item eq 'id') {
1934: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
1935: ':'.&escape($id).':'.$rulestr,
1936: $homeserver));
1.945 raeburn 1937: } elsif ($item eq 'selfcreate') {
1938: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 1939: &escape($udom).':'.&escape($uname).
1940: ':'.$rulestr,$homeserver));
1.923 raeburn 1941: }
1.912 raeburn 1942: if ($response ne 'refused') {
1943: my @pairs=split(/\&/,$response);
1944: foreach my $item (@pairs) {
1945: my ($key,$value)=split(/=/,$item,2);
1946: $key = &unescape($key);
1947: next if ($key =~ /^error: 2 /);
1948: $returnhash{$key}=&thaw_unescape($value);
1949: }
1950: }
1951: }
1952: }
1953: }
1954: return %returnhash;
1955: }
1956:
1957: sub inst_userrules {
1.923 raeburn 1958: my ($udom,$check) = @_;
1.912 raeburn 1959: my (%ruleshash,@ruleorder);
1960: if ($udom ne '') {
1961: my $homeserver=&domain($udom,'primary');
1962: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1963: my $response;
1964: if ($check eq 'id') {
1965: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 1966: $homeserver);
1.943 raeburn 1967: } elsif ($check eq 'email') {
1968: $response=&reply('instemailrules:'.&escape($udom),
1969: $homeserver);
1.923 raeburn 1970: } else {
1971: $response=&reply('instuserrules:'.&escape($udom),
1972: $homeserver);
1973: }
1.912 raeburn 1974: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 1975: ($response ne 'unknown_cmd') &&
1.912 raeburn 1976: ($response ne 'no_such_host')) {
1977: my ($hashitems,$orderitems) = split(/:/,$response);
1978: my @pairs=split(/\&/,$hashitems);
1979: foreach my $item (@pairs) {
1980: my ($key,$value)=split(/=/,$item,2);
1981: $key = &unescape($key);
1982: next if ($key =~ /^error: 2 /);
1983: $ruleshash{$key}=&thaw_unescape($value);
1984: }
1985: my @esc_order = split(/\&/,$orderitems);
1986: foreach my $item (@esc_order) {
1987: push(@ruleorder,&unescape($item));
1988: }
1989: }
1990: }
1991: }
1992: return (\%ruleshash,\@ruleorder);
1993: }
1994:
1.976 raeburn 1995: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 1996:
1997: sub get_domain_defaults {
1.1240 raeburn 1998: my ($domain,$ignore_cache) = @_;
1.1242 raeburn 1999: return if (($domain eq '') || ($domain eq 'public'));
1.943 raeburn 2000: my $cachetime = 60*60*24;
1.1240 raeburn 2001: unless ($ignore_cache) {
2002: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
2003: if (defined($cached)) {
2004: if (ref($result) eq 'HASH') {
2005: return %{$result};
2006: }
1.943 raeburn 2007: }
2008: }
2009: my %domdefaults;
2010: my %domconfig =
1.989 raeburn 2011: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 2012: 'requestcourses','inststatus',
1.1183 raeburn 2013: 'coursedefaults','usersessions',
1.1254 raeburn 2014: 'requestauthor','selfenrollment'],$domain);
2015: my @coursetypes = ('official','unofficial','community','textbook');
1.943 raeburn 2016: if (ref($domconfig{'defaults'}) eq 'HASH') {
2017: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
2018: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
2019: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 2020: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 2021: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147 raeburn 2022: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943 raeburn 2023: } else {
2024: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
2025: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
2026: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
2027: }
1.976 raeburn 2028: if (ref($domconfig{'quotas'}) eq 'HASH') {
2029: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
2030: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
2031: } else {
2032: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1229 raeburn 2033: }
1.1177 raeburn 2034: my @usertools = ('aboutme','blog','webdav','portfolio');
1.976 raeburn 2035: foreach my $item (@usertools) {
2036: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
2037: $domdefaults{$item} = $domconfig{'quotas'}{$item};
2038: }
2039: }
1.1229 raeburn 2040: if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
2041: $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
2042: }
1.976 raeburn 2043: }
1.985 raeburn 2044: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1246 raeburn 2045: foreach my $item ('official','unofficial','community','textbook') {
1.985 raeburn 2046: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
2047: }
2048: }
1.1183 raeburn 2049: if (ref($domconfig{'requestauthor'}) eq 'HASH') {
2050: $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
2051: }
1.989 raeburn 2052: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1256 ! raeburn 2053: foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989 raeburn 2054: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
2055: }
2056: }
1.1047 raeburn 2057: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1230 raeburn 2058: $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
1.1254 raeburn 2059: foreach my $type (@coursetypes) {
2060: if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
2061: unless ($type eq 'community') {
2062: $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
2063: }
2064: }
2065: if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
2066: $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
2067: }
1.1230 raeburn 2068: }
1.1047 raeburn 2069: }
1.1073 raeburn 2070: if (ref($domconfig{'usersessions'}) eq 'HASH') {
2071: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
2072: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
2073: }
2074: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
2075: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
2076: }
2077: }
1.1254 raeburn 2078: if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
2079: if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
2080: my @settings = ('types','registered','enroll_dates','access_dates','section',
2081: 'approval','limit');
2082: foreach my $type (@coursetypes) {
2083: if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
2084: my @mgrdc = ();
2085: foreach my $item (@settings) {
2086: if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
2087: push(@mgrdc,$item);
2088: }
2089: }
2090: if (@mgrdc) {
2091: $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
2092: }
2093: }
2094: }
2095: }
2096: if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
2097: foreach my $type (@coursetypes) {
2098: if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
2099: foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
2100: $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
2101: }
2102: }
2103: }
2104: }
2105: }
1.1219 raeburn 2106: &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943 raeburn 2107: return %domdefaults;
2108: }
2109:
1.344 www 2110: # --------------------------------------------------- Assign a key to a student
2111:
2112: sub assign_access_key {
1.364 www 2113: #
2114: # a valid key looks like uname:udom#comments
2115: # comments are being appended
2116: #
1.498 www 2117: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
2118: $kdom=
1.620 albertel 2119: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 2120: $knum=
1.620 albertel 2121: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 2122: $cdom=
1.620 albertel 2123: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2124: $cnum=
1.620 albertel 2125: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2126: $udom=$env{'user.name'} unless (defined($udom));
2127: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 2128: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 2129: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 2130: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 2131: # assigned to this person
2132: # - this should not happen,
1.345 www 2133: # unless something went wrong
2134: # the first time around
2135: # ready to assign
1.364 www 2136: $logentry=$1.'; '.$logentry;
1.496 www 2137: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 2138: $kdom,$knum) eq 'ok') {
1.345 www 2139: # key now belongs to user
1.346 www 2140: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 2141: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 2142: &appenv({'environment.'.$envkey => $ckey});
1.345 www 2143: return 'ok';
2144: } else {
2145: return
2146: 'error: Count not permanently assign key, will need to be re-entered later.';
2147: }
2148: } else {
2149: return 'error: Could not assign key, try again later.';
2150: }
1.364 www 2151: } elsif (!$existing{$ckey}) {
1.345 www 2152: # the key does not exist
2153: return 'error: The key does not exist';
2154: } else {
2155: # the key is somebody else's
2156: return 'error: The key is already in use';
2157: }
1.344 www 2158: }
2159:
1.364 www 2160: # ------------------------------------------ put an additional comment on a key
2161:
2162: sub comment_access_key {
2163: #
2164: # a valid key looks like uname:udom#comments
2165: # comments are being appended
2166: #
2167: my ($ckey,$cdom,$cnum,$logentry)=@_;
2168: $cdom=
1.620 albertel 2169: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 2170: $cnum=
1.620 albertel 2171: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 2172: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2173: if ($existing{$ckey}) {
2174: $existing{$ckey}.='; '.$logentry;
2175: # ready to assign
1.367 www 2176: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 2177: $cdom,$cnum) eq 'ok') {
2178: return 'ok';
2179: } else {
2180: return 'error: Count not store comment.';
2181: }
2182: } else {
2183: # the key does not exist
2184: return 'error: The key does not exist';
2185: }
2186: }
2187:
1.344 www 2188: # ------------------------------------------------------ Generate a set of keys
2189:
2190: sub generate_access_keys {
1.364 www 2191: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 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));
1.361 www 2196: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 2197: unless (($cdom) && ($cnum)) { return 0; }
2198: if ($number>10000) { return 0; }
2199: sleep(2); # make sure don't get same seed twice
2200: srand(time()^($$+($$<<15))); # from "Programming Perl"
2201: my $total=0;
2202: for (my $i=1;$i<=$number;$i++) {
2203: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
2204: sprintf("%lx",int(100000*rand)).'-'.
2205: sprintf("%lx",int(100000*rand));
2206: $newkey=~s/1/g/g; # folks mix up 1 and l
2207: $newkey=~s/0/h/g; # and also 0 and O
2208: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
2209: if ($existing{$newkey}) {
2210: $i--;
2211: } else {
1.364 www 2212: if (&put('accesskeys',
2213: { $newkey => '# generated '.localtime().
1.620 albertel 2214: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 2215: '; '.$logentry },
2216: $cdom,$cnum) eq 'ok') {
1.344 www 2217: $total++;
2218: }
2219: }
2220: }
1.620 albertel 2221: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 2222: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
2223: return $total;
2224: }
2225:
2226: # ------------------------------------------------------- Validate an accesskey
2227:
2228: sub validate_access_key {
2229: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
2230: $cdom=
1.620 albertel 2231: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2232: $cnum=
1.620 albertel 2233: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2234: $udom=$env{'user.domain'} unless (defined($udom));
2235: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 2236: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 2237: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 2238: }
2239:
2240: # ------------------------------------- Find the section of student in a course
1.652 albertel 2241: sub devalidate_getsection_cache {
2242: my ($udom,$unam,$courseid)=@_;
2243: my $hashid="$udom:$unam:$courseid";
2244: &devalidate_cache_new('getsection',$hashid);
2245: }
1.298 matthew 2246:
1.815 albertel 2247: sub courseid_to_courseurl {
2248: my ($courseid) = @_;
2249: #already url style courseid
2250: return $courseid if ($courseid =~ m{^/});
2251:
2252: if (exists($env{'course.'.$courseid.'.num'})) {
2253: my $cnum = $env{'course.'.$courseid.'.num'};
2254: my $cdom = $env{'course.'.$courseid.'.domain'};
2255: return "/$cdom/$cnum";
2256: }
2257:
2258: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
2259: if (exists($courseinfo{'num'})) {
2260: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
2261: }
2262:
2263: return undef;
2264: }
2265:
1.298 matthew 2266: sub getsection {
2267: my ($udom,$unam,$courseid)=@_;
1.599 albertel 2268: my $cachetime=1800;
1.551 albertel 2269:
2270: my $hashid="$udom:$unam:$courseid";
1.599 albertel 2271: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 2272: if (defined($cached)) { return $result; }
2273:
1.298 matthew 2274: my %Pending;
2275: my %Expired;
2276: #
2277: # Each role can either have not started yet (pending), be active,
2278: # or have expired.
2279: #
2280: # If there is an active role, we are done.
2281: #
2282: # If there is more than one role which has not started yet,
2283: # choose the one which will start sooner
2284: # If there is one role which has not started yet, return it.
2285: #
2286: # If there is more than one expired role, choose the one which ended last.
2287: # If there is a role which has expired, return it.
2288: #
1.815 albertel 2289: $courseid = &courseid_to_courseurl($courseid);
1.1166 raeburn 2290: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817 raeburn 2291: foreach my $key (keys(%roleshash)) {
1.479 albertel 2292: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 2293: my $section=$1;
2294: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 2295: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 2296: my $now=time;
1.548 albertel 2297: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 2298: $Expired{$end}=$section;
2299: next;
2300: }
1.548 albertel 2301: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 2302: $Pending{$start}=$section;
2303: next;
2304: }
1.599 albertel 2305: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 2306: }
2307: #
2308: # Presumedly there will be few matching roles from the above
2309: # loop and the sorting time will be negligible.
2310: if (scalar(keys(%Pending))) {
2311: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 2312: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 2313: }
2314: if (scalar(keys(%Expired))) {
2315: my @sorted = sort {$a <=> $b} keys(%Expired);
2316: my $time = pop(@sorted);
1.599 albertel 2317: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 2318: }
1.599 albertel 2319: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 2320: }
1.70 www 2321:
1.599 albertel 2322: sub save_cache {
2323: &purge_remembered();
1.722 albertel 2324: #&Apache::loncommon::validate_page();
1.620 albertel 2325: undef(%env);
1.780 albertel 2326: undef($env_loaded);
1.599 albertel 2327: }
1.452 albertel 2328:
1.599 albertel 2329: my $to_remember=-1;
2330: my %remembered;
2331: my %accessed;
2332: my $kicks=0;
2333: my $hits=0;
1.849 albertel 2334: sub make_key {
2335: my ($name,$id) = @_;
1.872 albertel 2336: if (length($id) > 65
2337: && length(&escape($id)) > 200) {
2338: $id=length($id).':'.&Digest::MD5::md5_hex($id);
2339: }
1.849 albertel 2340: return &escape($name.':'.$id);
2341: }
2342:
1.599 albertel 2343: sub devalidate_cache_new {
2344: my ($name,$id,$debug) = @_;
2345: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849 albertel 2346: $id=&make_key($name,$id);
1.599 albertel 2347: $memcache->delete($id);
2348: delete($remembered{$id});
2349: delete($accessed{$id});
2350: }
2351:
2352: sub is_cached_new {
2353: my ($name,$id,$debug) = @_;
1.849 albertel 2354: $id=&make_key($name,$id);
1.599 albertel 2355: if (exists($remembered{$id})) {
1.1133 foxr 2356: if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
1.599 albertel 2357: $accessed{$id}=[&gettimeofday()];
2358: $hits++;
2359: return ($remembered{$id},1);
2360: }
2361: my $value = $memcache->get($id);
2362: if (!(defined($value))) {
2363: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 2364: return (undef,undef);
1.416 albertel 2365: }
1.599 albertel 2366: if ($value eq '__undef__') {
2367: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
2368: $value=undef;
2369: }
2370: &make_room($id,$value,$debug);
2371: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
2372: return ($value,1);
2373: }
2374:
2375: sub do_cache_new {
2376: my ($name,$id,$value,$time,$debug) = @_;
1.849 albertel 2377: $id=&make_key($name,$id);
1.599 albertel 2378: my $setvalue=$value;
2379: if (!defined($setvalue)) {
2380: $setvalue='__undef__';
2381: }
1.623 albertel 2382: if (!defined($time) ) {
2383: $time=600;
2384: }
1.599 albertel 2385: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 2386: my $result = $memcache->set($id,$setvalue,$time);
2387: if (! $result) {
1.872 albertel 2388: &logthis("caching of id -> $id failed");
1.910 albertel 2389: $memcache->disconnect_all();
1.872 albertel 2390: }
1.600 albertel 2391: # need to make a copy of $value
1.919 albertel 2392: &make_room($id,$value,$debug);
1.599 albertel 2393: return $value;
2394: }
2395:
2396: sub make_room {
2397: my ($id,$value,$debug)=@_;
1.919 albertel 2398:
2399: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
2400: : $value;
1.599 albertel 2401: if ($to_remember<0) { return; }
2402: $accessed{$id}=[&gettimeofday()];
2403: if (scalar(keys(%remembered)) <= $to_remember) { return; }
2404: my $to_kick;
2405: my $max_time=0;
2406: foreach my $other (keys(%accessed)) {
2407: if (&tv_interval($accessed{$other}) > $max_time) {
2408: $to_kick=$other;
2409: $max_time=&tv_interval($accessed{$other});
2410: }
2411: }
2412: delete($remembered{$to_kick});
2413: delete($accessed{$to_kick});
2414: $kicks++;
2415: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 2416: return;
2417: }
2418:
1.599 albertel 2419: sub purge_remembered {
1.604 albertel 2420: #&logthis("Tossing ".scalar(keys(%remembered)));
2421: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 2422: undef(%remembered);
2423: undef(%accessed);
1.428 albertel 2424: }
1.70 www 2425: # ------------------------------------- Read an entry from a user's environment
2426:
2427: sub userenvironment {
2428: my ($udom,$unam,@what)=@_;
1.976 raeburn 2429: my $items;
2430: foreach my $item (@what) {
2431: $items.=&escape($item).'&';
2432: }
2433: $items=~s/\&$//;
1.70 www 2434: my %returnhash=();
1.1009 raeburn 2435: my $uhome = &homeserver($unam,$udom);
2436: unless ($uhome eq 'no_host') {
2437: my @answer=split(/\&/,
2438: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 2439: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
2440: return %returnhash;
2441: }
1.1009 raeburn 2442: my $i;
2443: for ($i=0;$i<=$#what;$i++) {
2444: $returnhash{$what[$i]}=&unescape($answer[$i]);
2445: }
1.70 www 2446: }
2447: return %returnhash;
1.1 albertel 2448: }
2449:
1.617 albertel 2450: # ---------------------------------------------------------- Get a studentphoto
2451: sub studentphoto {
2452: my ($udom,$unam,$ext) = @_;
2453: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 2454: if (defined($env{'request.course.id'})) {
1.708 raeburn 2455: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 2456: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
2457: return(&retrievestudentphoto($udom,$unam,$ext));
2458: } else {
2459: my ($result,$perm_reqd)=
1.707 albertel 2460: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2461: if ($result eq 'ok') {
2462: if (!($perm_reqd eq 'yes')) {
2463: return(&retrievestudentphoto($udom,$unam,$ext));
2464: }
2465: }
2466: }
2467: }
2468: } else {
2469: my ($result,$perm_reqd) =
1.707 albertel 2470: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2471: if ($result eq 'ok') {
2472: if (!($perm_reqd eq 'yes')) {
2473: return(&retrievestudentphoto($udom,$unam,$ext));
2474: }
2475: }
2476: }
2477: return '/adm/lonKaputt/lonlogo_broken.gif';
2478: }
2479:
2480: sub retrievestudentphoto {
2481: my ($udom,$unam,$ext,$type) = @_;
2482: my $home=&Apache::lonnet::homeserver($unam,$udom);
2483: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
2484: if ($ret eq 'ok') {
2485: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
2486: if ($type eq 'thumbnail') {
2487: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
2488: }
2489: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
2490: return $tokenurl;
2491: } else {
2492: if ($type eq 'thumbnail') {
2493: return '/adm/lonKaputt/genericstudent_tn.gif';
2494: } else {
2495: return '/adm/lonKaputt/lonlogo_broken.gif';
2496: }
1.617 albertel 2497: }
2498: }
2499:
1.263 www 2500: # -------------------------------------------------------------------- New chat
2501:
2502: sub chatsend {
1.724 raeburn 2503: my ($newentry,$anon,$group)=@_;
1.620 albertel 2504: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
2505: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2506: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 2507: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 2508: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 2509: &escape($newentry)).':'.$group,$chome);
1.292 www 2510: }
2511:
2512: # ------------------------------------------ Find current version of a resource
2513:
2514: sub getversion {
2515: my $fname=&clutter(shift);
1.1189 raeburn 2516: unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292 www 2517: return ¤tversion(&filelocation('',$fname));
2518: }
2519:
2520: sub currentversion {
2521: my $fname=shift;
2522: my $author=$fname;
2523: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2524: my ($udom,$uname)=split(/\//,$author);
1.1112 www 2525: my $home=&homeserver($uname,$udom);
1.292 www 2526: if ($home eq 'no_host') {
2527: return -1;
2528: }
1.1112 www 2529: my $answer=&reply("currentversion:$fname",$home);
1.292 www 2530: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2531: return -1;
2532: }
1.1112 www 2533: return $answer;
1.263 www 2534: }
2535:
1.1111 www 2536: #
2537: # Return special version number of resource if set by override, empty otherwise
2538: #
2539: sub usedversion {
2540: my $fname=shift;
2541: unless ($fname) { $fname=$env{'request.uri'}; }
2542: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
2543: if ($urlversion) { return $urlversion; }
2544: return '';
2545: }
2546:
1.1 albertel 2547: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 2548:
1.1 albertel 2549: sub subscribe {
2550: my $fname=shift;
1.761 raeburn 2551: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 2552: $fname=~s/[\n\r]//g;
1.1 albertel 2553: my $author=$fname;
2554: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2555: my ($udom,$uname)=split(/\//,$author);
2556: my $home=homeserver($uname,$udom);
1.335 albertel 2557: if ($home eq 'no_host') {
2558: return 'not_found';
1.1 albertel 2559: }
2560: my $answer=reply("sub:$fname",$home);
1.64 www 2561: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2562: $answer.=' by '.$home;
2563: }
1.1 albertel 2564: return $answer;
2565: }
2566:
1.8 www 2567: # -------------------------------------------------------------- Replicate file
2568:
2569: sub repcopy {
2570: my $filename=shift;
1.23 www 2571: $filename=~s/\/+/\//g;
1.1142 raeburn 2572: my $londocroot = $perlvar{'lonDocRoot'};
2573: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164 raeburn 2574: if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142 raeburn 2575: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
2576: $filename=~m{^/*(uploaded|editupload)/}) {
1.538 albertel 2577: return &repcopy_userfile($filename);
2578: }
1.532 albertel 2579: $filename=~s/[\n\r]//g;
1.8 www 2580: my $transname="$filename.in.transfer";
1.828 www 2581: # FIXME: this should flock
1.607 raeburn 2582: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 2583: my $remoteurl=subscribe($filename);
1.64 www 2584: if ($remoteurl =~ /^con_lost by/) {
2585: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2586: return 'unavailable';
1.8 www 2587: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 2588: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 2589: return 'not_found';
1.64 www 2590: } elsif ($remoteurl =~ /^rejected by/) {
2591: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2592: return 'forbidden';
1.20 www 2593: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 2594: return 'ok';
1.8 www 2595: } else {
1.290 www 2596: my $author=$filename;
2597: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2598: my ($udom,$uname)=split(/\//,$author);
2599: my $home=homeserver($uname,$udom);
2600: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 2601: my @parts=split(/\//,$filename);
2602: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142 raeburn 2603: if ($path ne "$londocroot/res") {
1.8 www 2604: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 2605: return 'bad_request';
1.8 www 2606: }
2607: my $count;
2608: for ($count=5;$count<$#parts;$count++) {
2609: $path.="/$parts[$count]";
2610: if ((-e $path)!=1) {
2611: mkdir($path,0777);
2612: }
2613: }
2614: my $ua=new LWP::UserAgent;
2615: my $request=new HTTP::Request('GET',"$remoteurl");
2616: my $response=$ua->request($request,$transname);
2617: if ($response->is_error()) {
2618: unlink($transname);
2619: my $message=$response->status_line;
1.672 albertel 2620: &logthis("<font color=\"blue\">WARNING:"
1.12 www 2621: ." LWP get: $message: $filename</font>");
1.607 raeburn 2622: return 'unavailable';
1.8 www 2623: } else {
1.16 www 2624: if ($remoteurl!~/\.meta$/) {
2625: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2626: my $mresponse=$ua->request($mrequest,$filename.'.meta');
2627: if ($mresponse->is_error()) {
2628: unlink($filename.'.meta');
2629: &logthis(
1.672 albertel 2630: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 2631: }
2632: }
1.8 www 2633: rename($transname,$filename);
1.607 raeburn 2634: return 'ok';
1.8 www 2635: }
1.290 www 2636: }
1.8 www 2637: }
1.330 www 2638: }
2639:
2640: # ------------------------------------------------ Get server side include body
2641: sub ssi_body {
1.381 albertel 2642: my ($filelink,%form)=@_;
1.606 matthew 2643: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
2644: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
2645: }
1.953 www 2646: my $output='';
2647: my $response;
1.980 raeburn 2648: if ($filelink=~/^https?\:/) {
1.954 raeburn 2649: ($output,$response)=&externalssi($filelink);
1.953 www 2650: } else {
1.1004 droeschl 2651: $filelink .= $filelink=~/\?/ ? '&' : '?';
2652: $filelink .= 'inhibitmenu=yes';
1.953 www 2653: ($output,$response)=&ssi($filelink,%form);
2654: }
1.778 albertel 2655: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 2656: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 2657: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 2658: if (wantarray) {
2659: return ($output, $response);
2660: } else {
2661: return $output;
2662: }
1.8 www 2663: }
2664:
1.15 www 2665: # --------------------------------------------------------- Server Side Include
2666:
1.782 albertel 2667: sub absolute_url {
2668: my ($host_name) = @_;
2669: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
2670: if ($host_name eq '') {
2671: $host_name = $ENV{'SERVER_NAME'};
2672: }
2673: return $protocol.$host_name;
2674: }
2675:
1.942 foxr 2676: #
2677: # Server side include.
2678: # Parameters:
2679: # fn Possibly encrypted resource name/id.
2680: # form Hash that describes how the rendering should be done
2681: # and other things.
1.944 foxr 2682: # Returns:
1.950 raeburn 2683: # Scalar context: The content of the response.
2684: # Array context: 2 element list of the content and the full response object.
1.942 foxr 2685: #
1.15 www 2686: sub ssi {
2687:
1.944 foxr 2688: my ($fn,%form)=@_;
1.15 www 2689: my $ua=new LWP::UserAgent;
1.23 www 2690: my $request;
1.711 albertel 2691:
2692: $form{'no_update_last_known'}=1;
1.895 albertel 2693: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 2694: if (%form) {
1.782 albertel 2695: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000 raeburn 2696: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23 www 2697: } else {
1.782 albertel 2698: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 2699: }
2700:
1.15 www 2701: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1173 foxr 2702: my $response= $ua->request($request);
1.1182 foxr 2703: my $content = $response->content;
2704:
2705:
1.944 foxr 2706: if (wantarray) {
1.1173 foxr 2707: return ($content, $response);
1.944 foxr 2708: } else {
1.1173 foxr 2709: return $content;
1.942 foxr 2710: }
1.324 www 2711: }
2712:
2713: sub externalssi {
2714: my ($url)=@_;
2715: my $ua=new LWP::UserAgent;
2716: my $request=new HTTP::Request('GET',$url);
2717: my $response=$ua->request($request);
1.954 raeburn 2718: if (wantarray) {
2719: return ($response->content, $response);
2720: } else {
2721: return $response->content;
2722: }
1.15 www 2723: }
1.254 www 2724:
1.492 albertel 2725: # -------------------------------- Allow a /uploaded/ URI to be vouched for
2726:
2727: sub allowuploaded {
2728: my ($srcurl,$url)=@_;
2729: $url=&clutter(&declutter($url));
2730: my $dir=$url;
2731: $dir=~s/\/[^\/]+$//;
2732: my %httpref=();
2733: my $httpurl=&hreflocation('',$url);
2734: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 2735: &Apache::lonnet::appenv(\%httpref);
1.254 www 2736: }
1.477 raeburn 2737:
1.1193 raeburn 2738: #
2739: # Determine if the current user should be able to edit a particular resource,
2740: # when viewing in course context.
2741: # (a) When viewing resource used to determine if "Edit" item is included in
2742: # Functions.
2743: # (b) When displaying folder contents in course editor, used to determine if
2744: # "Edit" link will be displayed alongside resource.
2745: #
1.1196 raeburn 2746: # input: six args -- filename (decluttered), course number, course domain,
2747: # url, symb (if registered) and group (if this is a group
2748: # item -- e.g., bulletin board, group page etc.).
2749: # output: array of five scalars --
1.1193 raeburn 2750: # $cfile -- url for file editing if editable on current server
2751: # $home -- homeserver of resource (i.e., for author if published,
2752: # or course if uploaded.).
2753: # $switchserver -- 1 if server switch will be needed.
1.1196 raeburn 2754: # $forceedit -- 1 if icon/link should be to go to edit mode
2755: # $forceview -- 1 if icon/link should be to go to view mode
1.1193 raeburn 2756: #
2757:
2758: sub can_edit_resource {
1.1194 raeburn 2759: my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
2760: my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
2761: #
2762: # For aboutme pages user can only edit his/her own.
2763: #
1.1199 raeburn 2764: if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
1.1194 raeburn 2765: my ($sdom,$sname) = ($1,$2);
2766: if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
2767: $home = $env{'user.home'};
2768: $cfile = $resurl;
2769: if ($env{'form.forceedit'}) {
2770: $forceview = 1;
2771: } else {
2772: $forceedit = 1;
2773: }
2774: return ($cfile,$home,$switchserver,$forceedit,$forceview);
2775: } else {
2776: return;
2777: }
2778: }
2779:
2780: if ($env{'request.course.id'}) {
2781: my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
2782: if ($group ne '') {
2783: # if this is a group homepage or group bulletin board, check group privs
2784: my $allowed = 0;
1.1197 raeburn 2785: if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
2786: if ((&allowed('mdg',$env{'request.course.id'}.
1.1198 raeburn 2787: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
1.1194 raeburn 2788: (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
2789: $allowed = 1;
2790: }
1.1197 raeburn 2791: } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
2792: if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
2793: (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
1.1194 raeburn 2794: $allowed = 1;
2795: }
2796: }
2797: if ($allowed) {
2798: $home=&homeserver($cnum,$cdom);
2799: if ($env{'form.forceedit'}) {
2800: $forceview = 1;
2801: } else {
2802: $forceedit = 1;
2803: }
2804: $cfile = $resurl;
2805: } else {
2806: return;
2807: }
2808: } else {
1.1208 raeburn 2809: if ($resurl =~ m{^/?adm/viewclasslist$}) {
2810: unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
2811: return;
2812: }
2813: } elsif (!$crsedit) {
1.1194 raeburn 2814: #
2815: # No edit allowed where CC has switched to student role.
2816: #
2817: return;
2818: }
2819: }
2820: }
2821:
1.1193 raeburn 2822: if ($file ne '') {
2823: if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
1.1194 raeburn 2824: if (&is_course_upload($file,$cnum,$cdom)) {
2825: $uploaded = 1;
2826: $incourse = 1;
1.1193 raeburn 2827: if ($file =~/\.(htm|html|css|js|txt)$/) {
2828: $cfile = &hreflocation('',$file);
1.1201 raeburn 2829: if ($env{'form.forceedit'}) {
2830: $forceview = 1;
2831: } else {
2832: $forceedit = 1;
2833: }
1.1194 raeburn 2834: }
2835: } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
2836: $incourse = 1;
2837: if ($env{'form.forceedit'}) {
2838: $forceview = 1;
2839: } else {
2840: $forceedit = 1;
2841: }
2842: $cfile = $resurl;
2843: } elsif (($resurl ne '') && (&is_on_map($resurl))) {
2844: if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
2845: $incourse = 1;
2846: if ($env{'form.forceedit'}) {
2847: $forceview = 1;
2848: } else {
2849: $forceedit = 1;
2850: }
2851: $cfile = $resurl;
1.1199 raeburn 2852: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
1.1194 raeburn 2853: $incourse = 1;
2854: $cfile = $resurl.'/smpedit';
1.1199 raeburn 2855: } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
1.1194 raeburn 2856: $incourse = 1;
1.1199 raeburn 2857: if ($env{'form.forceedit'}) {
2858: $forceview = 1;
2859: } else {
2860: $forceedit = 1;
2861: }
2862: $cfile = $resurl;
1.1208 raeburn 2863: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
2864: $incourse = 1;
2865: if ($env{'form.forceedit'}) {
2866: $forceview = 1;
2867: } else {
2868: $forceedit = 1;
2869: }
2870: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1194 raeburn 2871: }
2872: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
2873: my $template = '/res/lib/templates/simpleproblem.problem';
2874: if (&is_on_map($template)) {
2875: $incourse = 1;
2876: $forceview = 1;
2877: $cfile = $template;
1.1193 raeburn 2878: }
1.1199 raeburn 2879: } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
2880: $incourse = 1;
2881: if ($env{'form.forceedit'}) {
2882: $forceview = 1;
2883: } else {
2884: $forceedit = 1;
2885: }
2886: $cfile = $resurl;
2887: } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
2888: $incourse = 1;
2889: $forceview = 1;
2890: if ($symb) {
2891: my ($map,$id,$res)=&decode_symb($symb);
2892: $env{'request.symb'} = $symb;
2893: $cfile = &clutter($res);
2894: } else {
2895: $cfile = $env{'form.suppurl'};
2896: $cfile =~ s{^http://}{};
2897: $cfile = '/adm/wrapper/ext/'.$cfile;
2898: }
1.1234 raeburn 2899: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
2900: if ($env{'form.forceedit'}) {
2901: $forceview = 1;
2902: } else {
2903: $forceedit = 1;
2904: }
2905: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1193 raeburn 2906: }
2907: }
1.1194 raeburn 2908: if ($uploaded || $incourse) {
2909: $home=&homeserver($cnum,$cdom);
1.1207 raeburn 2910: } elsif ($file !~ m{/$}) {
1.1193 raeburn 2911: $file=~s{^(priv/$match_domain/$match_username)}{/$1};
2912: $file=~s{^($match_domain/$match_username)}{/priv/$1};
2913: # Check that the user has permission to edit this resource
2914: my $setpriv = 1;
2915: my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
2916: if (defined($cfudom)) {
2917: $home=&homeserver($cfuname,$cfudom);
2918: $cfile=$file;
2919: }
2920: }
1.1194 raeburn 2921: if (($cfile ne '') && (!$incourse || $uploaded) &&
2922: (($home ne '') && ($home ne 'no_host'))) {
1.1193 raeburn 2923: my @ids=¤t_machine_ids();
2924: unless (grep(/^\Q$home\E$/,@ids)) {
2925: $switchserver=1;
2926: }
2927: }
2928: }
1.1194 raeburn 2929: return ($cfile,$home,$switchserver,$forceedit,$forceview);
1.1193 raeburn 2930: }
2931:
2932: sub is_course_upload {
2933: my ($file,$cnum,$cdom) = @_;
2934: my $uploadpath = &LONCAPA::propath($cdom,$cnum);
2935: $uploadpath =~ s{^\/}{};
1.1201 raeburn 2936: if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
2937: ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
1.1193 raeburn 2938: return 1;
2939: }
2940: return;
2941: }
2942:
1.1194 raeburn 2943: sub in_course {
1.1195 raeburn 2944: my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
2945: if ($hideprivileged) {
2946: my $skipuser;
1.1219 raeburn 2947: my %coursehash = &coursedescription($cdom.'_'.$cnum);
2948: my @possdoms = ($cdom);
2949: if ($coursehash{'checkforpriv'}) {
2950: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
2951: }
2952: if (&privileged($uname,$udom,\@possdoms)) {
1.1195 raeburn 2953: $skipuser = 1;
2954: if ($coursehash{'nothideprivileged'}) {
2955: foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
2956: my $user;
2957: if ($item =~ /:/) {
2958: $user = $item;
2959: } else {
2960: $user = join(':',split(/[\@]/,$item));
2961: }
2962: if ($user eq $uname.':'.$udom) {
2963: undef($skipuser);
2964: last;
2965: }
2966: }
2967: }
2968: if ($skipuser) {
2969: return 0;
2970: }
2971: }
2972: }
1.1194 raeburn 2973: $type ||= 'any';
2974: if (!defined($cdom) || !defined($cnum)) {
2975: my $cid = $env{'request.course.id'};
2976: $cdom = $env{'course.'.$cid.'.domain'};
2977: $cnum = $env{'course.'.$cid.'.num'};
2978: }
2979: my $typesref;
1.1195 raeburn 2980: if (($type eq 'any') || ($type eq 'all')) {
1.1194 raeburn 2981: $typesref = ['active','previous','future'];
2982: } elsif ($type eq 'previous' || $type eq 'future') {
2983: $typesref = [$type];
2984: }
2985: my %roles = &get_my_roles($uname,$udom,'userroles',
2986: $typesref,undef,[$cdom]);
2987: my ($tmp) = keys(%roles);
2988: return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
2989: my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
2990: if (@course_roles > 0) {
2991: return 1;
2992: }
2993: return 0;
2994: }
2995:
1.478 albertel 2996: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 2997: # input: action, courseID, current domain, intended
1.637 raeburn 2998: # path to file, source of file, instruction to parse file for objects,
2999: # ref to hash for embedded objects,
3000: # ref to hash for codebase of java objects.
1.1095 raeburn 3001: # reference to scalar to accommodate mime type determined
3002: # from File::MMagic if $parser = parse.
1.637 raeburn 3003: #
1.485 raeburn 3004: # output: url to file (if action was uploaddoc),
3005: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 3006: #
1.478 albertel 3007: # Allows directory structure to be used within lonUsers/../userfiles/ for a
3008: # course.
1.477 raeburn 3009: #
1.478 albertel 3010: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3011: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
3012: # course's home server.
1.477 raeburn 3013: #
1.478 albertel 3014: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
3015: # be copied from $source (current location) to
3016: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3017: # and will then be copied to
3018: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
3019: # course's home server.
1.485 raeburn 3020: #
1.481 raeburn 3021: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 3022: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 3023: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3024: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
3025: # in course's home server.
1.637 raeburn 3026: #
1.477 raeburn 3027:
3028: sub process_coursefile {
1.1095 raeburn 3029: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
3030: $mimetype)=@_;
1.477 raeburn 3031: my $fetchresult;
1.638 albertel 3032: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 3033: if ($action eq 'propagate') {
1.638 albertel 3034: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
3035: $home);
1.481 raeburn 3036: } else {
1.477 raeburn 3037: my $fpath = '';
3038: my $fname = $file;
1.478 albertel 3039: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 3040: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 3041: my $filepath = &build_filepath($fpath);
1.481 raeburn 3042: if ($action eq 'copy') {
3043: if ($source eq '') {
3044: $fetchresult = 'no source file';
3045: return $fetchresult;
3046: } else {
3047: my $destination = $filepath.'/'.$fname;
3048: rename($source,$destination);
3049: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3050: $home);
1.481 raeburn 3051: }
3052: } elsif ($action eq 'uploaddoc') {
3053: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 3054: print $fh $env{'form.'.$source};
1.481 raeburn 3055: close($fh);
1.637 raeburn 3056: if ($parser eq 'parse') {
1.1024 raeburn 3057: my $mm = new File::MMagic;
1.1095 raeburn 3058: my $type = $mm->checktype_filename($filepath.'/'.$fname);
3059: if ($type eq 'text/html') {
1.1024 raeburn 3060: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
3061: unless ($parse_result eq 'ok') {
3062: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
3063: }
1.637 raeburn 3064: }
1.1095 raeburn 3065: if (ref($mimetype)) {
3066: $$mimetype = $type;
3067: }
1.637 raeburn 3068: }
1.477 raeburn 3069: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3070: $home);
1.481 raeburn 3071: if ($fetchresult eq 'ok') {
3072: return '/uploaded/'.$fpath.'/'.$fname;
3073: } else {
3074: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3075: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 3076: return '/adm/notfound.html';
3077: }
1.477 raeburn 3078: }
3079: }
1.485 raeburn 3080: unless ( $fetchresult eq 'ok') {
1.477 raeburn 3081: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3082: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 3083: }
3084: return $fetchresult;
3085: }
3086:
1.637 raeburn 3087: sub build_filepath {
3088: my ($fpath) = @_;
3089: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
3090: unless ($fpath eq '') {
3091: my @parts=split('/',$fpath);
3092: foreach my $part (@parts) {
3093: $filepath.= '/'.$part;
3094: if ((-e $filepath)!=1) {
3095: mkdir($filepath,0777);
3096: }
3097: }
3098: }
3099: return $filepath;
3100: }
3101:
3102: sub store_edited_file {
1.638 albertel 3103: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 3104: my $file = $primary_url;
3105: $file =~ s#^/uploaded/$docudom/$docuname/##;
3106: my $fpath = '';
3107: my $fname = $file;
3108: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
3109: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
3110: my $filepath = &build_filepath($fpath);
3111: open(my $fh,'>'.$filepath.'/'.$fname);
3112: print $fh $content;
3113: close($fh);
1.638 albertel 3114: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 3115: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3116: $home);
1.637 raeburn 3117: if ($$fetchresult eq 'ok') {
3118: return '/uploaded/'.$fpath.'/'.$fname;
3119: } else {
1.638 albertel 3120: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
3121: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 3122: return '/adm/notfound.html';
3123: }
3124: }
3125:
1.531 albertel 3126: sub clean_filename {
1.831 albertel 3127: my ($fname,$args)=@_;
1.315 www 3128: # Replace Windows backslashes by forward slashes
1.257 www 3129: $fname=~s/\\/\//g;
1.831 albertel 3130: if (!$args->{'keep_path'}) {
3131: # Get rid of everything but the actual filename
3132: $fname=~s/^.*\/([^\/]+)$/$1/;
3133: }
1.315 www 3134: # Replace spaces by underscores
3135: $fname=~s/\s+/\_/g;
3136: # Replace all other weird characters by nothing
1.831 albertel 3137: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 3138: # Replace all .\d. sequences with _\d. so they no longer look like version
3139: # numbers
3140: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 3141: return $fname;
3142: }
1.1051 raeburn 3143: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
3144: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
3145: # image with the same aspect ratio as the original, but with dimensions which do
3146: # not exceed $resizewidth and $resizeheight.
3147:
1.984 neumanie 3148: sub resizeImage {
1.1051 raeburn 3149: my ($img_path,$resizewidth,$resizeheight) = @_;
3150: my $ima = Image::Magick->new;
3151: my $resized;
3152: if (-e $img_path) {
3153: $ima->Read($img_path);
3154: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
3155: my $width = $ima->Get('width');
3156: my $height = $ima->Get('height');
3157: if ($width > $resizewidth) {
3158: my $factor = $width/$resizewidth;
3159: my $newheight = $height/$factor;
3160: $ima->Scale(width=>$resizewidth,height=>$newheight);
3161: $resized = 1;
3162: }
3163: }
3164: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
3165: my $width = $ima->Get('width');
3166: my $height = $ima->Get('height');
3167: if ($height > $resizeheight) {
3168: my $factor = $height/$resizeheight;
3169: my $newwidth = $width/$factor;
3170: $ima->Scale(width=>$newwidth,height=>$resizeheight);
3171: $resized = 1;
3172: }
3173: }
3174: if ($resized) {
3175: $ima->Write($img_path);
3176: }
3177: }
3178: return;
1.977 amueller 3179: }
3180:
1.608 albertel 3181: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 3182: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093 raeburn 3183: # the desired filename is in $env{"form.$formname.filename"}
1.1090 raeburn 3184: # $context - possible values: coursedoc, existingfile, overwrite,
3185: # canceloverwrite, or ''.
3186: # if 'coursedoc': upload to the current course
3187: # if 'existingfile': write file to tmp/overwrites directory
3188: # if 'canceloverwrite': delete file written to tmp/overwrites directory
3189: # $context is passed as argument to &finishuserfileupload
1.686 albertel 3190: # $subdir - directory in userfile to store the file into
1.858 raeburn 3191: # $parser - instruction to parse file for objects ($parser = parse)
3192: # $allfiles - reference to hash for embedded objects
3193: # $codebase - reference to hash for codebase of java objects
3194: # $desuname - username for permanent storage of uploaded file
3195: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 3196: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
3197: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 3198: # $resizewidth - width (pixels) to which to resize uploaded image
3199: # $resizeheight - height (pixels) to which to resize uploaded image
1.1095 raeburn 3200: # $mimetype - reference to scalar to accommodate mime type determined
1.1152 raeburn 3201: # from File::MMagic.
1.858 raeburn 3202: #
1.686 albertel 3203: # output: url of file in userspace, or error: <message>
3204: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 3205:
1.531 albertel 3206: sub userfileupload {
1.1090 raeburn 3207: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095 raeburn 3208: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531 albertel 3209: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 3210: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 3211: $fname=&clean_filename($fname);
1.1090 raeburn 3212: # See if there is anything left
1.257 www 3213: unless ($fname) { return 'error: no uploaded file'; }
1.1090 raeburn 3214: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
3215: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
3216: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
3217: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523 raeburn 3218: my $now = time;
1.1090 raeburn 3219: my $filepath;
1.1095 raeburn 3220: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090 raeburn 3221: $filepath = 'tmp/helprequests/'.$now;
3222: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
3223: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
3224: '_'.$env{'user.domain'}.'/pending';
3225: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
3226: my ($docuname,$docudom);
3227: if ($destudom) {
3228: $docudom = $destudom;
3229: } else {
3230: $docudom = $env{'user.domain'};
3231: }
3232: if ($destuname) {
3233: $docuname = $destuname;
3234: } else {
3235: $docuname = $env{'user.name'};
3236: }
3237: if (exists($env{'form.group'})) {
3238: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3239: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3240: }
3241: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
3242: if ($context eq 'canceloverwrite') {
3243: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
3244: if (-e $tempfile) {
3245: my @info = stat($tempfile);
3246: if ($info[9] eq $env{'form.timestamp'}) {
3247: unlink($tempfile);
3248: }
3249: }
3250: return;
1.523 raeburn 3251: }
3252: }
1.1090 raeburn 3253: # Create the directory if not present
1.741 raeburn 3254: my @parts=split(/\//,$filepath);
3255: my $fullpath = $perlvar{'lonDaemons'};
3256: for (my $i=0;$i<@parts;$i++) {
3257: $fullpath .= '/'.$parts[$i];
3258: if ((-e $fullpath)!=1) {
3259: mkdir($fullpath,0777);
3260: }
3261: }
3262: open(my $fh,'>'.$fullpath.'/'.$fname);
3263: print $fh $env{'form.'.$formname};
3264: close($fh);
1.1090 raeburn 3265: if ($context eq 'existingfile') {
3266: my @info = stat($fullpath.'/'.$fname);
3267: return ($fullpath.'/'.$fname,$info[9]);
3268: } else {
3269: return $fullpath.'/'.$fname;
3270: }
1.523 raeburn 3271: }
1.995 raeburn 3272: if ($subdir eq 'scantron') {
3273: $fname = 'scantron_orig_'.$fname;
1.1093 raeburn 3274: } else {
1.995 raeburn 3275: $fname="$subdir/$fname";
3276: }
1.1090 raeburn 3277: if ($context eq 'coursedoc') {
1.638 albertel 3278: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3279: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 3280: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 3281: return &finishuserfileupload($docuname,$docudom,
3282: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 3283: $codebase,$thumbwidth,$thumbheight,
1.1095 raeburn 3284: $resizewidth,$resizeheight,$context,$mimetype);
1.481 raeburn 3285: } else {
1.1218 raeburn 3286: if ($env{'form.folder'}) {
3287: $fname=$env{'form.folder'}.'/'.$fname;
3288: }
1.638 albertel 3289: return &process_coursefile('uploaddoc',$docuname,$docudom,
3290: $fname,$formname,$parser,
1.1095 raeburn 3291: $allfiles,$codebase,$mimetype);
1.481 raeburn 3292: }
1.719 banghart 3293: } elsif (defined($destuname)) {
3294: my $docuname=$destuname;
3295: my $docudom=$destudom;
1.860 raeburn 3296: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3297: $parser,$allfiles,$codebase,
1.1051 raeburn 3298: $thumbwidth,$thumbheight,
1.1095 raeburn 3299: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3300: } else {
1.638 albertel 3301: my $docuname=$env{'user.name'};
3302: my $docudom=$env{'user.domain'};
1.1220 raeburn 3303: if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714 raeburn 3304: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3305: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3306: }
1.860 raeburn 3307: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3308: $parser,$allfiles,$codebase,
1.1051 raeburn 3309: $thumbwidth,$thumbheight,
1.1095 raeburn 3310: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3311: }
1.271 www 3312: }
3313:
3314: sub finishuserfileupload {
1.860 raeburn 3315: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095 raeburn 3316: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477 raeburn 3317: my $path=$docudom.'/'.$docuname.'/';
1.258 www 3318: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 3319:
1.860 raeburn 3320: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 3321: $file=$fname;
3322: if ($fname=~m|/|) {
3323: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
3324: $path.=$fnamepath.'/';
3325: }
1.259 www 3326: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 3327: my $count;
3328: for ($count=4;$count<=$#parts;$count++) {
3329: $filepath.="/$parts[$count]";
3330: if ((-e $filepath)!=1) {
3331: mkdir($filepath,0777);
3332: }
3333: }
1.984 neumanie 3334:
1.258 www 3335: # Save the file
3336: {
1.701 albertel 3337: if (!open(FH,'>'.$filepath.'/'.$file)) {
3338: &logthis('Failed to create '.$filepath.'/'.$file);
3339: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
3340: return '/adm/notfound.html';
3341: }
1.1090 raeburn 3342: if ($context eq 'overwrite') {
1.1117 foxr 3343: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090 raeburn 3344: my $target = $filepath.'/'.$file;
3345: if (-e $source) {
3346: my @info = stat($source);
3347: if ($info[9] eq $env{'form.timestamp'}) {
3348: unless (&File::Copy::move($source,$target)) {
3349: &logthis('Failed to overwrite '.$filepath.'/'.$file);
3350: return "Moving from $source failed";
3351: }
3352: } else {
3353: return "Temporary file: $source had unexpected date/time for last modification";
3354: }
3355: } else {
3356: return "Temporary file: $source missing";
3357: }
3358: } elsif (!print FH ($env{'form.'.$formname})) {
1.701 albertel 3359: &logthis('Failed to write to '.$filepath.'/'.$file);
3360: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
3361: return '/adm/notfound.html';
3362: }
1.570 albertel 3363: close(FH);
1.1051 raeburn 3364: if ($resizewidth && $resizeheight) {
3365: my $mm = new File::MMagic;
3366: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
3367: if ($mime_type =~ m{^image/}) {
3368: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
3369: }
1.977 amueller 3370: }
1.258 www 3371: }
1.1152 raeburn 3372: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
3373: if (ref($mimetype)) {
3374: if ($$mimetype eq '') {
3375: my $mm = new File::MMagic;
3376: my $type = $mm->checktype_filename($filepath.'/'.$file);
3377: $$mimetype = $type;
3378: }
3379: }
3380: }
1.637 raeburn 3381: if ($parser eq 'parse') {
1.1152 raeburn 3382: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024 raeburn 3383: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
3384: $allfiles,$codebase);
3385: unless ($parse_result eq 'ok') {
3386: &logthis('Failed to parse '.$filepath.$file.
3387: ' for embedded media: '.$parse_result);
3388: }
1.637 raeburn 3389: }
3390: }
1.860 raeburn 3391: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
3392: my $input = $filepath.'/'.$file;
3393: my $output = $filepath.'/'.'tn-'.$file;
3394: my $thumbsize = $thumbwidth.'x'.$thumbheight;
3395: system("convert -sample $thumbsize $input $output");
3396: if (-e $filepath.'/'.'tn-'.$file) {
3397: $fetchthumb = 1;
3398: }
3399: }
1.858 raeburn 3400:
1.259 www 3401: # Notify homeserver to grep it
3402: #
1.984 neumanie 3403: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 3404: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 3405: if ($fetchresult eq 'ok') {
1.860 raeburn 3406: if ($fetchthumb) {
3407: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
3408: if ($thumbresult ne 'ok') {
3409: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
3410: $docuhome.': '.$thumbresult);
3411: }
3412: }
1.259 www 3413: #
1.258 www 3414: # Return the URL to it
1.494 albertel 3415: return '/uploaded/'.$path.$file;
1.263 www 3416: } else {
1.494 albertel 3417: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
3418: ': '.$fetchresult);
1.263 www 3419: return '/adm/notfound.html';
1.858 raeburn 3420: }
1.493 albertel 3421: }
3422:
1.637 raeburn 3423: sub extract_embedded_items {
1.961 raeburn 3424: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 3425: my @state = ();
1.1164 raeburn 3426: my (%lastids,%related,%shockwave,%flashvars);
1.637 raeburn 3427: my %javafiles = (
3428: codebase => '',
3429: code => '',
3430: archive => ''
3431: );
3432: my %mediafiles = (
3433: src => '',
3434: movie => '',
3435: );
1.648 raeburn 3436: my $p;
3437: if ($content) {
3438: $p = HTML::LCParser->new($content);
3439: } else {
1.961 raeburn 3440: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 3441: }
1.641 albertel 3442: while (my $t=$p->get_token()) {
1.640 albertel 3443: if ($t->[0] eq 'S') {
3444: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 3445: push(@state, $tagname);
1.648 raeburn 3446: if (lc($tagname) eq 'allow') {
3447: &add_filetype($allfiles,$attr->{'src'},'src');
3448: }
1.640 albertel 3449: if (lc($tagname) eq 'img') {
3450: &add_filetype($allfiles,$attr->{'src'},'src');
3451: }
1.886 albertel 3452: if (lc($tagname) eq 'a') {
1.1222 raeburn 3453: unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
1.1221 raeburn 3454: &add_filetype($allfiles,$attr->{'href'},'href');
3455: }
1.886 albertel 3456: }
1.645 raeburn 3457: if (lc($tagname) eq 'script') {
1.1164 raeburn 3458: my $src;
1.645 raeburn 3459: if ($attr->{'archive'} =~ /\.jar$/i) {
3460: &add_filetype($allfiles,$attr->{'archive'},'archive');
3461: } else {
1.1164 raeburn 3462: if ($attr->{'src'} ne '') {
3463: $src = $attr->{'src'};
3464: &add_filetype($allfiles,$src,'src');
3465: }
3466: }
3467: my $text = $p->get_trimmed_text();
3468: if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
3469: my @swfargs = split(/,/,$1);
3470: foreach my $item (@swfargs) {
3471: $item =~ s/["']//g;
3472: $item =~ s/^\s+//;
3473: $item =~ s/\s+$//;
3474: }
3475: if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
3476: if (ref($related{$swfargs[0]}) eq 'ARRAY') {
3477: push(@{$related{$swfargs[0]}},$swfargs[2]);
3478: } else {
3479: $related{$swfargs[0]} = [$swfargs[2]];
3480: }
3481: }
1.645 raeburn 3482: }
3483: }
3484: if (lc($tagname) eq 'link') {
3485: if (lc($attr->{'rel'}) eq 'stylesheet') {
3486: &add_filetype($allfiles,$attr->{'href'},'href');
3487: }
3488: }
1.640 albertel 3489: if (lc($tagname) eq 'object' ||
3490: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
3491: foreach my $item (keys(%javafiles)) {
3492: $javafiles{$item} = '';
3493: }
1.1164 raeburn 3494: if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
3495: $lastids{lc($tagname)} = $attr->{'id'};
3496: }
1.640 albertel 3497: }
3498: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
3499: my $name = lc($attr->{'name'});
3500: foreach my $item (keys(%javafiles)) {
3501: if ($name eq $item) {
3502: $javafiles{$item} = $attr->{'value'};
3503: last;
3504: }
3505: }
1.1164 raeburn 3506: my $pathfrom;
1.640 albertel 3507: foreach my $item (keys(%mediafiles)) {
3508: if ($name eq $item) {
1.1164 raeburn 3509: $pathfrom = $attr->{'value'};
3510: $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
3511: &add_filetype($allfiles,$pathfrom,$name);
1.640 albertel 3512: last;
3513: }
3514: }
1.1164 raeburn 3515: if ($name eq 'flashvars') {
3516: $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
3517: }
3518: if ($pathfrom ne '') {
3519: &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
3520: $pathfrom);
3521: }
1.640 albertel 3522: }
3523: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
3524: foreach my $item (keys(%javafiles)) {
3525: if ($attr->{$item}) {
3526: $javafiles{$item} = $attr->{$item};
3527: last;
3528: }
3529: }
3530: foreach my $item (keys(%mediafiles)) {
3531: if ($attr->{$item}) {
3532: &add_filetype($allfiles,$attr->{$item},$item);
3533: last;
3534: }
3535: }
1.1164 raeburn 3536: if (lc($tagname) eq 'embed') {
3537: if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
3538: &embedded_dependency($allfiles,\%related,$attr->{'name'},
3539: $attr->{'src'});
3540: }
3541: }
1.640 albertel 3542: }
1.1243 raeburn 3543: if (lc($tagname) eq 'iframe') {
3544: my $src = $attr->{'src'} ;
3545: if (($src ne '') && ($src !~ m{^(/|https?://)})) {
3546: &add_filetype($allfiles,$src,'src');
3547: } elsif ($src =~ m{^/}) {
3548: if ($env{'request.course.id'}) {
3549: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
3550: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
3551: my $url = &hreflocation('',$fullpath);
3552: if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
3553: my $relpath = $1;
3554: if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
3555: &add_filetype($allfiles,$1,'src');
3556: }
3557: }
3558: }
3559: }
3560: }
1.1164 raeburn 3561: if ($t->[4] =~ m{/>$}) {
1.1243 raeburn 3562: pop(@state);
1.1164 raeburn 3563: }
1.640 albertel 3564: } elsif ($t->[0] eq 'E') {
3565: my ($tagname) = ($t->[1]);
3566: if ($javafiles{'codebase'} ne '') {
3567: $javafiles{'codebase'} .= '/';
3568: }
3569: if (lc($tagname) eq 'applet' ||
3570: lc($tagname) eq 'object' ||
3571: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
3572: ) {
3573: foreach my $item (keys(%javafiles)) {
3574: if ($item ne 'codebase' && $javafiles{$item} ne '') {
3575: my $file=$javafiles{'codebase'}.$javafiles{$item};
3576: &add_filetype($allfiles,$file,$item);
3577: }
3578: }
3579: }
3580: pop @state;
3581: }
3582: }
1.1164 raeburn 3583: foreach my $id (sort(keys(%flashvars))) {
3584: if ($shockwave{$id} ne '') {
3585: my @pairs = split(/\&/,$flashvars{$id});
3586: foreach my $pair (@pairs) {
3587: my ($key,$value) = split(/\=/,$pair);
3588: if ($key eq 'thumb') {
3589: &add_filetype($allfiles,$value,$key);
3590: } elsif ($key eq 'content') {
3591: my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
3592: my ($ext) = ($value =~ /\.([^.]+)$/);
3593: if ($ext ne '') {
3594: &add_filetype($allfiles,$path.$value,$ext);
3595: }
3596: }
3597: }
3598: }
3599: }
1.637 raeburn 3600: return 'ok';
3601: }
3602:
1.639 albertel 3603: sub add_filetype {
3604: my ($allfiles,$file,$type)=@_;
3605: if (exists($allfiles->{$file})) {
3606: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
3607: push(@{$allfiles->{$file}}, &escape($type));
3608: }
3609: } else {
3610: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 3611: }
3612: }
3613:
1.1164 raeburn 3614: sub embedded_dependency {
3615: my ($allfiles,$related,$identifier,$pathfrom) = @_;
3616: if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
3617: if (($identifier ne '') &&
3618: (ref($related->{$identifier}) eq 'ARRAY') &&
3619: ($pathfrom ne '')) {
3620: my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
3621: foreach my $dep (@{$related->{$identifier}}) {
3622: &add_filetype($allfiles,$path.$dep,'object');
3623: }
3624: }
3625: }
3626: return;
3627: }
3628:
1.493 albertel 3629: sub removeuploadedurl {
1.984 neumanie 3630: my ($url)=@_;
3631: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 3632: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 3633: }
3634:
3635: sub removeuserfile {
3636: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 3637: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3638: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 3639: if ($result eq 'ok') {
1.798 raeburn 3640: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
3641: my $metafile = $fname.'.meta';
3642: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 3643: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 3644: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3645: my $sqlresult =
1.823 albertel 3646: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3647: 'portfolio_metadata',$group,
3648: 'delete');
1.798 raeburn 3649: }
3650: }
3651: return $result;
1.257 www 3652: }
1.15 www 3653:
1.530 albertel 3654: sub mkdiruserfile {
3655: my ($docuname,$docudom,$dir)=@_;
3656: my $home=&homeserver($docuname,$docudom);
3657: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
3658: }
3659:
1.531 albertel 3660: sub renameuserfile {
3661: my ($docuname,$docudom,$old,$new)=@_;
3662: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3663: my $result = &reply("renameuserfile:$docudom:$docuname:".
3664: &escape("$old").':'.&escape("$new"),$home);
3665: if ($result eq 'ok') {
3666: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
3667: my $oldmeta = $old.'.meta';
3668: my $newmeta = $new.'.meta';
3669: my $metaresult =
3670: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 3671: my $url = "/uploaded/$docudom/$docuname/$old";
3672: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3673: my $sqlresult =
1.823 albertel 3674: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3675: 'portfolio_metadata',$group,
3676: 'delete');
1.798 raeburn 3677: }
3678: }
3679: return $result;
1.531 albertel 3680: }
3681:
1.14 www 3682: # ------------------------------------------------------------------------- Log
3683:
3684: sub log {
3685: my ($dom,$nam,$hom,$what)=@_;
1.47 www 3686: return critical("log:$dom:$nam:$what",$hom);
1.157 www 3687: }
3688:
3689: # ------------------------------------------------------------------ Course Log
1.352 www 3690: #
3691: # This routine flushes several buffers of non-mission-critical nature
3692: #
1.157 www 3693:
3694: sub flushcourselogs {
1.352 www 3695: &logthis('Flushing log buffers');
3696: #
3697: # course logs
3698: # This is a log of all transactions in a course, which can be used
3699: # for data mining purposes
3700: #
3701: # It also collects the courseid database, which lists last transaction
3702: # times and course titles for all courseids
3703: #
3704: my %courseidbuffer=();
1.921 raeburn 3705: foreach my $crsid (keys(%courselogs)) {
1.352 www 3706: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 3707: &escape($courselogs{$crsid}),
3708: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 3709: delete $courselogs{$crsid};
3710: } else {
3711: &logthis('Failed to flush log buffer for '.$crsid);
3712: if (length($courselogs{$crsid})>40000) {
1.672 albertel 3713: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 3714: " exceeded maximum size, deleting.</font>");
3715: delete $courselogs{$crsid};
3716: }
1.352 www 3717: }
1.920 raeburn 3718: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 3719: 'description' => $coursedescrbuf{$crsid},
3720: 'inst_code' => $courseinstcodebuf{$crsid},
3721: 'type' => $coursetypebuf{$crsid},
3722: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 3723: };
1.191 harris41 3724: }
1.352 www 3725: #
3726: # Write course id database (reverse lookup) to homeserver of courses
3727: # Is used in pickcourse
3728: #
1.840 albertel 3729: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 3730: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 3731: $courseidbuffer{$crs_home},
3732: $crs_home,'timeonly');
1.352 www 3733: }
3734: #
3735: # File accesses
3736: # Writes to the dynamic metadata of resources to get hit counts, etc.
3737: #
1.449 matthew 3738: foreach my $entry (keys(%accesshash)) {
1.458 matthew 3739: if ($entry =~ /___count$/) {
3740: my ($dom,$name);
1.807 albertel 3741: ($dom,$name,undef)=
1.811 albertel 3742: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 3743: if (! defined($dom) || $dom eq '' ||
3744: ! defined($name) || $name eq '') {
1.620 albertel 3745: my $cid = $env{'request.course.id'};
3746: $dom = $env{'request.'.$cid.'.domain'};
3747: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 3748: }
1.450 matthew 3749: my $value = $accesshash{$entry};
3750: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
3751: my %temphash=($url => $value);
1.449 matthew 3752: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
3753: if ($result eq 'ok') {
3754: delete $accesshash{$entry};
3755: }
3756: } else {
1.811 albertel 3757: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159 www 3758: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450 matthew 3759: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 3760: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
3761: delete $accesshash{$entry};
3762: }
1.185 www 3763: }
1.191 harris41 3764: }
1.352 www 3765: #
3766: # Roles
3767: # Reverse lookup of user roles for course faculty/staff and co-authorship
3768: #
1.800 albertel 3769: foreach my $entry (keys(%userrolehash)) {
1.351 www 3770: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 3771: split(/\:/,$entry);
3772: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 3773: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 3774: $rudom,$runame) eq 'ok') {
3775: delete $userrolehash{$entry};
3776: }
3777: }
1.662 raeburn 3778: #
3779: # Reverse lookup of domain roles (dc, ad, li, sc, au)
3780: #
3781: my %domrolebuffer = ();
1.1000 raeburn 3782: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 3783: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 3784: if ($domrolebuffer{$rudom}) {
3785: $domrolebuffer{$rudom}.='&'.&escape($entry).
3786: '='.&escape($domainrolehash{$entry});
3787: } else {
3788: $domrolebuffer{$rudom}.=&escape($entry).
3789: '='.&escape($domainrolehash{$entry});
3790: }
3791: delete $domainrolehash{$entry};
3792: }
3793: foreach my $dom (keys(%domrolebuffer)) {
1.841 albertel 3794: my %servers = &get_servers($dom,'library');
3795: foreach my $tryserver (keys(%servers)) {
3796: unless (&reply('domroleput:'.$dom.':'.
3797: $domrolebuffer{$dom},$tryserver) eq 'ok') {
3798: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
3799: }
1.662 raeburn 3800: }
3801: }
1.186 www 3802: $dumpcount++;
1.157 www 3803: }
3804:
3805: sub courselog {
3806: my $what=shift;
1.158 www 3807: $what=time.':'.$what;
1.620 albertel 3808: unless ($env{'request.course.id'}) { return ''; }
3809: $coursedombuf{$env{'request.course.id'}}=
3810: $env{'course.'.$env{'request.course.id'}.'.domain'};
3811: $coursenumbuf{$env{'request.course.id'}}=
3812: $env{'course.'.$env{'request.course.id'}.'.num'};
3813: $coursehombuf{$env{'request.course.id'}}=
3814: $env{'course.'.$env{'request.course.id'}.'.home'};
3815: $coursedescrbuf{$env{'request.course.id'}}=
3816: $env{'course.'.$env{'request.course.id'}.'.description'};
3817: $courseinstcodebuf{$env{'request.course.id'}}=
3818: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
3819: $courseownerbuf{$env{'request.course.id'}}=
3820: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 3821: $coursetypebuf{$env{'request.course.id'}}=
3822: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 3823: if (defined $courselogs{$env{'request.course.id'}}) {
3824: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 3825: } else {
1.620 albertel 3826: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 3827: }
1.620 albertel 3828: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 3829: &flushcourselogs();
3830: }
1.158 www 3831: }
3832:
3833: sub courseacclog {
3834: my $fnsymb=shift;
1.620 albertel 3835: unless ($env{'request.course.id'}) { return ''; }
3836: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144 www 3837: if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187 www 3838: $what.=':POST';
1.583 matthew 3839: # FIXME: Probably ought to escape things....
1.800 albertel 3840: foreach my $key (keys(%env)) {
3841: if ($key=~/^form\.(.*)/) {
1.975 raeburn 3842: my $formitem = $1;
3843: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
3844: $what.=':'.$formitem.'='.$env{$key};
3845: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
3846: $what.=':'.$formitem.'='.$env{$key};
3847: }
1.158 www 3848: }
1.191 harris41 3849: }
1.583 matthew 3850: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
3851: # FIXME: We should not be depending on a form parameter that someone
3852: # editing lonsearchcat.pm might change in the future.
1.620 albertel 3853: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 3854: $what.= ':POST';
3855: # FIXME: Probably ought to escape things....
3856: foreach my $element ('courseexp','crsfulltext','crsrelated',
3857: 'crsdiscuss') {
1.620 albertel 3858: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 3859: }
3860: }
1.158 www 3861: }
3862: &courselog($what);
1.149 www 3863: }
3864:
1.185 www 3865: sub countacc {
3866: my $url=&declutter(shift);
1.458 matthew 3867: return if (! defined($url) || $url eq '');
1.620 albertel 3868: unless ($env{'request.course.id'}) { return ''; }
1.1158 www 3869: #
3870: # Mark that this url was used in this course
3871: #
1.620 albertel 3872: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158 www 3873: #
3874: # Increase the access count for this resource in this child process
3875: #
1.281 www 3876: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 3877: $accesshash{$key}++;
1.185 www 3878: }
1.349 www 3879:
1.361 www 3880: sub linklog {
3881: my ($from,$to)=@_;
3882: $from=&declutter($from);
3883: $to=&declutter($to);
3884: $accesshash{$from.'___'.$to.'___comefrom'}=1;
3885: $accesshash{$to.'___'.$from.'___goto'}=1;
3886: }
1.1160 www 3887:
3888: sub statslog {
3889: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
3890: if ($users<2) { return; }
3891: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
3892: 'course' => $env{'request.course.id'},
3893: 'sections' => '"all"',
3894: 'num_students' => $users,
3895: 'part' => $part,
3896: 'symb' => $symb,
3897: 'mean_tries' => $av_attempts,
3898: 'deg_of_diff' => $degdiff});
3899: foreach my $key (keys(%dynstore)) {
3900: $accesshash{$key}=$dynstore{$key};
3901: }
3902: }
1.361 www 3903:
1.349 www 3904: sub userrolelog {
3905: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169 droeschl 3906: if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350 www 3907: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3908: $userrolehash
3909: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 3910: =$tend.':'.$tstart;
1.662 raeburn 3911: }
1.1169 droeschl 3912: if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898 albertel 3913: $userrolehash
3914: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
3915: =$tend.':'.$tstart;
3916: }
1.1169 droeschl 3917: if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
1.662 raeburn 3918: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3919: $domainrolehash
3920: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
3921: = $tend.':'.$tstart;
3922: }
1.351 www 3923: }
3924:
1.957 raeburn 3925: sub courserolelog {
3926: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1184 raeburn 3927: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
3928: my $cdom = $1;
3929: my $cnum = $2;
3930: my $sec = $3;
3931: my $namespace = 'rolelog';
3932: my %storehash = (
3933: role => $trole,
3934: start => $tstart,
3935: end => $tend,
3936: selfenroll => $selfenroll,
3937: context => $context,
3938: );
3939: if ($trole eq 'gr') {
3940: $namespace = 'groupslog';
3941: $storehash{'group'} = $sec;
3942: } else {
3943: $storehash{'section'} = $sec;
3944: }
1.1188 raeburn 3945: &write_log('course',$namespace,\%storehash,$delflag,$username,
3946: $domain,$cnum,$cdom);
1.1184 raeburn 3947: if (($trole ne 'st') || ($sec ne '')) {
3948: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957 raeburn 3949: }
3950: }
3951: return;
3952: }
3953:
1.1184 raeburn 3954: sub domainrolelog {
3955: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
3956: if ($area =~ m{^/($match_domain)/$}) {
3957: my $cdom = $1;
3958: my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
3959: my $namespace = 'rolelog';
3960: my %storehash = (
3961: role => $trole,
3962: start => $tstart,
3963: end => $tend,
3964: context => $context,
3965: );
1.1188 raeburn 3966: &write_log('domain',$namespace,\%storehash,$delflag,$username,
3967: $domain,$domconfiguser,$cdom);
1.1184 raeburn 3968: }
3969: return;
3970:
3971: }
3972:
3973: sub coauthorrolelog {
3974: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
3975: if ($area =~ m{^/($match_domain)/($match_username)$}) {
3976: my $audom = $1;
3977: my $auname = $2;
3978: my $namespace = 'rolelog';
3979: my %storehash = (
3980: role => $trole,
3981: start => $tstart,
3982: end => $tend,
3983: context => $context,
3984: );
1.1188 raeburn 3985: &write_log('author',$namespace,\%storehash,$delflag,$username,
3986: $domain,$auname,$audom);
1.1184 raeburn 3987: }
3988: return;
3989: }
3990:
1.351 www 3991: sub get_course_adv_roles {
1.948 raeburn 3992: my ($cid,$codes) = @_;
1.620 albertel 3993: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 3994: my %coursehash=&coursedescription($cid);
1.988 raeburn 3995: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 3996: my %nothide=();
1.800 albertel 3997: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 3998: if ($user !~ /:/) {
3999: $nothide{join(':',split(/[\@]/,$user))}=1;
4000: } else {
4001: $nothide{$user}=1;
4002: }
1.470 www 4003: }
1.1219 raeburn 4004: my @possdoms = ($coursehash{'domain'});
4005: if ($coursehash{'checkforpriv'}) {
4006: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
4007: }
1.351 www 4008: my %returnhash=();
4009: my %dumphash=
4010: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
4011: my $now=time;
1.997 raeburn 4012: my %privileged;
1.1000 raeburn 4013: foreach my $entry (keys(%dumphash)) {
1.800 albertel 4014: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 4015: if (($tstart) && ($tstart<0)) { next; }
4016: if (($tend) && ($tend<$now)) { next; }
4017: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 4018: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 4019: if ($username eq '' || $domain eq '') { next; }
1.1219 raeburn 4020: if ((&privileged($username,$domain,\@possdoms)) &&
1.997 raeburn 4021: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 4022: if ($role eq 'cr') { next; }
1.948 raeburn 4023: if ($codes) {
4024: if ($section) { $role .= ':'.$section; }
4025: if ($returnhash{$role}) {
4026: $returnhash{$role}.=','.$username.':'.$domain;
4027: } else {
4028: $returnhash{$role}=$username.':'.$domain;
4029: }
1.351 www 4030: } else {
1.988 raeburn 4031: my $key=&plaintext($role,$crstype);
1.973 bisitz 4032: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 4033: if ($returnhash{$key}) {
4034: $returnhash{$key}.=','.$username.':'.$domain;
4035: } else {
4036: $returnhash{$key}=$username.':'.$domain;
4037: }
1.351 www 4038: }
1.948 raeburn 4039: }
1.400 www 4040: return %returnhash;
4041: }
4042:
4043: sub get_my_roles {
1.937 raeburn 4044: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 4045: unless (defined($uname)) { $uname=$env{'user.name'}; }
4046: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 4047: my (%dumphash,%nothide);
1.1086 raeburn 4048: if ($context eq 'userroles') {
1.1166 raeburn 4049: %dumphash = &dump('roles',$udom,$uname);
1.858 raeburn 4050: } else {
1.1219 raeburn 4051: %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 4052: if ($hidepriv) {
4053: my %coursehash=&coursedescription($udom.'_'.$uname);
4054: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
4055: if ($user !~ /:/) {
4056: $nothide{join(':',split(/[\@]/,$user))} = 1;
4057: } else {
4058: $nothide{$user} = 1;
4059: }
4060: }
4061: }
1.858 raeburn 4062: }
1.400 www 4063: my %returnhash=();
4064: my $now=time;
1.999 raeburn 4065: my %privileged;
1.800 albertel 4066: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 4067: my ($role,$tend,$tstart);
4068: if ($context eq 'userroles') {
1.1149 raeburn 4069: next if ($entry =~ /^rolesdef/);
1.867 raeburn 4070: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
4071: } else {
4072: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
4073: }
1.400 www 4074: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 4075: my $status = 'active';
1.939 raeburn 4076: if (($tend) && ($tend<=$now)) {
1.832 raeburn 4077: $status = 'previous';
4078: }
4079: if (($tstart) && ($now<$tstart)) {
4080: $status = 'future';
4081: }
4082: if (ref($types) eq 'ARRAY') {
4083: if (!grep(/^\Q$status\E$/,@{$types})) {
4084: next;
4085: }
4086: } else {
4087: if ($status ne 'active') {
4088: next;
4089: }
4090: }
1.867 raeburn 4091: my ($rolecode,$username,$domain,$section,$area);
4092: if ($context eq 'userroles') {
1.1186 raeburn 4093: ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867 raeburn 4094: (undef,$domain,$username,$section) = split(/\//,$area);
4095: } else {
4096: ($role,$username,$domain,$section) = split(/\:/,$entry);
4097: }
1.832 raeburn 4098: if (ref($roledoms) eq 'ARRAY') {
4099: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
4100: next;
4101: }
4102: }
4103: if (ref($roles) eq 'ARRAY') {
4104: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 4105: if ($role =~ /^cr\//) {
4106: if (!grep(/^cr$/,@{$roles})) {
4107: next;
4108: }
1.1104 raeburn 4109: } elsif ($role =~ /^gr\//) {
4110: if (!grep(/^gr$/,@{$roles})) {
4111: next;
4112: }
1.922 raeburn 4113: } else {
4114: next;
4115: }
1.832 raeburn 4116: }
1.867 raeburn 4117: }
1.937 raeburn 4118: if ($hidepriv) {
1.1219 raeburn 4119: my @privroles = ('dc','su');
1.999 raeburn 4120: if ($context eq 'userroles') {
1.1219 raeburn 4121: next if (grep(/^\Q$role\E$/,@privroles));
1.999 raeburn 4122: } else {
1.1219 raeburn 4123: my $possdoms = [$domain];
4124: if (ref($roledoms) eq 'ARRAY') {
4125: push(@{$possdoms},@{$roledoms});
1.999 raeburn 4126: }
1.1219 raeburn 4127: if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999 raeburn 4128: if (!$nothide{$username.':'.$domain}) {
4129: next;
4130: }
4131: }
1.937 raeburn 4132: }
4133: }
1.933 raeburn 4134: if ($withsec) {
4135: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
4136: $tstart.':'.$tend;
4137: } else {
4138: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
4139: }
1.832 raeburn 4140: }
1.373 www 4141: return %returnhash;
1.399 www 4142: }
4143:
4144: # ----------------------------------------------------- Frontpage Announcements
4145: #
4146: #
4147:
4148: sub postannounce {
4149: my ($server,$text)=@_;
1.844 albertel 4150: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 4151: unless ($text=~/\w/) { $text=''; }
4152: return &reply('setannounce:'.&escape($text),$server);
4153: }
4154:
4155: sub getannounce {
1.448 albertel 4156:
4157: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 4158: my $announcement='';
1.800 albertel 4159: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 4160: close($fh);
1.399 www 4161: if ($announcement=~/\w/) {
4162: return
4163: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 4164: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 4165: } else {
4166: return '';
4167: }
4168: } else {
4169: return '';
4170: }
1.351 www 4171: }
1.353 www 4172:
4173: # ---------------------------------------------------------- Course ID routines
4174: # Deal with domain's nohist_courseid.db files
4175: #
4176:
4177: sub courseidput {
1.921 raeburn 4178: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 4179: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 4180: my $outcome;
4181: if ($caller eq 'timeonly') {
4182: my $cids = '';
4183: foreach my $item (keys(%$storehash)) {
4184: $cids.=&escape($item).'&';
4185: }
4186: $cids=~s/\&$//;
4187: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
4188: $coursehome);
4189: } else {
4190: my $items = '';
4191: foreach my $item (keys(%$storehash)) {
4192: $items.= &escape($item).'='.
4193: &freeze_escape($$storehash{$item}).'&';
4194: }
4195: $items=~s/\&$//;
4196: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
4197: $coursehome);
1.918 raeburn 4198: }
4199: if ($outcome eq 'unknown_cmd') {
4200: my $what;
4201: foreach my $cid (keys(%$storehash)) {
4202: $what .= &escape($cid).'=';
1.921 raeburn 4203: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 4204: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 4205: }
4206: $what =~ s/\:$/&/;
4207: }
4208: $what =~ s/\&$//;
4209: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
4210: } else {
4211: return $outcome;
4212: }
1.353 www 4213: }
4214:
4215: sub courseiddump {
1.921 raeburn 4216: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 4217: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 4218: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1247 raeburn 4219: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
4220: $hasuniquecode)=@_;
1.918 raeburn 4221: my $as_hash = 1;
4222: my %returnhash;
4223: if (!$domfilter) { $domfilter=''; }
1.845 albertel 4224: my %libserv = &all_library();
4225: foreach my $tryserver (keys(%libserv)) {
4226: if ( ( $hostidflag == 1
4227: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
4228: || (!defined($hostidflag)) ) {
4229:
1.918 raeburn 4230: if (($domfilter eq '') ||
4231: (&host_domain($tryserver) eq $domfilter)) {
1.1180 droeschl 4232: my $rep;
4233: if (grep { $_ eq $tryserver } current_machine_ids()) {
4234: $rep = LONCAPA::Lond::dump_course_id_handler(
4235: join(":", (&host_domain($tryserver), $sincefilter,
4236: &escape($descfilter), &escape($instcodefilter),
4237: &escape($ownerfilter), &escape($coursefilter),
4238: &escape($typefilter), &escape($regexp_ok),
4239: $as_hash, &escape($selfenrollonly),
4240: &escape($catfilter), $showhidden, $caller,
4241: &escape($cloner), &escape($cc_clone), $cloneonly,
4242: &escape($createdbefore), &escape($createdafter),
1.1247 raeburn 4243: &escape($creationcontext), $domcloner, $hasuniquecode)));
1.1180 droeschl 4244: } else {
4245: $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
4246: $sincefilter.':'.&escape($descfilter).':'.
4247: &escape($instcodefilter).':'.&escape($ownerfilter).
4248: ':'.&escape($coursefilter).':'.&escape($typefilter).
4249: ':'.&escape($regexp_ok).':'.$as_hash.':'.
4250: &escape($selfenrollonly).':'.&escape($catfilter).':'.
4251: $showhidden.':'.$caller.':'.&escape($cloner).':'.
4252: &escape($cc_clone).':'.$cloneonly.':'.
4253: &escape($createdbefore).':'.&escape($createdafter).':'.
1.1247 raeburn 4254: &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode,
1.1180 droeschl 4255: $tryserver);
4256: }
4257:
1.918 raeburn 4258: my @pairs=split(/\&/,$rep);
4259: foreach my $item (@pairs) {
4260: my ($key,$value)=split(/\=/,$item,2);
4261: $key = &unescape($key);
4262: next if ($key =~ /^error: 2 /);
4263: my $result = &thaw_unescape($value);
4264: if (ref($result) eq 'HASH') {
4265: $returnhash{$key}=$result;
4266: } else {
1.921 raeburn 4267: my @responses = split(/:/,$value);
4268: my @items = ('description','inst_code','owner','type');
1.918 raeburn 4269: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 4270: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 4271: }
1.1008 raeburn 4272: }
1.353 www 4273: }
4274: }
4275: }
4276: }
4277: return %returnhash;
4278: }
4279:
1.1055 raeburn 4280: sub courselastaccess {
4281: my ($cdom,$cnum,$hostidref) = @_;
4282: my %returnhash;
4283: if ($cdom && $cnum) {
4284: my $chome = &homeserver($cnum,$cdom);
4285: if ($chome ne 'no_host') {
4286: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
4287: &extract_lastaccess(\%returnhash,$rep);
4288: }
4289: } else {
4290: if (!$cdom) { $cdom=''; }
4291: my %libserv = &all_library();
4292: foreach my $tryserver (keys(%libserv)) {
4293: if (ref($hostidref) eq 'ARRAY') {
4294: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
4295: }
4296: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
4297: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
4298: &extract_lastaccess(\%returnhash,$rep);
4299: }
4300: }
4301: }
4302: return %returnhash;
4303: }
4304:
4305: sub extract_lastaccess {
4306: my ($returnhash,$rep) = @_;
4307: if (ref($returnhash) eq 'HASH') {
4308: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
4309: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
4310: $rep eq '') {
4311: my @pairs=split(/\&/,$rep);
4312: foreach my $item (@pairs) {
4313: my ($key,$value)=split(/\=/,$item,2);
4314: $key = &unescape($key);
4315: next if ($key =~ /^error: 2 /);
4316: $returnhash->{$key} = &thaw_unescape($value);
4317: }
4318: }
4319: }
4320: return;
4321: }
4322:
1.658 raeburn 4323: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 4324:
4325: sub dcmailput {
1.685 raeburn 4326: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 4327: my $status = &Apache::lonnet::critical(
1.740 www 4328: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
4329: &escape($message),$server);
1.662 raeburn 4330: return $status;
4331: }
4332:
1.658 raeburn 4333: sub dcmaildump {
4334: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 4335: my %returnhash=();
1.846 albertel 4336:
4337: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 4338: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
4339: &escape($enddate).':';
4340: my @esc_senders=map { &escape($_)} @$senders;
4341: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 4342: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 4343: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 4344: if (($key) && ($value)) {
4345: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 4346: }
4347: }
4348: }
4349: return %returnhash;
4350: }
1.662 raeburn 4351: # ---------------------------------------------------------- Domain roles
4352:
4353: sub get_domain_roles {
4354: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 4355: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 4356: $startdate = '.';
4357: }
1.1018 raeburn 4358: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 4359: $enddate = '.';
4360: }
1.922 raeburn 4361: my $rolelist;
4362: if (ref($roles) eq 'ARRAY') {
1.1219 raeburn 4363: $rolelist = join('&',@{$roles});
1.922 raeburn 4364: }
1.662 raeburn 4365: my %personnel = ();
1.841 albertel 4366:
4367: my %servers = &get_servers($dom,'library');
4368: foreach my $tryserver (keys(%servers)) {
4369: %{$personnel{$tryserver}}=();
4370: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
4371: &escape($startdate).':'.
4372: &escape($enddate).':'.
4373: &escape($rolelist), $tryserver))) {
4374: my ($key,$value) = split(/\=/,$line,2);
4375: if (($key) && ($value)) {
4376: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
4377: }
4378: }
1.662 raeburn 4379: }
4380: return %personnel;
4381: }
1.658 raeburn 4382:
1.1057 www 4383: # ----------------------------------------------------------- Interval timing
1.149 www 4384:
1.1153 www 4385: {
4386: # Caches needed for speedup of navmaps
4387: # We don't want to cache this for very long at all (5 seconds at most)
4388: #
4389: # The user for whom we cache
4390: my $cachedkey='';
4391: # The cached times for this user
4392: my %cachedtimes=();
4393: # When this was last done
4394: my $cachedtime=();
4395:
4396: sub load_all_first_access {
1.1154 raeburn 4397: my ($uname,$udom)=@_;
1.1156 www 4398: if (($cachedkey eq $uname.':'.$udom) &&
1.1174 raeburn 4399: (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154 raeburn 4400: return;
4401: }
4402: $cachedtime=time;
4403: $cachedkey=$uname.':'.$udom;
4404: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153 www 4405: }
4406:
1.504 albertel 4407: sub get_first_access {
1.1162 raeburn 4408: my ($type,$argsymb,$argmap)=@_;
1.790 albertel 4409: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4410: if ($argsymb) { $symb=$argsymb; }
4411: my ($map,$id,$res)=&decode_symb($symb);
1.1162 raeburn 4412: if ($argmap) { $map = $argmap; }
1.926 albertel 4413: if ($type eq 'course') {
4414: $res='course';
4415: } elsif ($type eq 'map') {
1.588 albertel 4416: $res=&symbread($map);
4417: } else {
4418: $res=$symb;
4419: }
1.1153 www 4420: &load_all_first_access($uname,$udom);
4421: return $cachedtimes{"$courseid\0$res"};
1.504 albertel 4422: }
4423:
4424: sub set_first_access {
1.1162 raeburn 4425: my ($type,$interval)=@_;
1.790 albertel 4426: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4427: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 4428: if ($type eq 'course') {
4429: $res='course';
4430: } elsif ($type eq 'map') {
1.588 albertel 4431: $res=&symbread($map);
4432: } else {
4433: $res=$symb;
4434: }
1.1153 www 4435: $cachedkey='';
1.1162 raeburn 4436: my $firstaccess=&get_first_access($type,$symb,$map);
1.505 albertel 4437: if (!$firstaccess) {
1.1162 raeburn 4438: my $start = time;
4439: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
4440: $udom,$uname);
4441: if ($putres eq 'ok') {
4442: &put('timerinterval',{"$courseid\0$res"=>$interval},
4443: $udom,$uname);
4444: &appenv(
4445: {
4446: 'course.'.$courseid.'.firstaccess.'.$res => $start,
4447: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
4448: }
4449: );
4450: }
4451: return $putres;
1.505 albertel 4452: }
4453: return 'already_set';
1.504 albertel 4454: }
1.1153 www 4455: }
1.110 www 4456: # --------------------------------------------- Set Expire Date for Spreadsheet
4457:
4458: sub expirespread {
4459: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 4460: my $cid=$env{'request.course.id'};
1.110 www 4461: if ($cid) {
4462: my $now=time;
4463: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 4464: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
4465: $env{'course.'.$cid.'.num'}.
1.110 www 4466: ':nohist_expirationdates:'.
4467: &escape($key).'='.$now,
1.620 albertel 4468: $env{'course.'.$cid.'.home'})
1.110 www 4469: }
4470: return 'ok';
1.14 www 4471: }
4472:
1.109 www 4473: # ----------------------------------------------------- Devalidate Spreadsheets
4474:
4475: sub devalidate {
1.325 www 4476: my ($symb,$uname,$udom)=@_;
1.620 albertel 4477: my $cid=$env{'request.course.id'};
1.109 www 4478: if ($cid) {
1.391 matthew 4479: # delete the stored spreadsheets for
4480: # - the student level sheet of this user in course's homespace
4481: # - the assessment level sheet for this resource
4482: # for this user in user's homespace
1.553 albertel 4483: # - current conditional state info
1.325 www 4484: my $key=$uname.':'.$udom.':';
1.109 www 4485: my $status=
1.299 matthew 4486: &del('nohist_calculatedsheets',
1.391 matthew 4487: [$key.'studentcalc:'],
1.620 albertel 4488: $env{'course.'.$cid.'.domain'},
4489: $env{'course.'.$cid.'.num'})
1.133 albertel 4490: .' '.
4491: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 4492: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 4493: unless ($status eq 'ok ok') {
4494: &logthis('Could not devalidate spreadsheet '.
1.325 www 4495: $uname.' at '.$udom.' for '.
1.109 www 4496: $symb.': '.$status);
1.133 albertel 4497: }
1.553 albertel 4498: &delenv('user.state.'.$cid);
1.109 www 4499: }
4500: }
4501:
1.265 albertel 4502: sub get_scalar {
4503: my ($string,$end) = @_;
4504: my $value;
4505: if ($$string =~ s/^([^&]*?)($end)/$2/) {
4506: $value = $1;
4507: } elsif ($$string =~ s/^([^&]*?)&//) {
4508: $value = $1;
4509: }
4510: return &unescape($value);
4511: }
4512:
4513: sub array2str {
4514: my (@array) = @_;
4515: my $result=&arrayref2str(\@array);
4516: $result=~s/^__ARRAY_REF__//;
4517: $result=~s/__END_ARRAY_REF__$//;
4518: return $result;
4519: }
4520:
1.204 albertel 4521: sub arrayref2str {
4522: my ($arrayref) = @_;
1.265 albertel 4523: my $result='__ARRAY_REF__';
1.204 albertel 4524: foreach my $elem (@$arrayref) {
1.265 albertel 4525: if(ref($elem) eq 'ARRAY') {
4526: $result.=&arrayref2str($elem).'&';
4527: } elsif(ref($elem) eq 'HASH') {
4528: $result.=&hashref2str($elem).'&';
4529: } elsif(ref($elem)) {
4530: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 4531: } else {
4532: $result.=&escape($elem).'&';
4533: }
4534: }
4535: $result=~s/\&$//;
1.265 albertel 4536: $result .= '__END_ARRAY_REF__';
1.204 albertel 4537: return $result;
4538: }
4539:
1.168 albertel 4540: sub hash2str {
1.204 albertel 4541: my (%hash) = @_;
4542: my $result=&hashref2str(\%hash);
1.265 albertel 4543: $result=~s/^__HASH_REF__//;
4544: $result=~s/__END_HASH_REF__$//;
1.204 albertel 4545: return $result;
4546: }
4547:
4548: sub hashref2str {
4549: my ($hashref)=@_;
1.265 albertel 4550: my $result='__HASH_REF__';
1.800 albertel 4551: foreach my $key (sort(keys(%$hashref))) {
4552: if (ref($key) eq 'ARRAY') {
4553: $result.=&arrayref2str($key).'=';
4554: } elsif (ref($key) eq 'HASH') {
4555: $result.=&hashref2str($key).'=';
4556: } elsif (ref($key)) {
1.265 albertel 4557: $result.='=';
1.800 albertel 4558: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 4559: } else {
1.1132 raeburn 4560: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 4561: }
4562:
1.800 albertel 4563: if(ref($hashref->{$key}) eq 'ARRAY') {
4564: $result.=&arrayref2str($hashref->{$key}).'&';
4565: } elsif(ref($hashref->{$key}) eq 'HASH') {
4566: $result.=&hashref2str($hashref->{$key}).'&';
4567: } elsif(ref($hashref->{$key})) {
1.265 albertel 4568: $result.='&';
1.800 albertel 4569: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 4570: } else {
1.800 albertel 4571: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 4572: }
4573: }
1.168 albertel 4574: $result=~s/\&$//;
1.265 albertel 4575: $result .= '__END_HASH_REF__';
1.168 albertel 4576: return $result;
4577: }
4578:
4579: sub str2hash {
1.265 albertel 4580: my ($string)=@_;
4581: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
4582: return %$hash;
4583: }
4584:
4585: sub str2hashref {
1.168 albertel 4586: my ($string) = @_;
1.265 albertel 4587:
4588: my %hash;
4589:
4590: if($string !~ /^__HASH_REF__/) {
4591: if (! ($string eq '' || !defined($string))) {
4592: $hash{'error'}='Not hash reference';
4593: }
4594: return (\%hash, $string);
4595: }
4596:
4597: $string =~ s/^__HASH_REF__//;
4598:
4599: while($string !~ /^__END_HASH_REF__/) {
4600: #key
4601: my $key='';
4602: if($string =~ /^__HASH_REF__/) {
4603: ($key, $string)=&str2hashref($string);
4604: if(defined($key->{'error'})) {
4605: $hash{'error'}='Bad data';
4606: return (\%hash, $string);
4607: }
4608: } elsif($string =~ /^__ARRAY_REF__/) {
4609: ($key, $string)=&str2arrayref($string);
4610: if($key->[0] eq 'Array reference error') {
4611: $hash{'error'}='Bad data';
4612: return (\%hash, $string);
4613: }
4614: } else {
4615: $string =~ s/^(.*?)=//;
1.267 albertel 4616: $key=&unescape($1);
1.265 albertel 4617: }
4618: $string =~ s/^=//;
4619:
4620: #value
4621: my $value='';
4622: if($string =~ /^__HASH_REF__/) {
4623: ($value, $string)=&str2hashref($string);
4624: if(defined($value->{'error'})) {
4625: $hash{'error'}='Bad data';
4626: return (\%hash, $string);
4627: }
4628: } elsif($string =~ /^__ARRAY_REF__/) {
4629: ($value, $string)=&str2arrayref($string);
4630: if($value->[0] eq 'Array reference error') {
4631: $hash{'error'}='Bad data';
4632: return (\%hash, $string);
4633: }
4634: } else {
4635: $value=&get_scalar(\$string,'__END_HASH_REF__');
4636: }
4637: $string =~ s/^&//;
4638:
4639: $hash{$key}=$value;
1.204 albertel 4640: }
1.265 albertel 4641:
4642: $string =~ s/^__END_HASH_REF__//;
4643:
4644: return (\%hash, $string);
1.204 albertel 4645: }
4646:
4647: sub str2array {
1.265 albertel 4648: my ($string)=@_;
4649: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
4650: return @$array;
4651: }
4652:
4653: sub str2arrayref {
1.204 albertel 4654: my ($string) = @_;
1.265 albertel 4655: my @array;
4656:
4657: if($string !~ /^__ARRAY_REF__/) {
4658: if (! ($string eq '' || !defined($string))) {
4659: $array[0]='Array reference error';
4660: }
4661: return (\@array, $string);
4662: }
4663:
4664: $string =~ s/^__ARRAY_REF__//;
4665:
4666: while($string !~ /^__END_ARRAY_REF__/) {
4667: my $value='';
4668: if($string =~ /^__HASH_REF__/) {
4669: ($value, $string)=&str2hashref($string);
4670: if(defined($value->{'error'})) {
4671: $array[0] ='Array reference error';
4672: return (\@array, $string);
4673: }
4674: } elsif($string =~ /^__ARRAY_REF__/) {
4675: ($value, $string)=&str2arrayref($string);
4676: if($value->[0] eq 'Array reference error') {
4677: $array[0] ='Array reference error';
4678: return (\@array, $string);
4679: }
4680: } else {
4681: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
4682: }
4683: $string =~ s/^&//;
4684:
4685: push(@array, $value);
1.191 harris41 4686: }
1.265 albertel 4687:
4688: $string =~ s/^__END_ARRAY_REF__//;
4689:
4690: return (\@array, $string);
1.168 albertel 4691: }
4692:
1.167 albertel 4693: # -------------------------------------------------------------------Temp Store
4694:
1.168 albertel 4695: sub tmpreset {
4696: my ($symb,$namespace,$domain,$stuname) = @_;
4697: if (!$symb) {
4698: $symb=&symbread();
1.620 albertel 4699: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4700: }
4701: $symb=escape($symb);
4702:
1.620 albertel 4703: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 4704: $namespace=~s/\//\_/g;
4705: $namespace=~s/\W//g;
4706:
1.620 albertel 4707: if (!$domain) { $domain=$env{'user.domain'}; }
4708: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4709: if ($domain eq 'public' && $stuname eq 'public') {
4710: $stuname=$ENV{'REMOTE_ADDR'};
4711: }
1.1117 foxr 4712: my $path=LONCAPA::tempdir();
1.168 albertel 4713: my %hash;
4714: if (tie(%hash,'GDBM_File',
4715: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4716: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 4717: foreach my $key (keys(%hash)) {
1.180 albertel 4718: if ($key=~ /:$symb/) {
1.168 albertel 4719: delete($hash{$key});
4720: }
4721: }
4722: }
4723: }
4724:
1.167 albertel 4725: sub tmpstore {
1.168 albertel 4726: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4727:
4728: if (!$symb) {
4729: $symb=&symbread();
1.620 albertel 4730: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4731: }
4732: $symb=escape($symb);
4733:
4734: if (!$namespace) {
4735: # I don't think we would ever want to store this for a course.
4736: # it seems this will only be used if we don't have a course.
1.620 albertel 4737: #$namespace=$env{'request.course.id'};
1.168 albertel 4738: #if (!$namespace) {
1.620 albertel 4739: $namespace=$env{'request.state'};
1.168 albertel 4740: #}
4741: }
4742: $namespace=~s/\//\_/g;
4743: $namespace=~s/\W//g;
1.620 albertel 4744: if (!$domain) { $domain=$env{'user.domain'}; }
4745: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4746: if ($domain eq 'public' && $stuname eq 'public') {
4747: $stuname=$ENV{'REMOTE_ADDR'};
4748: }
1.168 albertel 4749: my $now=time;
4750: my %hash;
1.1117 foxr 4751: my $path=LONCAPA::tempdir();
1.168 albertel 4752: if (tie(%hash,'GDBM_File',
4753: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4754: &GDBM_WRCREAT(),0640)) {
1.168 albertel 4755: $hash{"version:$symb"}++;
4756: my $version=$hash{"version:$symb"};
4757: my $allkeys='';
4758: foreach my $key (keys(%$storehash)) {
4759: $allkeys.=$key.':';
1.591 albertel 4760: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 4761: }
4762: $hash{"$version:$symb:timestamp"}=$now;
4763: $allkeys.='timestamp';
4764: $hash{"$version:keys:$symb"}=$allkeys;
4765: if (untie(%hash)) {
4766: return 'ok';
4767: } else {
4768: return "error:$!";
4769: }
4770: } else {
4771: return "error:$!";
4772: }
4773: }
1.167 albertel 4774:
1.168 albertel 4775: # -----------------------------------------------------------------Temp Restore
1.167 albertel 4776:
1.168 albertel 4777: sub tmprestore {
4778: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 4779:
1.168 albertel 4780: if (!$symb) {
4781: $symb=&symbread();
1.620 albertel 4782: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4783: }
4784: $symb=escape($symb);
4785:
1.620 albertel 4786: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 4787:
1.620 albertel 4788: if (!$domain) { $domain=$env{'user.domain'}; }
4789: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4790: if ($domain eq 'public' && $stuname eq 'public') {
4791: $stuname=$ENV{'REMOTE_ADDR'};
4792: }
1.168 albertel 4793: my %returnhash;
4794: $namespace=~s/\//\_/g;
4795: $namespace=~s/\W//g;
4796: my %hash;
1.1117 foxr 4797: my $path=LONCAPA::tempdir();
1.168 albertel 4798: if (tie(%hash,'GDBM_File',
4799: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4800: &GDBM_READER(),0640)) {
1.168 albertel 4801: my $version=$hash{"version:$symb"};
4802: $returnhash{'version'}=$version;
4803: my $scope;
4804: for ($scope=1;$scope<=$version;$scope++) {
4805: my $vkeys=$hash{"$scope:keys:$symb"};
4806: my @keys=split(/:/,$vkeys);
4807: my $key;
4808: $returnhash{"$scope:keys"}=$vkeys;
4809: foreach $key (@keys) {
1.591 albertel 4810: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
4811: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 4812: }
4813: }
1.168 albertel 4814: if (!(untie(%hash))) {
4815: return "error:$!";
4816: }
4817: } else {
4818: return "error:$!";
4819: }
4820: return %returnhash;
1.167 albertel 4821: }
4822:
1.9 www 4823: # ----------------------------------------------------------------------- Store
4824:
4825: sub store {
1.124 www 4826: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4827: my $home='';
4828:
1.168 albertel 4829: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4830:
1.213 www 4831: $symb=&symbclean($symb);
1.122 albertel 4832: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 4833:
1.620 albertel 4834: if (!$domain) { $domain=$env{'user.domain'}; }
4835: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 4836:
4837: &devalidate($symb,$stuname,$domain);
1.109 www 4838:
4839: $symb=escape($symb);
1.187 www 4840: if (!$namespace) {
1.620 albertel 4841: unless ($namespace=$env{'request.course.id'}) {
1.187 www 4842: return '';
4843: }
4844: }
1.620 albertel 4845: if (!$home) { $home=$env{'user.home'}; }
1.447 www 4846:
4847: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4848: $$storehash{'host'}=$perlvar{'lonHostID'};
4849:
1.12 www 4850: my $namevalue='';
1.800 albertel 4851: foreach my $key (keys(%$storehash)) {
4852: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 4853: }
1.12 www 4854: $namevalue=~s/\&$//;
1.187 www 4855: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124 www 4856: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9 www 4857: }
4858:
1.47 www 4859: # -------------------------------------------------------------- Critical Store
4860:
4861: sub cstore {
1.124 www 4862: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4863: my $home='';
4864:
1.168 albertel 4865: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4866:
1.213 www 4867: $symb=&symbclean($symb);
1.122 albertel 4868: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 4869:
1.620 albertel 4870: if (!$domain) { $domain=$env{'user.domain'}; }
4871: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 4872:
4873: &devalidate($symb,$stuname,$domain);
1.109 www 4874:
4875: $symb=escape($symb);
1.187 www 4876: if (!$namespace) {
1.620 albertel 4877: unless ($namespace=$env{'request.course.id'}) {
1.187 www 4878: return '';
4879: }
4880: }
1.620 albertel 4881: if (!$home) { $home=$env{'user.home'}; }
1.447 www 4882:
4883: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4884: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 4885:
1.47 www 4886: my $namevalue='';
1.800 albertel 4887: foreach my $key (keys(%$storehash)) {
4888: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 4889: }
1.47 www 4890: $namevalue=~s/\&$//;
1.187 www 4891: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 4892: return critical
4893: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47 www 4894: }
4895:
1.9 www 4896: # --------------------------------------------------------------------- Restore
4897:
4898: sub restore {
1.124 www 4899: my ($symb,$namespace,$domain,$stuname) = @_;
4900: my $home='';
4901:
1.168 albertel 4902: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4903:
1.122 albertel 4904: if (!$symb) {
1.1224 raeburn 4905: return if ($namespace eq 'courserequests');
4906: unless ($symb=escape(&symbread())) { return ''; }
1.122 albertel 4907: } else {
1.1224 raeburn 4908: unless ($namespace eq 'courserequests') {
4909: $symb=&escape(&symbclean($symb));
4910: }
1.122 albertel 4911: }
1.188 www 4912: if (!$namespace) {
1.620 albertel 4913: unless ($namespace=$env{'request.course.id'}) {
1.188 www 4914: return '';
4915: }
4916: }
1.620 albertel 4917: if (!$domain) { $domain=$env{'user.domain'}; }
4918: if (!$stuname) { $stuname=$env{'user.name'}; }
4919: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 4920: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
4921:
1.12 www 4922: my %returnhash=();
1.800 albertel 4923: foreach my $line (split(/\&/,$answer)) {
4924: my ($name,$value)=split(/\=/,$line);
1.591 albertel 4925: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 4926: }
1.75 www 4927: my $version;
4928: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 4929: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
4930: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 4931: }
1.75 www 4932: }
1.13 www 4933: return %returnhash;
1.34 www 4934: }
4935:
4936: # ---------------------------------------------------------- Course Description
1.1118 foxr 4937: #
4938: #
1.34 www 4939:
4940: sub coursedescription {
1.731 albertel 4941: my ($courseid,$args)=@_;
1.34 www 4942: $courseid=~s/^\///;
1.49 www 4943: $courseid=~s/\_/\//g;
1.34 www 4944: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 4945: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 4946: my $normalid=$cdomain.'_'.$cnum;
4947: # need to always cache even if we get errors otherwise we keep
4948: # trying and trying and trying to get the course description.
4949: my %envhash=();
4950: my %returnhash=();
1.731 albertel 4951:
4952: my $expiretime=600;
4953: if ($env{'request.course.id'} eq $normalid) {
4954: $expiretime=120;
4955: }
4956:
4957: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
4958: if (!$args->{'freshen_cache'}
4959: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
4960: foreach my $key (keys(%env)) {
4961: next if ($key !~ /^\Q$prefix\E(.*)/);
4962: my ($setting) = $1;
4963: $returnhash{$setting} = $env{$key};
4964: }
4965: return %returnhash;
4966: }
4967:
1.1118 foxr 4968: # get the data again
4969:
1.731 albertel 4970: if (!$args->{'one_time'}) {
4971: $envhash{'course.'.$normalid.'.last_cache'}=time;
4972: }
1.811 albertel 4973:
1.34 www 4974: if ($chome ne 'no_host') {
1.302 albertel 4975: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 4976: if (!exists($returnhash{'con_lost'})) {
1.1118 foxr 4977: my $username = $env{'user.name'}; # Defult username
4978: if(defined $args->{'user'}) {
4979: $username = $args->{'user'};
4980: }
1.129 albertel 4981: $returnhash{'home'}= $chome;
4982: $returnhash{'domain'} = $cdomain;
4983: $returnhash{'num'} = $cnum;
1.741 raeburn 4984: if (!defined($returnhash{'type'})) {
4985: $returnhash{'type'} = 'Course';
4986: }
1.130 albertel 4987: while (my ($name,$value) = each %returnhash) {
1.53 www 4988: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 4989: }
1.270 www 4990: $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117 foxr 4991: $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118 foxr 4992: $username.'_'.$cdomain.'_'.$cnum;
1.60 www 4993: $envhash{'course.'.$normalid.'.home'}=$chome;
4994: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
4995: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 4996: }
4997: }
1.731 albertel 4998: if (!$args->{'one_time'}) {
1.949 raeburn 4999: &appenv(\%envhash);
1.731 albertel 5000: }
1.302 albertel 5001: return %returnhash;
1.461 www 5002: }
5003:
1.1080 raeburn 5004: sub update_released_required {
5005: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
5006: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
5007: $cid = $env{'request.course.id'};
5008: $cdom = $env{'course.'.$cid.'.domain'};
5009: $cnum = $env{'course.'.$cid.'.num'};
5010: $chome = $env{'course.'.$cid.'.home'};
5011: }
5012: if ($needsrelease) {
5013: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
5014: my $needsupdate;
5015: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
5016: $needsupdate = 1;
5017: } else {
5018: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
5019: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
5020: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
5021: $needsupdate = 1;
5022: }
5023: }
5024: if ($needsupdate) {
5025: my %needshash = (
5026: 'internal.releaserequired' => $needsrelease,
5027: );
5028: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
5029: if ($putresult eq 'ok') {
5030: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
5031: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
5032: if (ref($crsinfo{$cid}) eq 'HASH') {
5033: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
5034: &courseidput($cdom,\%crsinfo,$chome,'notime');
5035: }
5036: }
5037: }
5038: }
5039: return;
5040: }
5041:
1.461 www 5042: # -------------------------------------------------See if a user is privileged
5043:
5044: sub privileged {
1.1219 raeburn 5045: my ($username,$domain,$possdomains,$possroles)=@_;
1.1170 droeschl 5046: my $now = time;
1.1219 raeburn 5047: my $roles;
5048: if (ref($possroles) eq 'ARRAY') {
5049: $roles = $possroles;
5050: } else {
5051: $roles = ['dc','su'];
5052: }
5053: if (ref($possdomains) eq 'ARRAY') {
5054: my %privileged = &privileged_by_domain($possdomains,$roles);
5055: foreach my $dom (@{$possdomains}) {
5056: if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
5057: (ref($privileged{$dom}) eq 'HASH')) {
5058: foreach my $role (@{$roles}) {
5059: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5060: if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
5061: my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
5062: return 1 unless (($end && $end < $now) ||
5063: ($start && $start > $now));
5064: }
5065: }
5066: }
5067: }
5068: }
5069: } else {
5070: my %rolesdump = &dump("roles", $domain, $username) or return 0;
5071: my $now = time;
1.1170 droeschl 5072:
1.1219 raeburn 5073: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys %rolesdump}) {
1.1170 droeschl 5074: my ($trole, $tend, $tstart) = split(/_/, $role);
1.1219 raeburn 5075: if (grep(/^\Q$trole\E$/,@{$roles})) {
1.1170 droeschl 5076: return 1 unless ($tend && $tend < $now)
1.1219 raeburn 5077: or ($tstart && $tstart > $now);
1.1170 droeschl 5078: }
1.1219 raeburn 5079: }
5080: }
5081: return 0;
5082: }
1.1170 droeschl 5083:
1.1219 raeburn 5084: sub privileged_by_domain {
5085: my ($domains,$roles) = @_;
5086: my %privileged = ();
5087: my $cachetime = 60*60*24;
5088: my $now = time;
5089: unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
5090: return %privileged;
5091: }
5092: foreach my $dom (@{$domains}) {
5093: next if (ref($privileged{$dom}) eq 'HASH');
5094: my $needroles;
5095: foreach my $role (@{$roles}) {
5096: my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
5097: if (defined($cached)) {
5098: if (ref($result) eq 'HASH') {
5099: $privileged{$dom}{$role} = $result;
5100: }
5101: } else {
5102: $needroles = 1;
5103: }
5104: }
5105: if ($needroles) {
5106: my %dompersonnel = &get_domain_roles($dom,$roles);
5107: $privileged{$dom} = {};
5108: foreach my $server (keys(%dompersonnel)) {
5109: if (ref($dompersonnel{$server}) eq 'HASH') {
5110: foreach my $item (keys(%{$dompersonnel{$server}})) {
5111: my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
5112: my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
5113: next if ($end && $end < $now);
5114: $privileged{$dom}{$trole}{$uname.':'.$udom} =
5115: $dompersonnel{$server}{$item};
5116: }
5117: }
5118: }
5119: if (ref($privileged{$dom}) eq 'HASH') {
5120: foreach my $role (@{$roles}) {
5121: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5122: &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
5123: } else {
5124: my %hash = ();
5125: &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
5126: }
5127: }
5128: }
5129: }
5130: }
5131: return %privileged;
1.9 www 5132: }
1.1 albertel 5133:
1.103 harris41 5134: # -------------------------------------------------------- Get user privileges
1.11 www 5135:
5136: sub rolesinit {
1.1169 droeschl 5137: my ($domain, $username) = @_;
5138: my %userroles = ('user.login.time' => time);
5139: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
5140:
5141: # firstaccess and timerinterval are related to timed maps/resources.
5142: # also, blocking can be triggered by an activating timer
5143: # it's saved in the user's %env.
5144: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
5145: my %timerinterval = &dump('timerinterval', $domain, $username);
5146: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
5147: %timerintchk, %timerintenv);
5148:
1.1162 raeburn 5149: foreach my $key (keys(%firstaccess)) {
1.1169 droeschl 5150: my ($cid, $rest) = split(/\0/, $key);
1.1162 raeburn 5151: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
5152: }
1.1169 droeschl 5153:
1.1162 raeburn 5154: foreach my $key (keys(%timerinterval)) {
5155: my ($cid,$rest) = split(/\0/,$key);
5156: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
5157: }
1.1169 droeschl 5158:
1.11 www 5159: my %allroles=();
1.1162 raeburn 5160: my %allgroups=();
1.11 www 5161:
1.1169 droeschl 5162: for my $area (grep { ! /^rolesdef_/ } keys %rolesdump) {
5163: my $role = $rolesdump{$area};
5164: $area =~ s/\_\w\w$//;
5165:
5166: my ($trole, $tend, $tstart, $group_privs);
5167:
5168: if ($role =~ /^cr/) {
5169: # Custom role, defined by a user
5170: # e.g., user.role.cr/msu/smith/mynewrole
5171: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
5172: $trole = $1;
5173: ($tend, $tstart) = split('_', $2);
5174: } else {
5175: $trole = $role;
5176: }
5177: } elsif ($role =~ m|^gr/|) {
5178: # Role of member in a group, defined within a course/community
5179: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
5180: ($trole, $tend, $tstart) = split(/_/, $role);
5181: next if $tstart eq '-1';
5182: ($trole, $group_privs) = split(/\//, $trole);
5183: $group_privs = &unescape($group_privs);
5184: } else {
5185: # Just a normal role, defined in roles.tab
5186: ($trole, $tend, $tstart) = split(/_/,$role);
5187: }
5188:
5189: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
5190: $username);
5191: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
5192:
5193: # role expired or not available yet?
5194: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
5195: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
5196:
5197: next if $area eq '' or $trole eq '';
5198:
5199: my $spec = "$trole.$area";
5200: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
5201:
5202: if ($trole =~ /^cr\//) {
5203: # Custom role, defined by a user
5204: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5205: } elsif ($trole eq 'gr') {
5206: # Role of a member in a group, defined within a course/community
5207: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
5208: next;
5209: } else {
5210: # Normal role, defined in roles.tab
5211: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5212: }
5213:
5214: my $cid = $tdomain.'_'.$trest;
5215: unless ($firstaccchk{$cid}) {
5216: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
5217: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
5218: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
5219: $coursetimerstarts{$cid}{$item};
5220: }
5221: }
5222: $firstaccchk{$cid} = 1;
5223: }
5224: unless ($timerintchk{$cid}) {
5225: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
5226: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
5227: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
5228: $coursetimerintervals{$cid}{$item};
1.1162 raeburn 5229: }
1.12 www 5230: }
1.1169 droeschl 5231: $timerintchk{$cid} = 1;
1.191 harris41 5232: }
1.11 www 5233: }
1.1169 droeschl 5234:
5235: @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
5236: \%allroles, \%allgroups);
5237: $env{'user.adv'} = $userroles{'user.adv'};
5238:
1.1162 raeburn 5239: return (\%userroles,\%firstaccenv,\%timerintenv);
1.11 www 5240: }
5241:
1.567 raeburn 5242: sub set_arearole {
1.1215 raeburn 5243: my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
5244: unless ($nolog) {
1.567 raeburn 5245: # log the associated role with the area
1.1215 raeburn 5246: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
5247: }
1.743 albertel 5248: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 5249: }
5250:
5251: sub custom_roleprivs {
5252: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
5253: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1250 raeburn 5254: my $homsvr = &homeserver($rauthor,$rdomain);
1.838 albertel 5255: if (&hostname($homsvr) ne '') {
1.567 raeburn 5256: my ($rdummy,$roledef)=
5257: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
5258: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
5259: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
5260: if (defined($syspriv)) {
1.1043 raeburn 5261: if ($trest =~ /^$match_community$/) {
5262: $syspriv =~ s/bre\&S//;
5263: }
1.567 raeburn 5264: $$allroles{'cm./'}.=':'.$syspriv;
5265: $$allroles{$spec.'./'}.=':'.$syspriv;
5266: }
5267: if ($tdomain ne '') {
5268: if (defined($dompriv)) {
5269: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
5270: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
5271: }
5272: if (($trest ne '') && (defined($coursepriv))) {
5273: $$allroles{'cm.'.$area}.=':'.$coursepriv;
5274: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
5275: }
5276: }
5277: }
5278: }
5279: }
5280:
1.678 raeburn 5281: sub group_roleprivs {
5282: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
5283: my $access = 1;
5284: my $now = time;
5285: if (($tend!=0) && ($tend<$now)) { $access = 0; }
5286: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
5287: if ($access) {
1.811 albertel 5288: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 5289: $$allgroups{$course}{$group} .=':'.$group_privs;
5290: }
5291: }
1.567 raeburn 5292:
5293: sub standard_roleprivs {
5294: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
5295: if (defined($pr{$trole.':s'})) {
5296: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
5297: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
5298: }
5299: if ($tdomain ne '') {
5300: if (defined($pr{$trole.':d'})) {
5301: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5302: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5303: }
5304: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
5305: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
5306: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
5307: }
5308: }
5309: }
5310:
5311: sub set_userprivs {
1.1064 raeburn 5312: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 5313: my $author=0;
5314: my $adv=0;
1.678 raeburn 5315: my %grouproles = ();
5316: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 5317: my @groupkeys;
1.1000 raeburn 5318: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 5319: push(@groupkeys,$role);
5320: }
5321: if (ref($groups_roles) eq 'HASH') {
5322: foreach my $key (keys(%{$groups_roles})) {
5323: unless (grep(/^\Q$key\E$/,@groupkeys)) {
5324: push(@groupkeys,$key);
5325: }
5326: }
5327: }
5328: if (@groupkeys > 0) {
5329: foreach my $role (@groupkeys) {
5330: my ($trole,$area,$sec,$extendedarea);
5331: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
5332: $trole = $1;
5333: $area = $2;
5334: $sec = $3;
5335: $extendedarea = $area.$sec;
5336: if (exists($$allgroups{$area})) {
5337: foreach my $group (keys(%{$$allgroups{$area}})) {
5338: my $spec = $trole.'.'.$extendedarea;
5339: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 5340: $$allgroups{$area}{$group};
1.1064 raeburn 5341: }
1.678 raeburn 5342: }
5343: }
5344: }
5345: }
5346: }
1.800 albertel 5347: foreach my $group (keys(%grouproles)) {
5348: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 5349: }
1.800 albertel 5350: foreach my $role (keys(%{$allroles})) {
5351: my %thesepriv;
1.941 raeburn 5352: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 5353: foreach my $item (split(/:/,$$allroles{$role})) {
5354: if ($item ne '') {
5355: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 5356: if ($restrictions eq '') {
5357: $thesepriv{$privilege}='F';
5358: } elsif ($thesepriv{$privilege} ne 'F') {
5359: $thesepriv{$privilege}.=$restrictions;
5360: }
5361: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
5362: }
5363: }
5364: my $thesestr='';
1.1104 raeburn 5365: foreach my $priv (sort(keys(%thesepriv))) {
1.800 albertel 5366: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
5367: }
5368: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 5369: }
5370: return ($author,$adv);
5371: }
5372:
1.994 raeburn 5373: sub role_status {
1.1104 raeburn 5374: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 5375: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1250 raeburn 5376: my ($one,$two) = split(m{\./},$rolekey,2);
5377: (undef,undef,$$role) = split(/\./,$one,3);
1.994 raeburn 5378: unless (!defined($$role) || $$role eq '') {
1.1251 raeburn 5379: $$where = '/'.$two;
1.994 raeburn 5380: $$trolecode=$$role.'.'.$$where;
5381: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
5382: $$tstatus='is';
1.1104 raeburn 5383: if ($$tstart && $$tstart>$update) {
1.994 raeburn 5384: $$tstatus='future';
1.1034 raeburn 5385: if ($$tstart<$now) {
5386: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 5387: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 5388: my (%allroles,%allgroups,$group_privs,
5389: %groups_roles,@rolecodes);
1.1002 raeburn 5390: my %userroles = (
5391: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
5392: );
1.1064 raeburn 5393: @rolecodes = ('cm');
1.1002 raeburn 5394: my $spec=$$role.'.'.$$where;
5395: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
5396: if ($$role =~ /^cr\//) {
5397: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 5398: push(@rolecodes,'cr');
1.1002 raeburn 5399: } elsif ($$role eq 'gr') {
1.1064 raeburn 5400: push(@rolecodes,$$role);
1.1002 raeburn 5401: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
5402: $env{'user.name'});
1.1064 raeburn 5403: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 5404: (undef,my $group_privs) = split(/\//,$trole);
5405: $group_privs = &unescape($group_privs);
5406: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 5407: 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 5408: &get_groups_roles($tdomain,$trest,
5409: \%course_roles,\@rolecodes,
5410: \%groups_roles);
1.1002 raeburn 5411: } else {
1.1064 raeburn 5412: push(@rolecodes,$$role);
1.1002 raeburn 5413: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
5414: }
1.1064 raeburn 5415: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
5416: &appenv(\%userroles,\@rolecodes);
1.1002 raeburn 5417: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
5418: }
5419: }
1.1034 raeburn 5420: $$tstatus = 'is';
1.1002 raeburn 5421: }
1.994 raeburn 5422: }
5423: if ($$tend) {
1.1104 raeburn 5424: if ($$tend<$update) {
1.994 raeburn 5425: $$tstatus='expired';
5426: } elsif ($$tend<$now) {
5427: $$tstatus='will_not';
5428: }
5429: }
5430: }
5431: }
5432: }
5433:
1.1104 raeburn 5434: sub get_groups_roles {
5435: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
5436: return unless((ref($cdom_courseroles) eq 'HASH') &&
5437: (ref($rolecodes) eq 'ARRAY') &&
5438: (ref($groups_roles) eq 'HASH'));
5439: if (keys(%{$cdom_courseroles}) > 0) {
5440: my ($cnum) = ($rest =~ /^($match_courseid)/);
5441: if ($cdom ne '' && $cnum ne '') {
5442: foreach my $key (keys(%{$cdom_courseroles})) {
5443: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
5444: my $crsrole = $1;
5445: my $crssec = $2;
5446: if ($crsrole =~ /^cr/) {
5447: unless (grep(/^cr$/,@{$rolecodes})) {
5448: push(@{$rolecodes},'cr');
5449: }
5450: } else {
5451: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
5452: push(@{$rolecodes},$crsrole);
5453: }
5454: }
5455: my $rolekey = "$crsrole./$cdom/$cnum";
5456: if ($crssec ne '') {
5457: $rolekey .= "/$crssec";
5458: }
5459: $rolekey .= './';
5460: $groups_roles->{$rolekey} = $rolecodes;
5461: }
5462: }
5463: }
5464: }
5465: return;
5466: }
5467:
5468: sub delete_env_groupprivs {
5469: my ($where,$courseroles,$possroles) = @_;
5470: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
5471: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
5472: unless (ref($courseroles->{$udom}) eq 'HASH') {
5473: %{$courseroles->{$udom}} =
5474: &get_my_roles('','','userroles',['active'],
5475: $possroles,[$udom],1);
5476: }
5477: if (ref($courseroles->{$udom}) eq 'HASH') {
5478: foreach my $item (keys(%{$courseroles->{$udom}})) {
5479: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
5480: my $area = '/'.$cdom.'/'.$cnum;
5481: my $privkey = "user.priv.$crsrole.$area";
5482: if ($crssec ne '') {
5483: $privkey .= '/'.$crssec;
5484: }
5485: $privkey .= ".$area/$group";
5486: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
5487: }
5488: }
5489: return;
5490: }
5491:
1.994 raeburn 5492: sub check_adhoc_privs {
1.1104 raeburn 5493: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994 raeburn 5494: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1185 raeburn 5495: my $setprivs;
1.994 raeburn 5496: if ($env{$cckey}) {
5497: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104 raeburn 5498: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 5499: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088 raeburn 5500: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185 raeburn 5501: $setprivs = 1;
1.994 raeburn 5502: }
5503: } else {
1.1088 raeburn 5504: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185 raeburn 5505: $setprivs = 1;
1.994 raeburn 5506: }
1.1185 raeburn 5507: return $setprivs;
1.994 raeburn 5508: }
5509:
5510: sub set_adhoc_privileges {
5511: # role can be cc or ca
1.1088 raeburn 5512: my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994 raeburn 5513: my $area = '/'.$dcdom.'/'.$pickedcourse;
5514: my $spec = $role.'.'.$area;
5515: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1215 raeburn 5516: $env{'user.name'},1);
1.994 raeburn 5517: my %ccrole = ();
5518: &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
5519: my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
5520: &appenv(\%userroles,[$role,'cm']);
5521: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088 raeburn 5522: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
5523: &appenv( {'request.role' => $spec,
5524: 'request.role.domain' => $dcdom,
5525: 'request.course.sec' => ''
5526: }
5527: );
5528: my $tadv=0;
5529: if (&allowed('adv') eq 'F') { $tadv=1; }
5530: &appenv({'request.role.adv' => $tadv});
5531: }
1.994 raeburn 5532: }
5533:
1.12 www 5534: # --------------------------------------------------------------- get interface
5535:
5536: sub get {
1.131 albertel 5537: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 5538: my $items='';
1.800 albertel 5539: foreach my $item (@$storearr) {
5540: $items.=&escape($item).'&';
1.191 harris41 5541: }
1.12 www 5542: $items=~s/\&$//;
1.620 albertel 5543: if (!$udomain) { $udomain=$env{'user.domain'}; }
5544: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 5545: my $uhome=&homeserver($uname,$udomain);
5546:
1.133 albertel 5547: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 5548: my @pairs=split(/\&/,$rep);
1.273 albertel 5549: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
5550: return @pairs;
5551: }
1.15 www 5552: my %returnhash=();
1.42 www 5553: my $i=0;
1.800 albertel 5554: foreach my $item (@$storearr) {
5555: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 5556: $i++;
1.191 harris41 5557: }
1.15 www 5558: return %returnhash;
1.27 www 5559: }
5560:
5561: # --------------------------------------------------------------- del interface
5562:
5563: sub del {
1.133 albertel 5564: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 5565: my $items='';
1.800 albertel 5566: foreach my $item (@$storearr) {
5567: $items.=&escape($item).'&';
1.191 harris41 5568: }
1.984 neumanie 5569:
1.27 www 5570: $items=~s/\&$//;
1.620 albertel 5571: if (!$udomain) { $udomain=$env{'user.domain'}; }
5572: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 5573: my $uhome=&homeserver($uname,$udomain);
5574: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 5575: }
5576:
5577: # -------------------------------------------------------------- dump interface
5578:
1.1180 droeschl 5579: sub unserialize {
5580: my ($rep, $escapedkeys) = @_;
5581:
5582: return {} if $rep =~ /^error/;
5583:
5584: my %returnhash=();
1.1252 raeburn 5585: foreach my $item (split(/\&/,$rep)) {
1.1180 droeschl 5586: my ($key, $value) = split(/=/, $item, 2);
5587: $key = unescape($key) unless $escapedkeys;
5588: next if $key =~ /^error: 2 /;
1.1252 raeburn 5589: $returnhash{$key} = &thaw_unescape($value);
1.1180 droeschl 5590: }
5591: #return %returnhash;
5592: return \%returnhash;
5593: }
5594:
5595: # see Lond::dump_with_regexp
5596: # if $escapedkeys hash keys won't get unescaped.
1.15 www 5597: sub dump {
1.1180 droeschl 5598: my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755 albertel 5599: if (!$udomain) { $udomain=$env{'user.domain'}; }
5600: if (!$uname) { $uname=$env{'user.name'}; }
5601: my $uhome=&homeserver($uname,$udomain);
1.1167 droeschl 5602:
1.1180 droeschl 5603: my $reply;
5604: if (grep { $_ eq $uhome } current_machine_ids()) {
5605: # user is hosted on this machine
5606: $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
1.1226 raeburn 5607: $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1180 droeschl 5608: return %{unserialize($reply, $escapedkeys)};
5609: }
1.755 albertel 5610: if ($regexp) {
5611: $regexp=&escape($regexp);
5612: } else {
5613: $regexp='.';
5614: }
1.1166 raeburn 5615: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755 albertel 5616: my @pairs=split(/\&/,$rep);
5617: my %returnhash=();
1.1098 foxr 5618: if (!($rep =~ /^error/ )) {
5619: foreach my $item (@pairs) {
5620: my ($key,$value)=split(/=/,$item,2);
1.1180 droeschl 5621: $key = unescape($key) unless $escapedkeys;
5622: #$key = &unescape($key);
1.1098 foxr 5623: next if ($key =~ /^error: 2 /);
5624: $returnhash{$key}=&thaw_unescape($value);
5625: }
1.755 albertel 5626: }
5627: return %returnhash;
1.407 www 5628: }
5629:
1.1098 foxr 5630:
1.717 albertel 5631: # --------------------------------------------------------- dumpstore interface
5632:
5633: sub dumpstore {
5634: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180 droeschl 5635: # same as dump but keys must be escaped. They may contain colon separated
5636: # lists of values that may themself contain colons (e.g. symbs).
5637: return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717 albertel 5638: }
5639:
1.407 www 5640: # -------------------------------------------------------------- keys interface
5641:
5642: sub getkeys {
5643: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 5644: if (!$udomain) { $udomain=$env{'user.domain'}; }
5645: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 5646: my $uhome=&homeserver($uname,$udomain);
5647: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
5648: my @keyarray=();
1.800 albertel 5649: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 5650: next if ($key =~ /^error: 2 /);
1.800 albertel 5651: push(@keyarray,&unescape($key));
1.407 www 5652: }
5653: return @keyarray;
1.318 matthew 5654: }
5655:
1.319 matthew 5656: # --------------------------------------------------------------- currentdump
5657: sub currentdump {
1.328 matthew 5658: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 5659: $courseid = $env{'request.course.id'} if (! defined($courseid));
5660: $sdom = $env{'user.domain'} if (! defined($sdom));
5661: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 5662: my $uhome = &homeserver($sname,$sdom);
1.1180 droeschl 5663: my $rep;
5664:
5665: if (grep { $_ eq $uhome } current_machine_ids()) {
5666: $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
5667: $courseid)));
5668: } else {
5669: $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
5670: }
5671:
1.318 matthew 5672: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 5673: #
1.318 matthew 5674: my %returnhash=();
1.319 matthew 5675: #
5676: if ($rep eq "unknown_cmd") {
5677: # an old lond will not know currentdump
5678: # Do a dump and make it look like a currentdump
1.822 albertel 5679: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 5680: return if ($tmp[0] =~ /^(error:|no_such_host)/);
5681: my %hash = @tmp;
5682: @tmp=();
1.424 matthew 5683: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 5684: } else {
5685: my @pairs=split(/\&/,$rep);
1.800 albertel 5686: foreach my $pair (@pairs) {
5687: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 5688: my ($symb,$param) = split(/:/,$key);
5689: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 5690: &thaw_unescape($value);
1.319 matthew 5691: }
1.191 harris41 5692: }
1.12 www 5693: return %returnhash;
1.424 matthew 5694: }
5695:
5696: sub convert_dump_to_currentdump{
5697: my %hash = %{shift()};
5698: my %returnhash;
5699: # Code ripped from lond, essentially. The only difference
5700: # here is the unescaping done by lonnet::dump(). Conceivably
5701: # we might run in to problems with parameter names =~ /^v\./
5702: while (my ($key,$value) = each(%hash)) {
5703: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 5704: $symb = &unescape($symb);
5705: $param = &unescape($param);
1.424 matthew 5706: next if ($v eq 'version' || $symb eq 'keys');
5707: next if (exists($returnhash{$symb}) &&
5708: exists($returnhash{$symb}->{$param}) &&
5709: $returnhash{$symb}->{'v.'.$param} > $v);
5710: $returnhash{$symb}->{$param}=$value;
5711: $returnhash{$symb}->{'v.'.$param}=$v;
5712: }
5713: #
5714: # Remove all of the keys in the hashes which keep track of
5715: # the version of the parameter.
5716: while (my ($symb,$param_hash) = each(%returnhash)) {
5717: # use a foreach because we are going to delete from the hash.
5718: foreach my $key (keys(%$param_hash)) {
5719: delete($param_hash->{$key}) if ($key =~ /^v\./);
5720: }
5721: }
5722: return \%returnhash;
1.12 www 5723: }
5724:
1.627 albertel 5725: # ------------------------------------------------------ critical inc interface
5726:
5727: sub cinc {
5728: return &inc(@_,'critical');
5729: }
5730:
1.449 matthew 5731: # --------------------------------------------------------------- inc interface
5732:
5733: sub inc {
1.627 albertel 5734: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 5735: if (!$udomain) { $udomain=$env{'user.domain'}; }
5736: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 5737: my $uhome=&homeserver($uname,$udomain);
5738: my $items='';
5739: if (! ref($store)) {
5740: # got a single value, so use that instead
5741: $items = &escape($store).'=&';
5742: } elsif (ref($store) eq 'SCALAR') {
5743: $items = &escape($$store).'=&';
5744: } elsif (ref($store) eq 'ARRAY') {
5745: $items = join('=&',map {&escape($_);} @{$store});
5746: } elsif (ref($store) eq 'HASH') {
5747: while (my($key,$value) = each(%{$store})) {
5748: $items.= &escape($key).'='.&escape($value).'&';
5749: }
5750: }
5751: $items=~s/\&$//;
1.627 albertel 5752: if ($critical) {
5753: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
5754: } else {
5755: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
5756: }
1.449 matthew 5757: }
5758:
1.12 www 5759: # --------------------------------------------------------------- put interface
5760:
5761: sub put {
1.134 albertel 5762: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 5763: if (!$udomain) { $udomain=$env{'user.domain'}; }
5764: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 5765: my $uhome=&homeserver($uname,$udomain);
1.12 www 5766: my $items='';
1.800 albertel 5767: foreach my $item (keys(%$storehash)) {
5768: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 5769: }
1.12 www 5770: $items=~s/\&$//;
1.134 albertel 5771: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 5772: }
5773:
1.631 albertel 5774: # ------------------------------------------------------------ newput interface
5775:
5776: sub newput {
5777: my ($namespace,$storehash,$udomain,$uname)=@_;
5778: if (!$udomain) { $udomain=$env{'user.domain'}; }
5779: if (!$uname) { $uname=$env{'user.name'}; }
5780: my $uhome=&homeserver($uname,$udomain);
5781: my $items='';
5782: foreach my $key (keys(%$storehash)) {
5783: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
5784: }
5785: $items=~s/\&$//;
5786: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
5787: }
5788:
5789: # --------------------------------------------------------- putstore interface
5790:
1.524 raeburn 5791: sub putstore {
1.715 albertel 5792: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620 albertel 5793: if (!$udomain) { $udomain=$env{'user.domain'}; }
5794: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 5795: my $uhome=&homeserver($uname,$udomain);
5796: my $items='';
1.715 albertel 5797: foreach my $key (keys(%$storehash)) {
5798: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 5799: }
1.715 albertel 5800: $items=~s/\&$//;
1.716 albertel 5801: my $esc_symb=&escape($symb);
5802: my $esc_v=&escape($version);
1.715 albertel 5803: my $reply =
1.716 albertel 5804: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 5805: $uhome);
5806: if ($reply eq 'unknown_cmd') {
1.716 albertel 5807: # gfall back to way things use to be done
1.715 albertel 5808: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
5809: $uname);
1.524 raeburn 5810: }
1.715 albertel 5811: return $reply;
5812: }
5813:
5814: sub old_putstore {
1.716 albertel 5815: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
5816: if (!$udomain) { $udomain=$env{'user.domain'}; }
5817: if (!$uname) { $uname=$env{'user.name'}; }
5818: my $uhome=&homeserver($uname,$udomain);
5819: my %newstorehash;
1.800 albertel 5820: foreach my $item (keys(%$storehash)) {
5821: my $key = $version.':'.&escape($symb).':'.$item;
5822: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 5823: }
5824: my $items='';
5825: my %allitems = ();
1.800 albertel 5826: foreach my $item (keys(%newstorehash)) {
5827: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 5828: my $key = $1.':keys:'.$2;
5829: $allitems{$key} .= $3.':';
5830: }
1.800 albertel 5831: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 5832: }
1.800 albertel 5833: foreach my $item (keys(%allitems)) {
5834: $allitems{$item} =~ s/\:$//;
5835: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 5836: }
5837: $items=~s/\&$//;
5838: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 5839: }
5840:
1.47 www 5841: # ------------------------------------------------------ critical put interface
5842:
5843: sub cput {
1.134 albertel 5844: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 5845: if (!$udomain) { $udomain=$env{'user.domain'}; }
5846: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 5847: my $uhome=&homeserver($uname,$udomain);
1.47 www 5848: my $items='';
1.800 albertel 5849: foreach my $item (keys(%$storehash)) {
5850: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 5851: }
1.47 www 5852: $items=~s/\&$//;
1.134 albertel 5853: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 5854: }
5855:
5856: # -------------------------------------------------------------- eget interface
5857:
5858: sub eget {
1.133 albertel 5859: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 5860: my $items='';
1.800 albertel 5861: foreach my $item (@$storearr) {
5862: $items.=&escape($item).'&';
1.191 harris41 5863: }
1.12 www 5864: $items=~s/\&$//;
1.620 albertel 5865: if (!$udomain) { $udomain=$env{'user.domain'}; }
5866: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 5867: my $uhome=&homeserver($uname,$udomain);
5868: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 5869: my @pairs=split(/\&/,$rep);
5870: my %returnhash=();
1.42 www 5871: my $i=0;
1.800 albertel 5872: foreach my $item (@$storearr) {
5873: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 5874: $i++;
1.191 harris41 5875: }
1.12 www 5876: return %returnhash;
5877: }
5878:
1.667 albertel 5879: # ------------------------------------------------------------ tmpput interface
5880: sub tmpput {
1.802 raeburn 5881: my ($storehash,$server,$context)=@_;
1.667 albertel 5882: my $items='';
1.800 albertel 5883: foreach my $item (keys(%$storehash)) {
5884: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 5885: }
5886: $items=~s/\&$//;
1.802 raeburn 5887: if (defined($context)) {
5888: $items .= ':'.&escape($context);
5889: }
1.667 albertel 5890: return &reply("tmpput:$items",$server);
5891: }
5892:
5893: # ------------------------------------------------------------ tmpget interface
5894: sub tmpget {
1.688 albertel 5895: my ($token,$server)=@_;
5896: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5897: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 5898: my %returnhash;
5899: foreach my $item (split(/\&/,$rep)) {
5900: my ($key,$value)=split(/=/,$item);
1.951 raeburn 5901: next if ($key =~ /^error: 2 /);
1.667 albertel 5902: $returnhash{&unescape($key)}=&thaw_unescape($value);
5903: }
5904: return %returnhash;
5905: }
5906:
1.1113 raeburn 5907: # ------------------------------------------------------------ tmpdel interface
1.688 albertel 5908: sub tmpdel {
5909: my ($token,$server)=@_;
5910: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5911: return &reply("tmpdel:$token",$server);
5912: }
5913:
1.1198 raeburn 5914: # ------------------------------------------------------------ get_timebased_id
5915:
5916: sub get_timebased_id {
5917: my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
5918: $maxtries) = @_;
5919: my ($newid,$error,$dellock);
5920: unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
5921: return ('','ok','invalid call to get suffix');
5922: }
5923:
5924: # set defaults for any optional args for which values were not supplied
5925: if ($who eq '') {
5926: $who = $env{'user.name'}.':'.$env{'user.domain'};
5927: }
5928: if (!$locktries) {
5929: $locktries = 3;
5930: }
5931: if (!$maxtries) {
5932: $maxtries = 10;
5933: }
5934:
5935: if (($cdom eq '') || ($cnum eq '')) {
5936: if ($env{'request.course.id'}) {
5937: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
5938: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
5939: }
5940: if (($cdom eq '') || ($cnum eq '')) {
5941: return ('','ok','call to get suffix not in course context');
5942: }
5943: }
5944:
5945: # construct locking item
5946: my $lockhash = {
5947: $prefix."\0".'locked_'.$keyid => $who,
5948: };
5949: my $tries = 0;
5950:
5951: # attempt to get lock on nohist_$namespace file
5952: my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
5953: while (($gotlock ne 'ok') && $tries <$locktries) {
5954: $tries ++;
5955: sleep 1;
5956: $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
5957: }
5958:
5959: # attempt to get unique identifier, based on current timestamp
5960: if ($gotlock eq 'ok') {
5961: my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
5962: my $id = time;
5963: $newid = $id;
5964: my $idtries = 0;
5965: while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
5966: if ($idtype eq 'concat') {
5967: $newid = $id.$idtries;
5968: } else {
5969: $newid ++;
5970: }
5971: $idtries ++;
5972: }
5973: if (!exists($inuse{$prefix."\0".$newid})) {
5974: my %new_item = (
5975: $prefix."\0".$newid => $who,
5976: );
5977: my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
5978: $cdom,$cnum);
5979: if ($putresult ne 'ok') {
5980: undef($newid);
5981: $error = 'error saving new item: '.$putresult;
5982: }
5983: } else {
5984: $error = ('error: no unique suffix available for the new item ');
5985: }
5986: # remove lock
5987: my @del_lock = ($prefix."\0".'locked_'.$keyid);
5988: $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
5989: } else {
5990: $error = "error: could not obtain lockfile\n";
5991: $dellock = 'ok';
5992: }
5993: return ($newid,$dellock,$error);
5994: }
5995:
1.765 albertel 5996: # -------------------------------------------------- portfolio access checking
5997:
5998: sub portfolio_access {
1.766 albertel 5999: my ($requrl) = @_;
1.765 albertel 6000: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
6001: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814 raeburn 6002: if ($result) {
6003: my %setters;
6004: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6005: my ($startblock,$endblock) =
6006: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
6007: if ($startblock && $endblock) {
6008: return 'B';
6009: }
6010: } else {
6011: my ($startblock,$endblock) =
6012: &Apache::loncommon::blockcheck(\%setters,'port');
6013: if ($startblock && $endblock) {
6014: return 'B';
6015: }
6016: }
6017: }
1.765 albertel 6018: if ($result eq 'ok') {
1.766 albertel 6019: return 'F';
1.765 albertel 6020: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 6021: return 'A';
1.765 albertel 6022: }
1.766 albertel 6023: return '';
1.765 albertel 6024: }
6025:
6026: sub get_portfolio_access {
1.767 albertel 6027: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
6028:
6029: if (!ref($access_hash)) {
6030: my $current_perms = &get_portfile_permissions($udom,$unum);
6031: my %access_controls = &get_access_controls($current_perms,$group,
6032: $file_name);
6033: $access_hash = $access_controls{$file_name};
6034: }
6035:
1.765 albertel 6036: my ($public,$guest,@domains,@users,@courses,@groups);
6037: my $now = time;
6038: if (ref($access_hash) eq 'HASH') {
6039: foreach my $key (keys(%{$access_hash})) {
6040: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
6041: if ($start > $now) {
6042: next;
6043: }
6044: if ($end && $end<$now) {
6045: next;
6046: }
6047: if ($scope eq 'public') {
6048: $public = $key;
6049: last;
6050: } elsif ($scope eq 'guest') {
6051: $guest = $key;
6052: } elsif ($scope eq 'domains') {
6053: push(@domains,$key);
6054: } elsif ($scope eq 'users') {
6055: push(@users,$key);
6056: } elsif ($scope eq 'course') {
6057: push(@courses,$key);
6058: } elsif ($scope eq 'group') {
6059: push(@groups,$key);
6060: }
6061: }
6062: if ($public) {
6063: return 'ok';
6064: }
6065: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6066: if ($guest) {
6067: return $guest;
6068: }
6069: } else {
6070: if (@domains > 0) {
6071: foreach my $domkey (@domains) {
6072: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
6073: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
6074: return 'ok';
6075: }
6076: }
6077: }
6078: }
6079: if (@users > 0) {
6080: foreach my $userkey (@users) {
1.865 raeburn 6081: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
6082: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
6083: if (ref($item) eq 'HASH') {
6084: if (($item->{'uname'} eq $env{'user.name'}) &&
6085: ($item->{'udom'} eq $env{'user.domain'})) {
6086: return 'ok';
6087: }
6088: }
6089: }
6090: }
1.765 albertel 6091: }
6092: }
6093: my %roleshash;
6094: my @courses_and_groups = @courses;
6095: push(@courses_and_groups,@groups);
6096: if (@courses_and_groups > 0) {
6097: my (%allgroups,%allroles);
6098: my ($start,$end,$role,$sec,$group);
6099: foreach my $envkey (%env) {
1.1060 raeburn 6100: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6101: my $cid = $2.'_'.$3;
6102: if ($1 eq 'gr') {
6103: $group = $4;
6104: $allgroups{$cid}{$group} = $env{$envkey};
6105: } else {
6106: if ($4 eq '') {
6107: $sec = 'none';
6108: } else {
6109: $sec = $4;
6110: }
6111: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6112: }
1.811 albertel 6113: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6114: my $cid = $2.'_'.$3;
6115: if ($4 eq '') {
6116: $sec = 'none';
6117: } else {
6118: $sec = $4;
6119: }
6120: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6121: }
6122: }
6123: if (keys(%allroles) == 0) {
6124: return;
6125: }
6126: foreach my $key (@courses_and_groups) {
6127: my %content = %{$$access_hash{$key}};
6128: my $cnum = $content{'number'};
6129: my $cdom = $content{'domain'};
6130: my $cid = $cdom.'_'.$cnum;
6131: if (!exists($allroles{$cid})) {
6132: next;
6133: }
6134: foreach my $role_id (keys(%{$content{'roles'}})) {
6135: my @sections = @{$content{'roles'}{$role_id}{'section'}};
6136: my @groups = @{$content{'roles'}{$role_id}{'group'}};
6137: my @status = @{$content{'roles'}{$role_id}{'access'}};
6138: my @roles = @{$content{'roles'}{$role_id}{'role'}};
6139: foreach my $role (keys(%{$allroles{$cid}})) {
6140: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
6141: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
6142: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
6143: if (grep/^all$/,@sections) {
6144: return 'ok';
6145: } else {
6146: if (grep/^$sec$/,@sections) {
6147: return 'ok';
6148: }
6149: }
6150: }
6151: }
6152: if (keys(%{$allgroups{$cid}}) == 0) {
6153: if (grep/^none$/,@groups) {
6154: return 'ok';
6155: }
6156: } else {
6157: if (grep/^all$/,@groups) {
6158: return 'ok';
6159: }
6160: foreach my $group (keys(%{$allgroups{$cid}})) {
6161: if (grep/^$group$/,@groups) {
6162: return 'ok';
6163: }
6164: }
6165: }
6166: }
6167: }
6168: }
6169: }
6170: }
6171: if ($guest) {
6172: return $guest;
6173: }
6174: }
6175: }
6176: return;
6177: }
6178:
6179: sub course_group_datechecker {
6180: my ($dates,$now,$status) = @_;
6181: my ($start,$end) = split(/\./,$dates);
6182: if (!$start && !$end) {
6183: return 'ok';
6184: }
6185: if (grep/^active$/,@{$status}) {
6186: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
6187: return 'ok';
6188: }
6189: }
6190: if (grep/^previous$/,@{$status}) {
6191: if ($end > $now ) {
6192: return 'ok';
6193: }
6194: }
6195: if (grep/^future$/,@{$status}) {
6196: if ($start > $now) {
6197: return 'ok';
6198: }
6199: }
6200: return;
6201: }
6202:
6203: sub parse_portfolio_url {
6204: my ($url) = @_;
6205:
6206: my ($type,$udom,$unum,$group,$file_name);
6207:
1.823 albertel 6208: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 6209: $type = 1;
6210: $udom = $1;
6211: $unum = $2;
6212: $file_name = $3;
1.823 albertel 6213: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 6214: $type = 2;
6215: $udom = $1;
6216: $unum = $2;
6217: $group = $3;
6218: $file_name = $3.'/'.$4;
6219: }
6220: if (wantarray) {
6221: return ($type,$udom,$unum,$file_name,$group);
6222: }
6223: return $type;
6224: }
6225:
6226: sub is_portfolio_url {
6227: my ($url) = @_;
6228: return scalar(&parse_portfolio_url($url));
6229: }
6230:
1.798 raeburn 6231: sub is_portfolio_file {
6232: my ($file) = @_;
1.820 raeburn 6233: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 6234: return 1;
6235: }
6236: return;
6237: }
6238:
1.976 raeburn 6239: sub usertools_access {
1.1084 raeburn 6240: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 6241: my ($access,%tools);
6242: if ($context eq '') {
6243: $context = 'tools';
6244: }
6245: if ($context eq 'requestcourses') {
6246: %tools = (
6247: official => 1,
6248: unofficial => 1,
1.1006 raeburn 6249: community => 1,
1.1246 raeburn 6250: textbook => 1,
1.985 raeburn 6251: );
1.1183 raeburn 6252: } elsif ($context eq 'requestauthor') {
6253: %tools = (
6254: requestauthor => 1,
6255: );
1.985 raeburn 6256: } else {
6257: %tools = (
6258: aboutme => 1,
6259: blog => 1,
1.1177 raeburn 6260: webdav => 1,
1.985 raeburn 6261: portfolio => 1,
6262: );
6263: }
1.976 raeburn 6264: return if (!defined($tools{$tool}));
6265:
1.1242 raeburn 6266: if (($udom eq '') || ($uname eq '')) {
1.976 raeburn 6267: $udom = $env{'user.domain'};
6268: $uname = $env{'user.name'};
6269: }
6270:
1.978 raeburn 6271: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
6272: if ($action ne 'reload') {
1.985 raeburn 6273: if ($context eq 'requestcourses') {
6274: return $env{'environment.canrequest.'.$tool};
1.1183 raeburn 6275: } elsif ($context eq 'requestauthor') {
6276: return $env{'environment.canrequest.author'};
1.985 raeburn 6277: } else {
6278: return $env{'environment.availabletools.'.$tool};
6279: }
6280: }
1.976 raeburn 6281: }
6282:
1.1183 raeburn 6283: my ($toolstatus,$inststatus,$envkey);
6284: if ($context eq 'requestauthor') {
6285: $envkey = $context;
6286: } else {
6287: $envkey = $context.'.'.$tool;
6288: }
1.976 raeburn 6289:
1.985 raeburn 6290: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
6291: ($action ne 'reload')) {
1.1183 raeburn 6292: $toolstatus = $env{'environment.'.$envkey};
1.976 raeburn 6293: $inststatus = $env{'environment.inststatus'};
6294: } else {
1.1084 raeburn 6295: if (ref($userenvref) eq 'HASH') {
1.1183 raeburn 6296: $toolstatus = $userenvref->{$envkey};
1.1084 raeburn 6297: $inststatus = $userenvref->{'inststatus'};
6298: } else {
1.1183 raeburn 6299: my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
6300: $toolstatus = $userenv{$envkey};
1.1084 raeburn 6301: $inststatus = $userenv{'inststatus'};
6302: }
1.976 raeburn 6303: }
6304:
6305: if ($toolstatus ne '') {
6306: if ($toolstatus) {
6307: $access = 1;
6308: } else {
6309: $access = 0;
6310: }
6311: return $access;
6312: }
6313:
1.1084 raeburn 6314: my ($is_adv,%domdef);
6315: if (ref($is_advref) eq 'HASH') {
6316: $is_adv = $is_advref->{'is_adv'};
6317: } else {
6318: $is_adv = &is_advanced_user($udom,$uname);
6319: }
6320: if (ref($domdefref) eq 'HASH') {
6321: %domdef = %{$domdefref};
6322: } else {
6323: %domdef = &get_domain_defaults($udom);
6324: }
1.976 raeburn 6325: if (ref($domdef{$tool}) eq 'HASH') {
6326: if ($is_adv) {
6327: if ($domdef{$tool}{'_LC_adv'} ne '') {
6328: if ($domdef{$tool}{'_LC_adv'}) {
6329: $access = 1;
6330: } else {
6331: $access = 0;
6332: }
6333: return $access;
6334: }
6335: }
6336: if ($inststatus ne '') {
6337: my ($hasaccess,$hasnoaccess);
6338: foreach my $affiliation (split(/:/,$inststatus)) {
6339: if ($domdef{$tool}{$affiliation} ne '') {
6340: if ($domdef{$tool}{$affiliation}) {
6341: $hasaccess = 1;
6342: } else {
6343: $hasnoaccess = 1;
6344: }
6345: }
6346: }
6347: if ($hasaccess || $hasnoaccess) {
6348: if ($hasaccess) {
6349: $access = 1;
6350: } elsif ($hasnoaccess) {
6351: $access = 0;
6352: }
6353: return $access;
6354: }
6355: } else {
6356: if ($domdef{$tool}{'default'} ne '') {
6357: if ($domdef{$tool}{'default'}) {
6358: $access = 1;
6359: } elsif ($domdef{$tool}{'default'} == 0) {
6360: $access = 0;
6361: }
6362: return $access;
6363: }
6364: }
6365: } else {
1.1177 raeburn 6366: if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985 raeburn 6367: $access = 1;
6368: } else {
6369: $access = 0;
6370: }
1.976 raeburn 6371: return $access;
6372: }
6373: }
6374:
1.1050 raeburn 6375: sub is_course_owner {
6376: my ($cdom,$cnum,$udom,$uname) = @_;
6377: if (($udom eq '') || ($uname eq '')) {
6378: $udom = $env{'user.domain'};
6379: $uname = $env{'user.name'};
6380: }
6381: unless (($udom eq '') || ($uname eq '')) {
6382: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
6383: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
6384: return 1;
6385: } else {
6386: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
6387: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
6388: return 1;
6389: }
6390: }
6391: }
6392: }
6393: return;
6394: }
6395:
1.976 raeburn 6396: sub is_advanced_user {
6397: my ($udom,$uname) = @_;
1.1085 raeburn 6398: if ($udom ne '' && $uname ne '') {
6399: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128 raeburn 6400: if (wantarray) {
6401: return ($env{'user.adv'},$env{'user.author'});
6402: } else {
6403: return $env{'user.adv'};
6404: }
1.1085 raeburn 6405: }
6406: }
1.976 raeburn 6407: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
6408: my %allroles;
1.1128 raeburn 6409: my ($is_adv,$is_author);
1.976 raeburn 6410: foreach my $role (keys(%roleshash)) {
6411: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
6412: my $area = '/'.$tdomain.'/'.$trest;
6413: if ($sec ne '') {
6414: $area .= '/'.$sec;
6415: }
6416: if (($area ne '') && ($trole ne '')) {
6417: my $spec=$trole.'.'.$area;
6418: if ($trole =~ /^cr\//) {
6419: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
6420: } elsif ($trole ne 'gr') {
6421: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
6422: }
1.1128 raeburn 6423: if ($trole eq 'au') {
6424: $is_author = 1;
6425: }
1.976 raeburn 6426: }
6427: }
6428: foreach my $role (keys(%allroles)) {
6429: last if ($is_adv);
6430: foreach my $item (split(/:/,$allroles{$role})) {
6431: if ($item ne '') {
6432: my ($privilege,$restrictions)=split(/&/,$item);
6433: if ($privilege eq 'adv') {
6434: $is_adv = 1;
6435: last;
6436: }
6437: }
6438: }
6439: }
1.1128 raeburn 6440: if (wantarray) {
6441: return ($is_adv,$is_author);
6442: }
1.976 raeburn 6443: return $is_adv;
6444: }
1.798 raeburn 6445:
1.1035 raeburn 6446: sub check_can_request {
1.1036 raeburn 6447: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 6448: my $canreq = 0;
6449: my ($types,$typename) = &Apache::loncommon::course_types();
6450: my @options = ('approval','validate','autolimit');
6451: my $optregex = join('|',@options);
6452: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
6453: foreach my $type (@{$types}) {
6454: if (&usertools_access($env{'user.name'},
6455: $env{'user.domain'},
6456: $type,undef,'requestcourses')) {
6457: $canreq ++;
1.1036 raeburn 6458: if (ref($request_domains) eq 'HASH') {
6459: push(@{$request_domains->{$type}},$env{'user.domain'});
6460: }
1.1035 raeburn 6461: if ($dom eq $env{'user.domain'}) {
6462: $can_request->{$type} = 1;
6463: }
6464: }
6465: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
6466: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
6467: if (@curr > 0) {
1.1036 raeburn 6468: foreach my $item (@curr) {
6469: if (ref($request_domains) eq 'HASH') {
6470: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
6471: if ($otherdom ne '') {
6472: if (ref($request_domains->{$type}) eq 'ARRAY') {
6473: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
6474: push(@{$request_domains->{$type}},$otherdom);
6475: }
6476: } else {
6477: push(@{$request_domains->{$type}},$otherdom);
6478: }
6479: }
6480: }
6481: }
6482: unless($dom eq $env{'user.domain'}) {
6483: $canreq ++;
1.1035 raeburn 6484: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
6485: $can_request->{$type} = 1;
6486: }
6487: }
6488: }
6489: }
6490: }
6491: }
6492: return $canreq;
6493: }
6494:
1.341 www 6495: # ---------------------------------------------- Custom access rule evaluation
6496:
6497: sub customaccess {
6498: my ($priv,$uri)=@_;
1.807 albertel 6499: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 6500: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 6501: $udom = &LONCAPA::clean_domain($udom);
6502: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 6503: my $access=0;
1.800 albertel 6504: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 6505: my ($effect,$realm,$role,$type)=split(/\:/,$right);
6506: if ($type eq 'user') {
6507: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 6508: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 6509: if ($tdom) {
6510: if ($tdom ne $env{'user.domain'}) { next; }
6511: }
1.896 albertel 6512: if ($tuname) {
6513: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 6514: }
6515: $access=($effect eq 'allow');
6516: last;
6517: }
6518: } else {
6519: if ($role) {
6520: if ($role ne $urole) { next; }
6521: }
6522: foreach my $scope (split(/\s*\,\s*/,$realm)) {
6523: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
6524: if ($tdom) {
6525: if ($tdom ne $udom) { next; }
6526: }
6527: if ($tcrs) {
6528: if ($tcrs ne $ucrs) { next; }
6529: }
6530: if ($tsec) {
6531: if ($tsec ne $usec) { next; }
6532: }
6533: $access=($effect eq 'allow');
6534: last;
6535: }
6536: if ($realm eq '' && $role eq '') {
6537: $access=($effect eq 'allow');
6538: }
1.402 bowersj2 6539: }
1.341 www 6540: }
6541: return $access;
6542: }
6543:
1.103 harris41 6544: # ------------------------------------------------- Check for a user privilege
1.12 www 6545:
6546: sub allowed {
1.810 raeburn 6547: my ($priv,$uri,$symb,$role)=@_;
1.705 albertel 6548: my $ver_orguri=$uri;
1.439 www 6549: $uri=&deversion($uri);
1.152 www 6550: my $orguri=$uri;
1.52 www 6551: $uri=&declutter($uri);
1.809 raeburn 6552:
1.810 raeburn 6553: if ($priv eq 'evb') {
6554: # Evade communication block restrictions for specified role in a course
6555: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
6556: return $1;
6557: } else {
6558: return;
6559: }
6560: }
6561:
1.620 albertel 6562: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 6563: # Free bre access to adm and meta resources
1.775 albertel 6564: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 6565: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
6566: && ($priv eq 'bre')) {
1.14 www 6567: return 'F';
1.159 www 6568: }
6569:
1.545 banghart 6570: # Free bre access to user's own portfolio contents
1.714 raeburn 6571: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 6572: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 6573: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 6574: my %setters;
6575: my ($startblock,$endblock) =
6576: &Apache::loncommon::blockcheck(\%setters,'port');
6577: if ($startblock && $endblock) {
6578: return 'B';
6579: } else {
6580: return 'F';
6581: }
1.545 banghart 6582: }
6583:
1.762 raeburn 6584: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 6585: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
6586: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
6587: if (exists($env{'request.course.id'})) {
6588: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6589: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6590: if (($domain eq $cdom) && ($name eq $cnum)) {
6591: my $courseprivid=$env{'request.course.id'};
6592: $courseprivid=~s/\_/\//;
6593: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
6594: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
6595: return $1;
1.762 raeburn 6596: } else {
6597: if ($env{'request.course.sec'}) {
6598: $courseprivid.='/'.$env{'request.course.sec'};
6599: }
6600: if ($env{'user.priv.'.$env{'request.role'}.'./'.
6601: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
6602: return $2;
6603: }
1.714 raeburn 6604: }
6605: }
6606: }
6607: }
6608:
1.159 www 6609: # Free bre to public access
6610:
6611: if ($priv eq 'bre') {
1.238 www 6612: my $copyright=&metadata($uri,'copyright');
1.620 albertel 6613: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 6614: return 'F';
6615: }
1.238 www 6616: if ($copyright eq 'priv') {
6617: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 6618: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 6619: return '';
6620: }
6621: }
6622: if ($copyright eq 'domain') {
6623: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 6624: unless (($env{'user.domain'} eq $1) ||
6625: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 6626: return '';
6627: }
1.262 matthew 6628: }
1.620 albertel 6629: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 6630: # Library role, so allow browsing of resources in this domain.
6631: return 'F';
1.238 www 6632: }
1.341 www 6633: if ($copyright eq 'custom') {
6634: unless (&customaccess($priv,$uri)) { return ''; }
6635: }
1.14 www 6636: }
1.264 matthew 6637: # Domain coordinator is trying to create a course
1.620 albertel 6638: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 6639: # uri is the requested domain in this case.
6640: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 6641: # a role of dc for the domain in question.
1.620 albertel 6642: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 6643: }
1.29 www 6644:
1.52 www 6645: my $thisallowed='';
6646: my $statecond=0;
6647: my $courseprivid='';
6648:
1.1039 raeburn 6649: my $ownaccess;
1.1043 raeburn 6650: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 6651: if (($priv eq 'bro') && ($env{'user.author'})) {
6652: if ($uri eq '') {
6653: $ownaccess = 1;
6654: } else {
6655: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
6656: my $udom = $env{'user.domain'};
6657: my $uname = $env{'user.name'};
6658: if ($uri =~ m{^\Q$udom\E/?$}) {
6659: $ownaccess = 1;
1.1040 raeburn 6660: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 6661: unless ($uri =~ m{\.\./}) {
6662: $ownaccess = 1;
6663: }
6664: } elsif (($udom ne 'public') && ($uname ne 'public')) {
6665: my $now = time;
6666: if ($uri =~ m{^([^/]+)/?$}) {
6667: my $adom = $1;
6668: foreach my $key (keys(%env)) {
1.1042 raeburn 6669: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 6670: my ($start,$end) = split('.',$env{$key});
6671: if (($now >= $start) && (!$end || $end < $now)) {
6672: $ownaccess = 1;
6673: last;
6674: }
6675: }
6676: }
6677: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
6678: my $adom = $1;
6679: my $aname = $2;
1.1042 raeburn 6680: foreach my $role ('ca','aa') {
6681: if ($env{"user.role.$role./$adom/$aname"}) {
6682: my ($start,$end) =
6683: split('.',$env{"user.role.$role./$adom/$aname"});
6684: if (($now >= $start) && (!$end || $end < $now)) {
6685: $ownaccess = 1;
6686: last;
6687: }
1.1039 raeburn 6688: }
6689: }
6690: }
6691: }
6692: }
6693: }
6694: }
6695:
1.52 www 6696: # Course
6697:
1.620 albertel 6698: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6699: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6700: $thisallowed.=$1;
6701: }
1.52 www 6702: }
1.29 www 6703:
1.52 www 6704: # Domain
6705:
1.620 albertel 6706: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 6707: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6708: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6709: $thisallowed.=$1;
6710: }
1.12 www 6711: }
1.52 www 6712:
1.1141 raeburn 6713: # User who is not author or co-author might still be able to edit
6714: # resource of an author in the domain (e.g., if Domain Coordinator).
6715: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
6716: (&allowed('mdc',$env{'request.course.id'}))) {
6717: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
6718: $thisallowed.=$1;
6719: }
6720: }
6721:
1.52 www 6722: # Course: uri itself is a course
1.66 www 6723: my $courseuri=$uri;
6724: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 6725: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 6726:
1.620 albertel 6727: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 6728: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6729: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6730: $thisallowed.=$1;
6731: }
1.12 www 6732: }
1.29 www 6733:
1.665 albertel 6734: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 6735: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 6736: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 6737: $thisallowed='';
1.671 raeburn 6738: my ($match)=&is_on_map($uri);
6739: if ($match) {
6740: if ($env{'user.priv.'.$env{'request.role'}.'./'}
6741: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6742: my @blockers = &has_comm_blocking($priv,$symb,$uri);
6743: if (@blockers > 0) {
6744: $thisallowed = 'B';
6745: } else {
6746: $thisallowed.=$1;
6747: }
1.671 raeburn 6748: }
6749: } else {
1.705 albertel 6750: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 6751: if ($refuri) {
6752: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 6753: $thisallowed='F';
1.671 raeburn 6754: } else {
6755: $refuri=&declutter($refuri);
6756: my ($match) = &is_on_map($refuri);
6757: if ($match) {
1.1162 raeburn 6758: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
6759: if (@blockers > 0) {
6760: $thisallowed = 'B';
6761: } else {
6762: $thisallowed='F';
6763: }
1.671 raeburn 6764: }
1.669 raeburn 6765: }
1.671 raeburn 6766: }
6767: }
1.314 www 6768: }
1.492 albertel 6769:
1.766 albertel 6770: if ($priv eq 'bre'
6771: && $thisallowed ne 'F'
6772: && $thisallowed ne '2'
6773: && &is_portfolio_url($uri)) {
6774: $thisallowed = &portfolio_access($uri);
6775: }
1.1250 raeburn 6776:
1.52 www 6777: # Full access at system, domain or course-wide level? Exit.
1.29 www 6778: if ($thisallowed=~/F/) {
6779: return 'F';
6780: }
6781:
1.52 www 6782: # If this is generating or modifying users, exit with special codes
1.29 www 6783:
1.643 www 6784: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
6785: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 6786: my ($audom,$auname)=split('/',$uri);
1.643 www 6787: # no author name given, so this just checks on the general right to make a co-author in this domain
6788: unless ($auname) { return $thisallowed; }
6789: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 6790: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
6791: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
6792: ($audom ne $env{'request.role.domain'}))) { return ''; }
6793: }
1.52 www 6794: return $thisallowed;
6795: }
6796: #
1.103 harris41 6797: # Gathered so far: system, domain and course wide privileges
1.52 www 6798: #
6799: # Course: See if uri or referer is an individual resource that is part of
6800: # the course
6801:
1.620 albertel 6802: if ($env{'request.course.id'}) {
1.232 www 6803:
1.620 albertel 6804: $courseprivid=$env{'request.course.id'};
6805: if ($env{'request.course.sec'}) {
6806: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 6807: }
6808: $courseprivid=~s/\_/\//;
6809: my $checkreferer=1;
1.232 www 6810: my ($match,$cond)=&is_on_map($uri);
6811: if ($match) {
6812: $statecond=$cond;
1.620 albertel 6813: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 6814: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6815: my $value = $1;
6816: if ($priv eq 'bre') {
6817: my @blockers = &has_comm_blocking($priv,$symb,$uri);
6818: if (@blockers > 0) {
6819: $thisallowed = 'B';
6820: } else {
6821: $thisallowed.=$value;
6822: }
6823: } else {
6824: $thisallowed.=$value;
6825: }
1.52 www 6826: $checkreferer=0;
6827: }
1.29 www 6828: }
1.83 www 6829:
1.148 www 6830: if ($checkreferer) {
1.620 albertel 6831: my $refuri=$env{'httpref.'.$orguri};
1.148 www 6832: unless ($refuri) {
1.800 albertel 6833: foreach my $key (keys(%env)) {
6834: if ($key=~/^httpref\..*\*/) {
6835: my $pattern=$key;
1.156 www 6836: $pattern=~s/^httpref\.\/res\///;
1.148 www 6837: $pattern=~s/\*/\[\^\/\]\+/g;
6838: $pattern=~s/\//\\\//g;
1.152 www 6839: if ($orguri=~/$pattern/) {
1.800 albertel 6840: $refuri=$env{$key};
1.148 www 6841: }
6842: }
1.191 harris41 6843: }
1.148 www 6844: }
1.232 www 6845:
1.148 www 6846: if ($refuri) {
1.152 www 6847: $refuri=&declutter($refuri);
1.232 www 6848: my ($match,$cond)=&is_on_map($refuri);
6849: if ($match) {
6850: my $refstatecond=$cond;
1.620 albertel 6851: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 6852: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6853: my $value = $1;
6854: if ($priv eq 'bre') {
6855: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
6856: if (@blockers > 0) {
6857: $thisallowed = 'B';
6858: } else {
6859: $thisallowed.=$value;
6860: }
6861: } else {
6862: $thisallowed.=$value;
6863: }
1.53 www 6864: $uri=$refuri;
6865: $statecond=$refstatecond;
1.52 www 6866: }
6867: }
1.148 www 6868: }
1.29 www 6869: }
1.52 www 6870: }
1.29 www 6871:
1.52 www 6872: #
1.103 harris41 6873: # Gathered now: all privileges that could apply, and condition number
1.52 www 6874: #
6875: #
6876: # Full or no access?
6877: #
1.29 www 6878:
1.52 www 6879: if ($thisallowed=~/F/) {
6880: return 'F';
6881: }
1.29 www 6882:
1.52 www 6883: unless ($thisallowed) {
6884: return '';
6885: }
1.29 www 6886:
1.52 www 6887: # Restrictions exist, deal with them
6888: #
6889: # C:according to course preferences
6890: # R:according to resource settings
6891: # L:unless locked
6892: # X:according to user session state
6893: #
6894:
6895: # Possibly locked functionality, check all courses
1.54 www 6896: # Locks might take effect only after 10 minutes cache expiration for other
6897: # courses, and 2 minutes for current course
1.52 www 6898:
6899: my $envkey;
6900: if ($thisallowed=~/L/) {
1.1000 raeburn 6901: foreach $envkey (keys(%env)) {
1.54 www 6902: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
6903: my $courseid=$2;
6904: my $roleid=$1.'.'.$2;
1.92 www 6905: $courseid=~s/^\///;
1.54 www 6906: my $expiretime=600;
1.620 albertel 6907: if ($env{'request.role'} eq $roleid) {
1.54 www 6908: $expiretime=120;
6909: }
6910: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
6911: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 6912: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 6913: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 6914: }
1.620 albertel 6915: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
6916: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
6917: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
6918: &log($env{'user.domain'},$env{'user.name'},
6919: $env{'user.home'},
1.57 www 6920: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 6921: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 6922: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 6923: return '';
6924: }
6925: }
1.620 albertel 6926: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
6927: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
6928: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
6929: &log($env{'user.domain'},$env{'user.name'},
6930: $env{'user.home'},
1.57 www 6931: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 6932: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 6933: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 6934: return '';
6935: }
6936: }
6937: }
1.29 www 6938: }
1.52 www 6939: }
6940:
6941: #
6942: # Rest of the restrictions depend on selected course
6943: #
6944:
1.620 albertel 6945: unless ($env{'request.course.id'}) {
1.766 albertel 6946: if ($thisallowed eq 'A') {
6947: return 'A';
1.814 raeburn 6948: } elsif ($thisallowed eq 'B') {
6949: return 'B';
1.766 albertel 6950: } else {
6951: return '1';
6952: }
1.52 www 6953: }
1.29 www 6954:
1.52 www 6955: #
6956: # Now user is definitely in a course
6957: #
1.53 www 6958:
6959:
6960: # Course preferences
6961:
6962: if ($thisallowed=~/C/) {
1.620 albertel 6963: my $rolecode=(split(/\./,$env{'request.role'}))[0];
6964: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
6965: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 6966: =~/\Q$rolecode\E/) {
1.1103 raeburn 6967: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 6968: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
6969: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
6970: $env{'request.course.id'});
6971: }
1.237 www 6972: return '';
6973: }
6974:
1.620 albertel 6975: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 6976: =~/\Q$unamedom\E/) {
1.1103 raeburn 6977: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 6978: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
6979: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
6980: $env{'request.course.id'});
6981: }
1.54 www 6982: return '';
6983: }
1.53 www 6984: }
6985:
6986: # Resource preferences
6987:
6988: if ($thisallowed=~/R/) {
1.620 albertel 6989: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 6990: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103 raeburn 6991: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 6992: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
6993: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
6994: }
6995: return '';
1.54 www 6996: }
1.53 www 6997: }
1.30 www 6998:
1.246 www 6999: # Restricted by state or randomout?
1.30 www 7000:
1.52 www 7001: if ($thisallowed=~/X/) {
1.620 albertel 7002: if ($env{'acc.randomout'}) {
1.579 albertel 7003: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 7004: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 7005: return '';
7006: }
1.247 www 7007: }
7008: if (&condval($statecond)) {
1.52 www 7009: return '2';
7010: } else {
7011: return '';
7012: }
7013: }
1.30 www 7014:
1.766 albertel 7015: if ($thisallowed eq 'A') {
7016: return 'A';
1.814 raeburn 7017: } elsif ($thisallowed eq 'B') {
7018: return 'B';
1.766 albertel 7019: }
1.52 www 7020: return 'F';
1.232 www 7021: }
1.1162 raeburn 7022:
1.1192 raeburn 7023: # ------------------------------------------- Check construction space access
7024:
7025: sub constructaccess {
7026: my ($url,$setpriv)=@_;
7027:
7028: # We do not allow editing of previous versions of files
7029: if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
7030:
7031: # Get username and domain from URL
7032: my ($ownername,$ownerdomain,$ownerhome);
7033:
7034: ($ownerdomain,$ownername) =
7035: ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
7036:
7037: # The URL does not really point to any authorspace, forget it
7038: unless (($ownername) && ($ownerdomain)) { return ''; }
7039:
7040: # Now we need to see if the user has access to the authorspace of
7041: # $ownername at $ownerdomain
7042:
7043: if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
7044: # Real author for this?
7045: $ownerhome = $env{'user.home'};
7046: if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
7047: return ($ownername,$ownerdomain,$ownerhome);
7048: }
7049: } else {
7050: # Co-author for this?
7051: if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
7052: exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
7053: $ownerhome = &homeserver($ownername,$ownerdomain);
7054: return ($ownername,$ownerdomain,$ownerhome);
7055: }
7056: }
7057:
7058: # We don't have any access right now. If we are not possibly going to do anything about this,
7059: # we might as well leave
7060: unless ($setpriv) { return ''; }
7061:
7062: # Backdoor access?
7063: my $allowed=&allowed('eco',$ownerdomain);
7064: # Nope
7065: unless ($allowed) { return ''; }
7066: # Looks like we may have access, but could be locked by the owner of the construction space
7067: if ($allowed eq 'U') {
7068: my %blocked=&get('environment',['domcoord.author'],
7069: $ownerdomain,$ownername);
7070: # Is blocked by owner
7071: if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
7072: }
7073: if (($allowed eq 'F') || ($allowed eq 'U')) {
7074: # Grant temporary access
7075: my $then=$env{'user.login.time'};
1.1209 raeburn 7076: my $update=$env{'user.update.time'};
1.1192 raeburn 7077: if (!$update) { $update = $then; }
7078: my $refresh=$env{'user.refresh.time'};
7079: if (!$refresh) { $refresh = $update; }
7080: my $now = time;
7081: &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
7082: $now,'ca','constructaccess');
7083: $ownerhome = &homeserver($ownername,$ownerdomain);
7084: return($ownername,$ownerdomain,$ownerhome);
7085: }
7086: # No business here
7087: return '';
7088: }
7089:
1.1162 raeburn 7090: sub get_comm_blocks {
7091: my ($cdom,$cnum) = @_;
7092: if ($cdom eq '' || $cnum eq '') {
7093: return unless ($env{'request.course.id'});
7094: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7095: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7096: }
7097: my %commblocks;
7098: my $hashid=$cdom.'_'.$cnum;
7099: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
7100: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
7101: %commblocks = %{$blocksref};
7102: } else {
7103: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
7104: my $cachetime = 600;
7105: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
7106: }
7107: return %commblocks;
7108: }
7109:
7110: sub has_comm_blocking {
7111: my ($priv,$symb,$uri,$blocks) = @_;
7112: return unless ($env{'request.course.id'});
7113: return unless ($priv eq 'bre');
7114: return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
7115: my %commblocks;
7116: if (ref($blocks) eq 'HASH') {
7117: %commblocks = %{$blocks};
7118: } else {
7119: %commblocks = &get_comm_blocks();
7120: }
7121: return unless (keys(%commblocks) > 0);
7122: if (!$symb) { $symb=&symbread($uri,1); }
7123: my ($map,$resid,undef)=&decode_symb($symb);
7124: my %tocheck = (
7125: maps => $map,
7126: resources => $symb,
7127: );
7128: my @blockers;
7129: my $now = time;
1.1163 raeburn 7130: my $navmap = Apache::lonnavmaps::navmap->new();
1.1162 raeburn 7131: foreach my $block (keys(%commblocks)) {
7132: if ($block =~ /^(\d+)____(\d+)$/) {
7133: my ($start,$end) = ($1,$2);
7134: if ($start <= $now && $end >= $now) {
7135: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7136: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
7137: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
7138: if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
7139: unless (grep(/^\Q$block\E$/,@blockers)) {
7140: push(@blockers,$block);
7141: }
7142: }
7143: }
7144: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
7145: if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
7146: unless (grep(/^\Q$block\E$/,@blockers)) {
7147: push(@blockers,$block);
7148: }
7149: }
7150: }
7151: }
7152: }
7153: }
7154: } elsif ($block =~ /^firstaccess____(.+)$/) {
7155: my $item = $1;
1.1163 raeburn 7156: my @to_test;
1.1162 raeburn 7157: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7158: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
7159: my $check_interval;
7160: if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
7161: my @interval;
7162: my $type = 'map';
7163: if ($item eq 'course') {
7164: $type = 'course';
7165: @interval=&EXT("resource.0.interval");
7166: } else {
7167: if ($item =~ /___\d+___/) {
7168: $type = 'resource';
7169: @interval=&EXT("resource.0.interval",$item);
1.1163 raeburn 7170: if (ref($navmap)) {
7171: my $res = $navmap->getBySymb($item);
7172: push(@to_test,$res);
7173: }
1.1162 raeburn 7174: } else {
7175: my $mapsymb = &symbread($item,1);
7176: if ($mapsymb) {
7177: if (ref($navmap)) {
7178: my $mapres = $navmap->getBySymb($mapsymb);
1.1163 raeburn 7179: @to_test = $mapres->retrieveResources($mapres,undef,0,1);
7180: foreach my $res (@to_test) {
1.1162 raeburn 7181: my $symb = $res->symb();
7182: next if ($symb eq $mapsymb);
7183: if ($symb ne '') {
7184: @interval=&EXT("resource.0.interval",$symb);
7185: last;
7186: }
7187: }
7188: }
7189: }
7190: }
7191: }
7192: if ($interval[0] =~ /\d+/) {
7193: my $first_access;
7194: if ($type eq 'resource') {
7195: $first_access=&get_first_access($interval[1],$item);
7196: } elsif ($type eq 'map') {
7197: $first_access=&get_first_access($interval[1],undef,$item);
7198: } else {
7199: $first_access=&get_first_access($interval[1]);
7200: }
7201: if ($first_access) {
7202: my $timesup = $first_access+$interval[0];
7203: if ($timesup > $now) {
1.1163 raeburn 7204: foreach my $res (@to_test) {
7205: if ($res->is_problem()) {
7206: if ($res->completable()) {
7207: unless (grep(/^\Q$block\E$/,@blockers)) {
7208: push(@blockers,$block);
7209: }
7210: last;
7211: }
7212: }
1.1162 raeburn 7213: }
7214: }
7215: }
7216: }
7217: }
7218: }
7219: }
7220: }
7221: }
7222: return @blockers;
7223: }
7224:
7225: sub check_docs_block {
7226: my ($docsblock,$tocheck) =@_;
7227: if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
7228: return;
7229: }
7230: if (ref($docsblock->{'maps'}) eq 'HASH') {
7231: if ($tocheck->{'maps'}) {
7232: if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
7233: return 1;
7234: }
7235: }
7236: }
7237: if (ref($docsblock->{'resources'}) eq 'HASH') {
7238: if ($tocheck->{'resources'}) {
7239: if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
7240: return 1;
7241: }
7242: }
7243: }
7244: return;
7245: }
7246:
1.1133 foxr 7247: #
7248: # Removes the versino from a URI and
7249: # splits it in to its filename and path to the filename.
7250: # Seems like File::Basename could have done this more clearly.
7251: # Parameters:
7252: # $uri - input URI
7253: # Returns:
7254: # Two element list consisting of
7255: # $pathname - the URI up to and excluding the trailing /
7256: # $filename - The part of the URI following the last /
7257: # NOTE:
7258: # Another realization of this is simply:
7259: # use File::Basename;
7260: # ...
7261: # $uri = shift;
7262: # $filename = basename($uri);
7263: # $path = dirname($uri);
7264: # return ($filename, $path);
7265: #
7266: # The implementation below is probably faster however.
7267: #
1.710 albertel 7268: sub split_uri_for_cond {
7269: my $uri=&deversion(&declutter(shift));
7270: my @uriparts=split(/\//,$uri);
7271: my $filename=pop(@uriparts);
7272: my $pathname=join('/',@uriparts);
7273: return ($pathname,$filename);
7274: }
1.232 www 7275: # --------------------------------------------------- Is a resource on the map?
7276:
7277: sub is_on_map {
1.710 albertel 7278: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 7279: #Trying to find the conditional for the file
1.620 albertel 7280: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 7281: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 7282: if ($match) {
1.289 bowersj2 7283: return (1,$1);
7284: } else {
1.434 www 7285: return (0,0);
1.289 bowersj2 7286: }
1.12 www 7287: }
7288:
1.427 www 7289: # --------------------------------------------------------- Get symb from alias
7290:
7291: sub get_symb_from_alias {
7292: my $symb=shift;
7293: my ($map,$resid,$url)=&decode_symb($symb);
7294: # Already is a symb
7295: if ($url) { return $symb; }
7296: # Must be an alias
7297: my $aliassymb='';
7298: my %bighash;
1.620 albertel 7299: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 7300: &GDBM_READER(),0640)) {
7301: my $rid=$bighash{'mapalias_'.$symb};
7302: if ($rid) {
7303: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 7304: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
7305: $resid,$bighash{'src_'.$rid});
1.427 www 7306: }
7307: untie %bighash;
7308: }
7309: return $aliassymb;
7310: }
7311:
1.12 www 7312: # ----------------------------------------------------------------- Define Role
7313:
7314: sub definerole {
7315: if (allowed('mcr','/')) {
7316: my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800 albertel 7317: foreach my $role (split(':',$sysrole)) {
7318: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7319: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
7320: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
7321: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 7322: return "refused:s:$crole&$cqual";
7323: }
7324: }
1.191 harris41 7325: }
1.800 albertel 7326: foreach my $role (split(':',$domrole)) {
7327: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7328: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
7329: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
7330: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 7331: return "refused:d:$crole&$cqual";
7332: }
7333: }
1.191 harris41 7334: }
1.800 albertel 7335: foreach my $role (split(':',$courole)) {
7336: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7337: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
7338: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
7339: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 7340: return "refused:c:$crole&$cqual";
7341: }
7342: }
1.191 harris41 7343: }
1.620 albertel 7344: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
7345: "$env{'user.domain'}:$env{'user.name'}:".
1.21 www 7346: "rolesdef_$rolename=".
7347: escape($sysrole.'_'.$domrole.'_'.$courole);
1.620 albertel 7348: return reply($command,$env{'user.home'});
1.12 www 7349: } else {
7350: return 'refused';
7351: }
1.105 harris41 7352: }
7353:
7354: # ---------------- Make a metadata query against the network of library servers
7355:
7356: sub metadata_query {
1.1237 raeburn 7357: my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120 harris41 7358: my %rhash;
1.845 albertel 7359: my %libserv = &all_library();
1.244 matthew 7360: my @server_list = (defined($server_array) ? @$server_array
7361: : keys(%libserv) );
7362: for my $server (@server_list) {
1.1237 raeburn 7363: my $domains = '';
7364: if (ref($domains_hash) eq 'HASH') {
7365: $domains = $domains_hash->{$server};
7366: }
1.118 harris41 7367: unless ($custom or $customshow) {
1.1237 raeburn 7368: my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118 harris41 7369: $rhash{$server}=$reply;
7370: }
7371: else {
7372: my $reply=&reply("querysend:".&escape($query).':'.
1.1237 raeburn 7373: &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118 harris41 7374: $server);
7375: $rhash{$server}=$reply;
7376: }
1.112 harris41 7377: }
1.118 harris41 7378: return \%rhash;
1.240 www 7379: }
7380:
7381: # ----------------------------------------- Send log queries and wait for reply
7382:
7383: sub log_query {
7384: my ($uname,$udom,$query,%filters)=@_;
7385: my $uhome=&homeserver($uname,$udom);
7386: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 7387: my $uhost=&hostname($uhome);
1.800 albertel 7388: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 7389: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
7390: $uhome);
1.479 albertel 7391: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 7392: return get_query_reply($queryid);
7393: }
7394:
1.818 raeburn 7395: # -------------------------- Update MySQL table for portfolio file
7396:
7397: sub update_portfolio_table {
1.821 raeburn 7398: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 7399: if ($group ne '') {
7400: $file_name =~s /^\Q$group\E//;
7401: }
1.818 raeburn 7402: my $homeserver = &homeserver($uname,$udom);
7403: my $queryid=
1.821 raeburn 7404: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
7405: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 7406: my $reply = &get_query_reply($queryid);
7407: return $reply;
7408: }
7409:
1.899 raeburn 7410: # -------------------------- Update MySQL allusers table
7411:
7412: sub update_allusers_table {
7413: my ($uname,$udom,$names) = @_;
7414: my $homeserver = &homeserver($uname,$udom);
7415: my $queryid=
7416: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
7417: 'lastname='.&escape($names->{'lastname'}).'%%'.
7418: 'firstname='.&escape($names->{'firstname'}).'%%'.
7419: 'middlename='.&escape($names->{'middlename'}).'%%'.
7420: 'generation='.&escape($names->{'generation'}).'%%'.
7421: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
7422: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 7423: return;
1.899 raeburn 7424: }
7425:
1.508 raeburn 7426: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 7427:
7428: sub fetch_enrollment_query {
1.511 raeburn 7429: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508 raeburn 7430: my $homeserver;
1.547 raeburn 7431: my $maxtries = 1;
1.508 raeburn 7432: if ($context eq 'automated') {
7433: $homeserver = $perlvar{'lonHostID'};
1.547 raeburn 7434: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 7435: } else {
7436: $homeserver = &homeserver($cnum,$dom);
7437: }
1.838 albertel 7438: my $host=&hostname($homeserver);
1.506 raeburn 7439: my $cmd = '';
1.1000 raeburn 7440: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 7441: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 7442: }
7443: $cmd =~ s/%%$//;
7444: $cmd = &escape($cmd);
7445: my $query = 'fetchenrollment';
1.620 albertel 7446: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 7447: unless ($queryid=~/^\Q$host\E\_/) {
7448: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
7449: return 'error: '.$queryid;
7450: }
1.506 raeburn 7451: my $reply = &get_query_reply($queryid);
1.547 raeburn 7452: my $tries = 1;
7453: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
7454: $reply = &get_query_reply($queryid);
7455: $tries ++;
7456: }
1.526 raeburn 7457: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 7458: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 7459: } else {
1.901 albertel 7460: my @responses = split(/:/,$reply);
1.515 raeburn 7461: if ($homeserver eq $perlvar{'lonHostID'}) {
1.800 albertel 7462: foreach my $line (@responses) {
7463: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 7464: $$replyref{$key} = $value;
7465: }
7466: } else {
1.1117 foxr 7467: my $pathname = LONCAPA::tempdir();
1.800 albertel 7468: foreach my $line (@responses) {
7469: my ($key,$value) = split(/=/,$line);
1.506 raeburn 7470: $$replyref{$key} = $value;
7471: if ($value > 0) {
1.800 albertel 7472: foreach my $item (@{$$affiliatesref{$key}}) {
7473: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 7474: my $destname = $pathname.'/'.$filename;
7475: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 7476: if ($xml_classlist =~ /^error/) {
7477: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
7478: } else {
1.506 raeburn 7479: if ( open(FILE,">$destname") ) {
7480: print FILE &unescape($xml_classlist);
7481: close(FILE);
1.526 raeburn 7482: } else {
7483: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 7484: }
7485: }
7486: }
7487: }
7488: }
7489: }
7490: return 'ok';
7491: }
7492: return 'error';
7493: }
7494:
1.242 www 7495: sub get_query_reply {
7496: my $queryid=shift;
1.1117 foxr 7497: my $replyfile=LONCAPA::tempdir().$queryid;
1.240 www 7498: my $reply='';
7499: for (1..100) {
7500: sleep 2;
7501: if (-e $replyfile.'.end') {
1.448 albertel 7502: if (open(my $fh,$replyfile)) {
1.904 albertel 7503: $reply = join('',<$fh>);
7504: close($fh);
1.240 www 7505: } else { return 'error: reply_file_error'; }
1.242 www 7506: return &unescape($reply);
7507: }
1.240 www 7508: }
1.242 www 7509: return 'timeout:'.$queryid;
1.240 www 7510: }
7511:
7512: sub courselog_query {
1.241 www 7513: #
7514: # possible filters:
7515: # url: url or symb
7516: # username
7517: # domain
7518: # action: view, submit, grade
7519: # start: timestamp
7520: # end: timestamp
7521: #
1.240 www 7522: my (%filters)=@_;
1.620 albertel 7523: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 7524: if ($filters{'url'}) {
7525: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
7526: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
7527: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
7528: }
1.620 albertel 7529: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
7530: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 7531: return &log_query($cname,$cdom,'courselog',%filters);
7532: }
7533:
7534: sub userlog_query {
1.858 raeburn 7535: #
7536: # possible filters:
7537: # action: log check role
7538: # start: timestamp
7539: # end: timestamp
7540: #
1.240 www 7541: my ($uname,$udom,%filters)=@_;
7542: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 7543: }
7544:
1.506 raeburn 7545: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
7546:
7547: sub auto_run {
1.508 raeburn 7548: my ($cnum,$cdom) = @_;
1.876 raeburn 7549: my $response = 0;
7550: my $settings;
7551: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
7552: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
7553: $settings = $domconfig{'autoenroll'};
7554: if ($settings->{'run'} eq '1') {
7555: $response = 1;
7556: }
7557: } else {
1.934 raeburn 7558: my $homeserver;
7559: if (&is_course($cdom,$cnum)) {
7560: $homeserver = &homeserver($cnum,$cdom);
7561: } else {
7562: $homeserver = &domain($cdom,'primary');
7563: }
7564: if ($homeserver ne 'no_host') {
7565: $response = &reply('autorun:'.$cdom,$homeserver);
7566: }
1.876 raeburn 7567: }
1.506 raeburn 7568: return $response;
7569: }
1.776 albertel 7570:
1.506 raeburn 7571: sub auto_get_sections {
1.508 raeburn 7572: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 7573: my $homeserver;
7574: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7575: $homeserver = &homeserver($cnum,$cdom);
7576: }
7577: if (!defined($homeserver)) {
7578: if ($cdom =~ /^$match_domain$/) {
7579: $homeserver = &domain($cdom,'primary');
7580: }
7581: }
7582: my @secs;
7583: if (defined($homeserver)) {
7584: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
7585: unless ($response eq 'refused') {
7586: @secs = split(/:/,$response);
7587: }
1.506 raeburn 7588: }
7589: return @secs;
7590: }
1.776 albertel 7591:
1.506 raeburn 7592: sub auto_new_course {
1.1099 raeburn 7593: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 7594: my $homeserver = &homeserver($cnum,$cdom);
1.1099 raeburn 7595: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 7596: return $response;
7597: }
1.776 albertel 7598:
1.506 raeburn 7599: sub auto_validate_courseID {
1.508 raeburn 7600: my ($cnum,$cdom,$inst_course_id) = @_;
7601: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 7602: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 7603: return $response;
7604: }
1.776 albertel 7605:
1.1007 raeburn 7606: sub auto_validate_instcode {
1.1020 raeburn 7607: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 7608: my ($homeserver,$response);
7609: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7610: $homeserver = &homeserver($cnum,$cdom);
7611: }
7612: if (!defined($homeserver)) {
7613: if ($cdom =~ /^$match_domain$/) {
7614: $homeserver = &domain($cdom,'primary');
7615: }
7616: }
1.1065 raeburn 7617: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
7618: &escape($instcode).':'.&escape($owner),$homeserver));
1.1216 raeburn 7619: my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
7620: return ($outcome,$description,$defaultcredits);
1.1007 raeburn 7621: }
7622:
1.506 raeburn 7623: sub auto_create_password {
1.873 raeburn 7624: my ($cnum,$cdom,$authparam,$udom) = @_;
7625: my ($homeserver,$response);
1.506 raeburn 7626: my $create_passwd = 0;
7627: my $authchk = '';
1.873 raeburn 7628: if ($udom =~ /^$match_domain$/) {
7629: $homeserver = &domain($udom,'primary');
7630: }
7631: if ($homeserver eq '') {
7632: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7633: $homeserver = &homeserver($cnum,$cdom);
7634: }
7635: }
7636: if ($homeserver eq '') {
7637: $authchk = 'nodomain';
1.506 raeburn 7638: } else {
1.873 raeburn 7639: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
7640: if ($response eq 'refused') {
7641: $authchk = 'refused';
7642: } else {
1.901 albertel 7643: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 7644: }
1.506 raeburn 7645: }
7646: return ($authparam,$create_passwd,$authchk);
7647: }
7648:
1.706 raeburn 7649: sub auto_photo_permission {
7650: my ($cnum,$cdom,$students) = @_;
7651: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 7652: my ($outcome,$perm_reqd,$conditions) =
7653: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 7654: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7655: return (undef,undef);
7656: }
1.706 raeburn 7657: return ($outcome,$perm_reqd,$conditions);
7658: }
7659:
7660: sub auto_checkphotos {
7661: my ($uname,$udom,$pid) = @_;
7662: my $homeserver = &homeserver($uname,$udom);
7663: my ($result,$resulttype);
7664: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 7665: &escape($uname).':'.&escape($pid),
7666: $homeserver));
1.709 albertel 7667: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7668: return (undef,undef);
7669: }
1.706 raeburn 7670: if ($outcome) {
7671: ($result,$resulttype) = split(/:/,$outcome);
7672: }
7673: return ($result,$resulttype);
7674: }
7675:
7676: sub auto_photochoice {
7677: my ($cnum,$cdom) = @_;
7678: my $homeserver = &homeserver($cnum,$cdom);
7679: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 7680: &escape($cdom),
7681: $homeserver)));
1.709 albertel 7682: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7683: return (undef,undef);
7684: }
1.706 raeburn 7685: return ($update,$comment);
7686: }
7687:
7688: sub auto_photoupdate {
7689: my ($affiliatesref,$dom,$cnum,$photo) = @_;
7690: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 7691: my $host=&hostname($homeserver);
1.706 raeburn 7692: my $cmd = '';
7693: my $maxtries = 1;
1.800 albertel 7694: foreach my $affiliate (keys(%{$affiliatesref})) {
7695: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 7696: }
7697: $cmd =~ s/%%$//;
7698: $cmd = &escape($cmd);
7699: my $query = 'institutionalphotos';
7700: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
7701: unless ($queryid=~/^\Q$host\E\_/) {
7702: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
7703: return 'error: '.$queryid;
7704: }
7705: my $reply = &get_query_reply($queryid);
7706: my $tries = 1;
7707: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
7708: $reply = &get_query_reply($queryid);
7709: $tries ++;
7710: }
7711: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
7712: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
7713: } else {
7714: my @responses = split(/:/,$reply);
7715: my $outcome = shift(@responses);
7716: foreach my $item (@responses) {
7717: my ($key,$value) = split(/=/,$item);
7718: $$photo{$key} = $value;
7719: }
7720: return $outcome;
7721: }
7722: return 'error';
7723: }
7724:
1.521 raeburn 7725: sub auto_instcode_format {
1.793 albertel 7726: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
7727: $cat_order) = @_;
1.521 raeburn 7728: my $courses = '';
1.772 raeburn 7729: my @homeservers;
1.521 raeburn 7730: if ($caller eq 'global') {
1.841 albertel 7731: my %servers = &get_servers($codedom,'library');
7732: foreach my $tryserver (keys(%servers)) {
7733: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7734: push(@homeservers,$tryserver);
7735: }
1.584 raeburn 7736: }
1.1022 raeburn 7737: } elsif ($caller eq 'requests') {
7738: if ($codedom =~ /^$match_domain$/) {
7739: my $chome = &domain($codedom,'primary');
7740: unless ($chome eq 'no_host') {
7741: push(@homeservers,$chome);
7742: }
7743: }
1.521 raeburn 7744: } else {
1.772 raeburn 7745: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 7746: }
1.793 albertel 7747: foreach my $code (keys(%{$instcodes})) {
7748: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 7749: }
7750: chop($courses);
1.772 raeburn 7751: my $ok_response = 0;
7752: my $response;
7753: while (@homeservers > 0 && $ok_response == 0) {
7754: my $server = shift(@homeservers);
7755: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
7756: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
7757: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 7758: split(/:/,$response);
1.772 raeburn 7759: %{$codes} = (%{$codes},&str2hash($codes_str));
7760: push(@{$codetitles},&str2array($codetitles_str));
7761: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
7762: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
7763: $ok_response = 1;
7764: }
7765: }
7766: if ($ok_response) {
1.521 raeburn 7767: return 'ok';
1.772 raeburn 7768: } else {
7769: return $response;
1.521 raeburn 7770: }
7771: }
7772:
1.792 raeburn 7773: sub auto_instcode_defaults {
7774: my ($domain,$returnhash,$code_order) = @_;
7775: my @homeservers;
1.841 albertel 7776:
7777: my %servers = &get_servers($domain,'library');
7778: foreach my $tryserver (keys(%servers)) {
7779: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7780: push(@homeservers,$tryserver);
7781: }
1.792 raeburn 7782: }
1.841 albertel 7783:
1.792 raeburn 7784: my $response;
1.841 albertel 7785: foreach my $server (@homeservers) {
1.792 raeburn 7786: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 7787: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
7788:
7789: foreach my $pair (split(/\&/,$response)) {
7790: my ($name,$value)=split(/\=/,$pair);
7791: if ($name eq 'code_order') {
7792: @{$code_order} = split(/\&/,&unescape($value));
7793: } else {
7794: $returnhash->{&unescape($name)}=&unescape($value);
7795: }
7796: }
7797: return 'ok';
1.792 raeburn 7798: }
1.841 albertel 7799:
7800: return $response;
1.1003 raeburn 7801: }
7802:
7803: sub auto_possible_instcodes {
1.1007 raeburn 7804: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
7805: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
7806: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
7807: return;
7808: }
1.1003 raeburn 7809: my (@homeservers,$uhome);
7810: if (defined(&domain($domain,'primary'))) {
7811: $uhome=&domain($domain,'primary');
7812: push(@homeservers,&domain($domain,'primary'));
7813: } else {
7814: my %servers = &get_servers($domain,'library');
7815: foreach my $tryserver (keys(%servers)) {
7816: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7817: push(@homeservers,$tryserver);
7818: }
7819: }
7820: }
7821: my $response;
7822: foreach my $server (@homeservers) {
7823: $response=&reply('autopossibleinstcodes:'.$domain,$server);
7824: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 7825: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
7826: split(':',$response);
7827: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
7828: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 7829: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 7830: my ($name,$value)=split('=',$item);
7831: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 7832: }
7833: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 7834: my ($name,$value)=split('=',$item);
7835: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 7836: }
7837: return 'ok';
7838: }
7839: return $response;
7840: }
1.792 raeburn 7841:
1.1010 raeburn 7842: sub auto_courserequest_checks {
7843: my ($dom) = @_;
1.1020 raeburn 7844: my ($homeserver,%validations);
7845: if ($dom =~ /^$match_domain$/) {
7846: $homeserver = &domain($dom,'primary');
7847: }
7848: unless ($homeserver eq 'no_host') {
7849: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
7850: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
7851: my @items = split(/&/,$response);
7852: foreach my $item (@items) {
7853: my ($key,$value) = split('=',$item);
7854: $validations{&unescape($key)} = &thaw_unescape($value);
7855: }
7856: }
7857: }
1.1010 raeburn 7858: return %validations;
7859: }
7860:
1.1020 raeburn 7861: sub auto_courserequest_validation {
1.1255 raeburn 7862: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020 raeburn 7863: my ($homeserver,$response);
7864: if ($dom =~ /^$match_domain$/) {
7865: $homeserver = &domain($dom,'primary');
7866: }
1.1255 raeburn 7867: unless ($homeserver eq 'no_host') {
7868: my $customdata;
7869: if (ref($custominfo) eq 'HASH') {
7870: $customdata = &freeze_escape($custominfo);
7871: }
1.1020 raeburn 7872: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 7873: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1255 raeburn 7874: ':'.&escape($instcode).':'.&escape($instseclist).':'.
7875: $customdata,$homeserver));
1.1020 raeburn 7876: }
7877: return $response;
7878: }
7879:
1.777 albertel 7880: sub auto_validate_class_sec {
1.918 raeburn 7881: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 7882: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 7883: my $ownerlist;
7884: if (ref($owners) eq 'ARRAY') {
7885: $ownerlist = join(',',@{$owners});
7886: } else {
7887: $ownerlist = $owners;
7888: }
1.773 raeburn 7889: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 7890: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 7891: return $response;
7892: }
7893:
1.1248 raeburn 7894: sub auto_crsreq_update {
7895: my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
7896: $code,$inbound) = @_;
7897: my ($homeserver,%crsreqresponse);
7898: if ($cdom =~ /^$match_domain$/) {
7899: $homeserver = &domain($cdom,'primary');
7900: }
7901: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
7902: my $info;
7903: if (ref($inbound) eq 'HASH') {
7904: $info = &freeze_escape($inbound);
7905: }
7906: my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
7907: ':'.&escape($action).':'.&escape($ownername).':'.
7908: &escape($ownerdomain).':'.&escape($fullname).':'.
7909: &escape($title).':'.&escape($code).':'.$info,$homeserver);
7910: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
7911: my @items = split(/&/,$response);
7912: foreach my $item (@items) {
7913: my ($key,$value) = split('=',$item);
7914: $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
7915: }
7916: }
7917: }
7918: return \%crsreqresponse;
7919: }
7920:
1.679 raeburn 7921: # ------------------------------------------------------- Course Group routines
7922:
7923: sub get_coursegroups {
1.809 raeburn 7924: my ($cdom,$cnum,$group,$namespace) = @_;
7925: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 7926: }
7927:
1.679 raeburn 7928: sub modify_coursegroup {
7929: my ($cdom,$cnum,$groupsettings) = @_;
7930: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
7931: }
7932:
1.809 raeburn 7933: sub toggle_coursegroup_status {
7934: my ($cdom,$cnum,$group,$action) = @_;
7935: my ($from_namespace,$to_namespace);
7936: if ($action eq 'delete') {
7937: $from_namespace = 'coursegroups';
7938: $to_namespace = 'deleted_groups';
7939: } else {
7940: $from_namespace = 'deleted_groups';
7941: $to_namespace = 'coursegroups';
7942: }
7943: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 7944: if (my $tmp = &error(%curr_group)) {
7945: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
7946: return ('read error',$tmp);
7947: } else {
7948: my %savedsettings = %curr_group;
1.809 raeburn 7949: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 7950: my $deloutcome;
7951: if ($result eq 'ok') {
1.809 raeburn 7952: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 7953: } else {
7954: return ('write error',$result);
7955: }
7956: if ($deloutcome eq 'ok') {
7957: return 'ok';
7958: } else {
7959: return ('delete error',$deloutcome);
7960: }
7961: }
7962: }
7963:
1.679 raeburn 7964: sub modify_group_roles {
1.957 raeburn 7965: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 7966: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
7967: my $role = 'gr/'.&escape($userprivs);
7968: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 7969: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 7970: if ($result eq 'ok') {
7971: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
7972: }
1.679 raeburn 7973: return $result;
7974: }
7975:
7976: sub modify_coursegroup_membership {
7977: my ($cdom,$cnum,$membership) = @_;
7978: my $result = &put('groupmembership',$membership,$cdom,$cnum);
7979: return $result;
7980: }
7981:
1.682 raeburn 7982: sub get_active_groups {
7983: my ($udom,$uname,$cdom,$cnum) = @_;
7984: my $now = time;
7985: my %groups = ();
7986: foreach my $key (keys(%env)) {
1.811 albertel 7987: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 7988: my ($start,$end) = split(/\./,$env{$key});
7989: if (($end!=0) && ($end<$now)) { next; }
7990: if (($start!=0) && ($start>$now)) { next; }
7991: if ($1 eq $cdom && $2 eq $cnum) {
7992: $groups{$3} = $env{$key} ;
7993: }
7994: }
7995: }
7996: return %groups;
7997: }
7998:
1.683 raeburn 7999: sub get_group_membership {
8000: my ($cdom,$cnum,$group) = @_;
8001: return(&dump('groupmembership',$cdom,$cnum,$group));
8002: }
8003:
8004: sub get_users_groups {
8005: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 8006: my @usersgroups;
1.683 raeburn 8007: my $cachetime=1800;
8008:
8009: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 8010: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
8011: if (defined($cached)) {
1.734 albertel 8012: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 8013: } else {
8014: $grouplist = '';
1.816 raeburn 8015: my $courseurl = &courseid_to_courseurl($courseid);
1.1166 raeburn 8016: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 8017: my $access_end = $env{'course.'.$courseid.
8018: '.default_enrollment_end_date'};
8019: my $now = time;
8020: foreach my $key (keys(%roleshash)) {
8021: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
8022: my $group = $1;
8023: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
8024: my $start = $2;
8025: my $end = $1;
8026: if ($start == -1) { next; } # deleted from group
8027: if (($start!=0) && ($start>$now)) { next; }
8028: if (($end!=0) && ($end<$now)) {
8029: if ($access_end && $access_end < $now) {
8030: if ($access_end - $end < 86400) {
8031: push(@usersgroups,$group);
1.733 raeburn 8032: }
8033: }
1.817 raeburn 8034: next;
1.733 raeburn 8035: }
1.817 raeburn 8036: push(@usersgroups,$group);
1.683 raeburn 8037: }
8038: }
8039: }
1.817 raeburn 8040: @usersgroups = &sort_course_groups($courseid,@usersgroups);
8041: $grouplist = join(':',@usersgroups);
8042: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 8043: }
1.733 raeburn 8044: return @usersgroups;
1.683 raeburn 8045: }
8046:
8047: sub devalidate_getgroups_cache {
8048: my ($udom,$uname,$cdom,$cnum)=@_;
8049: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 8050:
1.683 raeburn 8051: my $hashid="$udom:$uname:$courseid";
8052: &devalidate_cache_new('getgroups',$hashid);
8053: }
8054:
1.12 www 8055: # ------------------------------------------------------------------ Plain Text
8056:
8057: sub plaintext {
1.988 raeburn 8058: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 8059: if ($short =~ m{^cr/}) {
1.758 albertel 8060: return (split('/',$short))[-1];
8061: }
1.742 raeburn 8062: if (!defined($cid)) {
8063: $cid = $env{'request.course.id'};
8064: }
8065: my %rolenames = (
1.1008 raeburn 8066: Course => 'std',
8067: Community => 'alt1',
1.742 raeburn 8068: );
1.1037 raeburn 8069: if ($cid ne '') {
8070: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
8071: unless ($forcedefault) {
8072: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
8073: &Apache::lonlocal::mt_escape(\$roletext);
8074: return &Apache::lonlocal::mt($roletext);
8075: }
8076: }
8077: }
8078: if ((defined($type)) && (defined($rolenames{$type})) &&
8079: (defined($rolenames{$type})) &&
8080: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 8081: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 8082: } elsif ($cid ne '') {
8083: my $crstype = $env{'course.'.$cid.'.type'};
8084: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
8085: (defined($prp{$short}{$rolenames{$crstype}}))) {
8086: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
8087: }
1.742 raeburn 8088: }
1.1037 raeburn 8089: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 8090: }
8091:
8092: # ----------------------------------------------------------------- Assign Role
8093:
8094: sub assignrole {
1.957 raeburn 8095: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
8096: $context)=@_;
1.21 www 8097: my $mrole;
8098: if ($role =~ /^cr\//) {
1.393 www 8099: my $cwosec=$url;
1.811 albertel 8100: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 8101: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 8102: my $refused = 1;
8103: if ($context eq 'requestcourses') {
8104: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
8105: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
8106: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
8107: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8108: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8109: if ($crsenv{'internal.courseowner'} eq
8110: $env{'user.name'}.':'.$env{'user.domain'}) {
8111: $refused = '';
8112: }
8113: }
8114: }
8115: }
8116: }
8117: if ($refused) {
8118: &logthis('Refused custom assignrole: '.
8119: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
8120: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
8121: return 'refused';
8122: }
1.104 www 8123: }
1.21 www 8124: $mrole='cr';
1.678 raeburn 8125: } elsif ($role =~ /^gr\//) {
8126: my $cwogrp=$url;
1.811 albertel 8127: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 8128: unless (&allowed('mdg',$cwogrp)) {
8129: &logthis('Refused group assignrole: '.
8130: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
8131: $env{'user.name'}.' at '.$env{'user.domain'});
8132: return 'refused';
8133: }
8134: $mrole='gr';
1.21 www 8135: } else {
1.82 www 8136: my $cwosec=$url;
1.811 albertel 8137: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 8138: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
8139: my $refused;
8140: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
8141: if (!(&allowed('c'.$role,$url))) {
8142: $refused = 1;
8143: }
8144: } else {
8145: $refused = 1;
8146: }
1.947 raeburn 8147: if ($refused) {
1.1045 raeburn 8148: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8149: if (!$selfenroll && $context eq 'course') {
8150: my %crsenv;
8151: if ($role eq 'cc' || $role eq 'co') {
8152: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8153: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
8154: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
8155: if ($crsenv{'internal.courseowner'} eq
8156: $env{'user.name'}.':'.$env{'user.domain'}) {
8157: $refused = '';
8158: }
8159: }
8160: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
8161: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
8162: if ($crsenv{'internal.courseowner'} eq
8163: $env{'user.name'}.':'.$env{'user.domain'}) {
8164: $refused = '';
8165: }
8166: }
8167: }
8168: }
8169: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 8170: $refused = '';
1.1017 raeburn 8171: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 8172: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 8173: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 8174: my $wrongcc;
8175: if ($cnum =~ /^$match_community$/) {
8176: $wrongcc = 1 if ($role eq 'cc');
8177: } else {
8178: $wrongcc = 1 if ($role eq 'co');
8179: }
8180: unless ($wrongcc) {
8181: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8182: if ($crsenv{'internal.courseowner'} eq
8183: $env{'user.name'}.':'.$env{'user.domain'}) {
8184: $refused = '';
8185: }
1.1017 raeburn 8186: }
8187: }
1.1183 raeburn 8188: } elsif ($context eq 'requestauthor') {
8189: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
8190: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
8191: if ($env{'environment.requestauthor'} eq 'automatic') {
8192: $refused = '';
8193: } else {
8194: my %domdefaults = &get_domain_defaults($udom);
8195: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
8196: my $checkbystatus;
8197: if ($env{'user.adv'}) {
8198: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
8199: if ($disposition eq 'automatic') {
8200: $refused = '';
8201: } elsif ($disposition eq '') {
8202: $checkbystatus = 1;
8203: }
8204: } else {
8205: $checkbystatus = 1;
8206: }
8207: if ($checkbystatus) {
8208: if ($env{'environment.inststatus'}) {
8209: my @inststatuses = split(/,/,$env{'environment.inststatus'});
8210: foreach my $type (@inststatuses) {
8211: if (($type ne '') &&
8212: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
8213: $refused = '';
8214: }
8215: }
8216: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
8217: $refused = '';
8218: }
8219: }
8220: }
8221: }
8222: }
1.1017 raeburn 8223: }
8224: if ($refused) {
1.947 raeburn 8225: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
8226: ' '.$role.' '.$end.' '.$start.' by '.
8227: $env{'user.name'}.' at '.$env{'user.domain'});
8228: return 'refused';
8229: }
1.932 raeburn 8230: }
1.1131 raeburn 8231: } elsif ($role eq 'au') {
8232: if ($url ne '/'.$udom.'/') {
8233: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
8234: ' to assign author role for '.$uname.':'.$udom.
8235: ' in domain: '.$url.' refused (wrong domain).');
8236: return 'refused';
8237: }
1.104 www 8238: }
1.21 www 8239: $mrole=$role;
8240: }
1.620 albertel 8241: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 8242: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 8243: if ($end) { $command.='_'.$end; }
1.21 www 8244: if ($start) {
8245: if ($end) {
1.81 www 8246: $command.='_'.$start;
1.21 www 8247: } else {
1.81 www 8248: $command.='_0_'.$start;
1.21 www 8249: }
8250: }
1.739 raeburn 8251: my $origstart = $start;
8252: my $origend = $end;
1.957 raeburn 8253: my $delflag;
1.357 www 8254: # actually delete
8255: if ($deleteflag) {
1.373 www 8256: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 8257: # modify command to delete the role
1.620 albertel 8258: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 8259: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 8260: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 8261: # set start and finish to negative values for userrolelog
8262: $start=-1;
8263: $end=-1;
1.957 raeburn 8264: $delflag = 1;
1.357 www 8265: }
8266: }
8267: # send command
1.349 www 8268: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 8269: # log new user role if status is ok
1.349 www 8270: if ($answer eq 'ok') {
1.663 raeburn 8271: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.1184 raeburn 8272: if (($role eq 'cc') || ($role eq 'in') ||
8273: ($role eq 'ep') || ($role eq 'ad') ||
8274: ($role eq 'ta') || ($role eq 'st') ||
8275: ($role=~/^cr/) || ($role eq 'gr') ||
8276: ($role eq 'co')) {
1.1200 raeburn 8277: # for course roles, perform group memberships changes triggered by role change.
8278: unless ($role =~ /^gr/) {
8279: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
8280: $origstart,$selfenroll,$context);
8281: }
1.1184 raeburn 8282: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8283: $selfenroll,$context);
8284: } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
8285: ($role eq 'au') || ($role eq 'dc')) {
8286: &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8287: $context);
8288: } elsif (($role eq 'ca') || ($role eq 'aa')) {
8289: &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8290: $context);
8291: }
1.1053 raeburn 8292: if ($role eq 'cc') {
8293: &autoupdate_coowners($url,$end,$start,$uname,$udom);
8294: }
1.349 www 8295: }
8296: return $answer;
1.169 harris41 8297: }
8298:
1.1053 raeburn 8299: sub autoupdate_coowners {
8300: my ($url,$end,$start,$uname,$udom) = @_;
8301: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
8302: if (($cdom ne '') && ($cnum ne '')) {
8303: my $now = time;
8304: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
8305: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
8306: my %coursehash = &coursedescription($cdom.'_'.$cnum);
8307: my $instcode = $coursehash{'internal.coursecode'};
8308: if ($instcode ne '') {
1.1056 raeburn 8309: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
8310: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 8311: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 8312: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
8313: if ($result eq 'valid') {
8314: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 8315: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
8316: push(@newcoowners,$coowner);
8317: }
8318: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
8319: push(@newcoowners,$uname.':'.$udom);
8320: }
8321: @newcoowners = sort(@newcoowners);
8322: } else {
8323: push(@newcoowners,$uname.':'.$udom);
8324: }
8325: } else {
8326: if ($coursehash{'internal.co-owners'}) {
8327: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
8328: unless ($coowner eq $uname.':'.$udom) {
8329: push(@newcoowners,$coowner);
8330: }
8331: }
8332: unless (@newcoowners > 0) {
8333: $delcoowners = 1;
8334: $coowners = '';
8335: }
8336: }
8337: }
8338: if (@newcoowners || $delcoowners) {
8339: &store_coowners($cdom,$cnum,$coursehash{'home'},
8340: $delcoowners,@newcoowners);
8341: }
8342: }
8343: }
8344: }
8345: }
8346: }
8347: }
8348:
8349: sub store_coowners {
8350: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
8351: my $cid = $cdom.'_'.$cnum;
8352: my ($coowners,$delresult,$putresult);
8353: if (@newcoowners) {
8354: $coowners = join(',',@newcoowners);
8355: my %coownershash = (
8356: 'internal.co-owners' => $coowners,
8357: );
8358: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
8359: if ($putresult eq 'ok') {
8360: if ($env{'course.'.$cid.'.num'} eq $cnum) {
8361: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
8362: }
8363: }
8364: }
8365: if ($delcoowners) {
8366: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
8367: if ($delresult eq 'ok') {
8368: if ($env{'course.'.$cid.'.internal.co-owners'}) {
8369: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
8370: }
8371: }
8372: }
8373: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
8374: my %crsinfo =
8375: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
8376: if (ref($crsinfo{$cid}) eq 'HASH') {
8377: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
8378: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
8379: }
8380: }
8381: }
8382:
1.169 harris41 8383: # -------------------------------------------------- Modify user authentication
1.197 www 8384: # Overrides without validation
8385:
1.169 harris41 8386: sub modifyuserauth {
8387: my ($udom,$uname,$umode,$upass)=@_;
8388: my $uhome=&homeserver($uname,$udom);
1.197 www 8389: unless (&allowed('mau',$udom)) { return 'refused'; }
8390: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 8391: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
8392: ' in domain '.$env{'request.role.domain'});
1.169 harris41 8393: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
8394: &escape($upass),$uhome);
1.620 albertel 8395: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 8396: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
8397: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
8398: &log($udom,,$uname,$uhome,
1.620 albertel 8399: 'Authentication changed by '.$env{'user.domain'}.', '.
8400: $env{'user.name'}.', '.$umode.
1.197 www 8401: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 8402: unless ($reply eq 'ok') {
1.197 www 8403: &logthis('Authentication mode error: '.$reply);
1.169 harris41 8404: return 'error: '.$reply;
8405: }
1.170 harris41 8406: return 'ok';
1.80 www 8407: }
8408:
1.81 www 8409: # --------------------------------------------------------------- Modify a user
1.80 www 8410:
1.81 www 8411: sub modifyuser {
1.206 matthew 8412: my ($udom, $uname, $uid,
8413: $umode, $upass, $first,
8414: $middle, $last, $gene,
1.1058 raeburn 8415: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 8416: $udom= &LONCAPA::clean_domain($udom);
8417: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 8418: my $showcandelete = 'none';
8419: if (ref($candelete) eq 'ARRAY') {
8420: if (@{$candelete} > 0) {
8421: $showcandelete = join(', ',@{$candelete});
8422: }
8423: }
1.81 www 8424: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 8425: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 8426: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 8427: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
8428: ' desiredhome not specified').
1.620 albertel 8429: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
8430: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 8431: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 8432: my $newuser;
8433: if ($uhome eq 'no_host') {
8434: $newuser = 1;
8435: }
1.80 www 8436: # ----------------------------------------------------------------- Create User
1.406 albertel 8437: if (($uhome eq 'no_host') &&
8438: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 8439: my $unhome='';
1.844 albertel 8440: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 8441: $unhome = $desiredhome;
1.620 albertel 8442: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
8443: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 8444: } else { # load balancing routine for determining $unhome
1.81 www 8445: my $loadm=10000000;
1.841 albertel 8446: my %servers = &get_servers($udom,'library');
8447: foreach my $tryserver (keys(%servers)) {
8448: my $answer=reply('load',$tryserver);
8449: if (($answer=~/\d+/) && ($answer<$loadm)) {
8450: $loadm=$answer;
8451: $unhome=$tryserver;
8452: }
1.80 www 8453: }
8454: }
8455: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 8456: return 'error: unable to find a home server for '.$uname.
8457: ' in domain '.$udom;
1.80 www 8458: }
8459: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
8460: &escape($upass),$unhome);
8461: unless ($reply eq 'ok') {
8462: return 'error: '.$reply;
8463: }
1.230 stredwic 8464: $uhome=&homeserver($uname,$udom,'true');
1.80 www 8465: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 8466: return 'error: unable verify users home machine.';
1.80 www 8467: }
1.209 matthew 8468: } # End of creation of new user
1.80 www 8469: # ---------------------------------------------------------------------- Add ID
8470: if ($uid) {
8471: $uid=~tr/A-Z/a-z/;
8472: my %uidhash=&idrget($udom,$uname);
1.196 www 8473: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
8474: && (!$forceid)) {
1.80 www 8475: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 8476: return 'error: user id "'.$uid.'" does not match '.
8477: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 8478: }
8479: } else {
8480: &idput($udom,($uname => $uid));
8481: }
8482: }
8483: # -------------------------------------------------------------- Add names, etc
1.313 matthew 8484: my @tmp=&get('environment',
1.899 raeburn 8485: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 8486: 'permanentemail','inststatus'],
1.134 albertel 8487: $udom,$uname);
1.1075 raeburn 8488: my (%names,%oldnames);
1.313 matthew 8489: if ($tmp[0] =~ m/^error:.*/) {
8490: %names=();
8491: } else {
8492: %names = @tmp;
1.1075 raeburn 8493: %oldnames = %names;
1.313 matthew 8494: }
1.388 www 8495: #
1.1058 raeburn 8496: # If name, email and/or uid are blank (e.g., because an uploaded file
8497: # of users did not contain them), do not overwrite existing values
8498: # unless field is in $candelete array ref.
8499: #
8500:
8501: my @fields = ('firstname','middlename','lastname','generation',
8502: 'permanentemail','id');
8503: my %newvalues;
8504: if (ref($candelete) eq 'ARRAY') {
8505: foreach my $field (@fields) {
8506: if (grep(/^\Q$field\E$/,@{$candelete})) {
8507: if ($field eq 'firstname') {
8508: $names{$field} = $first;
8509: } elsif ($field eq 'middlename') {
8510: $names{$field} = $middle;
8511: } elsif ($field eq 'lastname') {
8512: $names{$field} = $last;
8513: } elsif ($field eq 'generation') {
8514: $names{$field} = $gene;
8515: } elsif ($field eq 'permanentemail') {
8516: $names{$field} = $email;
8517: } elsif ($field eq 'id') {
8518: $names{$field} = $uid;
8519: }
8520: }
8521: }
8522: }
1.388 www 8523: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 8524: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 8525: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 8526: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 8527: if ($email) {
8528: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 8529: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 8530: }
1.899 raeburn 8531: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 8532: if (defined($inststatus)) {
8533: $names{'inststatus'} = '';
8534: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
8535: if (ref($usertypes) eq 'HASH') {
8536: my @okstatuses;
8537: foreach my $item (split(/:/,$inststatus)) {
8538: if (defined($usertypes->{$item})) {
8539: push(@okstatuses,$item);
8540: }
8541: }
8542: if (@okstatuses) {
8543: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
8544: }
8545: }
8546: }
1.1075 raeburn 8547: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 8548: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 8549: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 8550: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
8551: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
8552: } else {
8553: $logmsg .= ' during self creation';
8554: }
1.1075 raeburn 8555: my $changed;
8556: if ($newuser) {
8557: $changed = 1;
8558: } else {
8559: foreach my $field (@fields) {
8560: if ($names{$field} ne $oldnames{$field}) {
8561: $changed = 1;
8562: last;
8563: }
8564: }
8565: }
8566: unless ($changed) {
8567: $logmsg = 'No changes in user information needed for: '.$logmsg;
8568: &logthis($logmsg);
8569: return 'ok';
8570: }
8571: my $reply = &put('environment', \%names, $udom,$uname);
8572: if ($reply ne 'ok') {
8573: return 'error: '.$reply;
8574: }
1.1087 raeburn 8575: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
8576: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
8577: }
1.1075 raeburn 8578: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
8579: &devalidate_cache_new('namescache',$uname.':'.$udom);
8580: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 8581: &logthis($logmsg);
1.134 albertel 8582: return 'ok';
1.80 www 8583: }
8584:
1.81 www 8585: # -------------------------------------------------------------- Modify student
1.80 www 8586:
1.81 www 8587: sub modifystudent {
8588: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 8589: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1216 raeburn 8590: $selfenroll,$context,$inststatus,$credits)=@_;
1.455 albertel 8591: if (!$cid) {
1.620 albertel 8592: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 8593: return 'not_in_class';
8594: }
1.80 www 8595: }
8596: # --------------------------------------------------------------- Make the user
1.81 www 8597: my $reply=&modifyuser
1.209 matthew 8598: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 8599: $desiredhome,$email,$inststatus);
1.80 www 8600: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 8601: # This will cause &modify_student_enrollment to get the uid from the
1.1235 raeburn 8602: # student's environment
1.297 matthew 8603: $uid = undef if (!$forceid);
1.455 albertel 8604: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1216 raeburn 8605: $gene,$usec,$end,$start,$type,$locktype,
8606: $cid,$selfenroll,$context,$credits);
1.297 matthew 8607: return $reply;
8608: }
8609:
8610: sub modify_student_enrollment {
1.1216 raeburn 8611: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
8612: $locktype,$cid,$selfenroll,$context,$credits) = @_;
1.455 albertel 8613: my ($cdom,$cnum,$chome);
8614: if (!$cid) {
1.620 albertel 8615: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 8616: return 'not_in_class';
8617: }
1.620 albertel 8618: $cdom=$env{'course.'.$cid.'.domain'};
8619: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 8620: } else {
8621: ($cdom,$cnum)=split(/_/,$cid);
8622: }
1.620 albertel 8623: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 8624: if (!$chome) {
1.457 raeburn 8625: $chome=&homeserver($cnum,$cdom);
1.297 matthew 8626: }
1.455 albertel 8627: if (!$chome) { return 'unknown_course'; }
1.297 matthew 8628: # Make sure the user exists
1.81 www 8629: my $uhome=&homeserver($uname,$udom);
8630: if (($uhome eq '') || ($uhome eq 'no_host')) {
8631: return 'error: no such user';
8632: }
1.297 matthew 8633: # Get student data if we were not given enough information
8634: if (!defined($first) || $first eq '' ||
8635: !defined($last) || $last eq '' ||
8636: !defined($uid) || $uid eq '' ||
8637: !defined($middle) || $middle eq '' ||
8638: !defined($gene) || $gene eq '') {
1.294 matthew 8639: # They did not supply us with enough data to enroll the student, so
8640: # we need to pick up more information.
1.297 matthew 8641: my %tmp = &get('environment',
1.294 matthew 8642: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 8643: ,$udom,$uname);
8644:
1.800 albertel 8645: #foreach my $key (keys(%tmp)) {
8646: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 8647: #}
1.294 matthew 8648: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
8649: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
8650: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 8651: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 8652: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
8653: }
1.556 albertel 8654: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148 raeburn 8655: my $user = "$uname:$udom";
8656: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487 albertel 8657: my $reply=cput('classlist',
1.1148 raeburn 8658: {$user =>
1.1216 raeburn 8659: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits) },
1.487 albertel 8660: $cdom,$cnum);
1.1148 raeburn 8661: if (($reply eq 'ok') || ($reply eq 'delayed')) {
8662: &devalidate_getsection_cache($udom,$uname,$cid);
8663: } else {
1.81 www 8664: return 'error: '.$reply;
8665: }
1.297 matthew 8666: # Add student role to user
1.83 www 8667: my $uurl='/'.$cid;
1.81 www 8668: $uurl=~s/\_/\//g;
8669: if ($usec) {
8670: $uurl.='/'.$usec;
8671: }
1.1148 raeburn 8672: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
8673: $selfenroll,$context);
8674: if ($result ne 'ok') {
8675: if ($old_entry{$user} ne '') {
8676: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
8677: } else {
8678: $reply = &del('classlist',[$user],$cdom,$cnum);
8679: }
8680: }
8681: return $result;
1.21 www 8682: }
8683:
1.556 albertel 8684: sub format_name {
8685: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
8686: my $name;
8687: if ($first ne 'lastname') {
8688: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
8689: } else {
8690: if ($lastname=~/\S/) {
8691: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
8692: $name=~s/\s+,/,/;
8693: } else {
8694: $name.= $firstname.' '.$middlename.' '.$generation;
8695: }
8696: }
8697: $name=~s/^\s+//;
8698: $name=~s/\s+$//;
8699: $name=~s/\s+/ /g;
8700: return $name;
8701: }
8702:
1.84 www 8703: # ------------------------------------------------- Write to course preferences
8704:
8705: sub writecoursepref {
8706: my ($courseid,%prefs)=@_;
8707: $courseid=~s/^\///;
8708: $courseid=~s/\_/\//g;
8709: my ($cdomain,$cnum)=split(/\//,$courseid);
8710: my $chome=homeserver($cnum,$cdomain);
8711: if (($chome eq '') || ($chome eq 'no_host')) {
8712: return 'error: no such course';
8713: }
8714: my $cstring='';
1.800 albertel 8715: foreach my $pref (keys(%prefs)) {
8716: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 8717: }
1.84 www 8718: $cstring=~s/\&$//;
8719: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
8720: }
8721:
8722: # ---------------------------------------------------------- Make/modify course
8723:
8724: sub createcourse {
1.741 raeburn 8725: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 8726: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 8727: $url=&declutter($url);
8728: my $cid='';
1.1028 raeburn 8729: if ($context eq 'requestcourses') {
8730: my $can_create = 0;
8731: my ($ownername,$ownerdom) = split(':',$course_owner);
8732: if ($udom eq $ownerdom) {
8733: if (&usertools_access($ownername,$ownerdom,$category,undef,
8734: $context)) {
8735: $can_create = 1;
8736: }
8737: } else {
8738: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
8739: $category);
8740: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
8741: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
8742: if (@curr > 0) {
8743: my @options = qw(approval validate autolimit);
8744: my $optregex = join('|',@options);
8745: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
8746: $can_create = 1;
8747: }
8748: }
8749: }
8750: }
8751: if ($can_create) {
8752: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
8753: unless (&allowed('ccc',$udom)) {
8754: return 'refused';
8755: }
1.1017 raeburn 8756: }
8757: } else {
8758: return 'refused';
8759: }
1.1028 raeburn 8760: } elsif (!&allowed('ccc',$udom)) {
8761: return 'refused';
1.84 www 8762: }
1.1011 raeburn 8763: # --------------------------------------------------------------- Get Unique ID
8764: my $uname;
8765: if ($cnum =~ /^$match_courseid$/) {
8766: my $chome=&homeserver($cnum,$udom,'true');
8767: if (($chome eq '') || ($chome eq 'no_host')) {
8768: $uname = $cnum;
8769: } else {
1.1038 raeburn 8770: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 8771: }
8772: } else {
1.1038 raeburn 8773: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 8774: }
8775: return $uname if ($uname =~ /^error/);
8776: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 8777: if (!defined($course_server)) {
8778: if (defined(&domain($udom,'primary'))) {
8779: $course_server = &domain($udom,'primary');
8780: } else {
8781: $course_server = $env{'user.home'};
8782: }
8783: }
8784: my %host_servers =
8785: &Apache::lonnet::get_servers($udom,'library');
8786: unless ($host_servers{$course_server}) {
8787: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 8788: }
1.84 www 8789: # ------------------------------------------------------------- Make the course
8790: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 8791: $course_server);
1.84 www 8792: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 8793: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 8794: if (($uhome eq '') || ($uhome eq 'no_host')) {
8795: return 'error: no such course';
8796: }
1.271 www 8797: # ----------------------------------------------------------------- Course made
1.516 raeburn 8798: # log existence
1.1029 raeburn 8799: my $now = time;
1.918 raeburn 8800: my $newcourse = {
8801: $udom.'_'.$uname => {
1.921 raeburn 8802: description => $description,
8803: inst_code => $inst_code,
8804: owner => $course_owner,
8805: type => $crstype,
1.1029 raeburn 8806: creator => $env{'user.name'}.':'.
8807: $env{'user.domain'},
8808: created => $now,
8809: context => $context,
1.918 raeburn 8810: },
8811: };
1.921 raeburn 8812: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 8813: # set toplevel url
1.271 www 8814: my $topurl=$url;
8815: unless ($nonstandard) {
8816: # ------------------------------------------ For standard courses, make top url
8817: my $mapurl=&clutter($url);
1.278 www 8818: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 8819: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 8820: <map>
8821: <resource id="1" type="start"></resource>
8822: <resource id="2" src="$mapurl"></resource>
8823: <resource id="3" type="finish"></resource>
8824: <link index="1" from="1" to="2"></link>
8825: <link index="2" from="2" to="3"></link>
8826: </map>
8827: ENDINITMAP
8828: $topurl=&declutter(
1.638 albertel 8829: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 8830: );
8831: }
8832: # ----------------------------------------------------------- Write preferences
1.84 www 8833: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 8834: ('description' => $description,
8835: 'url' => $topurl,
8836: 'internal.creator' => $env{'user.name'}.':'.
8837: $env{'user.domain'},
8838: 'internal.created' => $now,
8839: 'internal.creationcontext' => $context)
8840: );
1.84 www 8841: return '/'.$udom.'/'.$uname;
8842: }
8843:
1.1011 raeburn 8844: # ------------------------------------------------------------------- Create ID
8845: sub generate_coursenum {
1.1038 raeburn 8846: my ($udom,$crstype) = @_;
1.1011 raeburn 8847: my $domdesc = &domain($udom);
8848: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 8849: my $first;
8850: if ($crstype eq 'Community') {
8851: $first = '0';
8852: } else {
8853: $first = int(1+rand(9));
8854: }
8855: my $uname=$first.
1.1011 raeburn 8856: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
8857: substr($$.time,0,5).unpack("H8",pack("I32",time)).
8858: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
8859: # ----------------------------------------------- Make sure that does not exist
8860: my $uhome=&homeserver($uname,$udom,'true');
8861: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 8862: if ($crstype eq 'Community') {
8863: $first = '0';
8864: } else {
8865: $first = int(1+rand(9));
8866: }
8867: $uname=$first.
1.1011 raeburn 8868: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
8869: substr($$.time,0,5).unpack("H8",pack("I32",time)).
8870: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
8871: $uhome=&homeserver($uname,$udom,'true');
8872: unless (($uhome eq '') || ($uhome eq 'no_host')) {
8873: return 'error: unable to generate unique course-ID';
8874: }
8875: }
8876: return $uname;
8877: }
8878:
1.813 albertel 8879: sub is_course {
1.1167 droeschl 8880: my ($cdom, $cnum) = scalar(@_) == 1 ?
8881: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
8882:
8883: return unless $cdom and $cnum;
8884:
8885: my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
8886: '.');
8887:
1.1219 raeburn 8888: return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167 droeschl 8889: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813 albertel 8890: }
8891:
1.1015 raeburn 8892: sub store_userdata {
8893: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 8894: my $result;
1.1016 raeburn 8895: if ($datakey ne '') {
1.1013 raeburn 8896: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 8897: if ($udom eq '' || $uname eq '') {
8898: $udom = $env{'user.domain'};
8899: $uname = $env{'user.name'};
8900: }
8901: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 8902: if (($uhome eq '') || ($uhome eq 'no_host')) {
8903: $result = 'error: no_host';
8904: } else {
8905: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
8906: $storehash->{'host'} = $perlvar{'lonHostID'};
8907:
8908: my $namevalue='';
8909: foreach my $key (keys(%{$storehash})) {
8910: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
8911: }
8912: $namevalue=~s/\&$//;
1.1224 raeburn 8913: unless ($namespace eq 'courserequests') {
8914: $datakey = &escape($datakey);
8915: }
1.1105 raeburn 8916: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
8917: $namevalue,$uhome);
1.1013 raeburn 8918: }
8919: } else {
8920: $result = 'error: data to store was not a hash reference';
8921: }
8922: } else {
8923: $result= 'error: invalid requestkey';
8924: }
8925: return $result;
8926: }
8927:
1.21 www 8928: # ---------------------------------------------------------- Assign Custom Role
8929:
8930: sub assigncustomrole {
1.957 raeburn 8931: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 8932: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 8933: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 8934: }
8935:
8936: # ----------------------------------------------------------------- Revoke Role
8937:
8938: sub revokerole {
1.957 raeburn 8939: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 8940: my $now=time;
1.965 raeburn 8941: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 8942: }
8943:
8944: # ---------------------------------------------------------- Revoke Custom Role
8945:
8946: sub revokecustomrole {
1.957 raeburn 8947: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 8948: my $now=time;
1.357 www 8949: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 8950: $deleteflag,$selfenroll,$context);
1.17 www 8951: }
8952:
1.533 banghart 8953: # ------------------------------------------------------------ Disk usage
1.535 albertel 8954: sub diskusage {
1.955 raeburn 8955: my ($udom,$uname,$directorypath,$getpropath)=@_;
8956: $directorypath =~ s/\/$//;
8957: my $listing=&reply('du2:'.&escape($directorypath).':'
8958: .&escape($getpropath).':'.&escape($uname).':'
8959: .&escape($udom),homeserver($uname,$udom));
8960: if ($listing eq 'unknown_cmd') {
8961: if ($getpropath) {
8962: $directorypath = &propath($udom,$uname).'/'.$directorypath;
8963: }
8964: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
8965: }
1.514 albertel 8966: return $listing;
1.512 banghart 8967: }
8968:
1.566 banghart 8969: sub is_locked {
1.1096 raeburn 8970: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 8971: my @check;
8972: my $is_locked;
1.1093 raeburn 8973: push (@check,$file_name);
1.613 albertel 8974: my %locked = &get('file_permissions',\@check,
1.620 albertel 8975: $env{'user.domain'},$env{'user.name'});
1.615 albertel 8976: my ($tmp)=keys(%locked);
8977: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 8978:
1.566 banghart 8979: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 8980: $is_locked = 'false';
8981: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 8982: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 8983: $is_locked = 'true';
1.1096 raeburn 8984: if (ref($which) eq 'ARRAY') {
8985: push(@{$which},$entry);
8986: } else {
8987: last;
8988: }
1.745 raeburn 8989: }
8990: }
1.566 banghart 8991: } else {
8992: $is_locked = 'false';
8993: }
1.1093 raeburn 8994: return $is_locked;
1.566 banghart 8995: }
8996:
1.759 albertel 8997: sub declutter_portfile {
8998: my ($file) = @_;
1.833 albertel 8999: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 9000: return $file;
9001: }
9002:
1.559 banghart 9003: # ------------------------------------------------------------- Mark as Read Only
9004:
9005: sub mark_as_readonly {
9006: my ($domain,$user,$files,$what) = @_;
1.613 albertel 9007: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 9008: my ($tmp)=keys(%current_permissions);
9009: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 9010: foreach my $file (@{$files}) {
1.759 albertel 9011: $file = &declutter_portfile($file);
1.561 banghart 9012: push(@{$current_permissions{$file}},$what);
1.559 banghart 9013: }
1.613 albertel 9014: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 9015: return;
9016: }
9017:
1.572 banghart 9018: # ------------------------------------------------------------Save Selected Files
9019:
9020: sub save_selected_files {
9021: my ($user, $path, @files) = @_;
9022: my $filename = $user."savedfiles";
1.573 banghart 9023: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 9024: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 9025: foreach my $file (@files) {
1.620 albertel 9026: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 9027: }
9028: foreach my $file (@other_files) {
1.574 banghart 9029: print (OUT $file."\n");
1.572 banghart 9030: }
1.574 banghart 9031: close (OUT);
1.572 banghart 9032: return 'ok';
9033: }
9034:
1.574 banghart 9035: sub clear_selected_files {
9036: my ($user) = @_;
9037: my $filename = $user."savedfiles";
1.1117 foxr 9038: open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574 banghart 9039: print (OUT undef);
9040: close (OUT);
9041: return ("ok");
9042: }
9043:
1.572 banghart 9044: sub files_in_path {
9045: my ($user, $path) = @_;
9046: my $filename = $user."savedfiles";
9047: my %return_files;
1.1117 foxr 9048: open (IN, '<'.LONCAPA::tempdir().$filename);
1.573 banghart 9049: while (my $line_in = <IN>) {
1.574 banghart 9050: chomp ($line_in);
9051: my @paths_and_file = split (m!/!, $line_in);
9052: my $file_part = pop (@paths_and_file);
9053: my $path_part = join ('/', @paths_and_file);
1.573 banghart 9054: $path_part.='/';
9055: my $path_and_file = $path_part.$file_part;
9056: if ($path_part eq $path) {
9057: $return_files{$file_part}= 'selected';
9058: }
9059: }
1.574 banghart 9060: close (IN);
9061: return (\%return_files);
1.572 banghart 9062: }
9063:
9064: # called in portfolio select mode, to show files selected NOT in current directory
9065: sub files_not_in_path {
9066: my ($user, $path) = @_;
9067: my $filename = $user."savedfiles";
9068: my @return_files;
9069: my $path_part;
1.1117 foxr 9070: open(IN, '<'.LONCAPA::.$filename);
1.800 albertel 9071: while (my $line = <IN>) {
1.572 banghart 9072: #ok, I know it's clunky, but I want it to work
1.800 albertel 9073: my @paths_and_file = split(m|/|, $line);
9074: my $file_part = pop(@paths_and_file);
9075: chomp($file_part);
9076: my $path_part = join('/', @paths_and_file);
1.572 banghart 9077: $path_part .= '/';
9078: my $path_and_file = $path_part.$file_part;
9079: if ($path_part ne $path) {
1.800 albertel 9080: push(@return_files, ($path_and_file));
1.572 banghart 9081: }
9082: }
1.800 albertel 9083: close(OUT);
1.574 banghart 9084: return (@return_files);
1.572 banghart 9085: }
9086:
1.745 raeburn 9087: #----------------------------------------------Get portfolio file permissions
1.629 banghart 9088:
1.745 raeburn 9089: sub get_portfile_permissions {
9090: my ($domain,$user) = @_;
1.613 albertel 9091: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 9092: my ($tmp)=keys(%current_permissions);
9093: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 9094: return \%current_permissions;
9095: }
9096:
9097: #---------------------------------------------Get portfolio file access controls
9098:
1.749 raeburn 9099: sub get_access_controls {
1.745 raeburn 9100: my ($current_permissions,$group,$file) = @_;
1.769 albertel 9101: my %access;
9102: my $real_file = $file;
9103: $file =~ s/\.meta$//;
1.745 raeburn 9104: if (defined($file)) {
1.749 raeburn 9105: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
9106: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 9107: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 9108: }
9109: }
1.745 raeburn 9110: } else {
1.749 raeburn 9111: foreach my $key (keys(%{$current_permissions})) {
9112: if ($key =~ /\0accesscontrol$/) {
9113: if (defined($group)) {
9114: if ($key !~ m-^\Q$group\E/-) {
9115: next;
9116: }
9117: }
9118: my ($fullpath) = split(/\0/,$key);
9119: if (ref($$current_permissions{$key}) eq 'HASH') {
9120: foreach my $control (keys(%{$$current_permissions{$key}})) {
9121: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
9122: }
9123: }
9124: }
9125: }
9126: }
9127: return %access;
9128: }
9129:
9130: sub modify_access_controls {
9131: my ($file_name,$changes,$domain,$user)=@_;
9132: my ($outcome,$deloutcome);
9133: my %store_permissions;
9134: my %new_values;
9135: my %new_control;
9136: my %translation;
9137: my @deletions = ();
9138: my $now = time;
9139: if (exists($$changes{'activate'})) {
9140: if (ref($$changes{'activate'}) eq 'HASH') {
9141: my @newitems = sort(keys(%{$$changes{'activate'}}));
9142: my $numnew = scalar(@newitems);
9143: for (my $i=0; $i<$numnew; $i++) {
9144: my $newkey = $newitems[$i];
9145: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 9146: if ($newkey =~ /^\d+:/) {
9147: $newkey =~ s/^(\d+)/$newid/;
9148: $translation{$1} = $newid;
9149: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
9150: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
9151: $translation{$1} = $newid;
9152: }
1.749 raeburn 9153: $new_values{$file_name."\0".$newkey} =
9154: $$changes{'activate'}{$newitems[$i]};
9155: $new_control{$newkey} = $now;
9156: }
9157: }
9158: }
9159: my %todelete;
9160: my %changed_items;
9161: foreach my $action ('delete','update') {
9162: if (exists($$changes{$action})) {
9163: if (ref($$changes{$action}) eq 'HASH') {
9164: foreach my $key (keys(%{$$changes{$action}})) {
9165: my ($itemnum) = ($key =~ /^([^:]+):/);
9166: if ($action eq 'delete') {
9167: $todelete{$itemnum} = 1;
9168: } else {
9169: $changed_items{$itemnum} = $key;
9170: }
9171: }
1.745 raeburn 9172: }
9173: }
1.749 raeburn 9174: }
9175: # get lock on access controls for file.
9176: my $lockhash = {
9177: $file_name."\0".'locked_access_records' => $env{'user.name'}.
9178: ':'.$env{'user.domain'},
9179: };
9180: my $tries = 0;
9181: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9182:
9183: while (($gotlock ne 'ok') && $tries <3) {
9184: $tries ++;
9185: sleep 1;
9186: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9187: }
9188: if ($gotlock eq 'ok') {
9189: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
9190: my ($tmp)=keys(%curr_permissions);
9191: if ($tmp=~/^error:/) { undef(%curr_permissions); }
9192: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
9193: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
9194: if (ref($curr_controls) eq 'HASH') {
9195: foreach my $control_item (keys(%{$curr_controls})) {
9196: my ($itemnum) = ($control_item =~ /^([^:]+):/);
9197: if (defined($todelete{$itemnum})) {
9198: push(@deletions,$file_name."\0".$control_item);
9199: } else {
9200: if (defined($changed_items{$itemnum})) {
9201: $new_control{$changed_items{$itemnum}} = $now;
9202: push(@deletions,$file_name."\0".$control_item);
9203: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
9204: } else {
9205: $new_control{$control_item} = $$curr_controls{$control_item};
9206: }
9207: }
1.745 raeburn 9208: }
9209: }
9210: }
1.970 raeburn 9211: my ($group);
9212: if (&is_course($domain,$user)) {
9213: ($group,my $file) = split(/\//,$file_name,2);
9214: }
1.749 raeburn 9215: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
9216: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
9217: $outcome = &put('file_permissions',\%new_values,$domain,$user);
9218: # remove lock
9219: my @del_lock = ($file_name."\0".'locked_access_records');
9220: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 9221: my $sqlresult =
1.970 raeburn 9222: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 9223: $group);
1.749 raeburn 9224: } else {
9225: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 9226: }
1.749 raeburn 9227: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 9228: }
9229:
1.827 raeburn 9230: sub make_public_indefinitely {
9231: my ($requrl) = @_;
9232: my $now = time;
9233: my $action = 'activate';
9234: my $aclnum = 0;
9235: if (&is_portfolio_url($requrl)) {
9236: my (undef,$udom,$unum,$file_name,$group) =
9237: &parse_portfolio_url($requrl);
9238: my $current_perms = &get_portfile_permissions($udom,$unum);
9239: my %access_controls = &get_access_controls($current_perms,
9240: $group,$file_name);
9241: foreach my $key (keys(%{$access_controls{$file_name}})) {
9242: my ($num,$scope,$end,$start) =
9243: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
9244: if ($scope eq 'public') {
9245: if ($start <= $now && $end == 0) {
9246: $action = 'none';
9247: } else {
9248: $action = 'update';
9249: $aclnum = $num;
9250: }
9251: last;
9252: }
9253: }
9254: if ($action eq 'none') {
9255: return 'ok';
9256: } else {
9257: my %changes;
9258: my $newend = 0;
9259: my $newstart = $now;
9260: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
9261: $changes{$action}{$newkey} = {
9262: type => 'public',
9263: time => {
9264: start => $newstart,
9265: end => $newend,
9266: },
9267: };
9268: my ($outcome,$deloutcome,$new_values,$translation) =
9269: &modify_access_controls($file_name,\%changes,$udom,$unum);
9270: return $outcome;
9271: }
9272: } else {
9273: return 'invalid';
9274: }
9275: }
9276:
1.745 raeburn 9277: #------------------------------------------------------Get Marked as Read Only
9278:
9279: sub get_marked_as_readonly {
9280: my ($domain,$user,$what,$group) = @_;
9281: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 9282: my @readonly_files;
1.629 banghart 9283: my $cmp1=$what;
9284: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 9285: while (my ($file_name,$value) = each(%{$current_permissions})) {
9286: if (defined($group)) {
9287: if ($file_name !~ m-^\Q$group\E/-) {
9288: next;
9289: }
9290: }
1.561 banghart 9291: if (ref($value) eq "ARRAY"){
9292: foreach my $stored_what (@{$value}) {
1.629 banghart 9293: my $cmp2=$stored_what;
1.759 albertel 9294: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 9295: $cmp2=join('',@{$stored_what});
1.745 raeburn 9296: }
1.629 banghart 9297: if ($cmp1 eq $cmp2) {
1.561 banghart 9298: push(@readonly_files, $file_name);
1.745 raeburn 9299: last;
1.563 banghart 9300: } elsif (!defined($what)) {
9301: push(@readonly_files, $file_name);
1.745 raeburn 9302: last;
1.561 banghart 9303: }
9304: }
1.745 raeburn 9305: }
1.561 banghart 9306: }
9307: return @readonly_files;
9308: }
1.577 banghart 9309: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 9310:
1.577 banghart 9311: sub get_marked_as_readonly_hash {
1.745 raeburn 9312: my ($current_permissions,$group,$what) = @_;
1.577 banghart 9313: my %readonly_files;
1.745 raeburn 9314: while (my ($file_name,$value) = each(%{$current_permissions})) {
9315: if (defined($group)) {
9316: if ($file_name !~ m-^\Q$group\E/-) {
9317: next;
9318: }
9319: }
1.577 banghart 9320: if (ref($value) eq "ARRAY"){
9321: foreach my $stored_what (@{$value}) {
1.745 raeburn 9322: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 9323: foreach my $lock_descriptor(@{$stored_what}) {
9324: if ($lock_descriptor eq 'graded') {
9325: $readonly_files{$file_name} = 'graded';
9326: } elsif ($lock_descriptor eq 'handback') {
9327: $readonly_files{$file_name} = 'handback';
9328: } else {
9329: if (!exists($readonly_files{$file_name})) {
9330: $readonly_files{$file_name} = 'locked';
9331: }
9332: }
1.745 raeburn 9333: }
1.750 banghart 9334: }
1.577 banghart 9335: }
9336: }
9337: }
9338: return %readonly_files;
9339: }
1.559 banghart 9340: # ------------------------------------------------------------ Unmark as Read Only
9341:
9342: sub unmark_as_readonly {
1.629 banghart 9343: # unmarks $file_name (if $file_name is defined), or all files locked by $what
9344: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 9345: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 9346: $file_name = &declutter_portfile($file_name);
1.634 albertel 9347: my $symb_crs = $what;
9348: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 9349: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 9350: my ($tmp)=keys(%current_permissions);
9351: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 9352: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 9353: foreach my $file (@readonly_files) {
1.759 albertel 9354: my $clean_file = &declutter_portfile($file);
9355: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 9356: my $current_locks = $current_permissions{$file};
1.563 banghart 9357: my @new_locks;
9358: my @del_keys;
9359: if (ref($current_locks) eq "ARRAY"){
9360: foreach my $locker (@{$current_locks}) {
1.632 albertel 9361: my $compare=$locker;
1.749 raeburn 9362: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 9363: $compare=join('',@{$locker});
1.746 raeburn 9364: if ($compare ne $symb_crs) {
9365: push(@new_locks, $locker);
9366: }
1.563 banghart 9367: }
9368: }
1.650 albertel 9369: if (scalar(@new_locks) > 0) {
1.563 banghart 9370: $current_permissions{$file} = \@new_locks;
9371: } else {
9372: push(@del_keys, $file);
1.613 albertel 9373: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 9374: delete($current_permissions{$file});
1.563 banghart 9375: }
9376: }
1.561 banghart 9377: }
1.613 albertel 9378: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 9379: return;
9380: }
1.512 banghart 9381:
1.17 www 9382: # ------------------------------------------------------------ Directory lister
9383:
9384: sub dirlist {
1.955 raeburn 9385: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 9386: $uri=~s/^\///;
9387: $uri=~s/\/$//;
1.253 stredwic 9388: my ($udom, $uname);
1.955 raeburn 9389: if ($getuserdir) {
1.253 stredwic 9390: $udom = $userdomain;
9391: $uname = $username;
1.955 raeburn 9392: } else {
9393: (undef,$udom,$uname)=split(/\//,$uri);
9394: if(defined($userdomain)) {
9395: $udom = $userdomain;
9396: }
9397: if(defined($username)) {
9398: $uname = $username;
9399: }
1.253 stredwic 9400: }
1.955 raeburn 9401: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 9402:
1.955 raeburn 9403: $dirRoot = $perlvar{'lonDocRoot'};
9404: if (defined($getpropath)) {
9405: $dirRoot = &propath($udom,$uname);
1.253 stredwic 9406: $dirRoot =~ s/\/$//;
1.955 raeburn 9407: } elsif (defined($getuserdir)) {
9408: my $subdir=$uname.'__';
9409: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
9410: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
9411: ."/$udom/$subdir/$uname";
9412: } elsif (defined($alternateRoot)) {
9413: $dirRoot = $alternateRoot;
1.751 banghart 9414: }
1.253 stredwic 9415:
9416: if($udom) {
9417: if($uname) {
1.1135 raeburn 9418: my $uhome = &homeserver($uname,$udom);
1.1136 raeburn 9419: if ($uhome eq 'no_host') {
9420: return ([],'no_host');
9421: }
1.955 raeburn 9422: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 9423: .$getuserdir.':'.&escape($dirRoot)
1.1135 raeburn 9424: .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955 raeburn 9425: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 9426: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955 raeburn 9427: } else {
9428: @listing_results = map { &unescape($_); } split(/:/,$listing);
9429: }
1.605 matthew 9430: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 9431: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605 matthew 9432: @listing_results = split(/:/,$listing);
9433: } else {
9434: @listing_results = map { &unescape($_); } split(/:/,$listing);
9435: }
1.1135 raeburn 9436: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
1.1136 raeburn 9437: ($listing eq 'rejected') || ($listing eq 'refused') ||
9438: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
9439: return ([],$listing);
9440: } else {
9441: return (\@listing_results);
1.1135 raeburn 9442: }
1.955 raeburn 9443: } elsif(!$alternateRoot) {
1.1136 raeburn 9444: my (%allusers,%listerror);
1.841 albertel 9445: my %servers = &get_servers($udom,'library');
1.955 raeburn 9446: foreach my $tryserver (keys(%servers)) {
9447: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
9448: &escape($udom),$tryserver);
9449: if ($listing eq 'unknown_cmd') {
9450: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
9451: $udom, $tryserver);
9452: } else {
9453: @listing_results = map { &unescape($_); } split(/:/,$listing);
9454: }
1.841 albertel 9455: if ($listing eq 'unknown_cmd') {
9456: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
9457: $udom, $tryserver);
9458: @listing_results = split(/:/,$listing);
9459: } else {
9460: @listing_results =
9461: map { &unescape($_); } split(/:/,$listing);
9462: }
1.1136 raeburn 9463: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
9464: ($listing eq 'rejected') || ($listing eq 'refused') ||
9465: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
9466: $listerror{$tryserver} = $listing;
9467: } else {
1.841 albertel 9468: foreach my $line (@listing_results) {
9469: my ($entry) = split(/&/,$line,2);
9470: $allusers{$entry} = 1;
9471: }
9472: }
1.253 stredwic 9473: }
1.1136 raeburn 9474: my @alluserslist=();
1.800 albertel 9475: foreach my $user (sort(keys(%allusers))) {
1.1136 raeburn 9476: push(@alluserslist,$user.'&user');
1.253 stredwic 9477: }
1.1136 raeburn 9478: return (\@alluserslist);
1.253 stredwic 9479: } else {
1.1136 raeburn 9480: return ([],'missing username');
1.253 stredwic 9481: }
1.955 raeburn 9482: } elsif(!defined($getpropath)) {
1.1136 raeburn 9483: my $path = $perlvar{'lonDocRoot'}.'/res/';
9484: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
9485: return (\@all_domains);
1.955 raeburn 9486: } else {
1.1136 raeburn 9487: return ([],'missing domain');
1.275 stredwic 9488: }
9489: }
9490:
9491: # --------------------------------------------- GetFileTimestamp
9492: # This function utilizes dirlist and returns the date stamp for
9493: # when it was last modified. It will also return an error of -1
9494: # if an error occurs
9495:
9496: sub GetFileTimestamp {
1.955 raeburn 9497: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 9498: $studentDomain = &LONCAPA::clean_domain($studentDomain);
9499: $studentName = &LONCAPA::clean_username($studentName);
1.1136 raeburn 9500: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
9501: undef,$getuserdir);
9502: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
9503: return -1;
9504: }
9505: if (ref($fileref) eq 'ARRAY') {
9506: my @stats = split('&',$fileref->[0]);
1.375 matthew 9507: # @stats contains first the filename, then the stat output
9508: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 9509: } else {
9510: return -1;
1.253 stredwic 9511: }
1.26 www 9512: }
9513:
1.712 albertel 9514: sub stat_file {
9515: my ($uri) = @_;
1.787 albertel 9516: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 9517:
1.955 raeburn 9518: my ($udom,$uname,$file);
1.712 albertel 9519: if ($uri =~ m-^/(uploaded|editupload)/-) {
9520: ($udom,$uname,$file) =
1.811 albertel 9521: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 9522: $file = 'userfiles/'.$file;
9523: }
9524: if ($uri =~ m-^/res/-) {
9525: ($udom,$uname) =
1.807 albertel 9526: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 9527: $file = $uri;
9528: }
9529:
9530: if (!$udom || !$uname || !$file) {
9531: # unable to handle the uri
9532: return ();
9533: }
1.956 raeburn 9534: my $getpropath;
9535: if ($file =~ /^userfiles\//) {
9536: $getpropath = 1;
9537: }
1.1136 raeburn 9538: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
9539: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
9540: return ();
9541: } else {
9542: if (ref($listref) eq 'ARRAY') {
9543: my @stats = split('&',$listref->[0]);
9544: shift(@stats); #filename is first
9545: return @stats;
9546: }
1.712 albertel 9547: }
9548: return ();
9549: }
9550:
1.26 www 9551: # -------------------------------------------------------- Value of a Condition
9552:
1.713 albertel 9553: # gets the value of a specific preevaluated condition
9554: # stored in the string $env{user.state.<cid>}
9555: # or looks up a condition reference in the bighash and if if hasn't
9556: # already been evaluated recurses into docondval to get the value of
9557: # the condition, then memoizing it to
9558: # $env{user.state.<cid>.<condition>}
1.40 www 9559: sub directcondval {
9560: my $number=shift;
1.620 albertel 9561: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 9562: &Apache::lonuserstate::evalstate();
9563: }
1.713 albertel 9564: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
9565: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
9566: } elsif ($number =~ /^_/) {
9567: my $sub_condition;
9568: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
9569: &GDBM_READER(),0640)) {
9570: $sub_condition=$bighash{'conditions'.$number};
9571: untie(%bighash);
9572: }
9573: my $value = &docondval($sub_condition);
1.949 raeburn 9574: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 9575: return $value;
9576: }
1.620 albertel 9577: if ($env{'user.state.'.$env{'request.course.id'}}) {
9578: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 9579: } else {
9580: return 2;
9581: }
9582: }
9583:
1.713 albertel 9584: # get the collection of conditions for this resource
1.26 www 9585: sub condval {
9586: my $condidx=shift;
1.54 www 9587: my $allpathcond='';
1.713 albertel 9588: foreach my $cond (split(/\|/,$condidx)) {
9589: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
9590: $allpathcond.=
9591: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
9592: }
1.191 harris41 9593: }
1.54 www 9594: $allpathcond=~s/\|$//;
1.713 albertel 9595: return &docondval($allpathcond);
9596: }
9597:
9598: #evaluates an expression of conditions
9599: sub docondval {
9600: my ($allpathcond) = @_;
9601: my $result=0;
9602: if ($env{'request.course.id'}
9603: && defined($allpathcond)) {
9604: my $operand='|';
9605: my @stack;
9606: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
9607: if ($chunk eq '(') {
9608: push @stack,($operand,$result);
9609: } elsif ($chunk eq ')') {
9610: my $before=pop @stack;
9611: if (pop @stack eq '&') {
9612: $result=$result>$before?$before:$result;
9613: } else {
9614: $result=$result>$before?$result:$before;
9615: }
9616: } elsif (($chunk eq '&') || ($chunk eq '|')) {
9617: $operand=$chunk;
9618: } else {
9619: my $new=directcondval($chunk);
9620: if ($operand eq '&') {
9621: $result=$result>$new?$new:$result;
9622: } else {
9623: $result=$result>$new?$result:$new;
9624: }
9625: }
9626: }
1.26 www 9627: }
9628: return $result;
1.421 albertel 9629: }
9630:
9631: # ---------------------------------------------------- Devalidate courseresdata
9632:
9633: sub devalidatecourseresdata {
9634: my ($coursenum,$coursedomain)=@_;
9635: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 9636: &devalidate_cache_new('courseres',$hashid);
1.28 www 9637: }
9638:
1.763 www 9639:
1.200 www 9640: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 9641: #
9642: # Parameters:
9643: # $coursenum - Number of the course.
9644: # $coursedomain - Domain at which the course was created.
9645: # Returns:
9646: # A hash of the course parameters along (I think) with timestamps
9647: # and version info.
1.877 foxr 9648:
1.624 albertel 9649: sub get_courseresdata {
9650: my ($coursenum,$coursedomain)=@_;
1.200 www 9651: my $coursehom=&homeserver($coursenum,$coursedomain);
9652: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 9653: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 9654: my %dumpreply;
1.417 albertel 9655: unless (defined($cached)) {
1.624 albertel 9656: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 9657: $result=\%dumpreply;
1.251 albertel 9658: my ($tmp) = keys(%dumpreply);
9659: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 9660: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 9661: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
9662: return $tmp;
1.416 albertel 9663: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 9664: $result=undef;
1.599 albertel 9665: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 9666: }
9667: }
1.624 albertel 9668: return $result;
9669: }
9670:
1.633 albertel 9671: sub devalidateuserresdata {
9672: my ($uname,$udom)=@_;
9673: my $hashid="$udom:$uname";
9674: &devalidate_cache_new('userres',$hashid);
9675: }
9676:
1.624 albertel 9677: sub get_userresdata {
9678: my ($uname,$udom)=@_;
9679: #most student don\'t have any data set, check if there is some data
9680: if (&EXT_cache_status($udom,$uname)) { return undef; }
9681:
9682: my $hashid="$udom:$uname";
9683: my ($result,$cached)=&is_cached_new('userres',$hashid);
9684: if (!defined($cached)) {
9685: my %resourcedata=&dump('resourcedata',$udom,$uname);
9686: $result=\%resourcedata;
9687: &do_cache_new('userres',$hashid,$result,600);
9688: }
9689: my ($tmp)=keys(%$result);
9690: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
9691: return $result;
9692: }
9693: #error 2 occurs when the .db doesn't exist
9694: if ($tmp!~/error: 2 /) {
1.672 albertel 9695: &logthis("<font color=\"blue\">WARNING:".
1.624 albertel 9696: " Trying to get resource data for ".
9697: $uname." at ".$udom.": ".
9698: $tmp."</font>");
9699: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 9700: #&EXT_cache_set($udom,$uname);
9701: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 9702: undef($tmp); # not really an error so don't send it back
1.624 albertel 9703: }
9704: return $tmp;
9705: }
1.879 foxr 9706: #----------------------------------------------- resdata - return resource data
9707: # Purpose:
9708: # Return resource data for either users or for a course.
9709: # Parameters:
9710: # $name - Course/user name.
9711: # $domain - Name of the domain the user/course is registered on.
9712: # $type - Type of thing $name is (must be 'course' or 'user'
9713: # @which - Array of names of resources desired.
9714: # Returns:
9715: # The value of the first reasource in @which that is found in the
9716: # resource hash.
9717: # Exceptional Conditions:
9718: # If the $type passed in is not valid (not the string 'course' or
9719: # 'user', an undefined reference is returned.
9720: # If none of the resources are found, an undef is returned
1.624 albertel 9721: sub resdata {
9722: my ($name,$domain,$type,@which)=@_;
9723: my $result;
9724: if ($type eq 'course') {
9725: $result=&get_courseresdata($name,$domain);
9726: } elsif ($type eq 'user') {
9727: $result=&get_userresdata($name,$domain);
9728: }
9729: if (!ref($result)) { return $result; }
1.251 albertel 9730: foreach my $item (@which) {
1.927 albertel 9731: if (defined($result->{$item->[0]})) {
9732: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 9733: }
1.250 albertel 9734: }
1.291 albertel 9735: return undef;
1.200 www 9736: }
9737:
1.1236 raeburn 9738: sub get_numsuppfiles {
9739: my ($cnum,$cdom,$ignorecache)=@_;
9740: my $hashid=$cnum.':'.$cdom;
9741: my ($suppcount,$cached);
9742: unless ($ignorecache) {
9743: ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
9744: }
9745: unless (defined($cached)) {
9746: my $chome=&homeserver($cnum,$cdom);
9747: unless ($chome eq 'no_host') {
9748: ($suppcount,my $errors) = (0,0);
9749: my $suppmap = 'supplemental.sequence';
9750: ($suppcount,$errors) =
9751: &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
9752: }
9753: &do_cache_new('suppcount',$hashid,$suppcount,600);
9754: }
9755: return $suppcount;
9756: }
9757:
1.379 matthew 9758: #
9759: # EXT resource caching routines
9760: #
9761:
9762: sub clear_EXT_cache_status {
1.383 albertel 9763: &delenv('cache.EXT.');
1.379 matthew 9764: }
9765:
9766: sub EXT_cache_status {
9767: my ($target_domain,$target_user) = @_;
1.383 albertel 9768: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 9769: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 9770: # We know already the user has no data
9771: return 1;
9772: } else {
9773: return 0;
9774: }
9775: }
9776:
9777: sub EXT_cache_set {
9778: my ($target_domain,$target_user) = @_;
1.383 albertel 9779: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 9780: #&appenv({$cachename => time});
1.379 matthew 9781: }
9782:
1.28 www 9783: # --------------------------------------------------------- Value of a Variable
1.58 www 9784: sub EXT {
1.715 albertel 9785:
1.1228 raeburn 9786: my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68 www 9787: unless ($varname) { return ''; }
1.218 albertel 9788: #get real user name/domain, courseid and symb
9789: my $courseid;
1.359 albertel 9790: my $publicuser;
1.427 www 9791: if ($symbparm) {
9792: $symbparm=&get_symb_from_alias($symbparm);
9793: }
1.218 albertel 9794: if (!($uname && $udom)) {
1.790 albertel 9795: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 9796: if (!$symbparm) { $symbparm=$cursymb; }
9797: } else {
1.620 albertel 9798: $courseid=$env{'request.course.id'};
1.218 albertel 9799: }
1.48 www 9800: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
9801: my $rest;
1.320 albertel 9802: if (defined($therest[0])) {
1.48 www 9803: $rest=join('.',@therest);
9804: } else {
9805: $rest='';
9806: }
1.320 albertel 9807:
1.57 www 9808: my $qualifierrest=$qualifier;
9809: if ($rest) { $qualifierrest.='.'.$rest; }
9810: my $spacequalifierrest=$space;
9811: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 9812: if ($realm eq 'user') {
1.48 www 9813: # --------------------------------------------------------------- user.resource
9814: if ($space eq 'resource') {
1.651 albertel 9815: if ( (defined($Apache::lonhomework::parsing_a_problem)
9816: || defined($Apache::lonhomework::parsing_a_task))
9817: &&
1.744 albertel 9818: ($symbparm eq &symbread()) ) {
9819: # if we are in the middle of processing the resource the
9820: # get the value we are planning on committing
9821: if (defined($Apache::lonhomework::results{$qualifierrest})) {
9822: return $Apache::lonhomework::results{$qualifierrest};
9823: } else {
9824: return $Apache::lonhomework::history{$qualifierrest};
9825: }
1.335 albertel 9826: } else {
1.359 albertel 9827: my %restored;
1.620 albertel 9828: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 9829: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
9830: } else {
9831: %restored=&restore($symbparm,$courseid,$udom,$uname);
9832: }
1.335 albertel 9833: return $restored{$qualifierrest};
9834: }
1.48 www 9835: # ----------------------------------------------------------------- user.access
9836: } elsif ($space eq 'access') {
1.218 albertel 9837: # FIXME - not supporting calls for a specific user
1.48 www 9838: return &allowed($qualifier,$rest);
9839: # ------------------------------------------ user.preferences, user.environment
9840: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 9841: if (($uname eq $env{'user.name'}) &&
9842: ($udom eq $env{'user.domain'})) {
9843: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 9844: } else {
1.359 albertel 9845: my %returnhash;
9846: if (!$publicuser) {
9847: %returnhash=&userenvironment($udom,$uname,
9848: $qualifierrest);
9849: }
1.218 albertel 9850: return $returnhash{$qualifierrest};
9851: }
1.48 www 9852: # ----------------------------------------------------------------- user.course
9853: } elsif ($space eq 'course') {
1.218 albertel 9854: # FIXME - not supporting calls for a specific user
1.620 albertel 9855: return $env{join('.',('request.course',$qualifier))};
1.48 www 9856: # ------------------------------------------------------------------- user.role
9857: } elsif ($space eq 'role') {
1.218 albertel 9858: # FIXME - not supporting calls for a specific user
1.620 albertel 9859: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 9860: if ($qualifier eq 'value') {
9861: return $role;
9862: } elsif ($qualifier eq 'extent') {
9863: return $where;
9864: }
9865: # ----------------------------------------------------------------- user.domain
9866: } elsif ($space eq 'domain') {
1.218 albertel 9867: return $udom;
1.48 www 9868: # ------------------------------------------------------------------- user.name
9869: } elsif ($space eq 'name') {
1.218 albertel 9870: return $uname;
1.48 www 9871: # ---------------------------------------------------- Any other user namespace
1.29 www 9872: } else {
1.359 albertel 9873: my %reply;
9874: if (!$publicuser) {
9875: %reply=&get($space,[$qualifierrest],$udom,$uname);
9876: }
9877: return $reply{$qualifierrest};
1.48 www 9878: }
1.236 www 9879: } elsif ($realm eq 'query') {
9880: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 9881: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
9882: [$spacequalifierrest]);
1.620 albertel 9883: return $env{'form.'.$spacequalifierrest};
1.236 www 9884: } elsif ($realm eq 'request') {
1.48 www 9885: # ------------------------------------------------------------- request.browser
9886: if ($space eq 'browser') {
1.1145 bisitz 9887: return $env{'browser.'.$qualifier};
1.57 www 9888: # ------------------------------------------------------------ request.filename
9889: } else {
1.620 albertel 9890: return $env{'request.'.$spacequalifierrest};
1.29 www 9891: }
1.28 www 9892: } elsif ($realm eq 'course') {
1.48 www 9893: # ---------------------------------------------------------- course.description
1.620 albertel 9894: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 9895: } elsif ($realm eq 'resource') {
1.165 www 9896:
1.620 albertel 9897: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 9898: if (!$symbparm) { $symbparm=&symbread(); }
9899: }
1.693 albertel 9900:
1.1232 raeburn 9901: if ($qualifier eq '') {
9902: if ($space eq 'title') {
9903: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
9904: return &gettitle($symbparm);
9905: }
1.693 albertel 9906:
1.1232 raeburn 9907: if ($space eq 'map') {
9908: my ($map) = &decode_symb($symbparm);
9909: return &symbread($map);
9910: }
9911: if ($space eq 'maptitle') {
9912: my ($map) = &decode_symb($symbparm);
9913: return &gettitle($map);
9914: }
9915: if ($space eq 'filename') {
9916: if ($symbparm) {
9917: return &clutter((&decode_symb($symbparm))[2]);
9918: }
9919: return &hreflocation('',$env{'request.filename'});
1.905 albertel 9920: }
1.1232 raeburn 9921:
1.1233 raeburn 9922: if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
9923: if ($space eq 'visibleparts') {
9924: my $navmap = Apache::lonnavmaps::navmap->new();
9925: my $item;
9926: if (ref($navmap)) {
9927: my $res = $navmap->getBySymb($symbparm);
9928: my $parts = $res->parts();
9929: if (ref($parts) eq 'ARRAY') {
9930: $item = join(',',@{$parts});
9931: }
9932: undef($navmap);
1.1232 raeburn 9933: }
1.1233 raeburn 9934: return $item;
1.1232 raeburn 9935: }
9936: }
9937: }
1.693 albertel 9938:
9939: my ($section, $group, @groups);
1.593 albertel 9940: my ($courselevelm,$courselevel);
1.1228 raeburn 9941: if (($courseid eq '') && ($cid)) {
9942: $courseid = $cid;
9943: }
9944: if (($symbparm && $courseid) &&
9945: (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165 www 9946:
1.218 albertel 9947: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 9948:
1.60 www 9949: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 9950: my $symbp=$symbparm;
1.735 albertel 9951: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 9952:
9953: my $symbparm=$symbp.'.'.$spacequalifierrest;
9954: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
9955:
1.620 albertel 9956: if (($env{'user.name'} eq $uname) &&
9957: ($env{'user.domain'} eq $udom)) {
9958: $section=$env{'request.course.sec'};
1.733 raeburn 9959: @groups = split(/:/,$env{'request.course.groups'});
9960: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 9961: } else {
1.539 albertel 9962: if (! defined($usection)) {
1.551 albertel 9963: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 9964: } else {
9965: $section = $usection;
9966: }
1.733 raeburn 9967: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 9968: }
9969:
9970: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
9971: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
9972: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
9973:
1.593 albertel 9974: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 9975: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 9976: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 9977:
1.60 www 9978: # ----------------------------------------------------------- first, check user
1.624 albertel 9979:
9980: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 9981: ([$courselevelr,'resource'],
9982: [$courselevelm,'map' ],
9983: [$courselevel, 'course' ]));
1.931 albertel 9984: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 9985:
1.594 albertel 9986: # ------------------------------------------------ second, check some of course
1.684 raeburn 9987: my $coursereply;
1.691 raeburn 9988: if (@groups > 0) {
9989: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
9990: $mapparm,$spacequalifierrest);
1.927 albertel 9991: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 9992: }
1.96 www 9993:
1.684 raeburn 9994: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 9995: $env{'course.'.$courseid.'.domain'},
9996: 'course',
9997: ([$seclevelr, 'resource'],
9998: [$seclevelm, 'map' ],
9999: [$seclevel, 'course' ],
10000: [$courselevelr,'resource']));
10001: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 10002:
1.60 www 10003: # ------------------------------------------------------ third, check map parms
1.218 albertel 10004: my %parmhash=();
10005: my $thisparm='';
10006: if (tie(%parmhash,'GDBM_File',
1.620 albertel 10007: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 10008: &GDBM_READER(),0640)) {
1.218 albertel 10009: $thisparm=$parmhash{$symbparm};
10010: untie(%parmhash);
10011: }
1.927 albertel 10012: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 10013: }
1.594 albertel 10014: # ------------------------------------------ fourth, look in resource metadata
1.71 www 10015:
1.218 albertel 10016: $spacequalifierrest=~s/\./\_/;
1.282 albertel 10017: my $filename;
10018: if (!$symbparm) { $symbparm=&symbread(); }
10019: if ($symbparm) {
1.409 www 10020: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 10021: } else {
1.620 albertel 10022: $filename=$env{'request.filename'};
1.282 albertel 10023: }
10024: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 10025: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 10026: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 10027: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 10028:
1.927 albertel 10029: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 10030: if ($symbparm && defined($courseid) &&
1.620 albertel 10031: $courseid eq $env{'request.course.id'}) {
1.624 albertel 10032: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
10033: $env{'course.'.$courseid.'.domain'},
10034: 'course',
1.927 albertel 10035: ([$courselevelm,'map' ],
10036: [$courselevel, 'course']));
10037: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 10038: }
1.145 www 10039: # ------------------------------------------------------------------ Cascade up
1.218 albertel 10040: unless ($space eq '0') {
1.336 albertel 10041: my @parts=split(/_/,$space);
10042: my $id=pop(@parts);
10043: my $part=join('_',@parts);
10044: if ($part eq '') { $part='0'; }
1.927 albertel 10045: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 10046: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 10047: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 10048: }
1.395 albertel 10049: if ($recurse) { return undef; }
10050: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 10051: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 10052: # ---------------------------------------------------- Any other user namespace
10053: } elsif ($realm eq 'environment') {
10054: # ----------------------------------------------------------------- environment
1.620 albertel 10055: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
10056: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 10057: } else {
1.770 albertel 10058: if ($uname eq 'anonymous' && $udom eq '') {
10059: return '';
10060: }
1.219 albertel 10061: my %returnhash=&userenvironment($udom,$uname,
10062: $spacequalifierrest);
10063: return $returnhash{$spacequalifierrest};
10064: }
1.28 www 10065: } elsif ($realm eq 'system') {
1.48 www 10066: # ----------------------------------------------------------------- system.time
10067: if ($space eq 'time') {
10068: return time;
10069: }
1.696 albertel 10070: } elsif ($realm eq 'server') {
10071: # ----------------------------------------------------------------- system.time
10072: if ($space eq 'name') {
10073: return $ENV{'SERVER_NAME'};
10074: }
1.28 www 10075: }
1.48 www 10076: return '';
1.61 www 10077: }
10078:
1.927 albertel 10079: sub get_reply {
10080: my ($reply_value) = @_;
1.940 raeburn 10081: if (ref($reply_value) eq 'ARRAY') {
10082: if (wantarray) {
10083: return @$reply_value;
10084: }
10085: return $reply_value->[0];
10086: } else {
10087: return $reply_value;
1.927 albertel 10088: }
10089: }
10090:
1.691 raeburn 10091: sub check_group_parms {
10092: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
10093: my @groupitems = ();
10094: my $resultitem;
1.927 albertel 10095: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 10096: foreach my $group (@{$groups}) {
10097: foreach my $level (@levels) {
1.927 albertel 10098: my $item = $courseid.'.['.$group.'].'.$level->[0];
10099: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 10100: }
10101: }
10102: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
10103: $env{'course.'.$courseid.'.domain'},
10104: 'course',@groupitems);
10105: return $coursereply;
10106: }
10107:
10108: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 10109: my ($courseid,@groups) = @_;
10110: @groups = sort(@groups);
1.691 raeburn 10111: return @groups;
10112: }
10113:
1.395 albertel 10114: sub packages_tab_default {
10115: my ($uri,$varname)=@_;
10116: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 10117:
10118: my (@extension,@specifics,$do_default);
10119: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 10120: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 10121: if ($pack_type eq 'default') {
10122: $do_default=1;
10123: } elsif ($pack_type eq 'extension') {
10124: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 10125: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 10126: # only look at packages defaults for packages that this id is
1.738 albertel 10127: push(@specifics,[$package,$pack_type,$pack_part]);
10128: }
10129: }
10130: # first look for a package that matches the requested part id
10131: foreach my $package (@specifics) {
10132: my (undef,$pack_type,$pack_part)=@{$package};
10133: next if ($pack_part ne $part);
10134: if (defined($packagetab{"$pack_type&$name&default"})) {
10135: return $packagetab{"$pack_type&$name&default"};
10136: }
10137: }
10138: # look for any possible matching non extension_ package
10139: foreach my $package (@specifics) {
10140: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 10141: if (defined($packagetab{"$pack_type&$name&default"})) {
10142: return $packagetab{"$pack_type&$name&default"};
10143: }
1.585 albertel 10144: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 10145: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
10146: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 10147: }
10148: }
1.738 albertel 10149: # look for any posible extension_ match
10150: foreach my $package (@extension) {
10151: my ($package,$pack_type)=@{$package};
10152: if (defined($packagetab{"$pack_type&$name&default"})) {
10153: return $packagetab{"$pack_type&$name&default"};
10154: }
10155: if (defined($packagetab{$package."&$name&default"})) {
10156: return $packagetab{$package."&$name&default"};
10157: }
10158: }
10159: # look for a global default setting
10160: if ($do_default && defined($packagetab{"default&$name&default"})) {
10161: return $packagetab{"default&$name&default"};
10162: }
1.395 albertel 10163: return undef;
10164: }
10165:
1.334 albertel 10166: sub add_prefix_and_part {
10167: my ($prefix,$part)=@_;
10168: my $keyroot;
10169: if (defined($prefix) && $prefix !~ /^__/) {
10170: # prefix that has a part already
10171: $keyroot=$prefix;
10172: } elsif (defined($prefix)) {
10173: # prefix that is missing a part
10174: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
10175: } else {
10176: # no prefix at all
10177: if (defined($part)) { $keyroot='_'.$part; }
10178: }
10179: return $keyroot;
10180: }
10181:
1.71 www 10182: # ---------------------------------------------------------------- Get metadata
10183:
1.599 albertel 10184: my %metaentry;
1.1070 www 10185: my %importedpartids;
1.71 www 10186: sub metadata {
1.176 www 10187: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 10188: $uri=&declutter($uri);
1.288 albertel 10189: # if it is a non metadata possible uri return quickly
1.529 albertel 10190: if (($uri eq '') ||
10191: (($uri =~ m|^/*adm/|) &&
1.1217 raeburn 10192: ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108 raeburn 10193: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 10194: return undef;
10195: }
1.1140 www 10196: if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/)
1.924 albertel 10197: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 10198: return undef;
1.288 albertel 10199: }
1.73 www 10200: my $filename=$uri;
10201: $uri=~s/\.meta$//;
1.172 www 10202: #
10203: # Is the metadata already cached?
1.177 www 10204: # Look at timestamp of caching
1.172 www 10205: # Everything is cached by the main uri, libraries are never directly cached
10206: #
1.428 albertel 10207: if (!defined($liburi)) {
1.599 albertel 10208: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 10209: if (defined($cached)) { return $result->{':'.$what}; }
10210: }
10211: {
1.1069 www 10212: # Imported parts would go here
1.1070 www 10213: my %importedids=();
10214: my @origfileimportpartids=();
1.1069 www 10215: my $importedparts=0;
1.172 www 10216: #
10217: # Is this a recursive call for a library?
10218: #
1.599 albertel 10219: # if (! exists($metacache{$uri})) {
10220: # $metacache{$uri}={};
10221: # }
1.924 albertel 10222: my $cachetime = 60*60;
1.171 www 10223: if ($liburi) {
10224: $liburi=&declutter($liburi);
10225: $filename=$liburi;
1.401 bowersj2 10226: } else {
1.599 albertel 10227: &devalidate_cache_new('meta',$uri);
10228: undef(%metaentry);
1.401 bowersj2 10229: }
1.140 www 10230: my %metathesekeys=();
1.73 www 10231: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 10232: my $metastring;
1.1140 www 10233: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929 albertel 10234: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 10235: $metastring =
1.929 albertel 10236: &Apache::lonnet::ssi_body($which,
1.924 albertel 10237: ('grade_target' => 'meta'));
10238: $cachetime = 1; # only want this cached in the child not long term
1.1108 raeburn 10239: } elsif (($uri !~ m -^(editupload)/-) &&
10240: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 10241: my $file=&filelocation('',&clutter($filename));
1.599 albertel 10242: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 10243: $metastring=&getfile($file);
1.489 albertel 10244: }
1.208 albertel 10245: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 10246: my $token;
1.140 www 10247: undef %metathesekeys;
1.71 www 10248: while ($token=$parser->get_token) {
1.339 albertel 10249: if ($token->[0] eq 'S') {
10250: if (defined($token->[2]->{'package'})) {
1.172 www 10251: #
10252: # This is a package - get package info
10253: #
1.339 albertel 10254: my $package=$token->[2]->{'package'};
10255: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10256: if (defined($token->[2]->{'id'})) {
10257: $keyroot.='_'.$token->[2]->{'id'};
10258: }
1.599 albertel 10259: if ($metaentry{':packages'}) {
10260: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 10261: } else {
1.599 albertel 10262: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 10263: }
1.736 albertel 10264: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 10265: my $part=$keyroot;
10266: $part=~s/^\_//;
1.736 albertel 10267: if ($pack_entry=~/^\Q$package\E\&/ ||
10268: $pack_entry=~/^\Q$package\E_0\&/) {
10269: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 10270: # ignore package.tab specified default values
10271: # here &package_tab_default() will fetch those
10272: if ($subp eq 'default') { next; }
1.736 albertel 10273: my $value=$packagetab{$pack_entry};
1.432 albertel 10274: my $unikey;
10275: if ($pack =~ /_0$/) {
10276: $unikey='parameter_0_'.$name;
10277: $part=0;
10278: } else {
10279: $unikey='parameter'.$keyroot.'_'.$name;
10280: }
1.339 albertel 10281: if ($subp eq 'display') {
10282: $value.=' [Part: '.$part.']';
10283: }
1.599 albertel 10284: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 10285: $metathesekeys{$unikey}=1;
1.599 albertel 10286: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10287: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 10288: }
1.599 albertel 10289: if (defined($metaentry{':'.$unikey.'.default'})) {
10290: $metaentry{':'.$unikey}=
10291: $metaentry{':'.$unikey.'.default'};
1.356 albertel 10292: }
1.339 albertel 10293: }
10294: }
10295: } else {
1.172 www 10296: #
10297: # This is not a package - some other kind of start tag
1.339 albertel 10298: #
10299: my $entry=$token->[1];
1.1068 www 10300: my $unikey='';
1.175 www 10301:
1.339 albertel 10302: if ($entry eq 'import') {
1.175 www 10303: #
10304: # Importing a library here
1.339 albertel 10305: #
1.1067 www 10306: my $location=$parser->get_text('/import');
10307: my $dir=$filename;
10308: $dir=~s|[^/]*$||;
10309: $location=&filelocation($dir,$location);
1.1069 www 10310:
1.1068 www 10311: my $importmode=$token->[2]->{'importmode'};
10312: if ($importmode eq 'problem') {
1.1069 www 10313: # Import as problem/response
1.1068 www 10314: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10315: } elsif ($importmode eq 'part') {
10316: # Import as part(s)
1.1069 www 10317: $importedparts=1;
10318: # We need to get the original file and the imported file to get the part order correct
10319: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
10320: # Load and inspect original file
1.1070 www 10321: if ($#origfileimportpartids<0) {
10322: undef(%importedpartids);
10323: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
10324: my $origfile=&getfile($origfilelocation);
10325: @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10326: }
10327:
1.1069 www 10328: # Load and inspect imported file
10329: my $impfile=&getfile($location);
10330: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10331: if ($#impfilepartids>=0) {
10332: # This problem had parts
1.1070 www 10333: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 10334: } else {
10335: # Importing by turning a single problem into a problem part
10336: # It gets the import-tags ID as part-ID
10337: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 10338: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 10339: }
1.1068 www 10340: } else {
10341: # Normal import
10342: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10343: if (defined($token->[2]->{'id'})) {
10344: $unikey.='_'.$token->[2]->{'id'};
10345: }
1.1067 www 10346: }
10347:
1.339 albertel 10348: if ($depthcount<20) {
1.736 albertel 10349: my $metadata =
10350: &metadata($uri,'keys', $location,$unikey,
10351: $depthcount+1);
10352: foreach my $meta (split(',',$metadata)) {
10353: $metaentry{':'.$meta}=$metaentry{':'.$meta};
10354: $metathesekeys{$meta}=1;
1.339 albertel 10355: }
1.1068 www 10356:
10357: }
1.1067 www 10358: } else {
10359: #
10360: # Not importing, some other kind of non-package, non-library start tag
10361: #
10362: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
10363: if (defined($token->[2]->{'id'})) {
10364: $unikey.='_'.$token->[2]->{'id'};
10365: }
1.339 albertel 10366: if (defined($token->[2]->{'name'})) {
10367: $unikey.='_'.$token->[2]->{'name'};
10368: }
10369: $metathesekeys{$unikey}=1;
1.736 albertel 10370: foreach my $param (@{$token->[3]}) {
10371: $metaentry{':'.$unikey.'.'.$param} =
10372: $token->[2]->{$param};
1.339 albertel 10373: }
10374: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 10375: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 10376: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
10377: # only ws inside the tag, and not in default, so use default
10378: # as value
1.599 albertel 10379: $metaentry{':'.$unikey}=$default;
1.908 albertel 10380: } elsif ( $internaltext =~ /\S/ ) {
10381: # something interesting inside the tag
10382: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 10383: } else {
1.908 albertel 10384: # no interesting values, don't set a default
1.339 albertel 10385: }
1.172 www 10386: # end of not-a-package not-a-library import
1.339 albertel 10387: }
1.172 www 10388: # end of not-a-package start tag
1.339 albertel 10389: }
1.172 www 10390: # the next is the end of "start tag"
1.339 albertel 10391: }
10392: }
1.483 albertel 10393: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 10394: $extension = lc($extension);
10395: if ($extension eq 'htm') { $extension='html'; }
10396:
1.737 albertel 10397: foreach my $key (keys(%packagetab)) {
1.483 albertel 10398: #no specific packages #how's our extension
10399: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 10400: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 10401: \%metathesekeys);
10402: }
1.883 albertel 10403:
10404: if (!exists($metaentry{':packages'})
10405: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 10406: foreach my $key (keys(%packagetab)) {
1.483 albertel 10407: #no specific packages well let's get default then
10408: if ($key!~/^default&/) { next; }
1.488 albertel 10409: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 10410: \%metathesekeys);
10411: }
10412: }
1.338 www 10413: # are there custom rights to evaluate
1.599 albertel 10414: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 10415:
1.338 www 10416: #
10417: # Importing a rights file here
1.339 albertel 10418: #
10419: unless ($depthcount) {
1.599 albertel 10420: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 10421: my $dir=$filename;
10422: $dir=~s|[^/]*$||;
10423: $location=&filelocation($dir,$location);
1.736 albertel 10424: my $rights_metadata =
10425: &metadata($uri,'keys',$location,'_rights',
10426: $depthcount+1);
10427: foreach my $rights (split(',',$rights_metadata)) {
10428: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
10429: $metathesekeys{$rights}=1;
1.339 albertel 10430: }
10431: }
10432: }
1.737 albertel 10433: # uniqifiy package listing
10434: my %seen;
10435: my @uniq_packages =
10436: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
10437: $metaentry{':packages'} = join(',',@uniq_packages);
10438:
1.1070 www 10439: if ($importedparts) {
10440: # We had imported parts and need to rebuild partorder
10441: $metaentry{':partorder'}='';
10442: $metathesekeys{'partorder'}=1;
10443: for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
10444: if ($origfileimportpartids[$index] eq 'part') {
10445: # original part, part of the problem
10446: $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
10447: } else {
10448: # we have imported parts at this position
10449: $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
10450: }
10451: }
10452: $metaentry{':partorder'}=~s/^\,//;
10453: }
10454:
1.737 albertel 10455: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 10456: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
10457: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924 albertel 10458: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 10459: # this is the end of "was not already recently cached
1.71 www 10460: }
1.599 albertel 10461: return $metaentry{':'.$what};
1.261 albertel 10462: }
10463:
1.488 albertel 10464: sub metadata_create_package_def {
1.483 albertel 10465: my ($uri,$key,$package,$metathesekeys)=@_;
10466: my ($pack,$name,$subp)=split(/\&/,$key);
10467: if ($subp eq 'default') { next; }
10468:
1.599 albertel 10469: if (defined($metaentry{':packages'})) {
10470: $metaentry{':packages'}.=','.$package;
1.483 albertel 10471: } else {
1.599 albertel 10472: $metaentry{':packages'}=$package;
1.483 albertel 10473: }
10474: my $value=$packagetab{$key};
10475: my $unikey;
10476: $unikey='parameter_0_'.$name;
1.599 albertel 10477: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 10478: $$metathesekeys{$unikey}=1;
1.599 albertel 10479: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10480: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 10481: }
1.599 albertel 10482: if (defined($metaentry{':'.$unikey.'.default'})) {
10483: $metaentry{':'.$unikey}=
10484: $metaentry{':'.$unikey.'.default'};
1.483 albertel 10485: }
10486: }
10487:
1.261 albertel 10488: sub metadata_generate_part0 {
10489: my ($metadata,$metacache,$uri) = @_;
10490: my %allnames;
1.737 albertel 10491: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 10492: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 10493: my $part=$$metacache{':'.$metakey.'.part'};
10494: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 10495: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 10496: $allnames{$name}=$part;
10497: }
10498: }
10499: }
10500: foreach my $name (keys(%allnames)) {
10501: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 10502: my $key=":parameter_0_$name";
1.261 albertel 10503: $$metacache{"$key.part"}='0';
10504: $$metacache{"$key.name"}=$name;
1.428 albertel 10505: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 10506: $allnames{$name}.'_'.$name.
10507: '.type'};
1.428 albertel 10508: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 10509: '.display'};
1.644 www 10510: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 10511: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 10512: $$metacache{"$key.display"}=$olddis;
10513: }
1.71 www 10514: }
10515:
1.764 albertel 10516: # ------------------------------------------------------ Devalidate title cache
10517:
10518: sub devalidate_title_cache {
10519: my ($url)=@_;
10520: if (!$env{'request.course.id'}) { return; }
10521: my $symb=&symbread($url);
10522: if (!$symb) { return; }
10523: my $key=$env{'request.course.id'}."\0".$symb;
10524: &devalidate_cache_new('title',$key);
10525: }
10526:
1.1014 droeschl 10527: # ------------------------------------------------- Get the title of a course
10528:
10529: sub current_course_title {
10530: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
10531: }
1.301 www 10532: # ------------------------------------------------- Get the title of a resource
10533:
10534: sub gettitle {
10535: my $urlsymb=shift;
10536: my $symb=&symbread($urlsymb);
1.534 albertel 10537: if ($symb) {
1.620 albertel 10538: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 10539: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 10540: if (defined($cached)) {
10541: return $result;
10542: }
1.534 albertel 10543: my ($map,$resid,$url)=&decode_symb($symb);
10544: my $title='';
1.907 albertel 10545: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
10546: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
10547: } else {
10548: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10549: &GDBM_READER(),0640)) {
10550: my $mapid=$bighash{'map_pc_'.&clutter($map)};
10551: $title=$bighash{'title_'.$mapid.'.'.$resid};
10552: untie(%bighash);
10553: }
1.534 albertel 10554: }
10555: $title=~s/\&colon\;/\:/gs;
10556: if ($title) {
1.1159 www 10557: # Remember both $symb and $title for dynamic metadata
10558: $accesshash{$symb.'___crstitle'}=$title;
1.1161 www 10559: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159 www 10560: # Cache this title and then return it
1.599 albertel 10561: return &do_cache_new('title',$key,$title,600);
1.534 albertel 10562: }
10563: $urlsymb=$url;
10564: }
10565: my $title=&metadata($urlsymb,'title');
10566: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
10567: return $title;
1.301 www 10568: }
1.613 albertel 10569:
1.614 albertel 10570: sub get_slot {
10571: my ($which,$cnum,$cdom)=@_;
10572: if (!$cnum || !$cdom) {
1.790 albertel 10573: (undef,my $courseid)=&whichuser();
1.620 albertel 10574: $cdom=$env{'course.'.$courseid.'.domain'};
10575: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 10576: }
1.703 albertel 10577: my $key=join("\0",'slots',$cdom,$cnum,$which);
10578: my %slotinfo;
10579: if (exists($remembered{$key})) {
10580: $slotinfo{$which} = $remembered{$key};
10581: } else {
10582: %slotinfo=&get('slots',[$which],$cdom,$cnum);
10583: &Apache::lonhomework::showhash(%slotinfo);
10584: my ($tmp)=keys(%slotinfo);
10585: if ($tmp=~/^error:/) { return (); }
10586: $remembered{$key} = $slotinfo{$which};
10587: }
1.616 albertel 10588: if (ref($slotinfo{$which}) eq 'HASH') {
10589: return %{$slotinfo{$which}};
10590: }
10591: return $slotinfo{$which};
1.614 albertel 10592: }
1.1150 raeburn 10593:
10594: sub get_reservable_slots {
10595: my ($cnum,$cdom,$uname,$udom) = @_;
10596: my $now = time;
10597: my $reservable_info;
10598: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
10599: if (exists($remembered{$key})) {
10600: $reservable_info = $remembered{$key};
10601: } else {
10602: my %resv;
10603: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
10604: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
10605: $reservable_info = \%resv;
10606: $remembered{$key} = $reservable_info;
10607: }
10608: return $reservable_info;
10609: }
10610:
10611: sub get_course_slots {
10612: my ($cnum,$cdom) = @_;
10613: my $hashid=$cnum.':'.$cdom;
10614: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
10615: if (defined($cached)) {
10616: if (ref($result) eq 'HASH') {
10617: return %{$result};
10618: }
10619: } else {
10620: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
10621: my ($tmp) = keys(%slots);
10622: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1219 raeburn 10623: &do_cache_new('allslots',$hashid,\%slots,600);
1.1150 raeburn 10624: return %slots;
10625: }
10626: }
10627: return;
10628: }
10629:
10630: sub devalidate_slots_cache {
10631: my ($cnum,$cdom)=@_;
10632: my $hashid=$cnum.':'.$cdom;
10633: &devalidate_cache_new('allslots',$hashid);
10634: }
10635:
1.1181 raeburn 10636: sub get_coursechange {
10637: my ($cdom,$cnum) = @_;
10638: if ($cdom eq '' || $cnum eq '') {
10639: return unless ($env{'request.course.id'});
10640: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10641: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10642: }
10643: my $hashid=$cdom.'_'.$cnum;
10644: my ($change,$cached)=&is_cached_new('crschange',$hashid);
10645: if ((defined($cached)) && ($change ne '')) {
10646: return $change;
10647: } else {
10648: my %crshash;
10649: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
10650: if ($crshash{'internal.contentchange'} eq '') {
10651: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
10652: if ($change eq '') {
10653: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
10654: $change = $crshash{'internal.created'};
10655: }
10656: } else {
10657: $change = $crshash{'internal.contentchange'};
10658: }
10659: my $cachetime = 600;
10660: &do_cache_new('crschange',$hashid,$change,$cachetime);
10661: }
10662: return $change;
10663: }
10664:
10665: sub devalidate_coursechange_cache {
10666: my ($cnum,$cdom)=@_;
10667: my $hashid=$cnum.':'.$cdom;
10668: &devalidate_cache_new('crschange',$hashid);
10669: }
10670:
1.31 www 10671: # ------------------------------------------------- Update symbolic store links
10672:
10673: sub symblist {
10674: my ($mapname,%newhash)=@_;
1.438 www 10675: $mapname=&deversion(&declutter($mapname));
1.31 www 10676: my %hash;
1.620 albertel 10677: if (($env{'request.course.fn'}) && (%newhash)) {
10678: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 10679: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 10680: foreach my $url (keys(%newhash)) {
1.711 albertel 10681: next if ($url eq 'last_known'
10682: && $env{'form.no_update_last_known'});
10683: $hash{declutter($url)}=&encode_symb($mapname,
10684: $newhash{$url}->[1],
10685: $newhash{$url}->[0]);
1.191 harris41 10686: }
1.31 www 10687: if (untie(%hash)) {
10688: return 'ok';
10689: }
10690: }
10691: }
10692: return 'error';
1.212 www 10693: }
10694:
10695: # --------------------------------------------------------------- Verify a symb
10696:
10697: sub symbverify {
1.1190 raeburn 10698: my ($symb,$thisurl,$encstate)=@_;
1.510 www 10699: my $thisfn=$thisurl;
1.439 www 10700: $thisfn=&declutter($thisfn);
1.215 www 10701: # direct jump to resource in page or to a sequence - will construct own symbs
10702: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
10703: # check URL part
1.409 www 10704: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 10705:
1.431 www 10706: unless ($url eq $thisfn) { return 0; }
1.213 www 10707:
1.216 www 10708: $symb=&symbclean($symb);
1.510 www 10709: $thisurl=&deversion($thisurl);
1.439 www 10710: $thisfn=&deversion($thisfn);
1.213 www 10711:
10712: my %bighash;
10713: my $okay=0;
1.431 www 10714:
1.620 albertel 10715: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 10716: &GDBM_READER(),0640)) {
1.1204 raeburn 10717: my $noclutter;
1.1032 raeburn 10718: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
10719: $thisurl =~ s/\?.+$//;
1.1204 raeburn 10720: if ($map =~ m{^uploaded/.+\.page$}) {
10721: $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
10722: $thisurl =~ s{^\Qhttp://https://\E}{https://};
10723: $noclutter = 1;
10724: }
10725: }
10726: my $ids;
10727: if ($noclutter) {
10728: $ids=$bighash{'ids_'.$thisurl};
10729: } else {
10730: $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032 raeburn 10731: }
1.1102 raeburn 10732: unless ($ids) {
10733: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
10734: $ids=$bighash{$idkey};
1.216 www 10735: }
10736: if ($ids) {
10737: # ------------------------------------------------------------------- Has ID(s)
1.1202 raeburn 10738: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
1.1203 raeburn 10739: $symb =~ s/\?.+$//;
1.1202 raeburn 10740: }
1.800 albertel 10741: foreach my $id (split(/\,/,$ids)) {
10742: my ($mapid,$resid)=split(/\./,$id);
1.216 www 10743: if (
10744: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190 raeburn 10745: eq $symb) {
10746: if (ref($encstate)) {
10747: $$encstate = $bighash{'encrypted_'.$id};
10748: }
1.620 albertel 10749: if (($env{'request.role.adv'}) ||
1.1101 raeburn 10750: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
10751: ($thisurl eq '/adm/navmaps')) {
1.1190 raeburn 10752: $okay=1;
1.1202 raeburn 10753: last;
1.582 albertel 10754: }
10755: }
1.216 www 10756: }
10757: }
1.213 www 10758: untie(%bighash);
10759: }
10760: return $okay;
1.31 www 10761: }
10762:
1.210 www 10763: # --------------------------------------------------------------- Clean-up symb
10764:
10765: sub symbclean {
10766: my $symb=shift;
1.568 albertel 10767: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 10768: # remove version from map
10769: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 10770:
1.210 www 10771: # remove version from URL
10772: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 10773:
1.507 www 10774: # remove wrapper
10775:
1.510 www 10776: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 10777: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 10778: return $symb;
1.409 www 10779: }
10780:
10781: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 10782:
10783: sub encode_symb {
10784: my ($map,$resid,$url)=@_;
10785: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
10786: }
1.409 www 10787:
10788: sub decode_symb {
1.568 albertel 10789: my $symb=shift;
10790: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
10791: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 10792: return (&fixversion($map),$resid,&fixversion($url));
10793: }
10794:
10795: sub fixversion {
10796: my $fn=shift;
1.609 banghart 10797: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 10798: my %bighash;
10799: my $uri=&clutter($fn);
1.620 albertel 10800: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 10801: # is this cached?
1.599 albertel 10802: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 10803: if (defined($cached)) { return $result; }
10804: # unfortunately not cached, or expired
1.620 albertel 10805: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 10806: &GDBM_READER(),0640)) {
10807: if ($bighash{'version_'.$uri}) {
10808: my $version=$bighash{'version_'.$uri};
1.444 www 10809: unless (($version eq 'mostrecent') ||
10810: ($version==&getversion($uri))) {
1.440 www 10811: $uri=~s/\.(\w+)$/\.$version\.$1/;
10812: }
10813: }
10814: untie %bighash;
1.413 www 10815: }
1.599 albertel 10816: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 10817: }
10818:
10819: sub deversion {
10820: my $url=shift;
10821: $url=~s/\.\d+\.(\w+)$/\.$1/;
10822: return $url;
1.210 www 10823: }
10824:
1.31 www 10825: # ------------------------------------------------------ Return symb list entry
10826:
10827: sub symbread {
1.249 www 10828: my ($thisfn,$donotrecurse)=@_;
1.1206 raeburn 10829: my $cache_str;
10830: if ($thisfn ne '') {
10831: $cache_str='request.symbread.cached.'.$thisfn;
10832: if ($env{$cache_str} ne '') {
1.1179 raeburn 10833: return $env{$cache_str};
10834: }
1.1206 raeburn 10835: } else {
1.242 www 10836: # no filename provided? try from environment
1.620 albertel 10837: if ($env{'request.symb'}) {
10838: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 10839: }
1.620 albertel 10840: $thisfn=$env{'request.filename'};
1.44 www 10841: }
1.569 albertel 10842: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 10843: # is that filename actually a symb? Verify, clean, and return
10844: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 10845: if (&symbverify($thisfn,$1)) {
1.620 albertel 10846: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 10847: }
1.242 www 10848: }
1.44 www 10849: $thisfn=declutter($thisfn);
1.31 www 10850: my %hash;
1.37 www 10851: my %bighash;
10852: my $syval='';
1.620 albertel 10853: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 10854: my $targetfn = $thisfn;
1.609 banghart 10855: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 10856: $targetfn = 'adm/wrapper/'.$thisfn;
10857: }
1.687 albertel 10858: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
10859: $targetfn=$1;
10860: }
1.620 albertel 10861: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 10862: &GDBM_READER(),0640)) {
1.481 raeburn 10863: $syval=$hash{$targetfn};
1.37 www 10864: untie(%hash);
10865: }
10866: # ---------------------------------------------------------- There was an entry
10867: if ($syval) {
1.601 albertel 10868: #unless ($syval=~/\_\d+$/) {
1.620 albertel 10869: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 10870: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 10871: #return $env{$cache_str}='';
1.601 albertel 10872: #}
10873: #$syval.=$1;
10874: #}
1.37 www 10875: } else {
10876: # ------------------------------------------------------- Was not in symb table
1.620 albertel 10877: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 10878: &GDBM_READER(),0640)) {
1.37 www 10879: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 10880: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 10881: unless ($ids) {
10882: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 10883: }
10884: unless ($ids) {
10885: # alias?
10886: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 10887: }
1.37 www 10888: if ($ids) {
10889: # ------------------------------------------------------------------- Has ID(s)
10890: my @possibilities=split(/\,/,$ids);
1.39 www 10891: if ($#possibilities==0) {
10892: # ----------------------------------------------- There is only one possibility
1.37 www 10893: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 10894: $syval=&encode_symb($bighash{'map_id_'.$mapid},
10895: $resid,$thisfn);
1.249 www 10896: } elsif (!$donotrecurse) {
1.39 www 10897: # ------------------------------------------ There is more than one possibility
10898: my $realpossible=0;
1.800 albertel 10899: foreach my $id (@possibilities) {
10900: my $file=$bighash{'src_'.$id};
1.39 www 10901: if (&allowed('bre',$file)) {
1.800 albertel 10902: my ($mapid,$resid)=split(/\./,$id);
1.39 www 10903: if ($bighash{'map_type_'.$mapid} ne 'page') {
10904: $realpossible++;
1.626 albertel 10905: $syval=&encode_symb($bighash{'map_id_'.$mapid},
10906: $resid,$thisfn);
1.39 www 10907: }
10908: }
1.191 harris41 10909: }
1.39 www 10910: if ($realpossible!=1) { $syval=''; }
1.249 www 10911: } else {
10912: $syval='';
1.37 www 10913: }
10914: }
10915: untie(%bighash)
1.481 raeburn 10916: }
1.31 www 10917: }
1.62 www 10918: if ($syval) {
1.620 albertel 10919: return $env{$cache_str}=$syval;
1.62 www 10920: }
1.31 www 10921: }
1.949 raeburn 10922: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 10923: return $env{$cache_str}='';
1.31 www 10924: }
10925:
10926: # ---------------------------------------------------------- Return random seed
10927:
1.32 www 10928: sub numval {
10929: my $txt=shift;
10930: $txt=~tr/A-J/0-9/;
10931: $txt=~tr/a-j/0-9/;
10932: $txt=~tr/K-T/0-9/;
10933: $txt=~tr/k-t/0-9/;
10934: $txt=~tr/U-Z/0-5/;
10935: $txt=~tr/u-z/0-5/;
10936: $txt=~s/\D//g;
1.564 albertel 10937: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 10938: return int($txt);
1.368 albertel 10939: }
10940:
1.484 albertel 10941: sub numval2 {
10942: my $txt=shift;
10943: $txt=~tr/A-J/0-9/;
10944: $txt=~tr/a-j/0-9/;
10945: $txt=~tr/K-T/0-9/;
10946: $txt=~tr/k-t/0-9/;
10947: $txt=~tr/U-Z/0-5/;
10948: $txt=~tr/u-z/0-5/;
10949: $txt=~s/\D//g;
10950: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10951: my $total;
10952: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 10953: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 10954: return int($total);
10955: }
10956:
1.575 albertel 10957: sub numval3 {
10958: use integer;
10959: my $txt=shift;
10960: $txt=~tr/A-J/0-9/;
10961: $txt=~tr/a-j/0-9/;
10962: $txt=~tr/K-T/0-9/;
10963: $txt=~tr/k-t/0-9/;
10964: $txt=~tr/U-Z/0-5/;
10965: $txt=~tr/u-z/0-5/;
10966: $txt=~s/\D//g;
10967: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10968: my $total;
10969: foreach my $val (@txts) { $total+=$val; }
10970: if ($_64bit) { $total=(($total<<32)>>32); }
10971: return $total;
10972: }
10973:
1.675 albertel 10974: sub digest {
10975: my ($data)=@_;
10976: my $digest=&Digest::MD5::md5($data);
10977: my ($a,$b,$c,$d)=unpack("iiii",$digest);
10978: my ($e,$f);
10979: {
10980: use integer;
10981: $e=($a+$b);
10982: $f=($c+$d);
10983: if ($_64bit) {
10984: $e=(($e<<32)>>32);
10985: $f=(($f<<32)>>32);
10986: }
10987: }
10988: if (wantarray) {
10989: return ($e,$f);
10990: } else {
10991: my $g;
10992: {
10993: use integer;
10994: $g=($e+$f);
10995: if ($_64bit) {
10996: $g=(($g<<32)>>32);
10997: }
10998: }
10999: return $g;
11000: }
11001: }
11002:
1.368 albertel 11003: sub latest_rnd_algorithm_id {
1.675 albertel 11004: return '64bit5';
1.366 albertel 11005: }
1.32 www 11006:
1.503 albertel 11007: sub get_rand_alg {
11008: my ($courseid)=@_;
1.790 albertel 11009: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 11010: if ($courseid) {
1.620 albertel 11011: return $env{"course.$courseid.rndseed"};
1.503 albertel 11012: }
11013: return &latest_rnd_algorithm_id();
11014: }
11015:
1.562 albertel 11016: sub validCODE {
11017: my ($CODE)=@_;
11018: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
11019: return 0;
11020: }
11021:
1.491 albertel 11022: sub getCODE {
1.620 albertel 11023: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 11024: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
11025: defined($Apache::lonhomework::parsing_a_task) ) &&
11026: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 11027: return $Apache::lonhomework::history{'resource.CODE'};
11028: }
11029: return undef;
11030: }
1.1133 foxr 11031: #
11032: # Determines the random seed for a specific context:
11033: #
11034: # parameters:
11035: # symb - in course context the symb for the seed.
11036: # course_id - The course id of the form domain_coursenum.
11037: # domain - Domain for the user.
11038: # course - Course for the user.
11039: # cenv - environment of the course.
11040: #
11041: # NOTE:
11042: # All parameters are picked out of the environment if missing
11043: # or not defined.
11044: # If a symb cannot be determined the current time is used instead.
11045: #
11046: # For a given well defined symb, courside, domain, username,
11047: # and course environment, the seed is reproducible.
11048: #
1.31 www 11049: sub rndseed {
1.1133 foxr 11050: my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790 albertel 11051: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 11052: if (!defined($symb)) {
1.366 albertel 11053: unless ($symb=$wsymb) { return time; }
11054: }
1.1146 foxr 11055: if (!defined $courseid) {
11056: $courseid=$wcourseid;
11057: }
11058: if (!defined $domain) { $domain=$wdomain; }
11059: if (!defined $username) { $username=$wusername }
1.1133 foxr 11060:
11061: my $which;
11062: if (defined($cenv->{'rndseed'})) {
11063: $which = $cenv->{'rndseed'};
11064: } else {
11065: $which =&get_rand_alg($courseid);
11066: }
1.491 albertel 11067: if (defined(&getCODE())) {
1.1133 foxr 11068:
1.675 albertel 11069: if ($which eq '64bit5') {
11070: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
11071: } elsif ($which eq '64bit4') {
1.575 albertel 11072: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
11073: } else {
11074: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
11075: }
1.675 albertel 11076: } elsif ($which eq '64bit5') {
11077: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 11078: } elsif ($which eq '64bit4') {
11079: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 11080: } elsif ($which eq '64bit3') {
11081: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 11082: } elsif ($which eq '64bit2') {
11083: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 11084: } elsif ($which eq '64bit') {
11085: return &rndseed_64bit($symb,$courseid,$domain,$username);
11086: }
11087: return &rndseed_32bit($symb,$courseid,$domain,$username);
11088: }
11089:
11090: sub rndseed_32bit {
11091: my ($symb,$courseid,$domain,$username)=@_;
11092: {
11093: use integer;
11094: my $symbchck=unpack("%32C*",$symb) << 27;
11095: my $symbseed=numval($symb) << 22;
11096: my $namechck=unpack("%32C*",$username) << 17;
11097: my $nameseed=numval($username) << 12;
11098: my $domainseed=unpack("%32C*",$domain) << 7;
11099: my $courseseed=unpack("%32C*",$courseid);
11100: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 11101: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11102: #&logthis("rndseed :$num:$symb");
1.564 albertel 11103: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 11104: return $num;
11105: }
11106: }
11107:
11108: sub rndseed_64bit {
11109: my ($symb,$courseid,$domain,$username)=@_;
11110: {
11111: use integer;
11112: my $symbchck=unpack("%32S*",$symb) << 21;
11113: my $symbseed=numval($symb) << 10;
11114: my $namechck=unpack("%32S*",$username);
11115:
11116: my $nameseed=numval($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 :$num:$symb");
1.564 albertel 11124: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 11125: return "$num1,$num2";
1.155 albertel 11126: }
1.366 albertel 11127: }
11128:
1.443 albertel 11129: sub rndseed_64bit2 {
11130: my ($symb,$courseid,$domain,$username)=@_;
11131: {
11132: use integer;
11133: # strings need to be an even # of cahracters long, it it is odd the
11134: # last characters gets thrown away
11135: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11136: my $symbseed=numval($symb) << 10;
11137: my $namechck=unpack("%32S*",$username.' ');
11138:
11139: my $nameseed=numval($username) << 21;
1.501 albertel 11140: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11141: my $courseseed=unpack("%32S*",$courseid.' ');
11142:
11143: my $num1=$symbchck+$symbseed+$namechck;
11144: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11145: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11146: #&logthis("rndseed :$num:$symb");
1.803 albertel 11147: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 11148: return "$num1,$num2";
11149: }
11150: }
11151:
11152: sub rndseed_64bit3 {
11153: my ($symb,$courseid,$domain,$username)=@_;
11154: {
11155: use integer;
11156: # strings need to be an even # of cahracters long, it it is odd the
11157: # last characters gets thrown away
11158: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11159: my $symbseed=numval2($symb) << 10;
11160: my $namechck=unpack("%32S*",$username.' ');
11161:
11162: my $nameseed=numval2($username) << 21;
1.443 albertel 11163: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11164: my $courseseed=unpack("%32S*",$courseid.' ');
11165:
11166: my $num1=$symbchck+$symbseed+$namechck;
11167: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11168: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11169: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 11170: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 11171:
1.503 albertel 11172: return "$num1:$num2";
1.443 albertel 11173: }
11174: }
11175:
1.575 albertel 11176: sub rndseed_64bit4 {
11177: my ($symb,$courseid,$domain,$username)=@_;
11178: {
11179: use integer;
11180: # strings need to be an even # of cahracters long, it it is odd the
11181: # last characters gets thrown away
11182: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11183: my $symbseed=numval3($symb) << 10;
11184: my $namechck=unpack("%32S*",$username.' ');
11185:
11186: my $nameseed=numval3($username) << 21;
11187: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11188: my $courseseed=unpack("%32S*",$courseid.' ');
11189:
11190: my $num1=$symbchck+$symbseed+$namechck;
11191: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11192: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11193: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 11194: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 11195:
1.575 albertel 11196: return "$num1:$num2";
11197: }
11198: }
11199:
1.675 albertel 11200: sub rndseed_64bit5 {
11201: my ($symb,$courseid,$domain,$username)=@_;
11202: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
11203: return "$num1:$num2";
11204: }
11205:
1.366 albertel 11206: sub rndseed_CODE_64bit {
11207: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 11208: {
1.366 albertel 11209: use integer;
1.443 albertel 11210: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 11211: my $symbseed=numval2($symb);
1.491 albertel 11212: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11213: my $CODEseed=numval(&getCODE());
1.443 albertel 11214: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 11215: my $num1=$symbseed+$CODEchck;
11216: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 11217: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11218: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 11219: if ($_64bit) { $num1=(($num1<<32)>>32); }
11220: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 11221: return "$num1:$num2";
1.366 albertel 11222: }
11223: }
11224:
1.575 albertel 11225: sub rndseed_CODE_64bit4 {
11226: my ($symb,$courseid,$domain,$username)=@_;
11227: {
11228: use integer;
11229: my $symbchck=unpack("%32S*",$symb.' ') << 16;
11230: my $symbseed=numval3($symb);
11231: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11232: my $CODEseed=numval3(&getCODE());
11233: my $courseseed=unpack("%32S*",$courseid.' ');
11234: my $num1=$symbseed+$CODEchck;
11235: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 11236: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11237: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 11238: if ($_64bit) { $num1=(($num1<<32)>>32); }
11239: if ($_64bit) { $num2=(($num2<<32)>>32); }
11240: return "$num1:$num2";
11241: }
11242: }
11243:
1.675 albertel 11244: sub rndseed_CODE_64bit5 {
11245: my ($symb,$courseid,$domain,$username)=@_;
11246: my $code = &getCODE();
11247: my ($num1,$num2)=&digest("$symb,$courseid,$code");
11248: return "$num1:$num2";
11249: }
11250:
1.366 albertel 11251: sub setup_random_from_rndseed {
11252: my ($rndseed)=@_;
1.503 albertel 11253: if ($rndseed =~/([,:])/) {
11254: my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366 albertel 11255: &Math::Random::random_set_seed(abs($num1),abs($num2));
11256: } else {
11257: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 11258: }
1.36 albertel 11259: }
11260:
1.474 albertel 11261: sub latest_receipt_algorithm_id {
1.835 albertel 11262: return 'receipt3';
1.474 albertel 11263: }
11264:
1.480 www 11265: sub recunique {
11266: my $fucourseid=shift;
11267: my $unique;
1.835 albertel 11268: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
11269: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 11270: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 11271: } else {
11272: $unique=$perlvar{'lonReceipt'};
11273: }
11274: return unpack("%32C*",$unique);
11275: }
11276:
11277: sub recprefix {
11278: my $fucourseid=shift;
11279: my $prefix;
1.835 albertel 11280: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
11281: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 11282: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 11283: } else {
11284: $prefix=$perlvar{'lonHostID'};
11285: }
11286: return unpack("%32C*",$prefix);
11287: }
11288:
1.76 www 11289: sub ireceipt {
1.474 albertel 11290: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 11291:
11292: my $return =&recprefix($fucourseid).'-';
11293:
11294: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
11295: $env{'request.state'} eq 'construct') {
11296: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
11297: return $return;
11298: }
11299:
1.76 www 11300: my $cuname=unpack("%32C*",$funame);
11301: my $cudom=unpack("%32C*",$fudom);
11302: my $cucourseid=unpack("%32C*",$fucourseid);
11303: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 11304: my $cunique=&recunique($fucourseid);
1.474 albertel 11305: my $cpart=unpack("%32S*",$part);
1.835 albertel 11306: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
11307:
1.790 albertel 11308: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 11309:
11310: $return.= ($cunique%$cuname+
11311: $cunique%$cudom+
11312: $cusymb%$cuname+
11313: $cusymb%$cudom+
11314: $cucourseid%$cuname+
11315: $cucourseid%$cudom+
11316: $cpart%$cuname+
11317: $cpart%$cudom);
11318: } else {
11319: $return.= ($cunique%$cuname+
11320: $cunique%$cudom+
11321: $cusymb%$cuname+
11322: $cusymb%$cudom+
11323: $cucourseid%$cuname+
11324: $cucourseid%$cudom);
11325: }
11326: return $return;
1.76 www 11327: }
11328:
11329: sub receipt {
1.474 albertel 11330: my ($part)=@_;
1.790 albertel 11331: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 11332: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 11333: }
1.260 ng 11334:
1.790 albertel 11335: sub whichuser {
11336: my ($passedsymb)=@_;
11337: my ($symb,$courseid,$domain,$name,$publicuser);
11338: if (defined($env{'form.grade_symb'})) {
11339: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
11340: my $allowed=&allowed('vgr',$tmp_courseid);
11341: if (!$allowed &&
11342: exists($env{'request.course.sec'}) &&
11343: $env{'request.course.sec'} !~ /^\s*$/) {
11344: $allowed=&allowed('vgr',$tmp_courseid.
11345: '/'.$env{'request.course.sec'});
11346: }
11347: if ($allowed) {
11348: ($symb)=&get_env_multiple('form.grade_symb');
11349: $courseid=$tmp_courseid;
11350: ($domain)=&get_env_multiple('form.grade_domain');
11351: ($name)=&get_env_multiple('form.grade_username');
11352: return ($symb,$courseid,$domain,$name,$publicuser);
11353: }
11354: }
11355: if (!$passedsymb) {
11356: $symb=&symbread();
11357: } else {
11358: $symb=$passedsymb;
11359: }
11360: $courseid=$env{'request.course.id'};
11361: $domain=$env{'user.domain'};
11362: $name=$env{'user.name'};
11363: if ($name eq 'public' && $domain eq 'public') {
11364: if (!defined($env{'form.username'})) {
11365: $env{'form.username'}.=time.rand(10000000);
11366: }
11367: $name.=$env{'form.username'};
11368: }
11369: return ($symb,$courseid,$domain,$name,$publicuser);
11370:
11371: }
11372:
1.36 albertel 11373: # ------------------------------------------------------------ Serves up a file
1.472 albertel 11374: # returns either the contents of the file or
11375: # -1 if the file doesn't exist
1.481 raeburn 11376: #
11377: # if the target is a file that was uploaded via DOCS,
11378: # a check will be made to see if a current copy exists on the local server,
11379: # if it does this will be served, otherwise a copy will be retrieved from
11380: # the home server for the course and stored in /home/httpd/html/userfiles on
11381: # the local server.
1.472 albertel 11382:
1.36 albertel 11383: sub getfile {
1.538 albertel 11384: my ($file) = @_;
1.609 banghart 11385: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 11386: &repcopy($file);
11387: return &readfile($file);
11388: }
11389:
11390: sub repcopy_userfile {
11391: my ($file)=@_;
1.1142 raeburn 11392: my $londocroot = $perlvar{'lonDocRoot'};
11393: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164 raeburn 11394: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538 albertel 11395: my ($cdom,$cnum,$filename) =
1.811 albertel 11396: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 11397: my $uri="/uploaded/$cdom/$cnum/$filename";
11398: if (-e "$file") {
1.828 www 11399: # we already have a local copy, check it out
1.538 albertel 11400: my @fileinfo = stat($file);
1.828 www 11401: my $rtncode;
11402: my $info;
1.538 albertel 11403: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 11404: if ($lwpresp ne 'ok') {
1.828 www 11405: # there is no such file anymore, even though we had a local copy
1.482 albertel 11406: if ($rtncode eq '404') {
1.538 albertel 11407: unlink($file);
1.482 albertel 11408: }
11409: return -1;
11410: }
11411: if ($info < $fileinfo[9]) {
1.828 www 11412: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 11413: return 'ok';
1.828 www 11414: } else {
11415: # the file is outdated, get rid of it
11416: unlink($file);
1.482 albertel 11417: }
1.828 www 11418: }
11419: # one way or the other, at this point, we don't have the file
11420: # construct the correct path for the file
11421: my @parts = ($cdom,$cnum);
11422: if ($filename =~ m|^(.+)/[^/]+$|) {
11423: push @parts, split(/\//,$1);
11424: }
11425: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
11426: foreach my $part (@parts) {
11427: $path .= '/'.$part;
11428: if (!-e $path) {
11429: mkdir($path,0770);
1.482 albertel 11430: }
11431: }
1.828 www 11432: # now the path exists for sure
11433: # get a user agent
11434: my $ua=new LWP::UserAgent;
11435: my $transferfile=$file.'.in.transfer';
11436: # FIXME: this should flock
11437: if (-e $transferfile) { return 'ok'; }
11438: my $request;
11439: $uri=~s/^\///;
1.980 raeburn 11440: my $homeserver = &homeserver($cnum,$cdom);
11441: my $protocol = $protocol{$homeserver};
11442: $protocol = 'http' if ($protocol ne 'https');
11443: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 11444: my $response=$ua->request($request,$transferfile);
11445: # did it work?
11446: if ($response->is_error()) {
11447: unlink($transferfile);
11448: &logthis("Userfile repcopy failed for $uri");
11449: return -1;
11450: }
11451: # worked, rename the transfer file
11452: rename($transferfile,$file);
1.607 raeburn 11453: return 'ok';
1.481 raeburn 11454: }
11455:
1.517 albertel 11456: sub tokenwrapper {
11457: my $uri=shift;
1.980 raeburn 11458: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 11459: $uri=~s|^/||;
1.620 albertel 11460: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 11461: my $token=$1;
1.552 albertel 11462: my (undef,$udom,$uname,$file)=split('/',$uri,4);
11463: if ($udom && $uname && $file) {
11464: $file=~s|(\?\.*)*$||;
1.949 raeburn 11465: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 11466: my $homeserver = &homeserver($uname,$udom);
11467: my $protocol = $protocol{$homeserver};
11468: $protocol = 'http' if ($protocol ne 'https');
11469: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 11470: (($uri=~/\?/)?'&':'?').'token='.$token.
11471: '&tokenissued='.$perlvar{'lonHostID'};
11472: } else {
11473: return '/adm/notfound.html';
11474: }
11475: }
11476:
1.828 www 11477: # call with reqtype HEAD: get last modification time
11478: # call with reqtype GET: get the file contents
11479: # Do not call this with reqtype GET for large files! It loads everything into memory
11480: #
1.481 raeburn 11481: sub getuploaded {
11482: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
11483: $uri=~s/^\///;
1.980 raeburn 11484: my $homeserver = &homeserver($cnum,$cdom);
11485: my $protocol = $protocol{$homeserver};
11486: $protocol = 'http' if ($protocol ne 'https');
11487: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 11488: my $ua=new LWP::UserAgent;
11489: my $request=new HTTP::Request($reqtype,$uri);
11490: my $response=$ua->request($request);
11491: $$rtncode = $response->code;
1.482 albertel 11492: if (! $response->is_success()) {
11493: return 'failed';
11494: }
11495: if ($reqtype eq 'HEAD') {
1.486 www 11496: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 11497: } elsif ($reqtype eq 'GET') {
11498: $$info = $response->content;
1.472 albertel 11499: }
1.482 albertel 11500: return 'ok';
1.36 albertel 11501: }
11502:
1.481 raeburn 11503: sub readfile {
11504: my $file = shift;
11505: if ( (! -e $file ) || ($file eq '') ) { return -1; };
11506: my $fh;
11507: open($fh,"<$file");
11508: my $a='';
1.800 albertel 11509: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 11510: return $a;
11511: }
11512:
1.36 albertel 11513: sub filelocation {
1.590 banghart 11514: my ($dir,$file) = @_;
11515: my $location;
11516: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 11517:
11518: if ($file =~ m-^/adm/-) {
11519: $file=~s-^/adm/wrapper/-/-;
11520: $file=~s-^/adm/coursedocs/showdoc/-/-;
11521: }
1.882 albertel 11522:
1.1139 www 11523: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956 raeburn 11524: $location = $file;
1.609 banghart 11525: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 11526: my ($udom,$uname,$filename)=
1.811 albertel 11527: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 11528: my $home=&homeserver($uname,$udom);
11529: my $is_me=0;
11530: my @ids=¤t_machine_ids();
11531: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
11532: if ($is_me) {
1.1117 foxr 11533: $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 11534: } else {
11535: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
11536: $udom.'/'.$uname.'/'.$filename;
11537: }
1.882 albertel 11538: } elsif ($file =~ m-^/adm/-) {
11539: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 11540: } else {
11541: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139 www 11542: $file=~s:^/(res|priv)/:/:;
11543: my $space=$1;
1.590 banghart 11544: if ( !( $file =~ m:^/:) ) {
11545: $location = $dir. '/'.$file;
11546: } else {
1.1142 raeburn 11547: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590 banghart 11548: }
1.59 albertel 11549: }
1.590 banghart 11550: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 11551: while ($location=~m{/\.\./}) {
11552: if ($location =~ m{/[^/]+/\.\./}) {
11553: $location=~ s{/[^/]+/\.\./}{/}g;
11554: } else {
11555: $location=~ s{/\.\./}{/}g;
11556: }
11557: } #remove dir/..
1.590 banghart 11558: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
11559: return $location;
1.46 www 11560: }
1.36 albertel 11561:
1.46 www 11562: sub hreflocation {
11563: my ($dir,$file)=@_;
1.980 raeburn 11564: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 11565: $file=filelocation($dir,$file);
1.700 albertel 11566: } elsif ($file=~m-^/adm/-) {
11567: $file=~s-^/adm/wrapper/-/-;
11568: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 11569: }
11570: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
11571: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
11572: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143 raeburn 11573: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
11574: {/uploaded/$1/$2/}x;
1.46 www 11575: }
1.913 albertel 11576: if ($file=~ m{^/userfiles/}) {
11577: $file =~ s{^/userfiles/}{/uploaded/};
11578: }
1.462 albertel 11579: return $file;
1.465 albertel 11580: }
11581:
1.1139 www 11582:
11583:
11584:
11585:
1.465 albertel 11586: sub current_machine_domains {
1.853 albertel 11587: return &machine_domains(&hostname($perlvar{'lonHostID'}));
11588: }
11589:
11590: sub machine_domains {
11591: my ($hostname) = @_;
1.465 albertel 11592: my @domains;
1.838 albertel 11593: my %hostname = &all_hostnames();
1.465 albertel 11594: while( my($id, $name) = each(%hostname)) {
1.467 matthew 11595: # &logthis("-$id-$name-$hostname-");
1.465 albertel 11596: if ($hostname eq $name) {
1.844 albertel 11597: push(@domains,&host_domain($id));
1.465 albertel 11598: }
11599: }
11600: return @domains;
11601: }
11602:
11603: sub current_machine_ids {
1.853 albertel 11604: return &machine_ids(&hostname($perlvar{'lonHostID'}));
11605: }
11606:
11607: sub machine_ids {
11608: my ($hostname) = @_;
11609: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 11610: my @ids;
1.888 albertel 11611: my %name_to_host = &all_names();
1.889 albertel 11612: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
11613: return @{ $name_to_host{$hostname} };
11614: }
11615: return;
1.31 www 11616: }
11617:
1.824 raeburn 11618: sub additional_machine_domains {
11619: my @domains;
11620: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
11621: while( my $line = <$fh>) {
11622: $line =~ s/\s//g;
11623: push(@domains,$line);
11624: }
11625: return @domains;
11626: }
11627:
11628: sub default_login_domain {
11629: my $domain = $perlvar{'lonDefDomain'};
11630: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
11631: foreach my $posdom (¤t_machine_domains(),
11632: &additional_machine_domains()) {
11633: if (lc($posdom) eq lc($testdomain)) {
11634: $domain=$posdom;
11635: last;
11636: }
11637: }
11638: return $domain;
11639: }
11640:
1.31 www 11641: # ------------------------------------------------------------- Declutters URLs
11642:
11643: sub declutter {
11644: my $thisfn=shift;
1.569 albertel 11645: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479 albertel 11646: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31 www 11647: $thisfn=~s/^\///;
1.697 albertel 11648: $thisfn=~s|^adm/wrapper/||;
11649: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 11650: $thisfn=~s/^res\///;
1.1172 bisitz 11651: $thisfn=~s/^priv\///;
1.1032 raeburn 11652: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
11653: $thisfn=~s/\?.+$//;
11654: }
1.268 www 11655: return $thisfn;
11656: }
11657:
11658: # ------------------------------------------------------------- Clutter up URLs
11659:
11660: sub clutter {
11661: my $thisfn='/'.&declutter(shift);
1.887 albertel 11662: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 11663: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 11664: $thisfn='/res'.$thisfn;
11665: }
1.1031 raeburn 11666: if ($thisfn !~m|^/adm|) {
11667: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 11668: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 11669: } else {
11670: my ($ext) = ($thisfn =~ /\.(\w+)$/);
11671: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 11672: if ($embstyle eq 'ssi'
11673: || ($embstyle eq 'hdn')
11674: || ($embstyle eq 'rat')
11675: || ($embstyle eq 'prv')
11676: || ($embstyle eq 'ign')) {
11677: #do nothing with these
11678: } elsif (($embstyle eq 'img')
1.695 albertel 11679: || ($embstyle eq 'emb')
11680: || ($embstyle eq 'wrp')) {
11681: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 11682: } elsif ($embstyle eq 'unk'
11683: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 11684: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 11685: } else {
1.718 www 11686: # &logthis("Got a blank emb style");
1.695 albertel 11687: }
1.694 albertel 11688: }
11689: }
1.31 www 11690: return $thisfn;
1.12 www 11691: }
11692:
1.787 albertel 11693: sub clutter_with_no_wrapper {
11694: my $uri = &clutter(shift);
11695: if ($uri =~ m-^/adm/-) {
11696: $uri =~ s-^/adm/wrapper/-/-;
11697: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
11698: }
11699: return $uri;
11700: }
11701:
1.557 albertel 11702: sub freeze_escape {
11703: my ($value)=@_;
11704: if (ref($value)) {
11705: $value=&nfreeze($value);
11706: return '__FROZEN__'.&escape($value);
11707: }
11708: return &escape($value);
11709: }
11710:
1.11 www 11711:
1.557 albertel 11712: sub thaw_unescape {
11713: my ($value)=@_;
11714: if ($value =~ /^__FROZEN__/) {
11715: substr($value,0,10,undef);
11716: $value=&unescape($value);
11717: return &thaw($value);
11718: }
11719: return &unescape($value);
11720: }
11721:
1.436 albertel 11722: sub correct_line_ends {
11723: my ($result)=@_;
11724: $$result =~s/\r\n/\n/mg;
11725: $$result =~s/\r/\n/mg;
1.415 albertel 11726: }
1.1 albertel 11727: # ================================================================ Main Program
11728:
1.184 www 11729: sub goodbye {
1.204 albertel 11730: &logthis("Starting Shut down");
1.443 albertel 11731: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 11732: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 11733: #converted
1.599 albertel 11734: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 11735: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
11736: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
11737: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 11738: #1.1 only
1.870 albertel 11739: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
11740: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
11741: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
11742: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
11743: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 11744: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
11745: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 11746: &flushcourselogs();
11747: &logthis("Shutting down");
11748: }
11749:
1.852 albertel 11750: sub get_dns {
1.1210 raeburn 11751: my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869 albertel 11752: if (!$ignore_cache) {
11753: my ($content,$cached)=
11754: &Apache::lonnet::is_cached_new('dns',$url);
11755: if ($cached) {
1.1210 raeburn 11756: &$func($content,$hashref);
1.869 albertel 11757: return;
11758: }
11759: }
11760:
11761: my %alldns;
1.852 albertel 11762: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11763: foreach my $dns (<$config>) {
11764: next if ($dns !~ /^\^(\S*)/x);
1.979 raeburn 11765: my $line = $1;
11766: my ($host,$protocol) = split(/:/,$line);
11767: if ($protocol ne 'https') {
11768: $protocol = 'http';
11769: }
11770: $alldns{$host} = $protocol;
1.869 albertel 11771: }
11772: while (%alldns) {
11773: my ($dns) = keys(%alldns);
1.852 albertel 11774: my $ua=new LWP::UserAgent;
1.1134 raeburn 11775: $ua->timeout(30);
1.979 raeburn 11776: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 11777: my $response=$ua->request($request);
1.979 raeburn 11778: delete($alldns{$dns});
1.852 albertel 11779: next if ($response->is_error());
11780: my @content = split("\n",$response->content);
1.1210 raeburn 11781: unless ($nocache) {
1.1219 raeburn 11782: &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1210 raeburn 11783: }
11784: &$func(\@content,$hashref);
1.869 albertel 11785: return;
1.852 albertel 11786: }
11787: close($config);
1.871 albertel 11788: my $which = (split('/',$url))[3];
11789: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
11790: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 11791: my @content = <$config>;
1.1210 raeburn 11792: &$func(\@content,$hashref);
11793: return;
11794: }
11795:
11796: # ------------------------------------------------------Get DNS checksums file
1.1211 raeburn 11797: sub parse_dns_checksums_tab {
1.1210 raeburn 11798: my ($lines,$hashref) = @_;
11799: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
11800: my $loncaparev = &get_server_loncaparev($machine_dom);
11801: my ($release,$timestamp) = split(/\-/,$loncaparev);
11802: my (%chksum,%revnum);
11803: if (ref($lines) eq 'ARRAY') {
11804: chomp(@{$lines});
1.1238 raeburn 11805: my $version = shift(@{$lines});
11806: if ($version eq $release) {
1.1210 raeburn 11807: foreach my $line (@{$lines}) {
1.1238 raeburn 11808: my ($file,$version,$shasum) = split(/,/,$line);
11809: $chksum{$file} = $shasum;
11810: $revnum{$file} = $version;
1.1210 raeburn 11811: }
11812: if (ref($hashref) eq 'HASH') {
11813: %{$hashref} = (
11814: sums => \%chksum,
11815: versions => \%revnum,
11816: );
11817: }
11818: }
11819: }
1.869 albertel 11820: return;
1.852 albertel 11821: }
1.1210 raeburn 11822:
11823: sub fetch_dns_checksums {
1.1238 raeburn 11824: my %checksums;
11825: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
11826: my $loncaparev = &get_server_loncaparev($machine_dom);
11827: my ($release,$timestamp) = split(/\-/,$loncaparev);
11828: &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1211 raeburn 11829: \%checksums);
1.1210 raeburn 11830: return \%checksums;
11831: }
11832:
1.327 albertel 11833: # ------------------------------------------------------------ Read domain file
11834: {
1.852 albertel 11835: my $loaded;
1.846 albertel 11836: my %domain;
11837:
1.852 albertel 11838: sub parse_domain_tab {
11839: my ($lines) = @_;
11840: foreach my $line (@$lines) {
11841: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 11842:
1.846 albertel 11843: chomp($line);
1.852 albertel 11844: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 11845: my %this_domain;
11846: foreach my $field ('description', 'auth_def', 'auth_arg_def',
11847: 'lang_def', 'city', 'longi', 'lati',
11848: 'primary') {
11849: $this_domain{$field} = shift(@elements);
11850: }
11851: $domain{$name} = \%this_domain;
1.852 albertel 11852: }
11853: }
1.864 albertel 11854:
11855: sub reset_domain_info {
11856: undef($loaded);
11857: undef(%domain);
11858: }
11859:
1.852 albertel 11860: sub load_domain_tab {
1.869 albertel 11861: my ($ignore_cache) = @_;
11862: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852 albertel 11863: my $fh;
11864: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
11865: my @lines = <$fh>;
11866: &parse_domain_tab(\@lines);
1.448 albertel 11867: }
1.852 albertel 11868: close($fh);
11869: $loaded = 1;
1.327 albertel 11870: }
1.846 albertel 11871:
11872: sub domain {
1.852 albertel 11873: &load_domain_tab() if (!$loaded);
11874:
1.846 albertel 11875: my ($name,$what) = @_;
11876: return if ( !exists($domain{$name}) );
11877:
11878: if (!$what) {
11879: return $domain{$name}{'description'};
11880: }
11881: return $domain{$name}{$what};
11882: }
1.974 raeburn 11883:
11884: sub domain_info {
11885: &load_domain_tab() if (!$loaded);
11886: return %domain;
11887: }
11888:
1.327 albertel 11889: }
11890:
11891:
1.1 albertel 11892: # ------------------------------------------------------------- Read hosts file
11893: {
1.838 albertel 11894: my %hostname;
1.844 albertel 11895: my %hostdom;
1.845 albertel 11896: my %libserv;
1.852 albertel 11897: my $loaded;
1.888 albertel 11898: my %name_to_host;
1.1074 raeburn 11899: my %internetdom;
1.1107 raeburn 11900: my %LC_dns_serv;
1.852 albertel 11901:
11902: sub parse_hosts_tab {
11903: my ($file) = @_;
11904: foreach my $configline (@$file) {
11905: next if ($configline =~ /^(\#|\s*$ )/x);
1.1107 raeburn 11906: chomp($configline);
11907: if ($configline =~ /^\^/) {
11908: if ($configline =~ /^\^([\w.\-]+)/) {
11909: $LC_dns_serv{$1} = 1;
11910: }
11911: next;
11912: }
1.1074 raeburn 11913: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 11914: $name=~s/\s//g;
11915: if ($id && $domain && $role && $name) {
11916: $hostname{$id}=$name;
1.888 albertel 11917: push(@{$name_to_host{$name}}, $id);
1.852 albertel 11918: $hostdom{$id}=$domain;
11919: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 11920: if (defined($protocol)) {
11921: if ($protocol eq 'https') {
11922: $protocol{$id} = $protocol;
11923: } else {
11924: $protocol{$id} = 'http';
11925: }
1.968 raeburn 11926: } else {
1.969 raeburn 11927: $protocol{$id} = 'http';
1.968 raeburn 11928: }
1.1074 raeburn 11929: if (defined($intdom)) {
11930: $internetdom{$id} = $intdom;
11931: }
1.852 albertel 11932: }
11933: }
11934: }
1.864 albertel 11935:
11936: sub reset_hosts_info {
1.897 albertel 11937: &purge_remembered();
1.864 albertel 11938: &reset_domain_info();
11939: &reset_hosts_ip_info();
1.892 albertel 11940: undef(%name_to_host);
1.864 albertel 11941: undef(%hostname);
11942: undef(%hostdom);
11943: undef(%libserv);
11944: undef($loaded);
11945: }
1.1 albertel 11946:
1.852 albertel 11947: sub load_hosts_tab {
1.869 albertel 11948: my ($ignore_cache) = @_;
11949: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852 albertel 11950: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11951: my @config = <$config>;
11952: &parse_hosts_tab(\@config);
11953: close($config);
11954: $loaded=1;
1.1 albertel 11955: }
1.852 albertel 11956:
1.838 albertel 11957: sub hostname {
1.852 albertel 11958: &load_hosts_tab() if (!$loaded);
11959:
1.838 albertel 11960: my ($lonid) = @_;
11961: return $hostname{$lonid};
11962: }
1.845 albertel 11963:
1.838 albertel 11964: sub all_hostnames {
1.852 albertel 11965: &load_hosts_tab() if (!$loaded);
11966:
1.838 albertel 11967: return %hostname;
11968: }
1.845 albertel 11969:
1.888 albertel 11970: sub all_names {
11971: &load_hosts_tab() if (!$loaded);
11972:
11973: return %name_to_host;
11974: }
11975:
1.974 raeburn 11976: sub all_host_domain {
11977: &load_hosts_tab() if (!$loaded);
11978: return %hostdom;
11979: }
11980:
1.845 albertel 11981: sub is_library {
1.852 albertel 11982: &load_hosts_tab() if (!$loaded);
11983:
1.845 albertel 11984: return exists($libserv{$_[0]});
11985: }
11986:
11987: sub all_library {
1.852 albertel 11988: &load_hosts_tab() if (!$loaded);
11989:
1.845 albertel 11990: return %libserv;
11991: }
11992:
1.1062 droeschl 11993: sub unique_library {
11994: #2x reverse removes all hostnames that appear more than once
11995: my %unique = reverse &all_library();
11996: return reverse %unique;
11997: }
11998:
1.841 albertel 11999: sub get_servers {
1.852 albertel 12000: &load_hosts_tab() if (!$loaded);
12001:
1.841 albertel 12002: my ($domain,$type) = @_;
12003: my %possible_hosts = ($type eq 'library') ? %libserv
12004: : %hostname;
12005: my %result;
1.842 albertel 12006: if (ref($domain) eq 'ARRAY') {
12007: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 12008: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 12009: $result{$host} = $hostname;
12010: }
12011: }
12012: } else {
12013: while ( my ($host,$hostname) = each(%possible_hosts)) {
12014: if ($hostdom{$host} eq $domain) {
12015: $result{$host} = $hostname;
12016: }
1.841 albertel 12017: }
12018: }
12019: return %result;
12020: }
1.845 albertel 12021:
1.1062 droeschl 12022: sub get_unique_servers {
12023: my %unique = reverse &get_servers(@_);
12024: return reverse %unique;
12025: }
12026:
1.844 albertel 12027: sub host_domain {
1.852 albertel 12028: &load_hosts_tab() if (!$loaded);
12029:
1.844 albertel 12030: my ($lonid) = @_;
12031: return $hostdom{$lonid};
12032: }
12033:
1.841 albertel 12034: sub all_domains {
1.852 albertel 12035: &load_hosts_tab() if (!$loaded);
12036:
1.841 albertel 12037: my %seen;
12038: my @uniq = grep(!$seen{$_}++, values(%hostdom));
12039: return @uniq;
12040: }
1.1074 raeburn 12041:
12042: sub internet_dom {
12043: &load_hosts_tab() if (!$loaded);
12044:
12045: my ($lonid) = @_;
12046: return $internetdom{$lonid};
12047: }
1.1107 raeburn 12048:
12049: sub is_LC_dns {
12050: &load_hosts_tab() if (!$loaded);
12051:
12052: my ($hostname) = @_;
12053: return exists($LC_dns_serv{$hostname});
12054: }
12055:
1.1 albertel 12056: }
12057:
1.847 albertel 12058: {
12059: my %iphost;
1.856 albertel 12060: my %name_to_ip;
12061: my %lonid_to_ip;
1.869 albertel 12062:
1.847 albertel 12063: sub get_hosts_from_ip {
12064: my ($ip) = @_;
12065: my %iphosts = &get_iphost();
12066: if (ref($iphosts{$ip})) {
12067: return @{$iphosts{$ip}};
12068: }
12069: return;
1.839 albertel 12070: }
1.864 albertel 12071:
12072: sub reset_hosts_ip_info {
12073: undef(%iphost);
12074: undef(%name_to_ip);
12075: undef(%lonid_to_ip);
12076: }
1.856 albertel 12077:
12078: sub get_host_ip {
12079: my ($lonid) = @_;
12080: if (exists($lonid_to_ip{$lonid})) {
12081: return $lonid_to_ip{$lonid};
12082: }
12083: my $name=&hostname($lonid);
12084: my $ip = gethostbyname($name);
12085: return if (!$ip || length($ip) ne 4);
12086: $ip=inet_ntoa($ip);
12087: $name_to_ip{$name} = $ip;
12088: $lonid_to_ip{$lonid} = $ip;
12089: return $ip;
12090: }
1.847 albertel 12091:
12092: sub get_iphost {
1.869 albertel 12093: my ($ignore_cache) = @_;
1.894 albertel 12094:
1.869 albertel 12095: if (!$ignore_cache) {
12096: if (%iphost) {
12097: return %iphost;
12098: }
12099: my ($ip_info,$cached)=
12100: &Apache::lonnet::is_cached_new('iphost','iphost');
12101: if ($cached) {
12102: %iphost = %{$ip_info->[0]};
12103: %name_to_ip = %{$ip_info->[1]};
12104: %lonid_to_ip = %{$ip_info->[2]};
12105: return %iphost;
12106: }
12107: }
1.894 albertel 12108:
12109: # get yesterday's info for fallback
12110: my %old_name_to_ip;
12111: my ($ip_info,$cached)=
12112: &Apache::lonnet::is_cached_new('iphost','iphost');
12113: if ($cached) {
12114: %old_name_to_ip = %{$ip_info->[1]};
12115: }
12116:
1.888 albertel 12117: my %name_to_host = &all_names();
12118: foreach my $name (keys(%name_to_host)) {
1.847 albertel 12119: my $ip;
12120: if (!exists($name_to_ip{$name})) {
12121: $ip = gethostbyname($name);
12122: if (!$ip || length($ip) ne 4) {
1.894 albertel 12123: if (defined($old_name_to_ip{$name})) {
12124: $ip = $old_name_to_ip{$name};
12125: &logthis("Can't find $name defaulting to old $ip");
12126: } else {
12127: &logthis("Name $name no IP found");
12128: next;
12129: }
12130: } else {
12131: $ip=inet_ntoa($ip);
1.847 albertel 12132: }
12133: $name_to_ip{$name} = $ip;
12134: } else {
12135: $ip = $name_to_ip{$name};
1.653 albertel 12136: }
1.888 albertel 12137: foreach my $id (@{ $name_to_host{$name} }) {
12138: $lonid_to_ip{$id} = $ip;
12139: }
12140: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 12141: }
1.1219 raeburn 12142: &do_cache_new('iphost','iphost',
12143: [\%iphost,\%name_to_ip,\%lonid_to_ip],
12144: 48*60*60);
1.869 albertel 12145:
1.847 albertel 12146: return %iphost;
1.598 albertel 12147: }
12148:
1.992 raeburn 12149: #
12150: # Given a DNS returns the loncapa host name for that DNS
12151: #
12152: sub host_from_dns {
12153: my ($dns) = @_;
12154: my @hosts;
12155: my $ip;
12156:
1.993 raeburn 12157: if (exists($name_to_ip{$dns})) {
1.992 raeburn 12158: $ip = $name_to_ip{$dns};
12159: }
12160: if (!$ip) {
12161: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
12162: if (length($ip) == 4) {
12163: $ip = &IO::Socket::inet_ntoa($ip);
12164: }
12165: }
12166: if ($ip) {
12167: @hosts = get_hosts_from_ip($ip);
12168: return $hosts[0];
12169: }
12170: return undef;
1.986 foxr 12171: }
1.992 raeburn 12172:
1.1074 raeburn 12173: sub get_internet_names {
12174: my ($lonid) = @_;
12175: return if ($lonid eq '');
12176: my ($idnref,$cached)=
12177: &Apache::lonnet::is_cached_new('internetnames',$lonid);
12178: if ($cached) {
12179: return $idnref;
12180: }
12181: my $ip = &get_host_ip($lonid);
12182: my @hosts = &get_hosts_from_ip($ip);
12183: my %iphost = &get_iphost();
12184: my (@idns,%seen);
12185: foreach my $id (@hosts) {
12186: my $dom = &host_domain($id);
12187: my $prim_id = &domain($dom,'primary');
12188: my $prim_ip = &get_host_ip($prim_id);
12189: next if ($seen{$prim_ip});
12190: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
12191: foreach my $id (@{$iphost{$prim_ip}}) {
12192: my $intdom = &internet_dom($id);
12193: unless (grep(/^\Q$intdom\E$/,@idns)) {
12194: push(@idns,$intdom);
12195: }
12196: }
12197: }
12198: $seen{$prim_ip} = 1;
12199: }
1.1219 raeburn 12200: return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074 raeburn 12201: }
12202:
1.986 foxr 12203: }
12204:
1.1079 raeburn 12205: sub all_loncaparevs {
1.1249 raeburn 12206: return qw(1.1 1.2 1.3 2.0 2.1 2.2 2.3 2.4 2.5 2.6 2.7 2.8 2.9 2.10 2.11);
1.1079 raeburn 12207: }
12208:
1.1227 raeburn 12209: # ---------------------------------------------------------- Read loncaparev table
12210: {
12211: sub load_loncaparevs {
12212: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
12213: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
12214: while (my $configline=<$config>) {
12215: chomp($configline);
12216: my ($hostid,$loncaparev)=split(/:/,$configline);
12217: $loncaparevs{$hostid}=$loncaparev;
12218: }
12219: close($config);
12220: }
12221: }
12222: }
12223: }
12224:
12225: # ---------------------------------------------------------- Read serverhostID table
12226: {
12227: sub load_serverhomeIDs {
12228: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
12229: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
12230: while (my $configline=<$config>) {
12231: chomp($configline);
12232: my ($name,$id)=split(/:/,$configline);
12233: $serverhomeIDs{$name}=$id;
12234: }
12235: close($config);
12236: }
12237: }
12238: }
12239: }
12240:
12241:
1.862 albertel 12242: BEGIN {
12243:
12244: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
12245: unless ($readit) {
12246: {
12247: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
12248: %perlvar = (%perlvar,%{$configvars});
12249: }
12250:
12251:
1.1 albertel 12252: # ------------------------------------------------------ Read spare server file
12253: {
1.448 albertel 12254: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 12255:
12256: while (my $configline=<$config>) {
12257: chomp($configline);
1.284 matthew 12258: if ($configline) {
1.784 albertel 12259: my ($host,$type) = split(':',$configline,2);
1.785 albertel 12260: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 12261: push(@{ $spareid{$type} }, $host);
1.1 albertel 12262: }
12263: }
1.448 albertel 12264: close($config);
1.1 albertel 12265: }
1.11 www 12266: # ------------------------------------------------------------ Read permissions
12267: {
1.448 albertel 12268: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 12269:
12270: while (my $configline=<$config>) {
1.448 albertel 12271: chomp($configline);
12272: if ($configline) {
12273: my ($role,$perm)=split(/ /,$configline);
12274: if ($perm ne '') { $pr{$role}=$perm; }
12275: }
1.11 www 12276: }
1.448 albertel 12277: close($config);
1.11 www 12278: }
12279:
12280: # -------------------------------------------- Read plain texts for permissions
12281: {
1.448 albertel 12282: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 12283:
12284: while (my $configline=<$config>) {
1.448 albertel 12285: chomp($configline);
12286: if ($configline) {
1.742 raeburn 12287: my ($short,@plain)=split(/:/,$configline);
12288: %{$prp{$short}} = ();
12289: if (@plain > 0) {
12290: $prp{$short}{'std'} = $plain[0];
12291: for (my $i=1; $i<@plain; $i++) {
12292: $prp{$short}{'alt'.$i} = $plain[$i];
12293: }
12294: }
1.448 albertel 12295: }
1.135 www 12296: }
1.448 albertel 12297: close($config);
1.135 www 12298: }
12299:
12300: # ---------------------------------------------------------- Read package table
12301: {
1.448 albertel 12302: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 12303:
12304: while (my $configline=<$config>) {
1.483 albertel 12305: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 12306: chomp($configline);
12307: my ($short,$plain)=split(/:/,$configline);
12308: my ($pack,$name)=split(/\&/,$short);
12309: if ($plain ne '') {
12310: $packagetab{$pack.'&'.$name.'&name'}=$name;
12311: $packagetab{$short}=$plain;
12312: }
1.11 www 12313: }
1.448 albertel 12314: close($config);
1.329 matthew 12315: }
12316:
1.1073 raeburn 12317: # ---------------------------------------------------------- Read loncaparev table
1.1227 raeburn 12318:
12319: &load_loncaparevs();
1.1073 raeburn 12320:
1.1074 raeburn 12321: # ---------------------------------------------------------- Read serverhostID table
12322:
1.1227 raeburn 12323: &load_serverhomeIDs();
12324:
12325: # ---------------------------------------------------------- Read releaseslist XML
1.1079 raeburn 12326: {
12327: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
12328: if (-e $file) {
12329: my $parser = HTML::LCParser->new($file);
12330: while (my $token = $parser->get_token()) {
12331: if ($token->[0] eq 'S') {
12332: my $item = $token->[1];
12333: my $name = $token->[2]{'name'};
12334: my $value = $token->[2]{'value'};
12335: if ($item ne '' && $name ne '' && $value ne '') {
12336: my $release = $parser->get_text();
12337: $release =~ s/(^\s*|\s*$ )//gx;
12338: $needsrelease{$item.':'.$name.':'.$value} = $release;
12339: }
12340: }
12341: }
12342: }
1.1073 raeburn 12343: }
12344:
1.1138 raeburn 12345: # ---------------------------------------------------------- Read managers table
12346: {
12347: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
12348: if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
12349: while (my $configline=<$config>) {
12350: chomp($configline);
12351: next if ($configline =~ /^\#/);
12352: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
12353: $managerstab{$configline} = 1;
12354: }
12355: }
12356: close($config);
12357: }
12358: }
12359: }
12360:
1.329 matthew 12361: # ------------- set up temporary directory
12362: {
1.1117 foxr 12363: $tmpdir = LONCAPA::tempdir();
1.329 matthew 12364:
1.11 www 12365: }
12366:
1.794 albertel 12367: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
12368: 'compress_threshold'=> 20_000,
12369: });
1.185 www 12370:
1.281 www 12371: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 12372: $dumpcount=0;
1.958 www 12373: $locknum=0;
1.22 www 12374:
1.163 harris41 12375: &logtouch();
1.672 albertel 12376: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 12377: $readit=1;
1.564 albertel 12378: {
12379: use integer;
12380: my $test=(2**32)+1;
1.568 albertel 12381: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 12382: &logthis(" Detected 64bit platform ($_64bit)");
12383: }
1.195 www 12384: }
1.1 albertel 12385: }
1.179 www 12386:
1.1 albertel 12387: 1;
1.191 harris41 12388: __END__
12389:
1.243 albertel 12390: =pod
12391:
1.191 harris41 12392: =head1 NAME
12393:
1.243 albertel 12394: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 12395:
12396: =head1 SYNOPSIS
12397:
1.243 albertel 12398: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 12399:
12400: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
12401:
1.243 albertel 12402: Common parameters:
12403:
12404: =over 4
12405:
12406: =item *
12407:
12408: $uname : an internal username (if $cname expecting a course Id specifically)
12409:
12410: =item *
12411:
12412: $udom : a domain (if $cdom expecting a course's domain specifically)
12413:
12414: =item *
12415:
12416: $symb : a resource instance identifier
12417:
12418: =item *
12419:
12420: $namespace : the name of a .db file that contains the data needed or
12421: being set.
12422:
12423: =back
12424:
1.394 bowersj2 12425: =head1 OVERVIEW
1.191 harris41 12426:
1.394 bowersj2 12427: lonnet provides subroutines which interact with the
12428: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
12429: about classes, users, and resources.
1.243 albertel 12430:
12431: For many of these objects you can also use this to store data about
12432: them or modify them in various ways.
1.191 harris41 12433:
1.394 bowersj2 12434: =head2 Symbs
1.191 harris41 12435:
1.394 bowersj2 12436: To identify a specific instance of a resource, LON-CAPA uses symbols
12437: or "symbs"X<symb>. These identifiers are built from the URL of the
12438: map, the resource number of the resource in the map, and the URL of
12439: the resource itself. The latter is somewhat redundant, but might help
12440: if maps change.
12441:
12442: An example is
12443:
12444: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
12445:
12446: The respective map entry is
12447:
12448: <resource id="19" src="/res/msu/korte/tests/part12.problem"
12449: title="Problem 2">
12450: </resource>
12451:
12452: Symbs are used by the random number generator, as well as to store and
12453: restore data specific to a certain instance of for example a problem.
12454:
12455: =head2 Storing And Retrieving Data
12456:
12457: X<store()>X<cstore()>X<restore()>Three of the most important functions
12458: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
12459: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
12460: is is the non-critical message twin of cstore. These functions are for
12461: handlers to store a perl hash to a user's permanent data space in an
12462: easy manner, and to retrieve it again on another call. It is expected
12463: that a handler would use this once at the beginning to retrieve data,
12464: and then again once at the end to send only the new data back.
12465:
12466: The data is stored in the user's data directory on the user's
12467: homeserver under the ID of the course.
12468:
12469: The hash that is returned by restore will have all of the previous
12470: value for all of the elements of the hash.
12471:
12472: Example:
12473:
12474: #creating a hash
12475: my %hash;
12476: $hash{'foo'}='bar';
12477:
12478: #storing it
12479: &Apache::lonnet::cstore(\%hash);
12480:
12481: #changing a value
12482: $hash{'foo'}='notbar';
12483:
12484: #adding a new value
12485: $hash{'bar'}='foo';
12486: &Apache::lonnet::cstore(\%hash);
12487:
12488: #retrieving the hash
12489: my %history=&Apache::lonnet::restore();
12490:
12491: #print the hash
12492: foreach my $key (sort(keys(%history))) {
12493: print("\%history{$key} = $history{$key}");
12494: }
12495:
12496: Will print out:
1.191 harris41 12497:
1.394 bowersj2 12498: %history{1:foo} = bar
12499: %history{1:keys} = foo:timestamp
12500: %history{1:timestamp} = 990455579
12501: %history{2:bar} = foo
12502: %history{2:foo} = notbar
12503: %history{2:keys} = foo:bar:timestamp
12504: %history{2:timestamp} = 990455580
12505: %history{bar} = foo
12506: %history{foo} = notbar
12507: %history{timestamp} = 990455580
12508: %history{version} = 2
12509:
12510: Note that the special hash entries C<keys>, C<version> and
12511: C<timestamp> were added to the hash. C<version> will be equal to the
12512: total number of versions of the data that have been stored. The
12513: C<timestamp> attribute will be the UNIX time the hash was
12514: stored. C<keys> is available in every historical section to list which
12515: keys were added or changed at a specific historical revision of a
12516: hash.
12517:
12518: B<Warning>: do not store the hash that restore returns directly. This
12519: will cause a mess since it will restore the historical keys as if the
12520: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 12521:
1.394 bowersj2 12522: Calling convention:
1.191 harris41 12523:
1.1225 raeburn 12524: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
12525: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname);
1.191 harris41 12526:
1.394 bowersj2 12527: For more detailed information, see lonnet specific documentation.
1.191 harris41 12528:
1.394 bowersj2 12529: =head1 RETURN MESSAGES
1.191 harris41 12530:
1.394 bowersj2 12531: =over 4
1.191 harris41 12532:
1.394 bowersj2 12533: =item * B<con_lost>: unable to contact remote host
1.191 harris41 12534:
1.394 bowersj2 12535: =item * B<con_delayed>: unable to contact remote host, message will be delivered
12536: when the connection is brought back up
1.191 harris41 12537:
1.394 bowersj2 12538: =item * B<con_failed>: unable to contact remote host and unable to save message
12539: for later delivery
1.191 harris41 12540:
1.967 bisitz 12541: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 12542:
1.394 bowersj2 12543: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 12544: that was requested
1.191 harris41 12545:
1.243 albertel 12546: =back
1.191 harris41 12547:
1.243 albertel 12548: =head1 PUBLIC SUBROUTINES
1.191 harris41 12549:
1.243 albertel 12550: =head2 Session Environment Functions
1.191 harris41 12551:
1.243 albertel 12552: =over 4
1.191 harris41 12553:
1.394 bowersj2 12554: =item *
12555: X<appenv()>
1.949 raeburn 12556: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 12557: the user envirnoment file, and will be restored for each access this
1.620 albertel 12558: user makes during this session, also modifies the %env for the current
1.949 raeburn 12559: process. Optional rolesarrayref - if defined contains a reference to an array
12560: of roles which are exempt from the restriction on modifying user.role entries
12561: in the user's environment.db and in %env.
1.191 harris41 12562:
12563: =item *
1.394 bowersj2 12564: X<delenv()>
1.987 raeburn 12565: B<delenv($delthis,$regexp)>: removes all items from the session
12566: environment file that begin with $delthis. If the
12567: optional second arg - $regexp - is true, $delthis is treated as a
12568: regular expression, otherwise \Q$delthis\E is used.
12569: The values are also deleted from the current processes %env.
1.191 harris41 12570:
1.795 albertel 12571: =item * get_env_multiple($name)
12572:
12573: gets $name from the %env hash, it seemlessly handles the cases where multiple
12574: values may be defined and end up as an array ref.
12575:
12576: returns an array of values
12577:
1.243 albertel 12578: =back
12579:
12580: =head2 User Information
1.191 harris41 12581:
1.243 albertel 12582: =over 4
1.191 harris41 12583:
12584: =item *
1.394 bowersj2 12585: X<queryauthenticate()>
12586: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 12587: authentication scheme
12588:
12589: =item *
1.394 bowersj2 12590: X<authenticate()>
1.1073 raeburn 12591: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 12592: authenticate user from domain's lib servers (first use the current
12593: one). C<$upass> should be the users password.
1.1073 raeburn 12594: $checkdefauth is optional (value is 1 if a check should be made to
12595: authenticate user using default authentication method, and allow
12596: account creation if username does not have account in the domain).
12597: $clientcancheckhost is optional (value is 1 if checking whether the
12598: server can host will occur on the client side in lonauth.pm).
1.191 harris41 12599:
12600: =item *
1.394 bowersj2 12601: X<homeserver()>
12602: B<homeserver($uname,$udom)>: find the server which has
12603: the user's directory and files (there must be only one), this caches
12604: the answer, and also caches if there is a borken connection.
1.191 harris41 12605:
12606: =item *
1.394 bowersj2 12607: X<idget()>
12608: B<idget($udom,@ids)>: find the usernames behind a list of IDs
12609: (IDs are a unique resource in a domain, there must be only 1 ID per
12610: username, and only 1 username per ID in a specific domain) (returns
12611: hash: id=>name,id=>name)
1.191 harris41 12612:
12613: =item *
1.394 bowersj2 12614: X<idrget()>
12615: B<idrget($udom,@unames)>: find the IDs behind a list of
12616: usernames (returns hash: name=>id,name=>id)
1.191 harris41 12617:
12618: =item *
1.394 bowersj2 12619: X<idput()>
12620: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 12621:
12622: =item *
1.394 bowersj2 12623: X<rolesinit()>
1.1169 droeschl 12624: B<rolesinit($udom,$username)>: get user privileges.
12625: returns user role, first access and timer interval hashes
1.243 albertel 12626:
12627: =item *
1.1171 droeschl 12628: X<privileged()>
12629: B<privileged($username,$domain)>: returns a true if user has a
12630: privileged and active role (i.e. su or dc), false otherwise.
12631:
12632: =item *
1.551 albertel 12633: X<getsection()>
12634: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 12635: course $cname, return section name/number or '' for "not in course"
12636: and '-1' for "no section"
12637:
12638: =item *
1.394 bowersj2 12639: X<userenvironment()>
12640: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 12641: passed in @what from the requested user's environment, returns a hash
12642:
1.858 raeburn 12643: =item *
12644: X<userlog_query()>
1.859 albertel 12645: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
12646: activity.log file. %filters defines filters applied when parsing the
12647: log file. These can be start or end timestamps, or the type of action
12648: - log to look for Login or Logout events, check for Checkin or
12649: Checkout, role for role selection. The response is in the form
12650: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
12651: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 12652:
1.243 albertel 12653: =back
12654:
12655: =head2 User Roles
12656:
12657: =over 4
12658:
12659: =item *
12660:
1.810 raeburn 12661: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243 albertel 12662: F: full access
12663: U,I,K: authentication modes (cxx only)
12664: '': forbidden
12665: 1: user needs to choose course
12666: 2: browse allowed
1.766 albertel 12667: A: passphrase authentication needed
1.243 albertel 12668:
12669: =item *
12670:
1.1192 raeburn 12671: constructaccess($url,$setpriv) : check for access to construction space URL
12672:
12673: See if the owner domain and name in the URL match those in the
12674: expected environment. If so, return three element list
12675: ($ownername,$ownerdomain,$ownerhome).
12676:
12677: Otherwise return the null string.
12678:
12679: If second argument 'setpriv' is true, it assigns the privileges,
12680: and returns the same three element list, unless the owner has
12681: blocked "ad hoc" Domain Coordinator access to the Author Space,
12682: in which case the null string is returned.
12683:
12684: =item *
12685:
1.243 albertel 12686: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
12687: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
12688: and course level
12689:
12690: =item *
12691:
1.988 raeburn 12692: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
12693: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 12694: $type is Course (default) or Community.
1.988 raeburn 12695: If $forcedefault evaluates to true, text returned will be default
12696: text for $type. Otherwise, if this is a course, the text returned
12697: will be a custom name for the role (if defined in the course's
12698: environment). If no custom name is defined the default is returned.
12699:
1.832 raeburn 12700: =item *
12701:
1.1219 raeburn 12702: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858 raeburn 12703: All arguments are optional. Returns a hash of a roles, either for
12704: co-author/assistant author roles for a user's Construction Space
1.906 albertel 12705: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 12706: In the hash, keys are set to colon-separated $uname,$udom,$role, and
12707: (optionally) if $withsec is true, a fourth colon-separated item - $section.
12708: For each key, value is set to colon-separated start and end times for
12709: the role. If no username and domain are specified, will default to
1.934 raeburn 12710: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 12711: of role statuses (active, future or previous), roles
12712: (e.g., cc,in, st etc.) and domains of the roles which can be used
12713: to restrict the list of roles reported. If no array ref is
12714: provided for types, will default to return only active roles.
1.834 albertel 12715:
1.1195 raeburn 12716: =item *
12717:
12718: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196 raeburn 12719: user: $uname:$udom has a role in the course: $cdom_$cnum.
12720:
12721: Additional optional arguments are: $type (if role checking is to be restricted
12722: to certain user status types -- previous (expired roles), active (currently
1.1195 raeburn 12723: available roles) or future (roles available in the future), and
12724: $hideprivileged -- if true will not report course roles for users who
1.1219 raeburn 12725: have active Domain Coordinator role in course's domain or in additional
12726: domains (specified in 'Domains to check for privileged users' in course
12727: environment -- set via: Course Settings -> Classlists and staff listing).
12728:
12729: =item *
12730:
12731: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
12732: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
12733: $possdomains and $possroles are optional array refs -- to domains to check and
12734: roles to check. If $possdomains is not specified, a dump will be done of the
12735: users' roles.db to check for a dc or su role in any domain. This can be
12736: time consuming if &privileged is called repeatedly (e.g., when displaying a
12737: classlist), so in such cases, supplying a $possdomains array is preferred, as
12738: this then allows &privileged_by_domain() to be used, which caches the identity
12739: of privileged users, eliminating the need for repeated calls to &dump().
12740:
12741: =item *
12742:
12743: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
12744: where the outer hash keys are domains specified in the $possdomains array ref,
12745: next inner hash keys are privileged roles specified in the $roles array ref,
12746: and the innermost hash contains key = value pairs for username:domain = end:start
12747: for active or future "privileged" users with that role in that domain. To avoid
12748: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
12749: innerhash are cached using priv_$role and $dom as the identifiers.
1.1195 raeburn 12750:
1.243 albertel 12751: =back
12752:
12753: =head2 User Modification
12754:
12755: =over 4
12756:
12757: =item *
12758:
1.957 raeburn 12759: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 12760: user for the level given by URL. Optional start and end dates (leave empty
12761: string or zero for "no date")
1.191 harris41 12762:
12763: =item *
12764:
1.243 albertel 12765: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
12766: change a users, password, possible return values are: ok,
12767: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
12768: refused
1.191 harris41 12769:
12770: =item *
12771:
1.243 albertel 12772: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 12773:
12774: =item *
12775:
1.1058 raeburn 12776: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
12777: $forceid,$desiredhome,$email,$inststatus,$candelete) :
12778:
12779: will update user information (firstname,middlename,lastname,generation,
12780: permanentemail), and if forceid is true, student/employee ID also.
12781: A user's institutional affiliation(s) can also be updated.
12782: User information fields will not be overwritten with empty entries
12783: unless the field is included in the $candelete array reference.
12784: This array is included when a single user is modified via "Manage Users",
12785: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 12786:
12787: =item *
12788:
1.286 matthew 12789: modifystudent
12790:
1.957 raeburn 12791: modify a student's enrollment and identification information.
1.1235 raeburn 12792: The course id is resolved based on the current user's environment.
12793: This means the invoking user must be a course coordinator or otherwise
1.286 matthew 12794: associated with a course.
12795:
1.297 matthew 12796: This call is essentially a wrapper for lonnet::modifyuser and
12797: lonnet::modify_student_enrollment
1.286 matthew 12798:
12799: Inputs:
12800:
12801: =over 4
12802:
1.957 raeburn 12803: =item B<$udom> Student's loncapa domain
1.286 matthew 12804:
1.957 raeburn 12805: =item B<$uname> Student's loncapa login name
1.286 matthew 12806:
1.964 bisitz 12807: =item B<$uid> Student/Employee ID
1.286 matthew 12808:
1.957 raeburn 12809: =item B<$umode> Student's authentication mode
1.286 matthew 12810:
1.957 raeburn 12811: =item B<$upass> Student's password
1.286 matthew 12812:
1.957 raeburn 12813: =item B<$first> Student's first name
1.286 matthew 12814:
1.957 raeburn 12815: =item B<$middle> Student's middle name
1.286 matthew 12816:
1.957 raeburn 12817: =item B<$last> Student's last name
1.286 matthew 12818:
1.957 raeburn 12819: =item B<$gene> Student's generation
1.286 matthew 12820:
1.957 raeburn 12821: =item B<$usec> Student's section in course
1.286 matthew 12822:
12823: =item B<$end> Unix time of the roles expiration
12824:
12825: =item B<$start> Unix time of the roles start date
12826:
12827: =item B<$forceid> If defined, allow $uid to be changed
12828:
12829: =item B<$desiredhome> server to use as home server for student
12830:
1.957 raeburn 12831: =item B<$email> Student's permanent e-mail address
12832:
12833: =item B<$type> Type of enrollment (auto or manual)
12834:
1.963 raeburn 12835: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
12836:
12837: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 12838:
1.963 raeburn 12839: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 12840:
1.963 raeburn 12841: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 12842:
1.1216 raeburn 12843: =item B<$inststatus> institutional status of user - : separated string of escaped status types
12844:
12845: =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 12846:
1.286 matthew 12847: =back
1.297 matthew 12848:
12849: =item *
12850:
12851: modify_student_enrollment
12852:
1.1235 raeburn 12853: Change a student's enrollment status in a class. The environment variable
1.297 matthew 12854: 'role.request.course' must be defined for this function to proceed.
12855:
12856: Inputs:
12857:
12858: =over 4
12859:
1.1235 raeburn 12860: =item $udom, student's domain
1.297 matthew 12861:
1.1235 raeburn 12862: =item $uname, student's name
1.297 matthew 12863:
1.1235 raeburn 12864: =item $uid, student's user id
1.297 matthew 12865:
1.1235 raeburn 12866: =item $first, student's first name
1.297 matthew 12867:
12868: =item $middle
12869:
12870: =item $last
12871:
12872: =item $gene
12873:
12874: =item $usec
12875:
12876: =item $end
12877:
12878: =item $start
12879:
1.957 raeburn 12880: =item $type
12881:
12882: =item $locktype
12883:
12884: =item $cid
12885:
12886: =item $selfenroll
12887:
12888: =item $context
12889:
1.1216 raeburn 12890: =item $credits, number of credits student will earn from this class
12891:
1.297 matthew 12892: =back
12893:
1.191 harris41 12894:
12895: =item *
12896:
1.243 albertel 12897: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
12898: custom role; give a custom role to a user for the level given by URL. Specify
12899: name and domain of role author, and role name
1.191 harris41 12900:
12901: =item *
12902:
1.243 albertel 12903: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 12904:
12905: =item *
12906:
1.243 albertel 12907: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
12908:
12909: =back
12910:
12911: =head2 Course Infomation
12912:
12913: =over 4
1.191 harris41 12914:
12915: =item *
12916:
1.1118 foxr 12917: coursedescription($courseid,$options) : returns a hash of information about the
1.631 albertel 12918: specified course id, including all environment settings for the
12919: course, the description of the course will be in the hash under the
12920: key 'description'
1.191 harris41 12921:
1.1118 foxr 12922: $options is an optional parameter that if supplied is a hash reference that controls
12923: what how this function works. It has the following key/values:
12924:
12925: =over 4
12926:
12927: =item freshen_cache
12928:
12929: If defined, and the environment cache for the course is valid, it is
12930: returned in the returned hash.
12931:
12932: =item one_time
12933:
12934: If defined, the last cache time is set to _now_
12935:
12936: =item user
12937:
12938: If defined, the supplied username is used instead of the current user.
12939:
12940:
12941: =back
12942:
1.191 harris41 12943: =item *
12944:
1.624 albertel 12945: resdata($name,$domain,$type,@which) : request for current parameter
12946: setting for a specific $type, where $type is either 'course' or 'user',
12947: @what should be a list of parameters to ask about. This routine caches
1.1235 raeburn 12948: answers for 10 minutes.
1.243 albertel 12949:
1.877 foxr 12950: =item *
12951:
12952: get_courseresdata($courseid, $domain) : dump the entire course resource
12953: data base, returning a hash that is keyed by the resource name and has
12954: values that are the resource value. I believe that the timestamps and
12955: versions are also returned.
12956:
1.1236 raeburn 12957: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
12958: supplemental content area. This routine caches the number of files for
12959: 10 minutes.
12960:
1.243 albertel 12961: =back
12962:
12963: =head2 Course Modification
12964:
12965: =over 4
1.191 harris41 12966:
12967: =item *
12968:
1.243 albertel 12969: writecoursepref($courseid,%prefs) : write preferences (environment
12970: database) for a course
1.191 harris41 12971:
12972: =item *
12973:
1.1011 raeburn 12974: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
12975:
12976: =item *
12977:
1.1038 raeburn 12978: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 12979:
1.1167 droeschl 12980: =item *
12981:
12982: is_course($courseid), is_course($cdom, $cnum)
12983:
12984: Accepts either a combined $courseid (in the form of domain_courseid) or the
12985: two component version $cdom, $cnum. It checks if the specified course exists.
12986:
12987: Returns:
12988: undef if the course doesn't exist, otherwise
12989: in scalar context the combined courseid.
12990: in list context the two components of the course identifier, domain and
12991: courseid.
12992:
1.243 albertel 12993: =back
12994:
12995: =head2 Resource Subroutines
12996:
12997: =over 4
1.191 harris41 12998:
12999: =item *
13000:
1.243 albertel 13001: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 13002:
13003: =item *
13004:
1.243 albertel 13005: repcopy($filename) : subscribes to the requested file, and attempts to
13006: replicate from the owning library server, Might return
1.607 raeburn 13007: 'unavailable', 'not_found', 'forbidden', 'ok', or
13008: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 13009: resource. Expects the local filesystem pathname
13010: (/home/httpd/html/res/....)
13011:
13012: =back
13013:
13014: =head2 Resource Information
13015:
13016: =over 4
1.191 harris41 13017:
13018: =item *
13019:
1.1228 raeburn 13020: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates
13021: and returns the value of a variety of different possible values,
13022: $varname should be a request string, and the other parameters can be
13023: used to specify who and what one is asking about. Ordinarily, $cid
13024: does not need to be specified, as it is retrived from
13025: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
13026: within lonuserstate::loadmap() when initializing a course, before
13027: $env{'request.course.id'} has been set, so it needs to be provided
13028: in that one case.
1.243 albertel 13029:
13030: Possible values for $varname are environment.lastname (or other item
13031: from the envirnment hash), user.name (or someother aspect about the
13032: user), resource.0.maxtries (or some other part and parameter of a
13033: resource)
1.204 albertel 13034:
13035: =item *
13036:
1.243 albertel 13037: directcondval($number) : get current value of a condition; reads from a state
13038: string
1.204 albertel 13039:
13040: =item *
13041:
1.243 albertel 13042: condval($condidx) : value of condition index based on state
1.204 albertel 13043:
13044: =item *
13045:
1.243 albertel 13046: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
13047: resource's metadata, $what should be either a specific key, or either
13048: 'keys' (to get a list of possible keys) or 'packages' to get a list of
13049: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
13050:
13051: this function automatically caches all requests
1.191 harris41 13052:
13053: =item *
13054:
1.243 albertel 13055: metadata_query($query,$custom,$customshow) : make a metadata query against the
13056: network of library servers; returns file handle of where SQL and regex results
13057: will be stored for query
1.191 harris41 13058:
13059: =item *
13060:
1.243 albertel 13061: symbread($filename) : return symbolic list entry (filename argument optional);
13062: returns the data handle
1.191 harris41 13063:
13064: =item *
13065:
1.1190 raeburn 13066: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
13067: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582 albertel 13068: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190 raeburn 13069: on failure, user must be in a course, as it assumes the existence of
13070: the course initial hash, and uses $env('request.course.id'}. The third
13071: arg is an optional reference to a scalar. If this arg is passed in the
13072: call to symbverify, it will be set to 1 if the symb has been set to be
13073: encrypted; otherwise it will be null.
1.191 harris41 13074:
13075: =item *
13076:
1.243 albertel 13077: symbclean($symb) : removes versions numbers from a symb, returns the
13078: cleaned symb
1.191 harris41 13079:
13080: =item *
13081:
1.243 albertel 13082: is_on_map($uri) : checks if the $uri is somewhere on the current
13083: course map, user must be in a course for it to work.
1.191 harris41 13084:
13085: =item *
13086:
1.243 albertel 13087: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 13088:
13089: =item *
13090:
1.243 albertel 13091: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
13092: a random seed, all arguments are optional, if they aren't sent it uses the
13093: environment to derive them. Note: if symb isn't sent and it can't get one
13094: from &symbread it will use the current time as its return value
1.191 harris41 13095:
13096: =item *
13097:
1.243 albertel 13098: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
13099: unfakeable, receipt
1.191 harris41 13100:
13101: =item *
13102:
1.620 albertel 13103: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 13104:
13105: =item *
13106:
1.243 albertel 13107: countacc($url) : count the number of accesses to a given URL
1.191 harris41 13108:
13109: =item *
13110:
1.243 albertel 13111: 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 13112:
13113: =item *
13114:
1.243 albertel 13115: 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 13116:
13117: =item *
13118:
1.243 albertel 13119: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 13120:
13121: =item *
13122:
1.243 albertel 13123: devalidate($symb) : devalidate temporary spreadsheet calculations,
13124: forcing spreadsheet to reevaluate the resource scores next time.
13125:
1.1195 raeburn 13126: =item *
13127:
1.1196 raeburn 13128: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
13129: when viewing in course context.
1.1195 raeburn 13130:
1.1196 raeburn 13131: input: six args -- filename (decluttered), course number, course domain,
13132: url, symb (if registered) and group (if this is a
13133: group item -- e.g., bulletin board, group page etc.).
1.1195 raeburn 13134:
1.1196 raeburn 13135: output: array of five scalars --
1.1195 raeburn 13136: $cfile -- url for file editing if editable on current server
13137: $home -- homeserver of resource (i.e., for author if published,
13138: or course if uploaded.).
13139: $switchserver -- 1 if server switch will be needed.
1.1196 raeburn 13140: $forceedit -- 1 if icon/link should be to go to edit mode
13141: $forceview -- 1 if icon/link should be to go to view mode
1.1195 raeburn 13142:
13143: =item *
13144:
13145: is_course_upload($file,$cnum,$cdom)
13146:
13147: Used in course context to determine if current file was uploaded to
13148: the course (i.e., would be found in /userfiles/docs on the course's
13149: homeserver.
13150:
13151: input: 3 args -- filename (decluttered), course number and course domain.
13152: output: boolean -- 1 if file was uploaded.
13153:
1.243 albertel 13154: =back
13155:
13156: =head2 Storing/Retreiving Data
13157:
13158: =over 4
1.191 harris41 13159:
13160: =item *
13161:
1.243 albertel 13162: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
13163: for this url; hashref needs to be given and should be a \%hashname; the
13164: remaining args aren't required and if they aren't passed or are '' they will
1.620 albertel 13165: be derived from the env
1.191 harris41 13166:
13167: =item *
13168:
1.243 albertel 13169: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
13170: uses critical subroutine
1.191 harris41 13171:
13172: =item *
13173:
1.243 albertel 13174: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
13175: all args are optional
1.191 harris41 13176:
13177: =item *
13178:
1.717 albertel 13179: dumpstore($namespace,$udom,$uname,$regexp,$range) :
13180: dumps the complete (or key matching regexp) namespace into a hash
13181: ($udom, $uname, $regexp, $range are optional) for a namespace that is
13182: normally &store()ed into
13183:
13184: $range should be either an integer '100' (give me the first 100
13185: matching records)
13186: or be two integers sperated by a - with no spaces
13187: '30-50' (give me the 30th through the 50th matching
13188: records)
13189:
13190:
13191: =item *
13192:
13193: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
13194: replaces a &store() version of data with a replacement set of data
13195: for a particular resource in a namespace passed in the $storehash hash
13196: reference
13197:
13198: =item *
13199:
1.243 albertel 13200: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
13201: works very similar to store/cstore, but all data is stored in a
13202: temporary location and can be reset using tmpreset, $storehash should
13203: be a hash reference, returns nothing on success
1.191 harris41 13204:
13205: =item *
13206:
1.243 albertel 13207: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
13208: similar to restore, but all data is stored in a temporary location and
13209: can be reset using tmpreset. Returns a hash of values on success,
13210: error string otherwise.
1.191 harris41 13211:
13212: =item *
13213:
1.243 albertel 13214: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
13215: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 13216:
13217: =item *
13218:
1.243 albertel 13219: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13220: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 13221:
13222: =item *
13223:
1.243 albertel 13224: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
13225: namesp ($udom and $uname are optional)
1.191 harris41 13226:
13227: =item *
13228:
1.702 albertel 13229: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 13230: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 13231: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 13232:
1.702 albertel 13233: $range should be either an integer '100' (give me the first 100
13234: matching records)
13235: or be two integers sperated by a - with no spaces
13236: '30-50' (give me the 30th through the 50th matching
13237: records)
1.449 matthew 13238: =item *
13239:
13240: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
13241: $store can be a scalar, an array reference, or if the amount to be
13242: incremented is > 1, a hash reference.
13243:
13244: ($udom and $uname are optional)
1.191 harris41 13245:
13246: =item *
13247:
1.243 albertel 13248: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
13249: ($udom and $uname are optional)
1.191 harris41 13250:
13251: =item *
13252:
1.243 albertel 13253: cput($namespace,$storehash,$udom,$uname) : critical put
13254: ($udom and $uname are optional)
1.191 harris41 13255:
13256: =item *
13257:
1.748 albertel 13258: newput($namespace,$storehash,$udom,$uname) :
13259:
13260: Attempts to store the items in the $storehash, but only if they don't
13261: currently exist, if this succeeds you can be certain that you have
13262: successfully created a new key value pair in the $namespace db.
13263:
13264:
13265: Args:
13266: $namespace: name of database to store values to
13267: $storehash: hashref to store to the db
13268: $udom: (optional) domain of user containing the db
13269: $uname: (optional) name of user caontaining the db
13270:
13271: Returns:
13272: 'ok' -> succeeded in storing all keys of $storehash
13273: 'key_exists: <key>' -> failed to anything out of $storehash, as at
13274: least <key> already existed in the db (other
13275: requested keys may also already exist)
1.967 bisitz 13276: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 13277: 'con_lost' -> unable to contact request server
13278: 'refused' -> action was not allowed by remote machine
13279:
13280:
13281: =item *
13282:
1.243 albertel 13283: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13284: reference filled in from namesp (encrypts the return communication)
13285: ($udom and $uname are optional)
1.191 harris41 13286:
13287: =item *
13288:
1.243 albertel 13289: log($udom,$name,$home,$message) : write to permanent log for user; use
13290: critical subroutine
13291:
1.806 raeburn 13292: =item *
13293:
1.860 raeburn 13294: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
13295: array reference filled in from namespace found in domain level on either
13296: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 13297:
13298: =item *
13299:
1.860 raeburn 13300: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
13301: domain level either on specified domain server ($uhome) or primary domain
13302: server ($udom and $uhome are optional)
1.806 raeburn 13303:
1.943 raeburn 13304: =item *
13305:
1.1240 raeburn 13306: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
13307: for: authentication, language, quotas, timezone, date locale, and portal URL in
13308: the target domain.
13309:
13310: May also include additional key => value pairs for the following groups:
13311:
13312: =over
13313:
13314: =item
13315: disk quotas (MB allocated by default to portfolios and authoring spaces).
13316:
13317: =over
13318:
13319: =item defaultquota, authorquota
13320:
13321: =back
13322:
13323: =item
13324: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
13325: portfolio for users).
13326:
13327: =over
13328:
13329: =item
13330: aboutme, blog, webdav, portfolio
13331:
13332: =back
13333:
13334: =item
13335: requestcourses: ability to request courses, and how requests are processed.
13336:
13337: =over
13338:
13339: =item
1.1246 raeburn 13340: official, unofficial, community, textbook
1.1240 raeburn 13341:
13342: =back
13343:
13344: =item
13345: inststatus: types of institutional affiliation, and order in which they are displayed.
13346:
13347: =over
13348:
13349: =item
1.1256 ! raeburn 13350: inststatustypes, inststatusorder, inststatusguest
1.1240 raeburn 13351:
13352: =back
13353:
13354: =item
13355: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
13356: for course's uploaded content.
13357:
13358: =over
13359:
13360: =item
1.1246 raeburn 13361: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
13362: communityquota, textbookquota
1.1240 raeburn 13363:
13364: =back
13365:
13366: =item
13367: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
13368: on your servers.
13369:
13370: =over
13371:
13372: =item
13373: remotesessions, hostedsessions
13374:
13375: =back
13376:
13377: =back
13378:
13379: In cases where a domain coordinator has never used the "Set Domain Configuration"
13380: utility to create a configuration.db file on a domain's primary library server
13381: only the following domain defaults: auth_def, auth_arg_def, lang_def
13382: -- corresponding values are authentication type (internal, krb4, krb5,
13383: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
13384: will be available. Values are retrieved from cache (if current), unless the
13385: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
13386: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
13387:
13388: Typical usage:
1.943 raeburn 13389:
1.1240 raeburn 13390: %domdefaults = &get_domain_defaults($target_domain);
1.943 raeburn 13391:
1.243 albertel 13392: =back
13393:
13394: =head2 Network Status Functions
13395:
13396: =over 4
1.191 harris41 13397:
13398: =item *
13399:
1.1137 raeburn 13400: dirlist() : return directory list based on URI (first arg).
13401:
13402: Inputs: 1 required, 5 optional.
13403:
13404: =over
13405:
13406: =item
13407: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
13408:
13409: =item
13410: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
13411:
13412: =item
13413: $username - username of user/course to be listed. Extracted from $uri if absent.
13414:
13415: =item
13416: $getpropath - boolean: 1 if prepend path using &propath().
13417:
13418: =item
13419: $getuserdir - boolean: 1 if prepend path for "userfiles".
13420:
13421: =item
13422: $alternateRoot - path to prepend in place of path from $uri.
13423:
13424: =back
13425:
13426: Returns: Array of up to two items.
13427:
13428: =over
13429:
13430: a reference to an array of files/subdirectories
13431:
13432: =over
13433:
13434: Each element in the array of files/subdirectories is a & separated list of
13435: item name and the result of running stat on the item. If dirlist was requested
13436: for a file instead of a directory, the item name will be ''. For a directory
13437: listing, if the item is a metadata file, the element will end &N&M
13438: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
13439: default copyright set (1).
13440:
13441: =back
13442:
13443: a scalar containing error condition (if encountered).
13444:
13445: =over
13446:
13447: =item
13448: no_host (no homeserver identified for $username:$domain).
13449:
13450: =item
13451: no_such_host (server contacted for listing not identified as valid host).
13452:
13453: =item
13454: con_lost (connection to remote server failed).
13455:
13456: =item
13457: refused (invalid $username:$domain received on lond side).
13458:
13459: =item
13460: no_such_dir (directory at specified path on lond side does not exist).
13461:
13462: =item
13463: empty (directory at specified path on lond side is empty).
13464:
13465: =over
13466:
13467: This is currently not encountered because the &ls3, &ls2,
13468: &ls (_handler) routines on the lond side do not filter out
13469: . and .. from a directory listing.
13470:
13471: =back
13472:
13473: =back
13474:
13475: =back
1.191 harris41 13476:
13477: =item *
13478:
1.243 albertel 13479: spareserver() : find server with least workload from spare.tab
13480:
1.986 foxr 13481:
13482: =item *
13483:
13484: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
13485: if there is no corresponding loncapa host.
13486:
1.243 albertel 13487: =back
13488:
1.986 foxr 13489:
1.243 albertel 13490: =head2 Apache Request
13491:
13492: =over 4
1.191 harris41 13493:
13494: =item *
13495:
1.243 albertel 13496: ssi($url,%hash) : server side include, does a complete request cycle on url to
13497: localhost, posts hash
13498:
13499: =back
13500:
13501: =head2 Data to String to Data
13502:
13503: =over 4
1.191 harris41 13504:
13505: =item *
13506:
1.243 albertel 13507: hash2str(%hash) : convert a hash into a string complete with escaping and '='
13508: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 13509:
13510: =item *
13511:
1.243 albertel 13512: hashref2str($hashref) : convert a hashref into a string complete with
13513: escaping and '=' and '&' separators, supports elements that are
13514: arrayrefs and hashrefs
1.191 harris41 13515:
13516: =item *
13517:
1.243 albertel 13518: arrayref2str($arrayref) : convert an arrayref into a string complete
13519: with escaping and '&' separators, supports elements that are arrayrefs
13520: and hashrefs
1.191 harris41 13521:
13522: =item *
13523:
1.243 albertel 13524: str2hash($string) : convert string to hash using unescaping and
13525: splitting on '=' and '&', supports elements that are arrayrefs and
13526: hashrefs
1.191 harris41 13527:
13528: =item *
13529:
1.243 albertel 13530: str2array($string) : convert string to hash using unescaping and
13531: splitting on '&', supports elements that are arrayrefs and hashrefs
13532:
13533: =back
13534:
13535: =head2 Logging Routines
13536:
13537:
13538: These routines allow one to make log messages in the lonnet.log and
13539: lonnet.perm logfiles.
1.191 harris41 13540:
1.1119 foxr 13541: =over 4
13542:
1.191 harris41 13543: =item *
13544:
1.243 albertel 13545: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 13546:
13547: =item *
13548:
1.243 albertel 13549: logthis() : append message to the normal lonnet.log file, it gets
13550: preiodically rolled over and deleted.
1.191 harris41 13551:
13552: =item *
13553:
1.243 albertel 13554: logperm() : append a permanent message to lonnet.perm.log, this log
13555: file never gets deleted by any automated portion of the system, only
13556: messages of critical importance should go in here.
13557:
1.1119 foxr 13558:
1.243 albertel 13559: =back
13560:
13561: =head2 General File Helper Routines
13562:
13563: =over 4
1.191 harris41 13564:
13565: =item *
13566:
1.481 raeburn 13567: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
13568: (a) files in /uploaded
13569: (i) If a local copy of the file exists -
13570: compares modification date of local copy with last-modified date for
13571: definitive version stored on home server for course. If local copy is
13572: stale, requests a new version from the home server and stores it.
13573: If the original has been removed from the home server, then local copy
13574: is unlinked.
13575: (ii) If local copy does not exist -
13576: requests the file from the home server and stores it.
13577:
13578: If $caller is 'uploadrep':
13579: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
13580: for request for files originally uploaded via DOCS.
13581: - returns 'ok' if fresh local copy now available, -1 otherwise.
13582:
13583: Otherwise:
13584: This indicates a call from the content generation phase of the request.
13585: - returns the entire contents of the file or -1.
13586:
13587: (b) files in /res
13588: - returns the entire contents of a file or -1;
13589: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 13590:
1.712 albertel 13591:
13592: =item *
13593:
13594: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
13595: reference
13596:
13597: returns either a stat() list of data about the file or an empty list
13598: if the file doesn't exist or couldn't find out about it (connection
13599: problems or user unknown)
13600:
1.191 harris41 13601: =item *
13602:
1.243 albertel 13603: filelocation($dir,$file) : returns file system location of a file
13604: based on URI; meant to be "fairly clean" absolute reference, $dir is a
13605: directory that relative $file lookups are to looked in ($dir of /a/dir
13606: and a file of ../bob will become /a/bob)
1.191 harris41 13607:
13608: =item *
13609:
13610: hreflocation($dir,$file) : returns file system location or a URL; same as
13611: filelocation except for hrefs
13612:
13613: =item *
13614:
13615: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
13616:
1.243 albertel 13617: =back
13618:
1.608 albertel 13619: =head2 Usererfile file routines (/uploaded*)
13620:
13621: =over 4
13622:
13623: =item *
13624:
13625: userfileupload(): main rotine for putting a file in a user or course's
13626: filespace, arguments are,
13627:
1.620 albertel 13628: formname - required - this is the name of the element in $env where the
1.608 albertel 13629: filename, and the contents of the file to create/modifed exist
1.620 albertel 13630: the filename is in $env{'form.'.$formname.'.filename'} and the
13631: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 13632: context - if coursedoc, store the file in the course of the active role
13633: of the current user;
13634: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
13635: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 13636: subdir - required - subdirectory to put the file in under ../userfiles/
13637: if undefined, it will be placed in "unknown"
13638:
13639: (This routine calls clean_filename() to remove any dangerous
13640: characters from the filename, and then calls finuserfileupload() to
13641: complete the transaction)
13642:
13643: returns either the url of the uploaded file (/uploaded/....) if successful
13644: and /adm/notfound.html if unsuccessful
13645:
13646: =item *
13647:
13648: clean_filename(): routine for cleaing a filename up for storage in
13649: userfile space, argument is:
13650:
13651: filename - proposed filename
13652:
13653: returns: the new clean filename
13654:
13655: =item *
13656:
1.1090 raeburn 13657: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 13658: userspace, probably shouldn't be called directly
13659:
13660: docuname: username or courseid of destination for the file
13661: docudom: domain of user/course of destination for the file
13662: formname: same as for userfileupload()
1.1090 raeburn 13663: fname: filename (including subdirectories) for the file
13664: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
13665: allfiles: reference to hash used to store objects found by parser
13666: codebase: reference to hash used for codebases of java objects found by parser
13667: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
13668: thumbheight: height (pixels) of thumbnail to be created for uploaded image
13669: resizewidth: width to be used to resize image using resizeImage from ImageMagick
13670: resizeheight: height to be used to resize image using resizeImage from ImageMagick
13671: context: if 'overwrite', will move the uploaded file from its temporary location to
13672: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 13673: mimetype: reference to scalar to accommodate mime type determined
13674: from File::MMagic if $parser = parse.
1.608 albertel 13675:
13676: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 13677: and /adm/notfound.html if unsuccessful (or an error message if context
13678: was 'overwrite').
13679:
1.608 albertel 13680:
13681: =item *
13682:
13683: renameuserfile(): renames an existing userfile to a new name
13684:
13685: Args:
13686: docuname: username or courseid of destination for the file
13687: docudom: domain of user/course of destination for the file
13688: old: current file name (including any subdirs under userfiles)
13689: new: desired file name (including any subdirs under userfiles)
13690:
13691: =item *
13692:
13693: mkdiruserfile(): creates a directory is a userfiles dir
13694:
13695: Args:
13696: docuname: username or courseid of destination for the file
13697: docudom: domain of user/course of destination for the file
13698: dir: dir to create (including any subdirs under userfiles)
13699:
13700: =item *
13701:
13702: removeuserfile(): removes a file that exists in userfiles
13703:
13704: Args:
13705: docuname: username or courseid of destination for the file
13706: docudom: domain of user/course of destination for the file
13707: fname: filname to delete (including any subdirs under userfiles)
13708:
13709: =item *
13710:
13711: removeuploadedurl(): convience function for removeuserfile()
13712:
13713: Args:
13714: url: a full /uploaded/... url to delete
13715:
1.747 albertel 13716: =item *
13717:
13718: get_portfile_permissions():
13719: Args:
13720: domain: domain of user or course contain the portfolio files
13721: user: name of user or num of course contain the portfolio files
13722: Returns:
13723: hashref of a dump of the proper file_permissions.db
13724:
13725:
13726: =item *
13727:
13728: get_access_controls():
13729:
13730: Args:
13731: current_permissions: the hash ref returned from get_portfile_permissions()
13732: group: (optional) the group you want the files associated with
13733: file: (optional) the file you want access info on
13734:
13735: Returns:
1.749 raeburn 13736: a hash (keys are file names) of hashes containing
13737: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
13738: values are XML containing access control settings (see below)
1.747 albertel 13739:
13740: Internal notes:
13741:
1.749 raeburn 13742: access controls are stored in file_permissions.db as key=value pairs.
13743: key -> path to file/file_name\0uniqueID:scope_end_start
13744: where scope -> public,guest,course,group,domains or users.
13745: end -> UNIX time for end of access (0 -> no end date)
13746: start -> UNIX time for start of access
13747:
13748: value -> XML description of access control
13749: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
13750: <start></start>
13751: <end></end>
13752:
13753: <password></password> for scope type = guest
13754:
13755: <domain></domain> for scope type = course or group
13756: <number></number>
13757: <roles id="">
13758: <role></role>
13759: <access></access>
13760: <section></section>
13761: <group></group>
13762: </roles>
13763:
13764: <dom></dom> for scope type = domains
13765:
13766: <users> for scope type = users
13767: <user>
13768: <uname></uname>
13769: <udom></udom>
13770: </user>
13771: </users>
13772: </scope>
13773:
13774: Access data is also aggregated for each file in an additional key=value pair:
13775: key -> path to file/file_name\0accesscontrol
13776: value -> reference to hash
13777: hash contains key = value pairs
13778: where key = uniqueID:scope_end_start
13779: value = UNIX time record was last updated
13780:
13781: Used to improve speed of look-ups of access controls for each file.
13782:
13783: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
13784:
1.1198 raeburn 13785: =item *
13786:
1.749 raeburn 13787: modify_access_controls():
13788:
13789: Modifies access controls for a portfolio file
13790: Args
13791: 1. file name
13792: 2. reference to hash of required changes,
13793: 3. domain
13794: 4. username
13795: where domain,username are the domain of the portfolio owner
13796: (either a user or a course)
13797:
13798: Returns:
13799: 1. result of additions or updates ('ok' or 'error', with error message).
13800: 2. result of deletions ('ok' or 'error', with error message).
13801: 3. reference to hash of any new or updated access controls.
13802: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
13803: key = integer (inbound ID)
1.1198 raeburn 13804: value = uniqueID
13805:
13806: =item *
13807:
13808: get_timebased_id():
13809:
13810: Attempts to get a unique timestamp-based suffix for use with items added to a
13811: course via the Course Editor (e.g., folders, composite pages,
13812: group bulletin boards).
13813:
13814: Args: (first three required; six others optional)
13815:
13816: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
13817: docssequence, or name of group
13818:
13819: 2. keyid (alphanumeric): name of temporary locking key in hash,
13820: e.g., num, boardids
13821:
13822: 3. namespace: name of gdbm file used to store suffixes already assigned;
13823: file will be named nohist_namespace.db
13824:
13825: 4. cdom: domain of course; default is current course domain from %env
13826:
13827: 5. cnum: course number; default is current course number from %env
13828:
13829: 6. idtype: set to concat if an additional digit is to be appended to the
13830: unix timestamp to form the suffix, if the plain timestamp is already
13831: in use. Default is to not do this, but simply increment the unix
13832: timestamp by 1 until a unique key is obtained.
13833:
13834: 7. who: holder of locking key; defaults to user:domain for user.
13835:
13836: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
13837: retrying); default is 3.
13838:
13839: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
13840:
13841: Returns:
13842:
13843: 1. suffix obtained (numeric)
13844:
13845: 2. result of deleting locking key (ok if deleted, or lock never obtained)
13846:
13847: 3. error: contains (localized) error message if an error occurred.
13848:
1.747 albertel 13849:
1.608 albertel 13850: =back
13851:
1.243 albertel 13852: =head2 HTTP Helper Routines
13853:
13854: =over 4
13855:
1.191 harris41 13856: =item *
13857:
13858: escape() : unpack non-word characters into CGI-compatible hex codes
13859:
13860: =item *
13861:
13862: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
13863:
1.243 albertel 13864: =back
13865:
13866: =head1 PRIVATE SUBROUTINES
13867:
13868: =head2 Underlying communication routines (Shouldn't call)
13869:
13870: =over 4
13871:
13872: =item *
13873:
13874: subreply() : tries to pass a message to lonc, returns con_lost if incapable
13875:
13876: =item *
13877:
13878: reply() : uses subreply to send a message to remote machine, logs all failures
13879:
13880: =item *
13881:
13882: critical() : passes a critical message to another server; if cannot
13883: get through then place message in connection buffer directory and
13884: returns con_delayed, if incapable of saving message, returns
13885: con_failed
13886:
13887: =item *
13888:
13889: reconlonc() : tries to reconnect lonc client processes.
13890:
13891: =back
13892:
13893: =head2 Resource Access Logging
13894:
13895: =over 4
13896:
13897: =item *
13898:
13899: flushcourselogs() : flush (save) buffer logs and access logs
13900:
13901: =item *
13902:
13903: courselog($what) : save message for course in hash
13904:
13905: =item *
13906:
13907: courseacclog($what) : save message for course using &courselog(). Perform
13908: special processing for specific resource types (problems, exams, quizzes, etc).
13909:
1.191 harris41 13910: =item *
13911:
13912: goodbye() : flush course logs and log shutting down; it is called in srm.conf
13913: as a PerlChildExitHandler
1.243 albertel 13914:
13915: =back
13916:
13917: =head2 Other
13918:
13919: =over 4
13920:
13921: =item *
13922:
13923: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 13924:
13925: =back
13926:
13927: =cut
1.877 foxr 13928:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>