Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1286
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1286 ! raeburn 4: # $Id: lonnet.pm,v 1.1285 2015/05/13 20:38:31 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'} }) {
1.1279 raeburn 852: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
853: $try_server));
1.1123 raeburn 854: ($spare_server, $lowest_load) =
855: &compare_server_load($try_server, $spare_server, $lowest_load);
856: }
1.1083 raeburn 857: }
1.784 albertel 858:
1.1123 raeburn 859: my $found_server = ($spare_server ne '' && $lowest_load < 100);
860:
861: if (!$found_server) {
862: if (ref($spareshash->{'default'}) eq 'ARRAY') {
863: foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1279 raeburn 864: next unless (&spare_can_host($udom,$uint_dom,
865: $remotesessions,$try_server));
1.1123 raeburn 866: ($spare_server, $lowest_load) =
867: &compare_server_load($try_server, $spare_server, $lowest_load);
868: }
869: }
870: }
1.784 albertel 871: }
872:
873: if (!$want_server_name) {
1.968 raeburn 874: my $protocol = 'http';
875: if ($protocol{$spare_server} eq 'https') {
876: $protocol = $protocol{$spare_server};
877: }
1.1001 raeburn 878: if (defined($spare_server)) {
879: my $hostname = &hostname($spare_server);
1.1083 raeburn 880: if (defined($hostname)) {
1.1001 raeburn 881: $spare_server = $protocol.'://'.$hostname;
882: }
883: }
1.784 albertel 884: }
885: return $spare_server;
886: }
887:
888: sub compare_server_load {
1.1253 raeburn 889: my ($try_server, $spare_server, $lowest_load, $required) = @_;
890:
891: if ($required) {
892: my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
893: my $remoterev = &get_server_loncaparev(undef,$try_server);
894: my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
895: if (($major eq '' && $minor eq '') ||
896: (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
897: return ($spare_server,$lowest_load);
898: }
899: }
1.784 albertel 900:
901: my $loadans = &reply('load', $try_server);
902: my $userloadans = &reply('userload',$try_server);
903:
904: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114 raeburn 905: return ($spare_server, $lowest_load); #didn't get a number from the server
1.784 albertel 906: }
907:
908: my $load;
909: if ($loadans =~ /\d/) {
910: if ($userloadans =~ /\d/) {
911: #both are numbers, pick the bigger one
912: $load = ($loadans > $userloadans) ? $loadans
913: : $userloadans;
1.411 albertel 914: } else {
1.784 albertel 915: $load = $loadans;
1.411 albertel 916: }
1.784 albertel 917: } else {
918: $load = $userloadans;
919: }
920:
921: if (($load =~ /\d/) && ($load < $lowest_load)) {
922: $spare_server = $try_server;
923: $lowest_load = $load;
1.370 albertel 924: }
1.784 albertel 925: return ($spare_server,$lowest_load);
1.202 matthew 926: }
1.914 albertel 927:
928: # --------------------------- ask offload servers if user already has a session
929: sub find_existing_session {
930: my ($udom,$uname) = @_;
1.1123 raeburn 931: my $spareshash = &this_host_spares($udom);
932: if (ref($spareshash) eq 'HASH') {
933: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
934: foreach my $try_server (@{ $spareshash->{'primary'} }) {
935: return $try_server if (&has_user_session($try_server, $udom, $uname));
936: }
937: }
938: if (ref($spareshash->{'default'}) eq 'ARRAY') {
939: foreach my $try_server (@{ $spareshash->{'default'} }) {
940: return $try_server if (&has_user_session($try_server, $udom, $uname));
941: }
942: }
1.914 albertel 943: }
944: return;
945: }
946:
947: # -------------------------------- ask if server already has a session for user
948: sub has_user_session {
949: my ($lonid,$udom,$uname) = @_;
950: my $result = &reply(join(':','userhassession',
951: map {&escape($_)} ($udom,$uname)),$lonid);
952: return 1 if ($result eq 'ok');
953:
954: return 0;
955: }
956:
1.1076 raeburn 957: # --------- determine least loaded server in a user's domain which allows login
958:
959: sub choose_server {
1.1259 raeburn 960: my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076 raeburn 961: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077 raeburn 962: my %servers = &get_servers($udom);
1.1076 raeburn 963: my $lowest_load = 30000;
1.1259 raeburn 964: my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
965: if ($skiploadbal) {
966: ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
967: unless (defined($cached)) {
968: my $cachetime = 60*60*24;
969: my %domconfig =
970: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
971: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
972: $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
973: $cachetime);
974: }
975: }
976: }
1.1076 raeburn 977: foreach my $lonhost (keys(%servers)) {
1.1259 raeburn 978: if ($skiploadbal) {
979: if (ref($balancers) eq 'HASH') {
980: next if (exists($balancers->{$lonhost}));
981: }
982: }
1.1115 raeburn 983: my $loginvia;
984: if ($checkloginvia) {
985: $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116 raeburn 986: if ($loginvia) {
987: my ($server,$path) = split(/:/,$loginvia);
988: ($login_host, $lowest_load) =
1.1253 raeburn 989: &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116 raeburn 990: if ($login_host eq $server) {
991: $portal_path = $path;
1.1151 raeburn 992: $isredirect = 1;
1.1116 raeburn 993: }
994: } else {
995: ($login_host, $lowest_load) =
1.1253 raeburn 996: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116 raeburn 997: if ($login_host eq $lonhost) {
998: $portal_path = '';
1.1151 raeburn 999: $isredirect = '';
1.1116 raeburn 1000: }
1001: }
1002: } else {
1.1076 raeburn 1003: ($login_host, $lowest_load) =
1.1253 raeburn 1004: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076 raeburn 1005: }
1006: }
1007: if ($login_host ne '') {
1.1116 raeburn 1008: $hostname = &hostname($login_host);
1.1076 raeburn 1009: }
1.1151 raeburn 1010: return ($login_host,$hostname,$portal_path,$isredirect);
1.1076 raeburn 1011: }
1012:
1.202 matthew 1013: # --------------------------------------------- Try to change a user's password
1014:
1015: sub changepass {
1.799 raeburn 1016: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 1017: $currentpass = &escape($currentpass);
1018: $newpass = &escape($newpass);
1.1030 raeburn 1019: my $lonhost = $perlvar{'lonHostID'};
1020: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202 matthew 1021: $server);
1022: if (! $answer) {
1023: &logthis("No reply on password change request to $server ".
1024: "by $uname in domain $udom.");
1025: } elsif ($answer =~ "^ok") {
1026: &logthis("$uname in $udom successfully changed their password ".
1027: "on $server.");
1028: } elsif ($answer =~ "^pwchange_failure") {
1029: &logthis("$uname in $udom was unable to change their password ".
1030: "on $server. The action was blocked by either lcpasswd ".
1031: "or pwchange");
1032: } elsif ($answer =~ "^non_authorized") {
1033: &logthis("$uname in $udom did not get their password correct when ".
1034: "attempting to change it on $server.");
1035: } elsif ($answer =~ "^auth_mode_error") {
1036: &logthis("$uname in $udom attempted to change their password despite ".
1037: "not being locally or internally authenticated on $server.");
1038: } elsif ($answer =~ "^unknown_user") {
1039: &logthis("$uname in $udom attempted to change their password ".
1040: "on $server but were unable to because $server is not ".
1041: "their home server.");
1042: } elsif ($answer =~ "^refused") {
1043: &logthis("$server refused to change $uname in $udom password because ".
1044: "it was sent an unencrypted request to change the password.");
1.1030 raeburn 1045: } elsif ($answer =~ "invalid_client") {
1046: &logthis("$server refused to change $uname in $udom password because ".
1047: "it was a reset by e-mail originating from an invalid server.");
1.202 matthew 1048: }
1049: return $answer;
1.1 albertel 1050: }
1051:
1.169 harris41 1052: # ----------------------- Try to determine user's current authentication scheme
1053:
1054: sub queryauthenticate {
1055: my ($uname,$udom)=@_;
1.456 albertel 1056: my $uhome=&homeserver($uname,$udom);
1057: if (!$uhome) {
1058: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
1059: return 'no_host';
1060: }
1061: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
1062: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
1063: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 1064: }
1.456 albertel 1065: return $answer;
1.169 harris41 1066: }
1067:
1.1 albertel 1068: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 1069:
1.1 albertel 1070: sub authenticate {
1.1073 raeburn 1071: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807 albertel 1072: $upass=&escape($upass);
1073: $uname= &LONCAPA::clean_username($uname);
1.836 www 1074: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 1075: my $newhome;
1.836 www 1076: if ((!$uhome) || ($uhome eq 'no_host')) {
1077: # Maybe the machine was offline and only re-appeared again recently?
1078: &reconlonc();
1079: # One more
1.952 raeburn 1080: $uhome=&homeserver($uname,$udom,1);
1081: if (($uhome eq 'no_host') && $checkdefauth) {
1082: if (defined(&domain($udom,'primary'))) {
1083: $newhome=&domain($udom,'primary');
1084: }
1085: if ($newhome ne '') {
1086: $uhome = $newhome;
1087: }
1088: }
1.836 www 1089: if ((!$uhome) || ($uhome eq 'no_host')) {
1090: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 1091: return 'no_host';
1092: }
1.1 albertel 1093: }
1.1073 raeburn 1094: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471 albertel 1095: if ($answer eq 'authorized') {
1.952 raeburn 1096: if ($newhome) {
1097: &logthis("User $uname at $udom authorized by $uhome, but needs account");
1098: return 'no_account_on_host';
1099: } else {
1100: &logthis("User $uname at $udom authorized by $uhome");
1101: return $uhome;
1102: }
1.471 albertel 1103: }
1104: if ($answer eq 'non_authorized') {
1105: &logthis("User $uname at $udom rejected by $uhome");
1106: return 'no_host';
1.9 www 1107: }
1.471 albertel 1108: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 1109: return 'no_host';
1110: }
1111:
1.1073 raeburn 1112: sub can_host_session {
1.1074 raeburn 1113: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073 raeburn 1114: my $canhost = 1;
1.1074 raeburn 1115: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073 raeburn 1116: if (ref($remotesessions) eq 'HASH') {
1117: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074 raeburn 1118: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073 raeburn 1119: $canhost = 0;
1120: } else {
1121: $canhost = 1;
1122: }
1123: }
1124: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074 raeburn 1125: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073 raeburn 1126: $canhost = 1;
1127: } else {
1128: $canhost = 0;
1129: }
1130: }
1131: if ($canhost) {
1132: if ($remotesessions->{'version'} ne '') {
1133: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1134: if ($reqmajor ne '' && $reqminor ne '') {
1135: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1136: my $major = $1;
1137: my $minor = $2;
1138: if (($major < $reqmajor ) ||
1139: (($major == $reqmajor) && ($minor < $reqminor))) {
1140: $canhost = 0;
1141: }
1142: } else {
1143: $canhost = 0;
1144: }
1145: }
1146: }
1147: }
1148: }
1149: if ($canhost) {
1150: if (ref($hostedsessions) eq 'HASH') {
1.1120 raeburn 1151: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1152: my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073 raeburn 1153: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120 raeburn 1154: if (($uint_dom ne '') &&
1155: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073 raeburn 1156: $canhost = 0;
1157: } else {
1158: $canhost = 1;
1159: }
1160: }
1161: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120 raeburn 1162: if (($uint_dom ne '') &&
1163: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073 raeburn 1164: $canhost = 1;
1165: } else {
1166: $canhost = 0;
1167: }
1168: }
1169: }
1170: }
1171: return $canhost;
1172: }
1173:
1.1083 raeburn 1174: sub spare_can_host {
1175: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1176: my $canhost=1;
1.1279 raeburn 1177: my $try_server_hostname = &hostname($try_server);
1178: my $serverhomeID = &get_server_homeID($try_server_hostname);
1179: my $serverhomedom = &host_domain($serverhomeID);
1180: my %defdomdefaults = &get_domain_defaults($serverhomedom);
1181: if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
1182: if ($defdomdefaults{'offloadnow'}{$try_server}) {
1183: $canhost = 0;
1184: }
1185: }
1186: if (($canhost) && ($uint_dom)) {
1187: my @intdoms;
1188: my $internet_names = &get_internet_names($try_server);
1189: if (ref($internet_names) eq 'ARRAY') {
1190: @intdoms = @{$internet_names};
1191: }
1192: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1193: my $remoterev = &get_server_loncaparev(undef,$try_server);
1194: $canhost = &can_host_session($udom,$try_server,$remoterev,
1195: $remotesessions,
1196: $defdomdefaults{'hostedsessions'});
1197: }
1.1083 raeburn 1198: }
1199: return $canhost;
1200: }
1201:
1.1123 raeburn 1202: sub this_host_spares {
1203: my ($dom) = @_;
1.1126 raeburn 1204: my ($dom_in_use,$lonhost_in_use,$result);
1.1123 raeburn 1205: my @hosts = ¤t_machine_ids();
1206: foreach my $lonhost (@hosts) {
1207: if (&host_domain($lonhost) eq $dom) {
1.1126 raeburn 1208: $dom_in_use = $dom;
1209: $lonhost_in_use = $lonhost;
1.1123 raeburn 1210: last;
1211: }
1212: }
1.1126 raeburn 1213: if ($dom_in_use ne '') {
1214: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1215: }
1216: if (ref($result) ne 'HASH') {
1217: $lonhost_in_use = $perlvar{'lonHostID'};
1218: $dom_in_use = &host_domain($lonhost_in_use);
1219: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1220: if (ref($result) ne 'HASH') {
1221: $result = \%spareid;
1222: }
1223: }
1224: return $result;
1225: }
1226:
1227: sub spares_for_offload {
1228: my ($dom_in_use,$lonhost_in_use) = @_;
1229: my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123 raeburn 1230: if (defined($cached)) {
1231: return $result;
1232: } else {
1.1126 raeburn 1233: my $cachetime = 60*60*24;
1234: my %domconfig =
1235: &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
1236: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1237: if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
1238: if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
1239: return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123 raeburn 1240: }
1241: }
1242: }
1243: }
1.1126 raeburn 1244: return;
1.1123 raeburn 1245: }
1246:
1.1129 raeburn 1247: sub get_lonbalancer_config {
1248: my ($servers) = @_;
1249: my ($currbalancer,$currtargets);
1250: if (ref($servers) eq 'HASH') {
1251: foreach my $server (keys(%{$servers})) {
1252: my %what = (
1253: spareid => 1,
1254: perlvar => 1,
1255: );
1256: my ($result,$returnhash) = &get_remote_globals($server,\%what);
1257: if ($result eq 'ok') {
1258: if (ref($returnhash) eq 'HASH') {
1259: if (ref($returnhash->{'perlvar'}) eq 'HASH') {
1260: if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
1261: $currbalancer = $server;
1262: $currtargets = {};
1263: if (ref($returnhash->{'spareid'}) eq 'HASH') {
1264: if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
1265: $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
1266: }
1267: if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
1268: $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
1269: }
1270: }
1271: last;
1272: }
1273: }
1274: }
1275: }
1276: }
1277: }
1278: return ($currbalancer,$currtargets);
1279: }
1280:
1281: sub check_loadbalancing {
1282: my ($uname,$udom) = @_;
1.1191 raeburn 1283: my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1284: $rule_in_effect,$offloadto,$otherserver);
1.1129 raeburn 1285: my $lonhost = $perlvar{'lonHostID'};
1.1175 raeburn 1286: my @hosts = ¤t_machine_ids();
1.1129 raeburn 1287: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1288: my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
1289: my $intdom = &Apache::lonnet::internet_dom($lonhost);
1290: my $serverhomedom = &host_domain($lonhost);
1291:
1292: my $cachetime = 60*60*24;
1293:
1294: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1295: $dom_in_use = $udom;
1296: $homeintdom = 1;
1297: } else {
1298: $dom_in_use = $serverhomedom;
1299: }
1300: my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
1301: unless (defined($cached)) {
1302: my %domconfig =
1303: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
1304: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1305: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129 raeburn 1306: }
1307: }
1308: if (ref($result) eq 'HASH') {
1.1191 raeburn 1309: ($is_balancer,$currtargets,$currrules) =
1310: &check_balancer_result($result,@hosts);
1.1129 raeburn 1311: if ($is_balancer) {
1312: if (ref($currrules) eq 'HASH') {
1313: if ($homeintdom) {
1314: if ($uname ne '') {
1315: if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
1316: my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
1317: if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
1318: $rule_in_effect = $currrules->{'_LC_author'};
1319: } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
1320: $rule_in_effect = $currrules->{'_LC_adv'}
1321: }
1322: }
1323: if ($rule_in_effect eq '') {
1324: my %userenv = &userenvironment($udom,$uname,'inststatus');
1325: if ($userenv{'inststatus'} ne '') {
1326: my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
1327: my ($othertitle,$usertypes,$types) =
1328: &Apache::loncommon::sorted_inst_types($udom);
1329: if (ref($types) eq 'ARRAY') {
1330: foreach my $type (@{$types}) {
1331: if (grep(/^\Q$type\E$/,@statuses)) {
1332: if (exists($currrules->{$type})) {
1333: $rule_in_effect = $currrules->{$type};
1334: }
1335: }
1336: }
1337: }
1338: } else {
1339: if (exists($currrules->{'default'})) {
1340: $rule_in_effect = $currrules->{'default'};
1341: }
1342: }
1343: }
1344: } else {
1345: if (exists($currrules->{'default'})) {
1346: $rule_in_effect = $currrules->{'default'};
1347: }
1348: }
1349: } else {
1350: if ($currrules->{'_LC_external'} ne '') {
1351: $rule_in_effect = $currrules->{'_LC_external'};
1352: }
1353: }
1354: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1355: $uname,$udom);
1356: }
1357: }
1358: } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1239 raeburn 1359: ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129 raeburn 1360: unless (defined($cached)) {
1361: my %domconfig =
1362: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
1363: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1364: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129 raeburn 1365: }
1366: }
1367: if (ref($result) eq 'HASH') {
1.1191 raeburn 1368: ($is_balancer,$currtargets,$currrules) =
1369: &check_balancer_result($result,@hosts);
1370: if ($is_balancer) {
1.1129 raeburn 1371: if (ref($currrules) eq 'HASH') {
1372: if ($currrules->{'_LC_internetdom'} ne '') {
1373: $rule_in_effect = $currrules->{'_LC_internetdom'};
1374: }
1375: }
1376: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1377: $uname,$udom);
1378: }
1379: } else {
1380: if ($perlvar{'lonBalancer'} eq 'yes') {
1381: $is_balancer = 1;
1382: $offloadto = &this_host_spares($dom_in_use);
1383: }
1384: }
1385: } else {
1386: if ($perlvar{'lonBalancer'} eq 'yes') {
1387: $is_balancer = 1;
1388: $offloadto = &this_host_spares($dom_in_use);
1389: }
1390: }
1.1176 raeburn 1391: if ($is_balancer) {
1392: my $lowest_load = 30000;
1393: if (ref($offloadto) eq 'HASH') {
1394: if (ref($offloadto->{'primary'}) eq 'ARRAY') {
1395: foreach my $try_server (@{$offloadto->{'primary'}}) {
1396: ($otherserver,$lowest_load) =
1397: &compare_server_load($try_server,$otherserver,$lowest_load);
1398: }
1.1129 raeburn 1399: }
1.1176 raeburn 1400: my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129 raeburn 1401:
1.1176 raeburn 1402: if (!$found_server) {
1403: if (ref($offloadto->{'default'}) eq 'ARRAY') {
1404: foreach my $try_server (@{$offloadto->{'default'}}) {
1405: ($otherserver,$lowest_load) =
1406: &compare_server_load($try_server,$otherserver,$lowest_load);
1407: }
1408: }
1409: }
1410: } elsif (ref($offloadto) eq 'ARRAY') {
1411: if (@{$offloadto} == 1) {
1412: $otherserver = $offloadto->[0];
1413: } elsif (@{$offloadto} > 1) {
1414: foreach my $try_server (@{$offloadto}) {
1.1129 raeburn 1415: ($otherserver,$lowest_load) =
1416: &compare_server_load($try_server,$otherserver,$lowest_load);
1417: }
1418: }
1419: }
1.1176 raeburn 1420: if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
1421: $is_balancer = 0;
1422: if ($uname ne '' && $udom ne '') {
1423: if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1424:
1425: &appenv({'user.loadbalexempt' => $lonhost,
1426: 'user.loadbalcheck.time' => time});
1427: }
1.1129 raeburn 1428: }
1429: }
1430: }
1431: return ($is_balancer,$otherserver);
1432: }
1433:
1.1191 raeburn 1434: sub check_balancer_result {
1435: my ($result,@hosts) = @_;
1436: my ($is_balancer,$currtargets,$currrules);
1437: if (ref($result) eq 'HASH') {
1438: if ($result->{'lonhost'} ne '') {
1439: my $currbalancer = $result->{'lonhost'};
1440: if (grep(/^\Q$currbalancer\E$/,@hosts)) {
1441: $is_balancer = 1;
1442: $currtargets = $result->{'targets'};
1443: $currrules = $result->{'rules'};
1444: }
1445: } else {
1446: foreach my $key (keys(%{$result})) {
1447: if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
1448: (ref($result->{$key}) eq 'HASH')) {
1449: $is_balancer = 1;
1450: $currrules = $result->{$key}{'rules'};
1451: $currtargets = $result->{$key}{'targets'};
1452: last;
1453: }
1454: }
1455: }
1456: }
1457: return ($is_balancer,$currtargets,$currrules);
1458: }
1459:
1.1129 raeburn 1460: sub get_loadbalancer_targets {
1461: my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
1462: my $offloadto;
1.1175 raeburn 1463: if ($rule_in_effect eq 'none') {
1464: return [$perlvar{'lonHostID'}];
1465: } elsif ($rule_in_effect eq '') {
1.1129 raeburn 1466: $offloadto = $currtargets;
1467: } else {
1468: if ($rule_in_effect eq 'homeserver') {
1469: my $homeserver = &homeserver($uname,$udom);
1470: if ($homeserver ne 'no_host') {
1471: $offloadto = [$homeserver];
1472: }
1473: } elsif ($rule_in_effect eq 'externalbalancer') {
1474: my %domconfig =
1475: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1476: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1477: if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
1478: if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
1479: $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
1480: }
1481: }
1482: } else {
1.1178 raeburn 1483: my %servers = &internet_dom_servers($udom);
1.1129 raeburn 1484: my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
1485: if (&hostname($remotebalancer) ne '') {
1486: $offloadto = [$remotebalancer];
1487: }
1488: }
1489: } elsif (&hostname($rule_in_effect) ne '') {
1490: $offloadto = [$rule_in_effect];
1491: }
1492: }
1493: return $offloadto;
1494: }
1495:
1.1127 raeburn 1496: sub internet_dom_servers {
1497: my ($dom) = @_;
1498: my (%uniqservers,%servers);
1499: my $primaryserver = &hostname(&domain($dom,'primary'));
1500: my @machinedoms = &machine_domains($primaryserver);
1501: foreach my $mdom (@machinedoms) {
1502: my %currservers = %servers;
1503: my %server = &get_servers($mdom);
1504: %servers = (%currservers,%server);
1505: }
1506: my %by_hostname;
1507: foreach my $id (keys(%servers)) {
1508: push(@{$by_hostname{$servers{$id}}},$id);
1509: }
1510: foreach my $hostname (sort(keys(%by_hostname))) {
1511: if (@{$by_hostname{$hostname}} > 1) {
1512: my $match = 0;
1513: foreach my $id (@{$by_hostname{$hostname}}) {
1514: if (&host_domain($id) eq $dom) {
1515: $uniqservers{$id} = $hostname;
1516: $match = 1;
1517: }
1518: }
1519: unless ($match) {
1520: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1521: }
1522: } else {
1523: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1524: }
1525: }
1526: return %uniqservers;
1527: }
1528:
1.1 albertel 1529: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 1530:
1.599 albertel 1531: my %homecache;
1.1 albertel 1532: sub homeserver {
1.230 stredwic 1533: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 1534: my $index="$uname:$udom";
1.426 albertel 1535:
1.599 albertel 1536: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 1537:
1538: my %servers = &get_servers($udom,'library');
1539: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 1540: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 1541: exists($badServerCache{$tryserver}));
1.841 albertel 1542:
1543: my $answer=reply("home:$udom:$uname",$tryserver);
1544: if ($answer eq 'found') {
1545: delete($badServerCache{$tryserver});
1546: return $homecache{$index}=$tryserver;
1547: } elsif ($answer eq 'no_host') {
1548: $badServerCache{$tryserver}=1;
1549: }
1.1 albertel 1550: }
1551: return 'no_host';
1.70 www 1552: }
1553:
1554: # ------------------------------------- Find the usernames behind a list of IDs
1555:
1556: sub idget {
1557: my ($udom,@ids)=@_;
1558: my %returnhash=();
1559:
1.841 albertel 1560: my %servers = &get_servers($udom,'library');
1561: foreach my $tryserver (keys(%servers)) {
1562: my $idlist=join('&',@ids);
1563: $idlist=~tr/A-Z/a-z/;
1564: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
1565: my @answer=();
1566: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1567: @answer=split(/\&/,$reply);
1568: } ;
1569: my $i;
1570: for ($i=0;$i<=$#ids;$i++) {
1571: if ($answer[$i]) {
1572: $returnhash{$ids[$i]}=$answer[$i];
1573: }
1574: }
1575: }
1.70 www 1576: return %returnhash;
1577: }
1578:
1579: # ------------------------------------- Find the IDs behind a list of usernames
1580:
1581: sub idrget {
1582: my ($udom,@unames)=@_;
1583: my %returnhash=();
1.800 albertel 1584: foreach my $uname (@unames) {
1585: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 1586: }
1.70 www 1587: return %returnhash;
1588: }
1589:
1590: # ------------------------------- Store away a list of names and associated IDs
1591:
1592: sub idput {
1593: my ($udom,%ids)=@_;
1594: my %servers=();
1.800 albertel 1595: foreach my $uname (keys(%ids)) {
1596: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1597: my $uhom=&homeserver($uname,$udom);
1.70 www 1598: if ($uhom ne 'no_host') {
1.800 albertel 1599: my $id=&escape($ids{$uname});
1.70 www 1600: $id=~tr/A-Z/a-z/;
1.800 albertel 1601: my $esc_unam=&escape($uname);
1.70 www 1602: if ($servers{$uhom}) {
1.800 albertel 1603: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70 www 1604: } else {
1.800 albertel 1605: $servers{$uhom}=$id.'='.$esc_unam;
1.70 www 1606: }
1607: }
1.191 harris41 1608: }
1.800 albertel 1609: foreach my $server (keys(%servers)) {
1610: &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191 harris41 1611: }
1.344 www 1612: }
1613:
1.1231 raeburn 1614: # ---------------------------------------- Delete unwanted IDs from ids.db file
1615:
1616: sub iddel {
1617: my ($udom,$idshashref,$uhome)=@_;
1618: my %result=();
1619: unless (ref($idshashref) eq 'HASH') {
1620: return %result;
1621: }
1622: my %servers=();
1623: while (my ($id,$uname) = each(%{$idshashref})) {
1624: my $uhom;
1625: if ($uhome) {
1626: $uhom = $uhome;
1627: } else {
1628: $uhom=&homeserver($uname,$udom);
1629: }
1630: if ($uhom ne 'no_host') {
1631: if ($servers{$uhom}) {
1632: $servers{$uhom}.='&'.&escape($id);
1633: } else {
1634: $servers{$uhom}=&escape($id);
1635: }
1636: }
1637: }
1638: foreach my $server (keys(%servers)) {
1639: $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
1640: }
1641: return %result;
1642: }
1643:
1.1023 raeburn 1644: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 1645: sub dump_dom {
1.1165 droeschl 1646: my ($namespace, $udom, $regexp) = @_;
1647:
1648: $udom ||= $env{'user.domain'};
1649:
1650: return () unless $udom;
1651:
1652: return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012 raeburn 1653: }
1654:
1.1023 raeburn 1655: # ------------------------------------------ get items from domain db files
1.806 raeburn 1656:
1657: sub get_dom {
1.860 raeburn 1658: my ($namespace,$storearr,$udom,$uhome)=@_;
1.1267 raeburn 1659: return if ($udom eq 'public');
1.806 raeburn 1660: my $items='';
1661: foreach my $item (@$storearr) {
1662: $items.=&escape($item).'&';
1663: }
1664: $items=~s/\&$//;
1.860 raeburn 1665: if (!$udom) {
1666: $udom=$env{'user.domain'};
1.1267 raeburn 1667: return if ($udom eq 'public');
1.860 raeburn 1668: if (defined(&domain($udom,'primary'))) {
1669: $uhome=&domain($udom,'primary');
1670: } else {
1.874 albertel 1671: undef($uhome);
1.860 raeburn 1672: }
1673: } else {
1674: if (!$uhome) {
1675: if (defined(&domain($udom,'primary'))) {
1676: $uhome=&domain($udom,'primary');
1677: }
1678: }
1679: }
1680: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1681: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866 raeburn 1682: my %returnhash;
1.875 albertel 1683: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 1684: return %returnhash;
1685: }
1.806 raeburn 1686: my @pairs=split(/\&/,$rep);
1687: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1688: return @pairs;
1689: }
1690: my $i=0;
1691: foreach my $item (@$storearr) {
1692: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1693: $i++;
1694: }
1695: return %returnhash;
1696: } else {
1.880 banghart 1697: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 1698: }
1699: }
1700:
1701: # -------------------------------------------- put items in domain db files
1702:
1703: sub put_dom {
1.860 raeburn 1704: my ($namespace,$storehash,$udom,$uhome)=@_;
1705: if (!$udom) {
1706: $udom=$env{'user.domain'};
1707: if (defined(&domain($udom,'primary'))) {
1708: $uhome=&domain($udom,'primary');
1709: } else {
1.874 albertel 1710: undef($uhome);
1.860 raeburn 1711: }
1712: } else {
1713: if (!$uhome) {
1714: if (defined(&domain($udom,'primary'))) {
1715: $uhome=&domain($udom,'primary');
1716: }
1717: }
1718: }
1719: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1720: my $items='';
1721: foreach my $item (keys(%$storehash)) {
1722: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1723: }
1724: $items=~s/\&$//;
1725: return &reply("putdom:$udom:$namespace:$items",$uhome);
1726: } else {
1.860 raeburn 1727: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 1728: }
1729: }
1730:
1.1023 raeburn 1731: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 1732: sub newput_dom {
1.1023 raeburn 1733: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 1734: my $result;
1735: if (!$udom) {
1736: $udom=$env{'user.domain'};
1737: }
1.1023 raeburn 1738: if ($udom) {
1739: my $uname = &get_domainconfiguser($udom);
1740: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 1741: }
1742: return $result;
1743: }
1744:
1.1023 raeburn 1745: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 1746: sub del_dom {
1.1023 raeburn 1747: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 1748: if (ref($storearr) eq 'ARRAY') {
1749: if (!$udom) {
1750: $udom=$env{'user.domain'};
1751: }
1.1023 raeburn 1752: if ($udom) {
1753: my $uname = &get_domainconfiguser($udom);
1754: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 1755: }
1756: }
1757: }
1758:
1.1023 raeburn 1759: # ----------------------------------construct domainconfig user for a domain
1760: sub get_domainconfiguser {
1761: my ($udom) = @_;
1762: return $udom.'-domainconfig';
1763: }
1764:
1.837 raeburn 1765: sub retrieve_inst_usertypes {
1766: my ($udom) = @_;
1767: my (%returnhash,@order);
1.989 raeburn 1768: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1769: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1770: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1256 raeburn 1771: return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989 raeburn 1772: } else {
1773: if (defined(&domain($udom,'primary'))) {
1774: my $uhome=&domain($udom,'primary');
1775: my $rep=&reply("inst_usertypes:$udom",$uhome);
1776: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1256 raeburn 1777: &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989 raeburn 1778: return (\%returnhash,\@order);
1779: }
1780: my ($hashitems,$orderitems) = split(/:/,$rep);
1781: my @pairs=split(/\&/,$hashitems);
1782: foreach my $item (@pairs) {
1783: my ($key,$value)=split(/=/,$item,2);
1784: $key = &unescape($key);
1785: next if ($key =~ /^error: 2 /);
1786: $returnhash{$key}=&thaw_unescape($value);
1787: }
1788: my @esc_order = split(/\&/,$orderitems);
1789: foreach my $item (@esc_order) {
1790: push(@order,&unescape($item));
1791: }
1792: } else {
1.1256 raeburn 1793: &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837 raeburn 1794: }
1.1256 raeburn 1795: return (\%returnhash,\@order);
1.837 raeburn 1796: }
1797: }
1798:
1.868 raeburn 1799: sub is_domainimage {
1800: my ($url) = @_;
1801: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
1802: if (&domain($1) ne '') {
1803: return '1';
1804: }
1805: }
1806: return;
1807: }
1808:
1.899 raeburn 1809: sub inst_directory_query {
1810: my ($srch) = @_;
1811: my $udom = $srch->{'srchdomain'};
1812: my %results;
1813: my $homeserver = &domain($udom,'primary');
1.909 raeburn 1814: my $outcome;
1.899 raeburn 1815: if ($homeserver ne '') {
1.904 albertel 1816: my $queryid=&reply("querysend:instdirsearch:".
1817: &escape($srch->{'srchby'}).':'.
1818: &escape($srch->{'srchterm'}).':'.
1819: &escape($srch->{'srchtype'}),$homeserver);
1820: my $host=&hostname($homeserver);
1821: if ($queryid !~/^\Q$host\E\_/) {
1822: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1823: return;
1824: }
1825: my $response = &get_query_reply($queryid);
1826: my $maxtries = 5;
1827: my $tries = 1;
1828: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1829: $response = &get_query_reply($queryid);
1830: $tries ++;
1831: }
1832:
1833: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 1834: if ($response eq 'unavailable') {
1835: $outcome = $response;
1836: } else {
1837: $outcome = 'ok';
1838: my @matches = split(/\n/,$response);
1839: foreach my $match (@matches) {
1840: my ($key,$value) = split(/=/,$match);
1841: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1842: }
1.899 raeburn 1843: }
1844: }
1845: }
1.909 raeburn 1846: return ($outcome,%results);
1.899 raeburn 1847: }
1848:
1849: sub usersearch {
1850: my ($srch) = @_;
1851: my $dom = $srch->{'srchdomain'};
1852: my %results;
1853: my %libserv = &all_library();
1854: my $query = 'usersearch';
1855: foreach my $tryserver (keys(%libserv)) {
1856: if (&host_domain($tryserver) eq $dom) {
1857: my $host=&hostname($tryserver);
1858: my $queryid=
1.911 raeburn 1859: &reply("querysend:".&escape($query).':'.
1860: &escape($srch->{'srchby'}).':'.
1.899 raeburn 1861: &escape($srch->{'srchtype'}).':'.
1862: &escape($srch->{'srchterm'}),$tryserver);
1863: if ($queryid !~/^\Q$host\E\_/) {
1864: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 1865: next;
1.899 raeburn 1866: }
1867: my $reply = &get_query_reply($queryid);
1868: my $maxtries = 1;
1869: my $tries = 1;
1870: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1871: $reply = &get_query_reply($queryid);
1872: $tries ++;
1873: }
1874: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1875: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1876: } else {
1.911 raeburn 1877: my @matches;
1878: if ($reply =~ /\n/) {
1879: @matches = split(/\n/,$reply);
1880: } else {
1881: @matches = split(/\&/,$reply);
1882: }
1.899 raeburn 1883: foreach my $match (@matches) {
1884: my ($uname,$udom,%userhash);
1.911 raeburn 1885: foreach my $entry (split(/:/,$match)) {
1886: my ($key,$value) =
1887: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 1888: $userhash{$key} = $value;
1889: if ($key eq 'username') {
1890: $uname = $value;
1891: } elsif ($key eq 'domain') {
1892: $udom = $value;
1.911 raeburn 1893: }
1.899 raeburn 1894: }
1895: $results{$uname.':'.$udom} = \%userhash;
1896: }
1897: }
1898: }
1899: }
1900: return %results;
1901: }
1902:
1.912 raeburn 1903: sub get_instuser {
1904: my ($udom,$uname,$id) = @_;
1905: my $homeserver = &domain($udom,'primary');
1906: my ($outcome,%results);
1907: if ($homeserver ne '') {
1908: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1909: &escape($id).':'.&escape($udom),$homeserver);
1910: my $host=&hostname($homeserver);
1911: if ($queryid !~/^\Q$host\E\_/) {
1912: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1913: return;
1914: }
1915: my $response = &get_query_reply($queryid);
1916: my $maxtries = 5;
1917: my $tries = 1;
1918: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1919: $response = &get_query_reply($queryid);
1920: $tries ++;
1921: }
1922: if (!&error($response) && $response ne 'refused') {
1923: if ($response eq 'unavailable') {
1924: $outcome = $response;
1925: } else {
1926: $outcome = 'ok';
1927: my @matches = split(/\n/,$response);
1928: foreach my $match (@matches) {
1929: my ($key,$value) = split(/=/,$match);
1930: $results{&unescape($key)} = &thaw_unescape($value);
1931: }
1932: }
1933: }
1934: }
1935: my %userinfo;
1936: if (ref($results{$uname}) eq 'HASH') {
1937: %userinfo = %{$results{$uname}};
1938: }
1939: return ($outcome,%userinfo);
1940: }
1941:
1942: sub inst_rulecheck {
1.923 raeburn 1943: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 1944: my %returnhash;
1945: if ($udom ne '') {
1946: if (ref($rules) eq 'ARRAY') {
1947: @{$rules} = map {&escape($_);} (@{$rules});
1948: my $rulestr = join(':',@{$rules});
1949: my $homeserver=&domain($udom,'primary');
1950: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1951: my $response;
1952: if ($item eq 'username') {
1953: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
1954: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 1955: $homeserver));
1.923 raeburn 1956: } elsif ($item eq 'id') {
1957: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
1958: ':'.&escape($id).':'.$rulestr,
1959: $homeserver));
1.945 raeburn 1960: } elsif ($item eq 'selfcreate') {
1961: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 1962: &escape($udom).':'.&escape($uname).
1963: ':'.$rulestr,$homeserver));
1.923 raeburn 1964: }
1.912 raeburn 1965: if ($response ne 'refused') {
1966: my @pairs=split(/\&/,$response);
1967: foreach my $item (@pairs) {
1968: my ($key,$value)=split(/=/,$item,2);
1969: $key = &unescape($key);
1970: next if ($key =~ /^error: 2 /);
1971: $returnhash{$key}=&thaw_unescape($value);
1972: }
1973: }
1974: }
1975: }
1976: }
1977: return %returnhash;
1978: }
1979:
1980: sub inst_userrules {
1.923 raeburn 1981: my ($udom,$check) = @_;
1.912 raeburn 1982: my (%ruleshash,@ruleorder);
1983: if ($udom ne '') {
1984: my $homeserver=&domain($udom,'primary');
1985: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1986: my $response;
1987: if ($check eq 'id') {
1988: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 1989: $homeserver);
1.943 raeburn 1990: } elsif ($check eq 'email') {
1991: $response=&reply('instemailrules:'.&escape($udom),
1992: $homeserver);
1.923 raeburn 1993: } else {
1994: $response=&reply('instuserrules:'.&escape($udom),
1995: $homeserver);
1996: }
1.912 raeburn 1997: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 1998: ($response ne 'unknown_cmd') &&
1.912 raeburn 1999: ($response ne 'no_such_host')) {
2000: my ($hashitems,$orderitems) = split(/:/,$response);
2001: my @pairs=split(/\&/,$hashitems);
2002: foreach my $item (@pairs) {
2003: my ($key,$value)=split(/=/,$item,2);
2004: $key = &unescape($key);
2005: next if ($key =~ /^error: 2 /);
2006: $ruleshash{$key}=&thaw_unescape($value);
2007: }
2008: my @esc_order = split(/\&/,$orderitems);
2009: foreach my $item (@esc_order) {
2010: push(@ruleorder,&unescape($item));
2011: }
2012: }
2013: }
2014: }
2015: return (\%ruleshash,\@ruleorder);
2016: }
2017:
1.976 raeburn 2018: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 2019:
2020: sub get_domain_defaults {
1.1240 raeburn 2021: my ($domain,$ignore_cache) = @_;
1.1242 raeburn 2022: return if (($domain eq '') || ($domain eq 'public'));
1.943 raeburn 2023: my $cachetime = 60*60*24;
1.1240 raeburn 2024: unless ($ignore_cache) {
2025: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
2026: if (defined($cached)) {
2027: if (ref($result) eq 'HASH') {
2028: return %{$result};
2029: }
1.943 raeburn 2030: }
2031: }
2032: my %domdefaults;
2033: my %domconfig =
1.989 raeburn 2034: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 2035: 'requestcourses','inststatus',
1.1183 raeburn 2036: 'coursedefaults','usersessions',
1.1258 raeburn 2037: 'requestauthor','selfenrollment',
2038: 'coursecategories'],$domain);
1.1254 raeburn 2039: my @coursetypes = ('official','unofficial','community','textbook');
1.943 raeburn 2040: if (ref($domconfig{'defaults'}) eq 'HASH') {
2041: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
2042: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
2043: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 2044: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 2045: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147 raeburn 2046: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943 raeburn 2047: } else {
2048: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
2049: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
2050: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
2051: }
1.976 raeburn 2052: if (ref($domconfig{'quotas'}) eq 'HASH') {
2053: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
2054: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
2055: } else {
2056: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1229 raeburn 2057: }
1.1177 raeburn 2058: my @usertools = ('aboutme','blog','webdav','portfolio');
1.976 raeburn 2059: foreach my $item (@usertools) {
2060: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
2061: $domdefaults{$item} = $domconfig{'quotas'}{$item};
2062: }
2063: }
1.1229 raeburn 2064: if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
2065: $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
2066: }
1.976 raeburn 2067: }
1.985 raeburn 2068: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1246 raeburn 2069: foreach my $item ('official','unofficial','community','textbook') {
1.985 raeburn 2070: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
2071: }
2072: }
1.1183 raeburn 2073: if (ref($domconfig{'requestauthor'}) eq 'HASH') {
2074: $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
2075: }
1.989 raeburn 2076: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1256 raeburn 2077: foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989 raeburn 2078: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
2079: }
2080: }
1.1047 raeburn 2081: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1230 raeburn 2082: $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
1.1277 raeburn 2083: $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
2084: $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
2085: if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
2086: $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
2087: }
1.1254 raeburn 2088: foreach my $type (@coursetypes) {
2089: if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
2090: unless ($type eq 'community') {
2091: $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
2092: }
2093: }
2094: if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
2095: $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
2096: }
1.1277 raeburn 2097: if ($domdefaults{'postsubmit'} eq 'on') {
2098: if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
2099: $domdefaults{$type.'postsubtimeout'} =
2100: $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
2101: }
2102: }
1.1230 raeburn 2103: }
1.1286 ! raeburn 2104: if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
! 2105: if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
! 2106: my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
! 2107: if (@clonecodes) {
! 2108: $domdefaults{'canclone'} = join('+',@clonecodes);
! 2109: }
! 2110: }
! 2111: } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
! 2112: $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
! 2113: }
1.1047 raeburn 2114: }
1.1073 raeburn 2115: if (ref($domconfig{'usersessions'}) eq 'HASH') {
2116: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
2117: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
2118: }
2119: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
2120: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
2121: }
1.1279 raeburn 2122: if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
2123: $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
2124: }
1.1073 raeburn 2125: }
1.1254 raeburn 2126: if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
2127: if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
2128: my @settings = ('types','registered','enroll_dates','access_dates','section',
2129: 'approval','limit');
2130: foreach my $type (@coursetypes) {
2131: if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
2132: my @mgrdc = ();
2133: foreach my $item (@settings) {
2134: if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
2135: push(@mgrdc,$item);
2136: }
2137: }
2138: if (@mgrdc) {
2139: $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
2140: }
2141: }
2142: }
2143: }
2144: if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
2145: foreach my $type (@coursetypes) {
2146: if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
2147: foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
2148: $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
2149: }
2150: }
2151: }
2152: }
2153: }
1.1258 raeburn 2154: if (ref($domconfig{'coursecategories'}) eq 'HASH') {
2155: $domdefaults{'catauth'} = 'std';
2156: $domdefaults{'catunauth'} = 'std';
2157: if ($domconfig{'coursecategories'}{'auth'}) {
2158: $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
2159: }
2160: if ($domconfig{'coursecategories'}{'unauth'}) {
2161: $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
2162: }
2163: }
1.1219 raeburn 2164: &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943 raeburn 2165: return %domdefaults;
2166: }
2167:
1.344 www 2168: # --------------------------------------------------- Assign a key to a student
2169:
2170: sub assign_access_key {
1.364 www 2171: #
2172: # a valid key looks like uname:udom#comments
2173: # comments are being appended
2174: #
1.498 www 2175: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
2176: $kdom=
1.620 albertel 2177: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 2178: $knum=
1.620 albertel 2179: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 2180: $cdom=
1.620 albertel 2181: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2182: $cnum=
1.620 albertel 2183: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2184: $udom=$env{'user.name'} unless (defined($udom));
2185: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 2186: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 2187: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 2188: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 2189: # assigned to this person
2190: # - this should not happen,
1.345 www 2191: # unless something went wrong
2192: # the first time around
2193: # ready to assign
1.364 www 2194: $logentry=$1.'; '.$logentry;
1.496 www 2195: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 2196: $kdom,$knum) eq 'ok') {
1.345 www 2197: # key now belongs to user
1.346 www 2198: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 2199: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 2200: &appenv({'environment.'.$envkey => $ckey});
1.345 www 2201: return 'ok';
2202: } else {
2203: return
2204: 'error: Count not permanently assign key, will need to be re-entered later.';
2205: }
2206: } else {
2207: return 'error: Could not assign key, try again later.';
2208: }
1.364 www 2209: } elsif (!$existing{$ckey}) {
1.345 www 2210: # the key does not exist
2211: return 'error: The key does not exist';
2212: } else {
2213: # the key is somebody else's
2214: return 'error: The key is already in use';
2215: }
1.344 www 2216: }
2217:
1.364 www 2218: # ------------------------------------------ put an additional comment on a key
2219:
2220: sub comment_access_key {
2221: #
2222: # a valid key looks like uname:udom#comments
2223: # comments are being appended
2224: #
2225: my ($ckey,$cdom,$cnum,$logentry)=@_;
2226: $cdom=
1.620 albertel 2227: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 2228: $cnum=
1.620 albertel 2229: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 2230: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2231: if ($existing{$ckey}) {
2232: $existing{$ckey}.='; '.$logentry;
2233: # ready to assign
1.367 www 2234: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 2235: $cdom,$cnum) eq 'ok') {
2236: return 'ok';
2237: } else {
2238: return 'error: Count not store comment.';
2239: }
2240: } else {
2241: # the key does not exist
2242: return 'error: The key does not exist';
2243: }
2244: }
2245:
1.344 www 2246: # ------------------------------------------------------ Generate a set of keys
2247:
2248: sub generate_access_keys {
1.364 www 2249: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 2250: $cdom=
1.620 albertel 2251: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2252: $cnum=
1.620 albertel 2253: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 2254: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 2255: unless (($cdom) && ($cnum)) { return 0; }
2256: if ($number>10000) { return 0; }
2257: sleep(2); # make sure don't get same seed twice
2258: srand(time()^($$+($$<<15))); # from "Programming Perl"
2259: my $total=0;
2260: for (my $i=1;$i<=$number;$i++) {
2261: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
2262: sprintf("%lx",int(100000*rand)).'-'.
2263: sprintf("%lx",int(100000*rand));
2264: $newkey=~s/1/g/g; # folks mix up 1 and l
2265: $newkey=~s/0/h/g; # and also 0 and O
2266: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
2267: if ($existing{$newkey}) {
2268: $i--;
2269: } else {
1.364 www 2270: if (&put('accesskeys',
2271: { $newkey => '# generated '.localtime().
1.620 albertel 2272: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 2273: '; '.$logentry },
2274: $cdom,$cnum) eq 'ok') {
1.344 www 2275: $total++;
2276: }
2277: }
2278: }
1.620 albertel 2279: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 2280: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
2281: return $total;
2282: }
2283:
2284: # ------------------------------------------------------- Validate an accesskey
2285:
2286: sub validate_access_key {
2287: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
2288: $cdom=
1.620 albertel 2289: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2290: $cnum=
1.620 albertel 2291: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2292: $udom=$env{'user.domain'} unless (defined($udom));
2293: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 2294: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 2295: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 2296: }
2297:
2298: # ------------------------------------- Find the section of student in a course
1.652 albertel 2299: sub devalidate_getsection_cache {
2300: my ($udom,$unam,$courseid)=@_;
2301: my $hashid="$udom:$unam:$courseid";
2302: &devalidate_cache_new('getsection',$hashid);
2303: }
1.298 matthew 2304:
1.815 albertel 2305: sub courseid_to_courseurl {
2306: my ($courseid) = @_;
2307: #already url style courseid
2308: return $courseid if ($courseid =~ m{^/});
2309:
2310: if (exists($env{'course.'.$courseid.'.num'})) {
2311: my $cnum = $env{'course.'.$courseid.'.num'};
2312: my $cdom = $env{'course.'.$courseid.'.domain'};
2313: return "/$cdom/$cnum";
2314: }
2315:
2316: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
2317: if (exists($courseinfo{'num'})) {
2318: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
2319: }
2320:
2321: return undef;
2322: }
2323:
1.298 matthew 2324: sub getsection {
2325: my ($udom,$unam,$courseid)=@_;
1.599 albertel 2326: my $cachetime=1800;
1.551 albertel 2327:
2328: my $hashid="$udom:$unam:$courseid";
1.599 albertel 2329: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 2330: if (defined($cached)) { return $result; }
2331:
1.298 matthew 2332: my %Pending;
2333: my %Expired;
2334: #
2335: # Each role can either have not started yet (pending), be active,
2336: # or have expired.
2337: #
2338: # If there is an active role, we are done.
2339: #
2340: # If there is more than one role which has not started yet,
2341: # choose the one which will start sooner
2342: # If there is one role which has not started yet, return it.
2343: #
2344: # If there is more than one expired role, choose the one which ended last.
2345: # If there is a role which has expired, return it.
2346: #
1.815 albertel 2347: $courseid = &courseid_to_courseurl($courseid);
1.1166 raeburn 2348: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817 raeburn 2349: foreach my $key (keys(%roleshash)) {
1.479 albertel 2350: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 2351: my $section=$1;
2352: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 2353: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 2354: my $now=time;
1.548 albertel 2355: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 2356: $Expired{$end}=$section;
2357: next;
2358: }
1.548 albertel 2359: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 2360: $Pending{$start}=$section;
2361: next;
2362: }
1.599 albertel 2363: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 2364: }
2365: #
2366: # Presumedly there will be few matching roles from the above
2367: # loop and the sorting time will be negligible.
2368: if (scalar(keys(%Pending))) {
2369: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 2370: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 2371: }
2372: if (scalar(keys(%Expired))) {
2373: my @sorted = sort {$a <=> $b} keys(%Expired);
2374: my $time = pop(@sorted);
1.599 albertel 2375: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 2376: }
1.599 albertel 2377: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 2378: }
1.70 www 2379:
1.599 albertel 2380: sub save_cache {
2381: &purge_remembered();
1.722 albertel 2382: #&Apache::loncommon::validate_page();
1.620 albertel 2383: undef(%env);
1.780 albertel 2384: undef($env_loaded);
1.599 albertel 2385: }
1.452 albertel 2386:
1.599 albertel 2387: my $to_remember=-1;
2388: my %remembered;
2389: my %accessed;
2390: my $kicks=0;
2391: my $hits=0;
1.849 albertel 2392: sub make_key {
2393: my ($name,$id) = @_;
1.872 albertel 2394: if (length($id) > 65
2395: && length(&escape($id)) > 200) {
2396: $id=length($id).':'.&Digest::MD5::md5_hex($id);
2397: }
1.849 albertel 2398: return &escape($name.':'.$id);
2399: }
2400:
1.599 albertel 2401: sub devalidate_cache_new {
2402: my ($name,$id,$debug) = @_;
2403: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849 albertel 2404: $id=&make_key($name,$id);
1.599 albertel 2405: $memcache->delete($id);
2406: delete($remembered{$id});
2407: delete($accessed{$id});
2408: }
2409:
2410: sub is_cached_new {
2411: my ($name,$id,$debug) = @_;
1.849 albertel 2412: $id=&make_key($name,$id);
1.599 albertel 2413: if (exists($remembered{$id})) {
1.1133 foxr 2414: if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
1.599 albertel 2415: $accessed{$id}=[&gettimeofday()];
2416: $hits++;
2417: return ($remembered{$id},1);
2418: }
2419: my $value = $memcache->get($id);
2420: if (!(defined($value))) {
2421: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 2422: return (undef,undef);
1.416 albertel 2423: }
1.599 albertel 2424: if ($value eq '__undef__') {
2425: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
2426: $value=undef;
2427: }
2428: &make_room($id,$value,$debug);
2429: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
2430: return ($value,1);
2431: }
2432:
2433: sub do_cache_new {
2434: my ($name,$id,$value,$time,$debug) = @_;
1.849 albertel 2435: $id=&make_key($name,$id);
1.599 albertel 2436: my $setvalue=$value;
2437: if (!defined($setvalue)) {
2438: $setvalue='__undef__';
2439: }
1.623 albertel 2440: if (!defined($time) ) {
2441: $time=600;
2442: }
1.599 albertel 2443: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 2444: my $result = $memcache->set($id,$setvalue,$time);
2445: if (! $result) {
1.872 albertel 2446: &logthis("caching of id -> $id failed");
1.910 albertel 2447: $memcache->disconnect_all();
1.872 albertel 2448: }
1.600 albertel 2449: # need to make a copy of $value
1.919 albertel 2450: &make_room($id,$value,$debug);
1.599 albertel 2451: return $value;
2452: }
2453:
2454: sub make_room {
2455: my ($id,$value,$debug)=@_;
1.919 albertel 2456:
2457: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
2458: : $value;
1.599 albertel 2459: if ($to_remember<0) { return; }
2460: $accessed{$id}=[&gettimeofday()];
2461: if (scalar(keys(%remembered)) <= $to_remember) { return; }
2462: my $to_kick;
2463: my $max_time=0;
2464: foreach my $other (keys(%accessed)) {
2465: if (&tv_interval($accessed{$other}) > $max_time) {
2466: $to_kick=$other;
2467: $max_time=&tv_interval($accessed{$other});
2468: }
2469: }
2470: delete($remembered{$to_kick});
2471: delete($accessed{$to_kick});
2472: $kicks++;
2473: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 2474: return;
2475: }
2476:
1.599 albertel 2477: sub purge_remembered {
1.604 albertel 2478: #&logthis("Tossing ".scalar(keys(%remembered)));
2479: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 2480: undef(%remembered);
2481: undef(%accessed);
1.428 albertel 2482: }
1.70 www 2483: # ------------------------------------- Read an entry from a user's environment
2484:
2485: sub userenvironment {
2486: my ($udom,$unam,@what)=@_;
1.976 raeburn 2487: my $items;
2488: foreach my $item (@what) {
2489: $items.=&escape($item).'&';
2490: }
2491: $items=~s/\&$//;
1.70 www 2492: my %returnhash=();
1.1009 raeburn 2493: my $uhome = &homeserver($unam,$udom);
2494: unless ($uhome eq 'no_host') {
2495: my @answer=split(/\&/,
2496: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 2497: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
2498: return %returnhash;
2499: }
1.1009 raeburn 2500: my $i;
2501: for ($i=0;$i<=$#what;$i++) {
2502: $returnhash{$what[$i]}=&unescape($answer[$i]);
2503: }
1.70 www 2504: }
2505: return %returnhash;
1.1 albertel 2506: }
2507:
1.617 albertel 2508: # ---------------------------------------------------------- Get a studentphoto
2509: sub studentphoto {
2510: my ($udom,$unam,$ext) = @_;
2511: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 2512: if (defined($env{'request.course.id'})) {
1.708 raeburn 2513: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 2514: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
2515: return(&retrievestudentphoto($udom,$unam,$ext));
2516: } else {
2517: my ($result,$perm_reqd)=
1.707 albertel 2518: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2519: if ($result eq 'ok') {
2520: if (!($perm_reqd eq 'yes')) {
2521: return(&retrievestudentphoto($udom,$unam,$ext));
2522: }
2523: }
2524: }
2525: }
2526: } else {
2527: my ($result,$perm_reqd) =
1.707 albertel 2528: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2529: if ($result eq 'ok') {
2530: if (!($perm_reqd eq 'yes')) {
2531: return(&retrievestudentphoto($udom,$unam,$ext));
2532: }
2533: }
2534: }
2535: return '/adm/lonKaputt/lonlogo_broken.gif';
2536: }
2537:
2538: sub retrievestudentphoto {
2539: my ($udom,$unam,$ext,$type) = @_;
2540: my $home=&Apache::lonnet::homeserver($unam,$udom);
2541: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
2542: if ($ret eq 'ok') {
2543: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
2544: if ($type eq 'thumbnail') {
2545: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
2546: }
2547: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
2548: return $tokenurl;
2549: } else {
2550: if ($type eq 'thumbnail') {
2551: return '/adm/lonKaputt/genericstudent_tn.gif';
2552: } else {
2553: return '/adm/lonKaputt/lonlogo_broken.gif';
2554: }
1.617 albertel 2555: }
2556: }
2557:
1.263 www 2558: # -------------------------------------------------------------------- New chat
2559:
2560: sub chatsend {
1.724 raeburn 2561: my ($newentry,$anon,$group)=@_;
1.620 albertel 2562: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
2563: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2564: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 2565: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 2566: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 2567: &escape($newentry)).':'.$group,$chome);
1.292 www 2568: }
2569:
2570: # ------------------------------------------ Find current version of a resource
2571:
2572: sub getversion {
2573: my $fname=&clutter(shift);
1.1189 raeburn 2574: unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292 www 2575: return ¤tversion(&filelocation('',$fname));
2576: }
2577:
2578: sub currentversion {
2579: my $fname=shift;
2580: my $author=$fname;
2581: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2582: my ($udom,$uname)=split(/\//,$author);
1.1112 www 2583: my $home=&homeserver($uname,$udom);
1.292 www 2584: if ($home eq 'no_host') {
2585: return -1;
2586: }
1.1112 www 2587: my $answer=&reply("currentversion:$fname",$home);
1.292 www 2588: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2589: return -1;
2590: }
1.1112 www 2591: return $answer;
1.263 www 2592: }
2593:
1.1111 www 2594: #
2595: # Return special version number of resource if set by override, empty otherwise
2596: #
2597: sub usedversion {
2598: my $fname=shift;
2599: unless ($fname) { $fname=$env{'request.uri'}; }
2600: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
2601: if ($urlversion) { return $urlversion; }
2602: return '';
2603: }
2604:
1.1 albertel 2605: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 2606:
1.1 albertel 2607: sub subscribe {
2608: my $fname=shift;
1.761 raeburn 2609: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 2610: $fname=~s/[\n\r]//g;
1.1 albertel 2611: my $author=$fname;
2612: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2613: my ($udom,$uname)=split(/\//,$author);
2614: my $home=homeserver($uname,$udom);
1.335 albertel 2615: if ($home eq 'no_host') {
2616: return 'not_found';
1.1 albertel 2617: }
2618: my $answer=reply("sub:$fname",$home);
1.64 www 2619: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2620: $answer.=' by '.$home;
2621: }
1.1 albertel 2622: return $answer;
2623: }
2624:
1.8 www 2625: # -------------------------------------------------------------- Replicate file
2626:
2627: sub repcopy {
2628: my $filename=shift;
1.23 www 2629: $filename=~s/\/+/\//g;
1.1142 raeburn 2630: my $londocroot = $perlvar{'lonDocRoot'};
2631: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164 raeburn 2632: if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142 raeburn 2633: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
2634: $filename=~m{^/*(uploaded|editupload)/}) {
1.538 albertel 2635: return &repcopy_userfile($filename);
2636: }
1.532 albertel 2637: $filename=~s/[\n\r]//g;
1.8 www 2638: my $transname="$filename.in.transfer";
1.828 www 2639: # FIXME: this should flock
1.607 raeburn 2640: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 2641: my $remoteurl=subscribe($filename);
1.64 www 2642: if ($remoteurl =~ /^con_lost by/) {
2643: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2644: return 'unavailable';
1.8 www 2645: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 2646: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 2647: return 'not_found';
1.64 www 2648: } elsif ($remoteurl =~ /^rejected by/) {
2649: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2650: return 'forbidden';
1.20 www 2651: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 2652: return 'ok';
1.8 www 2653: } else {
1.290 www 2654: my $author=$filename;
2655: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2656: my ($udom,$uname)=split(/\//,$author);
2657: my $home=homeserver($uname,$udom);
2658: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 2659: my @parts=split(/\//,$filename);
2660: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142 raeburn 2661: if ($path ne "$londocroot/res") {
1.8 www 2662: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 2663: return 'bad_request';
1.8 www 2664: }
2665: my $count;
2666: for ($count=5;$count<$#parts;$count++) {
2667: $path.="/$parts[$count]";
2668: if ((-e $path)!=1) {
2669: mkdir($path,0777);
2670: }
2671: }
2672: my $ua=new LWP::UserAgent;
2673: my $request=new HTTP::Request('GET',"$remoteurl");
2674: my $response=$ua->request($request,$transname);
2675: if ($response->is_error()) {
2676: unlink($transname);
2677: my $message=$response->status_line;
1.672 albertel 2678: &logthis("<font color=\"blue\">WARNING:"
1.12 www 2679: ." LWP get: $message: $filename</font>");
1.607 raeburn 2680: return 'unavailable';
1.8 www 2681: } else {
1.16 www 2682: if ($remoteurl!~/\.meta$/) {
2683: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2684: my $mresponse=$ua->request($mrequest,$filename.'.meta');
2685: if ($mresponse->is_error()) {
2686: unlink($filename.'.meta');
2687: &logthis(
1.672 albertel 2688: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 2689: }
2690: }
1.8 www 2691: rename($transname,$filename);
1.607 raeburn 2692: return 'ok';
1.8 www 2693: }
1.290 www 2694: }
1.8 www 2695: }
1.330 www 2696: }
2697:
2698: # ------------------------------------------------ Get server side include body
2699: sub ssi_body {
1.381 albertel 2700: my ($filelink,%form)=@_;
1.606 matthew 2701: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
2702: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
2703: }
1.953 www 2704: my $output='';
2705: my $response;
1.980 raeburn 2706: if ($filelink=~/^https?\:/) {
1.954 raeburn 2707: ($output,$response)=&externalssi($filelink);
1.953 www 2708: } else {
1.1004 droeschl 2709: $filelink .= $filelink=~/\?/ ? '&' : '?';
2710: $filelink .= 'inhibitmenu=yes';
1.953 www 2711: ($output,$response)=&ssi($filelink,%form);
2712: }
1.778 albertel 2713: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 2714: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 2715: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 2716: if (wantarray) {
2717: return ($output, $response);
2718: } else {
2719: return $output;
2720: }
1.8 www 2721: }
2722:
1.15 www 2723: # --------------------------------------------------------- Server Side Include
2724:
1.782 albertel 2725: sub absolute_url {
2726: my ($host_name) = @_;
2727: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
2728: if ($host_name eq '') {
2729: $host_name = $ENV{'SERVER_NAME'};
2730: }
2731: return $protocol.$host_name;
2732: }
2733:
1.942 foxr 2734: #
2735: # Server side include.
2736: # Parameters:
2737: # fn Possibly encrypted resource name/id.
2738: # form Hash that describes how the rendering should be done
2739: # and other things.
1.944 foxr 2740: # Returns:
1.950 raeburn 2741: # Scalar context: The content of the response.
2742: # Array context: 2 element list of the content and the full response object.
1.942 foxr 2743: #
1.15 www 2744: sub ssi {
2745:
1.944 foxr 2746: my ($fn,%form)=@_;
1.15 www 2747: my $ua=new LWP::UserAgent;
1.23 www 2748: my $request;
1.711 albertel 2749:
2750: $form{'no_update_last_known'}=1;
1.895 albertel 2751: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 2752: if (%form) {
1.782 albertel 2753: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1272 droeschl 2754: $request->content(join('&',map {
2755: my $name = escape($_);
2756: "$name=" . ( ref($form{$_}) eq 'ARRAY'
2757: ? join("&$name=", map {escape($_) } @{$form{$_}})
2758: : &escape($form{$_}) );
2759: } keys(%form)));
1.23 www 2760: } else {
1.782 albertel 2761: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 2762: }
2763:
1.15 www 2764: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1173 foxr 2765: my $response= $ua->request($request);
1.1182 foxr 2766: my $content = $response->content;
2767:
2768:
1.944 foxr 2769: if (wantarray) {
1.1173 foxr 2770: return ($content, $response);
1.944 foxr 2771: } else {
1.1173 foxr 2772: return $content;
1.942 foxr 2773: }
1.324 www 2774: }
2775:
2776: sub externalssi {
2777: my ($url)=@_;
2778: my $ua=new LWP::UserAgent;
2779: my $request=new HTTP::Request('GET',$url);
2780: my $response=$ua->request($request);
1.954 raeburn 2781: if (wantarray) {
2782: return ($response->content, $response);
2783: } else {
2784: return $response->content;
2785: }
1.15 www 2786: }
1.254 www 2787:
1.492 albertel 2788: # -------------------------------- Allow a /uploaded/ URI to be vouched for
2789:
2790: sub allowuploaded {
2791: my ($srcurl,$url)=@_;
2792: $url=&clutter(&declutter($url));
2793: my $dir=$url;
2794: $dir=~s/\/[^\/]+$//;
2795: my %httpref=();
2796: my $httpurl=&hreflocation('',$url);
2797: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 2798: &Apache::lonnet::appenv(\%httpref);
1.254 www 2799: }
1.477 raeburn 2800:
1.1193 raeburn 2801: #
2802: # Determine if the current user should be able to edit a particular resource,
2803: # when viewing in course context.
2804: # (a) When viewing resource used to determine if "Edit" item is included in
2805: # Functions.
2806: # (b) When displaying folder contents in course editor, used to determine if
2807: # "Edit" link will be displayed alongside resource.
2808: #
1.1196 raeburn 2809: # input: six args -- filename (decluttered), course number, course domain,
2810: # url, symb (if registered) and group (if this is a group
2811: # item -- e.g., bulletin board, group page etc.).
2812: # output: array of five scalars --
1.1193 raeburn 2813: # $cfile -- url for file editing if editable on current server
2814: # $home -- homeserver of resource (i.e., for author if published,
2815: # or course if uploaded.).
2816: # $switchserver -- 1 if server switch will be needed.
1.1196 raeburn 2817: # $forceedit -- 1 if icon/link should be to go to edit mode
2818: # $forceview -- 1 if icon/link should be to go to view mode
1.1193 raeburn 2819: #
2820:
2821: sub can_edit_resource {
1.1194 raeburn 2822: my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
2823: my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
2824: #
2825: # For aboutme pages user can only edit his/her own.
2826: #
1.1199 raeburn 2827: if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
1.1194 raeburn 2828: my ($sdom,$sname) = ($1,$2);
2829: if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
2830: $home = $env{'user.home'};
2831: $cfile = $resurl;
2832: if ($env{'form.forceedit'}) {
2833: $forceview = 1;
2834: } else {
2835: $forceedit = 1;
2836: }
2837: return ($cfile,$home,$switchserver,$forceedit,$forceview);
2838: } else {
2839: return;
2840: }
2841: }
2842:
2843: if ($env{'request.course.id'}) {
2844: my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
2845: if ($group ne '') {
2846: # if this is a group homepage or group bulletin board, check group privs
2847: my $allowed = 0;
1.1197 raeburn 2848: if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
2849: if ((&allowed('mdg',$env{'request.course.id'}.
1.1198 raeburn 2850: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
1.1194 raeburn 2851: (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
2852: $allowed = 1;
2853: }
1.1197 raeburn 2854: } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
2855: if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
2856: (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
1.1194 raeburn 2857: $allowed = 1;
2858: }
2859: }
2860: if ($allowed) {
2861: $home=&homeserver($cnum,$cdom);
2862: if ($env{'form.forceedit'}) {
2863: $forceview = 1;
2864: } else {
2865: $forceedit = 1;
2866: }
2867: $cfile = $resurl;
2868: } else {
2869: return;
2870: }
2871: } else {
1.1208 raeburn 2872: if ($resurl =~ m{^/?adm/viewclasslist$}) {
2873: unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
2874: return;
2875: }
2876: } elsif (!$crsedit) {
1.1194 raeburn 2877: #
2878: # No edit allowed where CC has switched to student role.
2879: #
2880: return;
2881: }
2882: }
2883: }
2884:
1.1193 raeburn 2885: if ($file ne '') {
2886: if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
1.1194 raeburn 2887: if (&is_course_upload($file,$cnum,$cdom)) {
2888: $uploaded = 1;
2889: $incourse = 1;
1.1193 raeburn 2890: if ($file =~/\.(htm|html|css|js|txt)$/) {
2891: $cfile = &hreflocation('',$file);
1.1201 raeburn 2892: if ($env{'form.forceedit'}) {
2893: $forceview = 1;
2894: } else {
2895: $forceedit = 1;
2896: }
1.1194 raeburn 2897: }
2898: } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
2899: $incourse = 1;
2900: if ($env{'form.forceedit'}) {
2901: $forceview = 1;
2902: } else {
2903: $forceedit = 1;
2904: }
2905: $cfile = $resurl;
2906: } elsif (($resurl ne '') && (&is_on_map($resurl))) {
2907: if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
2908: $incourse = 1;
2909: if ($env{'form.forceedit'}) {
2910: $forceview = 1;
2911: } else {
2912: $forceedit = 1;
2913: }
2914: $cfile = $resurl;
1.1199 raeburn 2915: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
1.1194 raeburn 2916: $incourse = 1;
2917: $cfile = $resurl.'/smpedit';
1.1199 raeburn 2918: } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
1.1194 raeburn 2919: $incourse = 1;
1.1199 raeburn 2920: if ($env{'form.forceedit'}) {
2921: $forceview = 1;
2922: } else {
2923: $forceedit = 1;
2924: }
2925: $cfile = $resurl;
1.1208 raeburn 2926: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
2927: $incourse = 1;
2928: if ($env{'form.forceedit'}) {
2929: $forceview = 1;
2930: } else {
2931: $forceedit = 1;
2932: }
2933: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1194 raeburn 2934: }
2935: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
2936: my $template = '/res/lib/templates/simpleproblem.problem';
2937: if (&is_on_map($template)) {
2938: $incourse = 1;
2939: $forceview = 1;
2940: $cfile = $template;
1.1193 raeburn 2941: }
1.1199 raeburn 2942: } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
2943: $incourse = 1;
2944: if ($env{'form.forceedit'}) {
2945: $forceview = 1;
2946: } else {
2947: $forceedit = 1;
2948: }
2949: $cfile = $resurl;
2950: } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
2951: $incourse = 1;
2952: $forceview = 1;
2953: if ($symb) {
2954: my ($map,$id,$res)=&decode_symb($symb);
2955: $env{'request.symb'} = $symb;
2956: $cfile = &clutter($res);
2957: } else {
2958: $cfile = $env{'form.suppurl'};
2959: $cfile =~ s{^http://}{};
2960: $cfile = '/adm/wrapper/ext/'.$cfile;
2961: }
1.1234 raeburn 2962: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
2963: if ($env{'form.forceedit'}) {
2964: $forceview = 1;
2965: } else {
2966: $forceedit = 1;
2967: }
2968: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1193 raeburn 2969: }
2970: }
1.1194 raeburn 2971: if ($uploaded || $incourse) {
2972: $home=&homeserver($cnum,$cdom);
1.1207 raeburn 2973: } elsif ($file !~ m{/$}) {
1.1193 raeburn 2974: $file=~s{^(priv/$match_domain/$match_username)}{/$1};
2975: $file=~s{^($match_domain/$match_username)}{/priv/$1};
2976: # Check that the user has permission to edit this resource
2977: my $setpriv = 1;
2978: my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
2979: if (defined($cfudom)) {
2980: $home=&homeserver($cfuname,$cfudom);
2981: $cfile=$file;
2982: }
2983: }
1.1194 raeburn 2984: if (($cfile ne '') && (!$incourse || $uploaded) &&
2985: (($home ne '') && ($home ne 'no_host'))) {
1.1193 raeburn 2986: my @ids=¤t_machine_ids();
2987: unless (grep(/^\Q$home\E$/,@ids)) {
2988: $switchserver=1;
2989: }
2990: }
2991: }
1.1194 raeburn 2992: return ($cfile,$home,$switchserver,$forceedit,$forceview);
1.1193 raeburn 2993: }
2994:
2995: sub is_course_upload {
2996: my ($file,$cnum,$cdom) = @_;
2997: my $uploadpath = &LONCAPA::propath($cdom,$cnum);
2998: $uploadpath =~ s{^\/}{};
1.1201 raeburn 2999: if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
3000: ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
1.1193 raeburn 3001: return 1;
3002: }
3003: return;
3004: }
3005:
1.1194 raeburn 3006: sub in_course {
1.1195 raeburn 3007: my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
3008: if ($hideprivileged) {
3009: my $skipuser;
1.1219 raeburn 3010: my %coursehash = &coursedescription($cdom.'_'.$cnum);
3011: my @possdoms = ($cdom);
3012: if ($coursehash{'checkforpriv'}) {
3013: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
3014: }
3015: if (&privileged($uname,$udom,\@possdoms)) {
1.1195 raeburn 3016: $skipuser = 1;
3017: if ($coursehash{'nothideprivileged'}) {
3018: foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3019: my $user;
3020: if ($item =~ /:/) {
3021: $user = $item;
3022: } else {
3023: $user = join(':',split(/[\@]/,$item));
3024: }
3025: if ($user eq $uname.':'.$udom) {
3026: undef($skipuser);
3027: last;
3028: }
3029: }
3030: }
3031: if ($skipuser) {
3032: return 0;
3033: }
3034: }
3035: }
1.1194 raeburn 3036: $type ||= 'any';
3037: if (!defined($cdom) || !defined($cnum)) {
3038: my $cid = $env{'request.course.id'};
3039: $cdom = $env{'course.'.$cid.'.domain'};
3040: $cnum = $env{'course.'.$cid.'.num'};
3041: }
3042: my $typesref;
1.1195 raeburn 3043: if (($type eq 'any') || ($type eq 'all')) {
1.1194 raeburn 3044: $typesref = ['active','previous','future'];
3045: } elsif ($type eq 'previous' || $type eq 'future') {
3046: $typesref = [$type];
3047: }
3048: my %roles = &get_my_roles($uname,$udom,'userroles',
3049: $typesref,undef,[$cdom]);
3050: my ($tmp) = keys(%roles);
3051: return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
3052: my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
3053: if (@course_roles > 0) {
3054: return 1;
3055: }
3056: return 0;
3057: }
3058:
1.478 albertel 3059: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 3060: # input: action, courseID, current domain, intended
1.637 raeburn 3061: # path to file, source of file, instruction to parse file for objects,
3062: # ref to hash for embedded objects,
3063: # ref to hash for codebase of java objects.
1.1095 raeburn 3064: # reference to scalar to accommodate mime type determined
3065: # from File::MMagic if $parser = parse.
1.637 raeburn 3066: #
1.485 raeburn 3067: # output: url to file (if action was uploaddoc),
3068: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 3069: #
1.478 albertel 3070: # Allows directory structure to be used within lonUsers/../userfiles/ for a
3071: # course.
1.477 raeburn 3072: #
1.478 albertel 3073: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3074: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
3075: # course's home server.
1.477 raeburn 3076: #
1.478 albertel 3077: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
3078: # be copied from $source (current location) to
3079: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3080: # and will then be copied to
3081: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
3082: # course's home server.
1.485 raeburn 3083: #
1.481 raeburn 3084: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 3085: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 3086: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3087: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
3088: # in course's home server.
1.637 raeburn 3089: #
1.477 raeburn 3090:
3091: sub process_coursefile {
1.1095 raeburn 3092: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
3093: $mimetype)=@_;
1.477 raeburn 3094: my $fetchresult;
1.638 albertel 3095: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 3096: if ($action eq 'propagate') {
1.638 albertel 3097: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
3098: $home);
1.481 raeburn 3099: } else {
1.477 raeburn 3100: my $fpath = '';
3101: my $fname = $file;
1.478 albertel 3102: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 3103: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 3104: my $filepath = &build_filepath($fpath);
1.481 raeburn 3105: if ($action eq 'copy') {
3106: if ($source eq '') {
3107: $fetchresult = 'no source file';
3108: return $fetchresult;
3109: } else {
3110: my $destination = $filepath.'/'.$fname;
3111: rename($source,$destination);
3112: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3113: $home);
1.481 raeburn 3114: }
3115: } elsif ($action eq 'uploaddoc') {
3116: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 3117: print $fh $env{'form.'.$source};
1.481 raeburn 3118: close($fh);
1.637 raeburn 3119: if ($parser eq 'parse') {
1.1024 raeburn 3120: my $mm = new File::MMagic;
1.1095 raeburn 3121: my $type = $mm->checktype_filename($filepath.'/'.$fname);
3122: if ($type eq 'text/html') {
1.1024 raeburn 3123: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
3124: unless ($parse_result eq 'ok') {
3125: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
3126: }
1.637 raeburn 3127: }
1.1095 raeburn 3128: if (ref($mimetype)) {
3129: $$mimetype = $type;
3130: }
1.637 raeburn 3131: }
1.477 raeburn 3132: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3133: $home);
1.481 raeburn 3134: if ($fetchresult eq 'ok') {
3135: return '/uploaded/'.$fpath.'/'.$fname;
3136: } else {
3137: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3138: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 3139: return '/adm/notfound.html';
3140: }
1.477 raeburn 3141: }
3142: }
1.485 raeburn 3143: unless ( $fetchresult eq 'ok') {
1.477 raeburn 3144: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3145: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 3146: }
3147: return $fetchresult;
3148: }
3149:
1.637 raeburn 3150: sub build_filepath {
3151: my ($fpath) = @_;
3152: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
3153: unless ($fpath eq '') {
3154: my @parts=split('/',$fpath);
3155: foreach my $part (@parts) {
3156: $filepath.= '/'.$part;
3157: if ((-e $filepath)!=1) {
3158: mkdir($filepath,0777);
3159: }
3160: }
3161: }
3162: return $filepath;
3163: }
3164:
3165: sub store_edited_file {
1.638 albertel 3166: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 3167: my $file = $primary_url;
3168: $file =~ s#^/uploaded/$docudom/$docuname/##;
3169: my $fpath = '';
3170: my $fname = $file;
3171: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
3172: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
3173: my $filepath = &build_filepath($fpath);
3174: open(my $fh,'>'.$filepath.'/'.$fname);
3175: print $fh $content;
3176: close($fh);
1.638 albertel 3177: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 3178: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3179: $home);
1.637 raeburn 3180: if ($$fetchresult eq 'ok') {
3181: return '/uploaded/'.$fpath.'/'.$fname;
3182: } else {
1.638 albertel 3183: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
3184: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 3185: return '/adm/notfound.html';
3186: }
3187: }
3188:
1.531 albertel 3189: sub clean_filename {
1.831 albertel 3190: my ($fname,$args)=@_;
1.315 www 3191: # Replace Windows backslashes by forward slashes
1.257 www 3192: $fname=~s/\\/\//g;
1.831 albertel 3193: if (!$args->{'keep_path'}) {
3194: # Get rid of everything but the actual filename
3195: $fname=~s/^.*\/([^\/]+)$/$1/;
3196: }
1.315 www 3197: # Replace spaces by underscores
3198: $fname=~s/\s+/\_/g;
3199: # Replace all other weird characters by nothing
1.831 albertel 3200: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 3201: # Replace all .\d. sequences with _\d. so they no longer look like version
3202: # numbers
3203: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 3204: return $fname;
3205: }
1.1051 raeburn 3206: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
3207: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
3208: # image with the same aspect ratio as the original, but with dimensions which do
3209: # not exceed $resizewidth and $resizeheight.
3210:
1.984 neumanie 3211: sub resizeImage {
1.1051 raeburn 3212: my ($img_path,$resizewidth,$resizeheight) = @_;
3213: my $ima = Image::Magick->new;
3214: my $resized;
3215: if (-e $img_path) {
3216: $ima->Read($img_path);
3217: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
3218: my $width = $ima->Get('width');
3219: my $height = $ima->Get('height');
3220: if ($width > $resizewidth) {
3221: my $factor = $width/$resizewidth;
3222: my $newheight = $height/$factor;
3223: $ima->Scale(width=>$resizewidth,height=>$newheight);
3224: $resized = 1;
3225: }
3226: }
3227: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
3228: my $width = $ima->Get('width');
3229: my $height = $ima->Get('height');
3230: if ($height > $resizeheight) {
3231: my $factor = $height/$resizeheight;
3232: my $newwidth = $width/$factor;
3233: $ima->Scale(width=>$newwidth,height=>$resizeheight);
3234: $resized = 1;
3235: }
3236: }
3237: if ($resized) {
3238: $ima->Write($img_path);
3239: }
3240: }
3241: return;
1.977 amueller 3242: }
3243:
1.608 albertel 3244: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 3245: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093 raeburn 3246: # the desired filename is in $env{"form.$formname.filename"}
1.1090 raeburn 3247: # $context - possible values: coursedoc, existingfile, overwrite,
3248: # canceloverwrite, or ''.
3249: # if 'coursedoc': upload to the current course
3250: # if 'existingfile': write file to tmp/overwrites directory
3251: # if 'canceloverwrite': delete file written to tmp/overwrites directory
3252: # $context is passed as argument to &finishuserfileupload
1.686 albertel 3253: # $subdir - directory in userfile to store the file into
1.858 raeburn 3254: # $parser - instruction to parse file for objects ($parser = parse)
3255: # $allfiles - reference to hash for embedded objects
3256: # $codebase - reference to hash for codebase of java objects
3257: # $desuname - username for permanent storage of uploaded file
3258: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 3259: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
3260: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 3261: # $resizewidth - width (pixels) to which to resize uploaded image
3262: # $resizeheight - height (pixels) to which to resize uploaded image
1.1095 raeburn 3263: # $mimetype - reference to scalar to accommodate mime type determined
1.1152 raeburn 3264: # from File::MMagic.
1.858 raeburn 3265: #
1.686 albertel 3266: # output: url of file in userspace, or error: <message>
3267: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 3268:
1.531 albertel 3269: sub userfileupload {
1.1090 raeburn 3270: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095 raeburn 3271: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531 albertel 3272: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 3273: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 3274: $fname=&clean_filename($fname);
1.1090 raeburn 3275: # See if there is anything left
1.257 www 3276: unless ($fname) { return 'error: no uploaded file'; }
1.1090 raeburn 3277: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
3278: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
3279: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
3280: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523 raeburn 3281: my $now = time;
1.1090 raeburn 3282: my $filepath;
1.1095 raeburn 3283: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090 raeburn 3284: $filepath = 'tmp/helprequests/'.$now;
3285: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
3286: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
3287: '_'.$env{'user.domain'}.'/pending';
3288: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
3289: my ($docuname,$docudom);
3290: if ($destudom) {
3291: $docudom = $destudom;
3292: } else {
3293: $docudom = $env{'user.domain'};
3294: }
3295: if ($destuname) {
3296: $docuname = $destuname;
3297: } else {
3298: $docuname = $env{'user.name'};
3299: }
3300: if (exists($env{'form.group'})) {
3301: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3302: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3303: }
3304: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
3305: if ($context eq 'canceloverwrite') {
3306: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
3307: if (-e $tempfile) {
3308: my @info = stat($tempfile);
3309: if ($info[9] eq $env{'form.timestamp'}) {
3310: unlink($tempfile);
3311: }
3312: }
3313: return;
1.523 raeburn 3314: }
3315: }
1.1090 raeburn 3316: # Create the directory if not present
1.741 raeburn 3317: my @parts=split(/\//,$filepath);
3318: my $fullpath = $perlvar{'lonDaemons'};
3319: for (my $i=0;$i<@parts;$i++) {
3320: $fullpath .= '/'.$parts[$i];
3321: if ((-e $fullpath)!=1) {
3322: mkdir($fullpath,0777);
3323: }
3324: }
3325: open(my $fh,'>'.$fullpath.'/'.$fname);
3326: print $fh $env{'form.'.$formname};
3327: close($fh);
1.1090 raeburn 3328: if ($context eq 'existingfile') {
3329: my @info = stat($fullpath.'/'.$fname);
3330: return ($fullpath.'/'.$fname,$info[9]);
3331: } else {
3332: return $fullpath.'/'.$fname;
3333: }
1.523 raeburn 3334: }
1.995 raeburn 3335: if ($subdir eq 'scantron') {
3336: $fname = 'scantron_orig_'.$fname;
1.1093 raeburn 3337: } else {
1.995 raeburn 3338: $fname="$subdir/$fname";
3339: }
1.1090 raeburn 3340: if ($context eq 'coursedoc') {
1.638 albertel 3341: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3342: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 3343: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 3344: return &finishuserfileupload($docuname,$docudom,
3345: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 3346: $codebase,$thumbwidth,$thumbheight,
1.1095 raeburn 3347: $resizewidth,$resizeheight,$context,$mimetype);
1.481 raeburn 3348: } else {
1.1218 raeburn 3349: if ($env{'form.folder'}) {
3350: $fname=$env{'form.folder'}.'/'.$fname;
3351: }
1.638 albertel 3352: return &process_coursefile('uploaddoc',$docuname,$docudom,
3353: $fname,$formname,$parser,
1.1095 raeburn 3354: $allfiles,$codebase,$mimetype);
1.481 raeburn 3355: }
1.719 banghart 3356: } elsif (defined($destuname)) {
3357: my $docuname=$destuname;
3358: my $docudom=$destudom;
1.860 raeburn 3359: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3360: $parser,$allfiles,$codebase,
1.1051 raeburn 3361: $thumbwidth,$thumbheight,
1.1095 raeburn 3362: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3363: } else {
1.638 albertel 3364: my $docuname=$env{'user.name'};
3365: my $docudom=$env{'user.domain'};
1.1220 raeburn 3366: if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714 raeburn 3367: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3368: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3369: }
1.860 raeburn 3370: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3371: $parser,$allfiles,$codebase,
1.1051 raeburn 3372: $thumbwidth,$thumbheight,
1.1095 raeburn 3373: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3374: }
1.271 www 3375: }
3376:
3377: sub finishuserfileupload {
1.860 raeburn 3378: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095 raeburn 3379: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477 raeburn 3380: my $path=$docudom.'/'.$docuname.'/';
1.258 www 3381: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 3382:
1.860 raeburn 3383: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 3384: $file=$fname;
3385: if ($fname=~m|/|) {
3386: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
3387: $path.=$fnamepath.'/';
3388: }
1.259 www 3389: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 3390: my $count;
3391: for ($count=4;$count<=$#parts;$count++) {
3392: $filepath.="/$parts[$count]";
3393: if ((-e $filepath)!=1) {
3394: mkdir($filepath,0777);
3395: }
3396: }
1.984 neumanie 3397:
1.258 www 3398: # Save the file
3399: {
1.701 albertel 3400: if (!open(FH,'>'.$filepath.'/'.$file)) {
3401: &logthis('Failed to create '.$filepath.'/'.$file);
3402: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
3403: return '/adm/notfound.html';
3404: }
1.1090 raeburn 3405: if ($context eq 'overwrite') {
1.1117 foxr 3406: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090 raeburn 3407: my $target = $filepath.'/'.$file;
3408: if (-e $source) {
3409: my @info = stat($source);
3410: if ($info[9] eq $env{'form.timestamp'}) {
3411: unless (&File::Copy::move($source,$target)) {
3412: &logthis('Failed to overwrite '.$filepath.'/'.$file);
3413: return "Moving from $source failed";
3414: }
3415: } else {
3416: return "Temporary file: $source had unexpected date/time for last modification";
3417: }
3418: } else {
3419: return "Temporary file: $source missing";
3420: }
3421: } elsif (!print FH ($env{'form.'.$formname})) {
1.701 albertel 3422: &logthis('Failed to write to '.$filepath.'/'.$file);
3423: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
3424: return '/adm/notfound.html';
3425: }
1.570 albertel 3426: close(FH);
1.1051 raeburn 3427: if ($resizewidth && $resizeheight) {
3428: my $mm = new File::MMagic;
3429: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
3430: if ($mime_type =~ m{^image/}) {
3431: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
3432: }
1.977 amueller 3433: }
1.258 www 3434: }
1.1152 raeburn 3435: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
3436: if (ref($mimetype)) {
3437: if ($$mimetype eq '') {
3438: my $mm = new File::MMagic;
3439: my $type = $mm->checktype_filename($filepath.'/'.$file);
3440: $$mimetype = $type;
3441: }
3442: }
3443: }
1.637 raeburn 3444: if ($parser eq 'parse') {
1.1152 raeburn 3445: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024 raeburn 3446: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
3447: $allfiles,$codebase);
3448: unless ($parse_result eq 'ok') {
3449: &logthis('Failed to parse '.$filepath.$file.
3450: ' for embedded media: '.$parse_result);
3451: }
1.637 raeburn 3452: }
3453: }
1.860 raeburn 3454: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
3455: my $input = $filepath.'/'.$file;
3456: my $output = $filepath.'/'.'tn-'.$file;
3457: my $thumbsize = $thumbwidth.'x'.$thumbheight;
3458: system("convert -sample $thumbsize $input $output");
3459: if (-e $filepath.'/'.'tn-'.$file) {
3460: $fetchthumb = 1;
3461: }
3462: }
1.858 raeburn 3463:
1.259 www 3464: # Notify homeserver to grep it
3465: #
1.984 neumanie 3466: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 3467: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 3468: if ($fetchresult eq 'ok') {
1.860 raeburn 3469: if ($fetchthumb) {
3470: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
3471: if ($thumbresult ne 'ok') {
3472: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
3473: $docuhome.': '.$thumbresult);
3474: }
3475: }
1.259 www 3476: #
1.258 www 3477: # Return the URL to it
1.494 albertel 3478: return '/uploaded/'.$path.$file;
1.263 www 3479: } else {
1.494 albertel 3480: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
3481: ': '.$fetchresult);
1.263 www 3482: return '/adm/notfound.html';
1.858 raeburn 3483: }
1.493 albertel 3484: }
3485:
1.637 raeburn 3486: sub extract_embedded_items {
1.961 raeburn 3487: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 3488: my @state = ();
1.1164 raeburn 3489: my (%lastids,%related,%shockwave,%flashvars);
1.637 raeburn 3490: my %javafiles = (
3491: codebase => '',
3492: code => '',
3493: archive => ''
3494: );
3495: my %mediafiles = (
3496: src => '',
3497: movie => '',
3498: );
1.648 raeburn 3499: my $p;
3500: if ($content) {
3501: $p = HTML::LCParser->new($content);
3502: } else {
1.961 raeburn 3503: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 3504: }
1.641 albertel 3505: while (my $t=$p->get_token()) {
1.640 albertel 3506: if ($t->[0] eq 'S') {
3507: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 3508: push(@state, $tagname);
1.648 raeburn 3509: if (lc($tagname) eq 'allow') {
3510: &add_filetype($allfiles,$attr->{'src'},'src');
3511: }
1.640 albertel 3512: if (lc($tagname) eq 'img') {
3513: &add_filetype($allfiles,$attr->{'src'},'src');
3514: }
1.886 albertel 3515: if (lc($tagname) eq 'a') {
1.1222 raeburn 3516: unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
1.1221 raeburn 3517: &add_filetype($allfiles,$attr->{'href'},'href');
3518: }
1.886 albertel 3519: }
1.645 raeburn 3520: if (lc($tagname) eq 'script') {
1.1164 raeburn 3521: my $src;
1.645 raeburn 3522: if ($attr->{'archive'} =~ /\.jar$/i) {
3523: &add_filetype($allfiles,$attr->{'archive'},'archive');
3524: } else {
1.1164 raeburn 3525: if ($attr->{'src'} ne '') {
3526: $src = $attr->{'src'};
3527: &add_filetype($allfiles,$src,'src');
3528: }
3529: }
3530: my $text = $p->get_trimmed_text();
3531: if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
3532: my @swfargs = split(/,/,$1);
3533: foreach my $item (@swfargs) {
3534: $item =~ s/["']//g;
3535: $item =~ s/^\s+//;
3536: $item =~ s/\s+$//;
3537: }
3538: if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
3539: if (ref($related{$swfargs[0]}) eq 'ARRAY') {
3540: push(@{$related{$swfargs[0]}},$swfargs[2]);
3541: } else {
3542: $related{$swfargs[0]} = [$swfargs[2]];
3543: }
3544: }
1.645 raeburn 3545: }
3546: }
3547: if (lc($tagname) eq 'link') {
3548: if (lc($attr->{'rel'}) eq 'stylesheet') {
3549: &add_filetype($allfiles,$attr->{'href'},'href');
3550: }
3551: }
1.640 albertel 3552: if (lc($tagname) eq 'object' ||
3553: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
3554: foreach my $item (keys(%javafiles)) {
3555: $javafiles{$item} = '';
3556: }
1.1164 raeburn 3557: if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
3558: $lastids{lc($tagname)} = $attr->{'id'};
3559: }
1.640 albertel 3560: }
3561: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
3562: my $name = lc($attr->{'name'});
3563: foreach my $item (keys(%javafiles)) {
3564: if ($name eq $item) {
3565: $javafiles{$item} = $attr->{'value'};
3566: last;
3567: }
3568: }
1.1164 raeburn 3569: my $pathfrom;
1.640 albertel 3570: foreach my $item (keys(%mediafiles)) {
3571: if ($name eq $item) {
1.1164 raeburn 3572: $pathfrom = $attr->{'value'};
3573: $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
3574: &add_filetype($allfiles,$pathfrom,$name);
1.640 albertel 3575: last;
3576: }
3577: }
1.1164 raeburn 3578: if ($name eq 'flashvars') {
3579: $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
3580: }
3581: if ($pathfrom ne '') {
3582: &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
3583: $pathfrom);
3584: }
1.640 albertel 3585: }
3586: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
3587: foreach my $item (keys(%javafiles)) {
3588: if ($attr->{$item}) {
3589: $javafiles{$item} = $attr->{$item};
3590: last;
3591: }
3592: }
3593: foreach my $item (keys(%mediafiles)) {
3594: if ($attr->{$item}) {
3595: &add_filetype($allfiles,$attr->{$item},$item);
3596: last;
3597: }
3598: }
1.1164 raeburn 3599: if (lc($tagname) eq 'embed') {
3600: if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
3601: &embedded_dependency($allfiles,\%related,$attr->{'name'},
3602: $attr->{'src'});
3603: }
3604: }
1.640 albertel 3605: }
1.1243 raeburn 3606: if (lc($tagname) eq 'iframe') {
3607: my $src = $attr->{'src'} ;
3608: if (($src ne '') && ($src !~ m{^(/|https?://)})) {
3609: &add_filetype($allfiles,$src,'src');
3610: } elsif ($src =~ m{^/}) {
3611: if ($env{'request.course.id'}) {
3612: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
3613: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
3614: my $url = &hreflocation('',$fullpath);
3615: if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
3616: my $relpath = $1;
3617: if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
3618: &add_filetype($allfiles,$1,'src');
3619: }
3620: }
3621: }
3622: }
3623: }
1.1164 raeburn 3624: if ($t->[4] =~ m{/>$}) {
1.1243 raeburn 3625: pop(@state);
1.1164 raeburn 3626: }
1.640 albertel 3627: } elsif ($t->[0] eq 'E') {
3628: my ($tagname) = ($t->[1]);
3629: if ($javafiles{'codebase'} ne '') {
3630: $javafiles{'codebase'} .= '/';
3631: }
3632: if (lc($tagname) eq 'applet' ||
3633: lc($tagname) eq 'object' ||
3634: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
3635: ) {
3636: foreach my $item (keys(%javafiles)) {
3637: if ($item ne 'codebase' && $javafiles{$item} ne '') {
3638: my $file=$javafiles{'codebase'}.$javafiles{$item};
3639: &add_filetype($allfiles,$file,$item);
3640: }
3641: }
3642: }
3643: pop @state;
3644: }
3645: }
1.1164 raeburn 3646: foreach my $id (sort(keys(%flashvars))) {
3647: if ($shockwave{$id} ne '') {
3648: my @pairs = split(/\&/,$flashvars{$id});
3649: foreach my $pair (@pairs) {
3650: my ($key,$value) = split(/\=/,$pair);
3651: if ($key eq 'thumb') {
3652: &add_filetype($allfiles,$value,$key);
3653: } elsif ($key eq 'content') {
3654: my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
3655: my ($ext) = ($value =~ /\.([^.]+)$/);
3656: if ($ext ne '') {
3657: &add_filetype($allfiles,$path.$value,$ext);
3658: }
3659: }
3660: }
3661: }
3662: }
1.637 raeburn 3663: return 'ok';
3664: }
3665:
1.639 albertel 3666: sub add_filetype {
3667: my ($allfiles,$file,$type)=@_;
3668: if (exists($allfiles->{$file})) {
3669: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
3670: push(@{$allfiles->{$file}}, &escape($type));
3671: }
3672: } else {
3673: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 3674: }
3675: }
3676:
1.1164 raeburn 3677: sub embedded_dependency {
3678: my ($allfiles,$related,$identifier,$pathfrom) = @_;
3679: if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
3680: if (($identifier ne '') &&
3681: (ref($related->{$identifier}) eq 'ARRAY') &&
3682: ($pathfrom ne '')) {
3683: my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
3684: foreach my $dep (@{$related->{$identifier}}) {
3685: &add_filetype($allfiles,$path.$dep,'object');
3686: }
3687: }
3688: }
3689: return;
3690: }
3691:
1.493 albertel 3692: sub removeuploadedurl {
1.984 neumanie 3693: my ($url)=@_;
3694: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 3695: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 3696: }
3697:
3698: sub removeuserfile {
3699: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 3700: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3701: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 3702: if ($result eq 'ok') {
1.798 raeburn 3703: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
3704: my $metafile = $fname.'.meta';
3705: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 3706: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 3707: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3708: my $sqlresult =
1.823 albertel 3709: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3710: 'portfolio_metadata',$group,
3711: 'delete');
1.798 raeburn 3712: }
3713: }
3714: return $result;
1.257 www 3715: }
1.15 www 3716:
1.530 albertel 3717: sub mkdiruserfile {
3718: my ($docuname,$docudom,$dir)=@_;
3719: my $home=&homeserver($docuname,$docudom);
3720: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
3721: }
3722:
1.531 albertel 3723: sub renameuserfile {
3724: my ($docuname,$docudom,$old,$new)=@_;
3725: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3726: my $result = &reply("renameuserfile:$docudom:$docuname:".
3727: &escape("$old").':'.&escape("$new"),$home);
3728: if ($result eq 'ok') {
3729: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
3730: my $oldmeta = $old.'.meta';
3731: my $newmeta = $new.'.meta';
3732: my $metaresult =
3733: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 3734: my $url = "/uploaded/$docudom/$docuname/$old";
3735: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3736: my $sqlresult =
1.823 albertel 3737: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3738: 'portfolio_metadata',$group,
3739: 'delete');
1.798 raeburn 3740: }
3741: }
3742: return $result;
1.531 albertel 3743: }
3744:
1.14 www 3745: # ------------------------------------------------------------------------- Log
3746:
3747: sub log {
3748: my ($dom,$nam,$hom,$what)=@_;
1.47 www 3749: return critical("log:$dom:$nam:$what",$hom);
1.157 www 3750: }
3751:
3752: # ------------------------------------------------------------------ Course Log
1.352 www 3753: #
3754: # This routine flushes several buffers of non-mission-critical nature
3755: #
1.157 www 3756:
3757: sub flushcourselogs {
1.352 www 3758: &logthis('Flushing log buffers');
3759: #
3760: # course logs
3761: # This is a log of all transactions in a course, which can be used
3762: # for data mining purposes
3763: #
3764: # It also collects the courseid database, which lists last transaction
3765: # times and course titles for all courseids
3766: #
3767: my %courseidbuffer=();
1.921 raeburn 3768: foreach my $crsid (keys(%courselogs)) {
1.352 www 3769: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 3770: &escape($courselogs{$crsid}),
3771: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 3772: delete $courselogs{$crsid};
3773: } else {
3774: &logthis('Failed to flush log buffer for '.$crsid);
3775: if (length($courselogs{$crsid})>40000) {
1.672 albertel 3776: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 3777: " exceeded maximum size, deleting.</font>");
3778: delete $courselogs{$crsid};
3779: }
1.352 www 3780: }
1.920 raeburn 3781: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 3782: 'description' => $coursedescrbuf{$crsid},
3783: 'inst_code' => $courseinstcodebuf{$crsid},
3784: 'type' => $coursetypebuf{$crsid},
3785: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 3786: };
1.191 harris41 3787: }
1.352 www 3788: #
3789: # Write course id database (reverse lookup) to homeserver of courses
3790: # Is used in pickcourse
3791: #
1.840 albertel 3792: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 3793: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 3794: $courseidbuffer{$crs_home},
3795: $crs_home,'timeonly');
1.352 www 3796: }
3797: #
3798: # File accesses
3799: # Writes to the dynamic metadata of resources to get hit counts, etc.
3800: #
1.449 matthew 3801: foreach my $entry (keys(%accesshash)) {
1.458 matthew 3802: if ($entry =~ /___count$/) {
3803: my ($dom,$name);
1.807 albertel 3804: ($dom,$name,undef)=
1.811 albertel 3805: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 3806: if (! defined($dom) || $dom eq '' ||
3807: ! defined($name) || $name eq '') {
1.620 albertel 3808: my $cid = $env{'request.course.id'};
3809: $dom = $env{'request.'.$cid.'.domain'};
3810: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 3811: }
1.450 matthew 3812: my $value = $accesshash{$entry};
3813: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
3814: my %temphash=($url => $value);
1.449 matthew 3815: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
3816: if ($result eq 'ok') {
3817: delete $accesshash{$entry};
3818: }
3819: } else {
1.811 albertel 3820: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159 www 3821: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450 matthew 3822: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 3823: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
3824: delete $accesshash{$entry};
3825: }
1.185 www 3826: }
1.191 harris41 3827: }
1.352 www 3828: #
3829: # Roles
3830: # Reverse lookup of user roles for course faculty/staff and co-authorship
3831: #
1.800 albertel 3832: foreach my $entry (keys(%userrolehash)) {
1.351 www 3833: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 3834: split(/\:/,$entry);
3835: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 3836: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 3837: $rudom,$runame) eq 'ok') {
3838: delete $userrolehash{$entry};
3839: }
3840: }
1.662 raeburn 3841: #
3842: # Reverse lookup of domain roles (dc, ad, li, sc, au)
3843: #
3844: my %domrolebuffer = ();
1.1000 raeburn 3845: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 3846: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 3847: if ($domrolebuffer{$rudom}) {
3848: $domrolebuffer{$rudom}.='&'.&escape($entry).
3849: '='.&escape($domainrolehash{$entry});
3850: } else {
3851: $domrolebuffer{$rudom}.=&escape($entry).
3852: '='.&escape($domainrolehash{$entry});
3853: }
3854: delete $domainrolehash{$entry};
3855: }
3856: foreach my $dom (keys(%domrolebuffer)) {
1.841 albertel 3857: my %servers = &get_servers($dom,'library');
3858: foreach my $tryserver (keys(%servers)) {
3859: unless (&reply('domroleput:'.$dom.':'.
3860: $domrolebuffer{$dom},$tryserver) eq 'ok') {
3861: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
3862: }
1.662 raeburn 3863: }
3864: }
1.186 www 3865: $dumpcount++;
1.157 www 3866: }
3867:
3868: sub courselog {
3869: my $what=shift;
1.158 www 3870: $what=time.':'.$what;
1.620 albertel 3871: unless ($env{'request.course.id'}) { return ''; }
3872: $coursedombuf{$env{'request.course.id'}}=
3873: $env{'course.'.$env{'request.course.id'}.'.domain'};
3874: $coursenumbuf{$env{'request.course.id'}}=
3875: $env{'course.'.$env{'request.course.id'}.'.num'};
3876: $coursehombuf{$env{'request.course.id'}}=
3877: $env{'course.'.$env{'request.course.id'}.'.home'};
3878: $coursedescrbuf{$env{'request.course.id'}}=
3879: $env{'course.'.$env{'request.course.id'}.'.description'};
3880: $courseinstcodebuf{$env{'request.course.id'}}=
3881: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
3882: $courseownerbuf{$env{'request.course.id'}}=
3883: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 3884: $coursetypebuf{$env{'request.course.id'}}=
3885: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 3886: if (defined $courselogs{$env{'request.course.id'}}) {
3887: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 3888: } else {
1.620 albertel 3889: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 3890: }
1.620 albertel 3891: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 3892: &flushcourselogs();
3893: }
1.158 www 3894: }
3895:
3896: sub courseacclog {
3897: my $fnsymb=shift;
1.620 albertel 3898: unless ($env{'request.course.id'}) { return ''; }
3899: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144 www 3900: if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187 www 3901: $what.=':POST';
1.583 matthew 3902: # FIXME: Probably ought to escape things....
1.800 albertel 3903: foreach my $key (keys(%env)) {
3904: if ($key=~/^form\.(.*)/) {
1.975 raeburn 3905: my $formitem = $1;
3906: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
3907: $what.=':'.$formitem.'='.$env{$key};
3908: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
3909: $what.=':'.$formitem.'='.$env{$key};
3910: }
1.158 www 3911: }
1.191 harris41 3912: }
1.583 matthew 3913: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
3914: # FIXME: We should not be depending on a form parameter that someone
3915: # editing lonsearchcat.pm might change in the future.
1.620 albertel 3916: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 3917: $what.= ':POST';
3918: # FIXME: Probably ought to escape things....
3919: foreach my $element ('courseexp','crsfulltext','crsrelated',
3920: 'crsdiscuss') {
1.620 albertel 3921: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 3922: }
3923: }
1.158 www 3924: }
3925: &courselog($what);
1.149 www 3926: }
3927:
1.185 www 3928: sub countacc {
3929: my $url=&declutter(shift);
1.458 matthew 3930: return if (! defined($url) || $url eq '');
1.620 albertel 3931: unless ($env{'request.course.id'}) { return ''; }
1.1158 www 3932: #
3933: # Mark that this url was used in this course
3934: #
1.620 albertel 3935: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158 www 3936: #
3937: # Increase the access count for this resource in this child process
3938: #
1.281 www 3939: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 3940: $accesshash{$key}++;
1.185 www 3941: }
1.349 www 3942:
1.361 www 3943: sub linklog {
3944: my ($from,$to)=@_;
3945: $from=&declutter($from);
3946: $to=&declutter($to);
3947: $accesshash{$from.'___'.$to.'___comefrom'}=1;
3948: $accesshash{$to.'___'.$from.'___goto'}=1;
3949: }
1.1160 www 3950:
3951: sub statslog {
3952: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
3953: if ($users<2) { return; }
3954: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
3955: 'course' => $env{'request.course.id'},
3956: 'sections' => '"all"',
3957: 'num_students' => $users,
3958: 'part' => $part,
3959: 'symb' => $symb,
3960: 'mean_tries' => $av_attempts,
3961: 'deg_of_diff' => $degdiff});
3962: foreach my $key (keys(%dynstore)) {
3963: $accesshash{$key}=$dynstore{$key};
3964: }
3965: }
1.361 www 3966:
1.349 www 3967: sub userrolelog {
3968: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169 droeschl 3969: if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350 www 3970: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3971: $userrolehash
3972: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 3973: =$tend.':'.$tstart;
1.662 raeburn 3974: }
1.1169 droeschl 3975: if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898 albertel 3976: $userrolehash
3977: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
3978: =$tend.':'.$tstart;
3979: }
1.1169 droeschl 3980: if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
1.662 raeburn 3981: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3982: $domainrolehash
3983: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
3984: = $tend.':'.$tstart;
3985: }
1.351 www 3986: }
3987:
1.957 raeburn 3988: sub courserolelog {
3989: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1184 raeburn 3990: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
3991: my $cdom = $1;
3992: my $cnum = $2;
3993: my $sec = $3;
3994: my $namespace = 'rolelog';
3995: my %storehash = (
3996: role => $trole,
3997: start => $tstart,
3998: end => $tend,
3999: selfenroll => $selfenroll,
4000: context => $context,
4001: );
4002: if ($trole eq 'gr') {
4003: $namespace = 'groupslog';
4004: $storehash{'group'} = $sec;
4005: } else {
4006: $storehash{'section'} = $sec;
4007: }
1.1188 raeburn 4008: &write_log('course',$namespace,\%storehash,$delflag,$username,
4009: $domain,$cnum,$cdom);
1.1184 raeburn 4010: if (($trole ne 'st') || ($sec ne '')) {
4011: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957 raeburn 4012: }
4013: }
4014: return;
4015: }
4016:
1.1184 raeburn 4017: sub domainrolelog {
4018: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4019: if ($area =~ m{^/($match_domain)/$}) {
4020: my $cdom = $1;
4021: my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
4022: my $namespace = 'rolelog';
4023: my %storehash = (
4024: role => $trole,
4025: start => $tstart,
4026: end => $tend,
4027: context => $context,
4028: );
1.1188 raeburn 4029: &write_log('domain',$namespace,\%storehash,$delflag,$username,
4030: $domain,$domconfiguser,$cdom);
1.1184 raeburn 4031: }
4032: return;
4033:
4034: }
4035:
4036: sub coauthorrolelog {
4037: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4038: if ($area =~ m{^/($match_domain)/($match_username)$}) {
4039: my $audom = $1;
4040: my $auname = $2;
4041: my $namespace = 'rolelog';
4042: my %storehash = (
4043: role => $trole,
4044: start => $tstart,
4045: end => $tend,
4046: context => $context,
4047: );
1.1188 raeburn 4048: &write_log('author',$namespace,\%storehash,$delflag,$username,
4049: $domain,$auname,$audom);
1.1184 raeburn 4050: }
4051: return;
4052: }
4053:
1.351 www 4054: sub get_course_adv_roles {
1.948 raeburn 4055: my ($cid,$codes) = @_;
1.620 albertel 4056: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 4057: my %coursehash=&coursedescription($cid);
1.988 raeburn 4058: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 4059: my %nothide=();
1.800 albertel 4060: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 4061: if ($user !~ /:/) {
4062: $nothide{join(':',split(/[\@]/,$user))}=1;
4063: } else {
4064: $nothide{$user}=1;
4065: }
1.470 www 4066: }
1.1219 raeburn 4067: my @possdoms = ($coursehash{'domain'});
4068: if ($coursehash{'checkforpriv'}) {
4069: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
4070: }
1.351 www 4071: my %returnhash=();
4072: my %dumphash=
4073: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
4074: my $now=time;
1.997 raeburn 4075: my %privileged;
1.1000 raeburn 4076: foreach my $entry (keys(%dumphash)) {
1.800 albertel 4077: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 4078: if (($tstart) && ($tstart<0)) { next; }
4079: if (($tend) && ($tend<$now)) { next; }
4080: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 4081: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 4082: if ($username eq '' || $domain eq '') { next; }
1.1219 raeburn 4083: if ((&privileged($username,$domain,\@possdoms)) &&
1.997 raeburn 4084: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 4085: if ($role eq 'cr') { next; }
1.948 raeburn 4086: if ($codes) {
4087: if ($section) { $role .= ':'.$section; }
4088: if ($returnhash{$role}) {
4089: $returnhash{$role}.=','.$username.':'.$domain;
4090: } else {
4091: $returnhash{$role}=$username.':'.$domain;
4092: }
1.351 www 4093: } else {
1.988 raeburn 4094: my $key=&plaintext($role,$crstype);
1.973 bisitz 4095: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 4096: if ($returnhash{$key}) {
4097: $returnhash{$key}.=','.$username.':'.$domain;
4098: } else {
4099: $returnhash{$key}=$username.':'.$domain;
4100: }
1.351 www 4101: }
1.948 raeburn 4102: }
1.400 www 4103: return %returnhash;
4104: }
4105:
4106: sub get_my_roles {
1.937 raeburn 4107: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 4108: unless (defined($uname)) { $uname=$env{'user.name'}; }
4109: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 4110: my (%dumphash,%nothide);
1.1086 raeburn 4111: if ($context eq 'userroles') {
1.1166 raeburn 4112: %dumphash = &dump('roles',$udom,$uname);
1.858 raeburn 4113: } else {
1.1219 raeburn 4114: %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 4115: if ($hidepriv) {
4116: my %coursehash=&coursedescription($udom.'_'.$uname);
4117: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
4118: if ($user !~ /:/) {
4119: $nothide{join(':',split(/[\@]/,$user))} = 1;
4120: } else {
4121: $nothide{$user} = 1;
4122: }
4123: }
4124: }
1.858 raeburn 4125: }
1.400 www 4126: my %returnhash=();
4127: my $now=time;
1.999 raeburn 4128: my %privileged;
1.800 albertel 4129: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 4130: my ($role,$tend,$tstart);
4131: if ($context eq 'userroles') {
1.1149 raeburn 4132: next if ($entry =~ /^rolesdef/);
1.867 raeburn 4133: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
4134: } else {
4135: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
4136: }
1.400 www 4137: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 4138: my $status = 'active';
1.939 raeburn 4139: if (($tend) && ($tend<=$now)) {
1.832 raeburn 4140: $status = 'previous';
4141: }
4142: if (($tstart) && ($now<$tstart)) {
4143: $status = 'future';
4144: }
4145: if (ref($types) eq 'ARRAY') {
4146: if (!grep(/^\Q$status\E$/,@{$types})) {
4147: next;
4148: }
4149: } else {
4150: if ($status ne 'active') {
4151: next;
4152: }
4153: }
1.867 raeburn 4154: my ($rolecode,$username,$domain,$section,$area);
4155: if ($context eq 'userroles') {
1.1186 raeburn 4156: ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867 raeburn 4157: (undef,$domain,$username,$section) = split(/\//,$area);
4158: } else {
4159: ($role,$username,$domain,$section) = split(/\:/,$entry);
4160: }
1.832 raeburn 4161: if (ref($roledoms) eq 'ARRAY') {
4162: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
4163: next;
4164: }
4165: }
4166: if (ref($roles) eq 'ARRAY') {
4167: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 4168: if ($role =~ /^cr\//) {
4169: if (!grep(/^cr$/,@{$roles})) {
4170: next;
4171: }
1.1104 raeburn 4172: } elsif ($role =~ /^gr\//) {
4173: if (!grep(/^gr$/,@{$roles})) {
4174: next;
4175: }
1.922 raeburn 4176: } else {
4177: next;
4178: }
1.832 raeburn 4179: }
1.867 raeburn 4180: }
1.937 raeburn 4181: if ($hidepriv) {
1.1219 raeburn 4182: my @privroles = ('dc','su');
1.999 raeburn 4183: if ($context eq 'userroles') {
1.1219 raeburn 4184: next if (grep(/^\Q$role\E$/,@privroles));
1.999 raeburn 4185: } else {
1.1219 raeburn 4186: my $possdoms = [$domain];
4187: if (ref($roledoms) eq 'ARRAY') {
4188: push(@{$possdoms},@{$roledoms});
1.999 raeburn 4189: }
1.1219 raeburn 4190: if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999 raeburn 4191: if (!$nothide{$username.':'.$domain}) {
4192: next;
4193: }
4194: }
1.937 raeburn 4195: }
4196: }
1.933 raeburn 4197: if ($withsec) {
4198: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
4199: $tstart.':'.$tend;
4200: } else {
4201: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
4202: }
1.832 raeburn 4203: }
1.373 www 4204: return %returnhash;
1.399 www 4205: }
4206:
4207: # ----------------------------------------------------- Frontpage Announcements
4208: #
4209: #
4210:
4211: sub postannounce {
4212: my ($server,$text)=@_;
1.844 albertel 4213: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 4214: unless ($text=~/\w/) { $text=''; }
4215: return &reply('setannounce:'.&escape($text),$server);
4216: }
4217:
4218: sub getannounce {
1.448 albertel 4219:
4220: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 4221: my $announcement='';
1.800 albertel 4222: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 4223: close($fh);
1.399 www 4224: if ($announcement=~/\w/) {
4225: return
4226: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 4227: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 4228: } else {
4229: return '';
4230: }
4231: } else {
4232: return '';
4233: }
1.351 www 4234: }
1.353 www 4235:
4236: # ---------------------------------------------------------- Course ID routines
4237: # Deal with domain's nohist_courseid.db files
4238: #
4239:
4240: sub courseidput {
1.921 raeburn 4241: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 4242: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 4243: my $outcome;
4244: if ($caller eq 'timeonly') {
4245: my $cids = '';
4246: foreach my $item (keys(%$storehash)) {
4247: $cids.=&escape($item).'&';
4248: }
4249: $cids=~s/\&$//;
4250: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
4251: $coursehome);
4252: } else {
4253: my $items = '';
4254: foreach my $item (keys(%$storehash)) {
4255: $items.= &escape($item).'='.
4256: &freeze_escape($$storehash{$item}).'&';
4257: }
4258: $items=~s/\&$//;
4259: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
4260: $coursehome);
1.918 raeburn 4261: }
4262: if ($outcome eq 'unknown_cmd') {
4263: my $what;
4264: foreach my $cid (keys(%$storehash)) {
4265: $what .= &escape($cid).'=';
1.921 raeburn 4266: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 4267: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 4268: }
4269: $what =~ s/\:$/&/;
4270: }
4271: $what =~ s/\&$//;
4272: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
4273: } else {
4274: return $outcome;
4275: }
1.353 www 4276: }
4277:
4278: sub courseiddump {
1.921 raeburn 4279: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 4280: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 4281: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1247 raeburn 4282: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
4283: $hasuniquecode)=@_;
1.918 raeburn 4284: my $as_hash = 1;
4285: my %returnhash;
4286: if (!$domfilter) { $domfilter=''; }
1.845 albertel 4287: my %libserv = &all_library();
4288: foreach my $tryserver (keys(%libserv)) {
4289: if ( ( $hostidflag == 1
4290: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
4291: || (!defined($hostidflag)) ) {
4292:
1.918 raeburn 4293: if (($domfilter eq '') ||
4294: (&host_domain($tryserver) eq $domfilter)) {
1.1180 droeschl 4295: my $rep;
4296: if (grep { $_ eq $tryserver } current_machine_ids()) {
4297: $rep = LONCAPA::Lond::dump_course_id_handler(
4298: join(":", (&host_domain($tryserver), $sincefilter,
4299: &escape($descfilter), &escape($instcodefilter),
4300: &escape($ownerfilter), &escape($coursefilter),
4301: &escape($typefilter), &escape($regexp_ok),
4302: $as_hash, &escape($selfenrollonly),
4303: &escape($catfilter), $showhidden, $caller,
4304: &escape($cloner), &escape($cc_clone), $cloneonly,
4305: &escape($createdbefore), &escape($createdafter),
1.1247 raeburn 4306: &escape($creationcontext), $domcloner, $hasuniquecode)));
1.1180 droeschl 4307: } else {
4308: $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
4309: $sincefilter.':'.&escape($descfilter).':'.
4310: &escape($instcodefilter).':'.&escape($ownerfilter).
4311: ':'.&escape($coursefilter).':'.&escape($typefilter).
4312: ':'.&escape($regexp_ok).':'.$as_hash.':'.
4313: &escape($selfenrollonly).':'.&escape($catfilter).':'.
4314: $showhidden.':'.$caller.':'.&escape($cloner).':'.
4315: &escape($cc_clone).':'.$cloneonly.':'.
4316: &escape($createdbefore).':'.&escape($createdafter).':'.
1.1247 raeburn 4317: &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode,
1.1180 droeschl 4318: $tryserver);
4319: }
4320:
1.918 raeburn 4321: my @pairs=split(/\&/,$rep);
4322: foreach my $item (@pairs) {
4323: my ($key,$value)=split(/\=/,$item,2);
4324: $key = &unescape($key);
4325: next if ($key =~ /^error: 2 /);
4326: my $result = &thaw_unescape($value);
4327: if (ref($result) eq 'HASH') {
4328: $returnhash{$key}=$result;
4329: } else {
1.921 raeburn 4330: my @responses = split(/:/,$value);
4331: my @items = ('description','inst_code','owner','type');
1.918 raeburn 4332: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 4333: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 4334: }
1.1008 raeburn 4335: }
1.353 www 4336: }
4337: }
4338: }
4339: }
4340: return %returnhash;
4341: }
4342:
1.1055 raeburn 4343: sub courselastaccess {
4344: my ($cdom,$cnum,$hostidref) = @_;
4345: my %returnhash;
4346: if ($cdom && $cnum) {
4347: my $chome = &homeserver($cnum,$cdom);
4348: if ($chome ne 'no_host') {
4349: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
4350: &extract_lastaccess(\%returnhash,$rep);
4351: }
4352: } else {
4353: if (!$cdom) { $cdom=''; }
4354: my %libserv = &all_library();
4355: foreach my $tryserver (keys(%libserv)) {
4356: if (ref($hostidref) eq 'ARRAY') {
4357: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
4358: }
4359: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
4360: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
4361: &extract_lastaccess(\%returnhash,$rep);
4362: }
4363: }
4364: }
4365: return %returnhash;
4366: }
4367:
4368: sub extract_lastaccess {
4369: my ($returnhash,$rep) = @_;
4370: if (ref($returnhash) eq 'HASH') {
4371: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
4372: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
4373: $rep eq '') {
4374: my @pairs=split(/\&/,$rep);
4375: foreach my $item (@pairs) {
4376: my ($key,$value)=split(/\=/,$item,2);
4377: $key = &unescape($key);
4378: next if ($key =~ /^error: 2 /);
4379: $returnhash->{$key} = &thaw_unescape($value);
4380: }
4381: }
4382: }
4383: return;
4384: }
4385:
1.658 raeburn 4386: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 4387:
4388: sub dcmailput {
1.685 raeburn 4389: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 4390: my $status = &Apache::lonnet::critical(
1.740 www 4391: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
4392: &escape($message),$server);
1.662 raeburn 4393: return $status;
4394: }
4395:
1.658 raeburn 4396: sub dcmaildump {
4397: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 4398: my %returnhash=();
1.846 albertel 4399:
4400: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 4401: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
4402: &escape($enddate).':';
4403: my @esc_senders=map { &escape($_)} @$senders;
4404: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 4405: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 4406: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 4407: if (($key) && ($value)) {
4408: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 4409: }
4410: }
4411: }
4412: return %returnhash;
4413: }
1.662 raeburn 4414: # ---------------------------------------------------------- Domain roles
4415:
4416: sub get_domain_roles {
4417: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 4418: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 4419: $startdate = '.';
4420: }
1.1018 raeburn 4421: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 4422: $enddate = '.';
4423: }
1.922 raeburn 4424: my $rolelist;
4425: if (ref($roles) eq 'ARRAY') {
1.1219 raeburn 4426: $rolelist = join('&',@{$roles});
1.922 raeburn 4427: }
1.662 raeburn 4428: my %personnel = ();
1.841 albertel 4429:
4430: my %servers = &get_servers($dom,'library');
4431: foreach my $tryserver (keys(%servers)) {
4432: %{$personnel{$tryserver}}=();
4433: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
4434: &escape($startdate).':'.
4435: &escape($enddate).':'.
4436: &escape($rolelist), $tryserver))) {
4437: my ($key,$value) = split(/\=/,$line,2);
4438: if (($key) && ($value)) {
4439: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
4440: }
4441: }
1.662 raeburn 4442: }
4443: return %personnel;
4444: }
1.658 raeburn 4445:
1.1057 www 4446: # ----------------------------------------------------------- Interval timing
1.149 www 4447:
1.1153 www 4448: {
4449: # Caches needed for speedup of navmaps
4450: # We don't want to cache this for very long at all (5 seconds at most)
4451: #
4452: # The user for whom we cache
4453: my $cachedkey='';
4454: # The cached times for this user
4455: my %cachedtimes=();
4456: # When this was last done
1.1282 raeburn 4457: my $cachedtime='';
1.1153 www 4458:
4459: sub load_all_first_access {
1.1154 raeburn 4460: my ($uname,$udom)=@_;
1.1156 www 4461: if (($cachedkey eq $uname.':'.$udom) &&
1.1174 raeburn 4462: (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154 raeburn 4463: return;
4464: }
4465: $cachedtime=time;
4466: $cachedkey=$uname.':'.$udom;
4467: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153 www 4468: }
4469:
1.504 albertel 4470: sub get_first_access {
1.1162 raeburn 4471: my ($type,$argsymb,$argmap)=@_;
1.790 albertel 4472: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4473: if ($argsymb) { $symb=$argsymb; }
4474: my ($map,$id,$res)=&decode_symb($symb);
1.1162 raeburn 4475: if ($argmap) { $map = $argmap; }
1.926 albertel 4476: if ($type eq 'course') {
4477: $res='course';
4478: } elsif ($type eq 'map') {
1.588 albertel 4479: $res=&symbread($map);
4480: } else {
4481: $res=$symb;
4482: }
1.1153 www 4483: &load_all_first_access($uname,$udom);
4484: return $cachedtimes{"$courseid\0$res"};
1.504 albertel 4485: }
4486:
4487: sub set_first_access {
1.1162 raeburn 4488: my ($type,$interval)=@_;
1.790 albertel 4489: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4490: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 4491: if ($type eq 'course') {
4492: $res='course';
4493: } elsif ($type eq 'map') {
1.588 albertel 4494: $res=&symbread($map);
4495: } else {
4496: $res=$symb;
4497: }
1.1153 www 4498: $cachedkey='';
1.1162 raeburn 4499: my $firstaccess=&get_first_access($type,$symb,$map);
1.505 albertel 4500: if (!$firstaccess) {
1.1162 raeburn 4501: my $start = time;
4502: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
4503: $udom,$uname);
4504: if ($putres eq 'ok') {
4505: &put('timerinterval',{"$courseid\0$res"=>$interval},
4506: $udom,$uname);
4507: &appenv(
4508: {
4509: 'course.'.$courseid.'.firstaccess.'.$res => $start,
4510: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
4511: }
4512: );
4513: }
4514: return $putres;
1.505 albertel 4515: }
4516: return 'already_set';
1.504 albertel 4517: }
1.1153 www 4518: }
1.1282 raeburn 4519:
1.110 www 4520: # --------------------------------------------- Set Expire Date for Spreadsheet
4521:
4522: sub expirespread {
4523: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 4524: my $cid=$env{'request.course.id'};
1.110 www 4525: if ($cid) {
4526: my $now=time;
4527: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 4528: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
4529: $env{'course.'.$cid.'.num'}.
1.110 www 4530: ':nohist_expirationdates:'.
4531: &escape($key).'='.$now,
1.620 albertel 4532: $env{'course.'.$cid.'.home'})
1.110 www 4533: }
4534: return 'ok';
1.14 www 4535: }
4536:
1.109 www 4537: # ----------------------------------------------------- Devalidate Spreadsheets
4538:
4539: sub devalidate {
1.325 www 4540: my ($symb,$uname,$udom)=@_;
1.620 albertel 4541: my $cid=$env{'request.course.id'};
1.109 www 4542: if ($cid) {
1.391 matthew 4543: # delete the stored spreadsheets for
4544: # - the student level sheet of this user in course's homespace
4545: # - the assessment level sheet for this resource
4546: # for this user in user's homespace
1.553 albertel 4547: # - current conditional state info
1.325 www 4548: my $key=$uname.':'.$udom.':';
1.109 www 4549: my $status=
1.299 matthew 4550: &del('nohist_calculatedsheets',
1.391 matthew 4551: [$key.'studentcalc:'],
1.620 albertel 4552: $env{'course.'.$cid.'.domain'},
4553: $env{'course.'.$cid.'.num'})
1.133 albertel 4554: .' '.
4555: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 4556: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 4557: unless ($status eq 'ok ok') {
4558: &logthis('Could not devalidate spreadsheet '.
1.325 www 4559: $uname.' at '.$udom.' for '.
1.109 www 4560: $symb.': '.$status);
1.133 albertel 4561: }
1.553 albertel 4562: &delenv('user.state.'.$cid);
1.109 www 4563: }
4564: }
4565:
1.265 albertel 4566: sub get_scalar {
4567: my ($string,$end) = @_;
4568: my $value;
4569: if ($$string =~ s/^([^&]*?)($end)/$2/) {
4570: $value = $1;
4571: } elsif ($$string =~ s/^([^&]*?)&//) {
4572: $value = $1;
4573: }
4574: return &unescape($value);
4575: }
4576:
4577: sub array2str {
4578: my (@array) = @_;
4579: my $result=&arrayref2str(\@array);
4580: $result=~s/^__ARRAY_REF__//;
4581: $result=~s/__END_ARRAY_REF__$//;
4582: return $result;
4583: }
4584:
1.204 albertel 4585: sub arrayref2str {
4586: my ($arrayref) = @_;
1.265 albertel 4587: my $result='__ARRAY_REF__';
1.204 albertel 4588: foreach my $elem (@$arrayref) {
1.265 albertel 4589: if(ref($elem) eq 'ARRAY') {
4590: $result.=&arrayref2str($elem).'&';
4591: } elsif(ref($elem) eq 'HASH') {
4592: $result.=&hashref2str($elem).'&';
4593: } elsif(ref($elem)) {
4594: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 4595: } else {
4596: $result.=&escape($elem).'&';
4597: }
4598: }
4599: $result=~s/\&$//;
1.265 albertel 4600: $result .= '__END_ARRAY_REF__';
1.204 albertel 4601: return $result;
4602: }
4603:
1.168 albertel 4604: sub hash2str {
1.204 albertel 4605: my (%hash) = @_;
4606: my $result=&hashref2str(\%hash);
1.265 albertel 4607: $result=~s/^__HASH_REF__//;
4608: $result=~s/__END_HASH_REF__$//;
1.204 albertel 4609: return $result;
4610: }
4611:
4612: sub hashref2str {
4613: my ($hashref)=@_;
1.265 albertel 4614: my $result='__HASH_REF__';
1.800 albertel 4615: foreach my $key (sort(keys(%$hashref))) {
4616: if (ref($key) eq 'ARRAY') {
4617: $result.=&arrayref2str($key).'=';
4618: } elsif (ref($key) eq 'HASH') {
4619: $result.=&hashref2str($key).'=';
4620: } elsif (ref($key)) {
1.265 albertel 4621: $result.='=';
1.800 albertel 4622: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 4623: } else {
1.1132 raeburn 4624: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 4625: }
4626:
1.800 albertel 4627: if(ref($hashref->{$key}) eq 'ARRAY') {
4628: $result.=&arrayref2str($hashref->{$key}).'&';
4629: } elsif(ref($hashref->{$key}) eq 'HASH') {
4630: $result.=&hashref2str($hashref->{$key}).'&';
4631: } elsif(ref($hashref->{$key})) {
1.265 albertel 4632: $result.='&';
1.800 albertel 4633: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 4634: } else {
1.800 albertel 4635: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 4636: }
4637: }
1.168 albertel 4638: $result=~s/\&$//;
1.265 albertel 4639: $result .= '__END_HASH_REF__';
1.168 albertel 4640: return $result;
4641: }
4642:
4643: sub str2hash {
1.265 albertel 4644: my ($string)=@_;
4645: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
4646: return %$hash;
4647: }
4648:
4649: sub str2hashref {
1.168 albertel 4650: my ($string) = @_;
1.265 albertel 4651:
4652: my %hash;
4653:
4654: if($string !~ /^__HASH_REF__/) {
4655: if (! ($string eq '' || !defined($string))) {
4656: $hash{'error'}='Not hash reference';
4657: }
4658: return (\%hash, $string);
4659: }
4660:
4661: $string =~ s/^__HASH_REF__//;
4662:
4663: while($string !~ /^__END_HASH_REF__/) {
4664: #key
4665: my $key='';
4666: if($string =~ /^__HASH_REF__/) {
4667: ($key, $string)=&str2hashref($string);
4668: if(defined($key->{'error'})) {
4669: $hash{'error'}='Bad data';
4670: return (\%hash, $string);
4671: }
4672: } elsif($string =~ /^__ARRAY_REF__/) {
4673: ($key, $string)=&str2arrayref($string);
4674: if($key->[0] eq 'Array reference error') {
4675: $hash{'error'}='Bad data';
4676: return (\%hash, $string);
4677: }
4678: } else {
4679: $string =~ s/^(.*?)=//;
1.267 albertel 4680: $key=&unescape($1);
1.265 albertel 4681: }
4682: $string =~ s/^=//;
4683:
4684: #value
4685: my $value='';
4686: if($string =~ /^__HASH_REF__/) {
4687: ($value, $string)=&str2hashref($string);
4688: if(defined($value->{'error'})) {
4689: $hash{'error'}='Bad data';
4690: return (\%hash, $string);
4691: }
4692: } elsif($string =~ /^__ARRAY_REF__/) {
4693: ($value, $string)=&str2arrayref($string);
4694: if($value->[0] eq 'Array reference error') {
4695: $hash{'error'}='Bad data';
4696: return (\%hash, $string);
4697: }
4698: } else {
4699: $value=&get_scalar(\$string,'__END_HASH_REF__');
4700: }
4701: $string =~ s/^&//;
4702:
4703: $hash{$key}=$value;
1.204 albertel 4704: }
1.265 albertel 4705:
4706: $string =~ s/^__END_HASH_REF__//;
4707:
4708: return (\%hash, $string);
1.204 albertel 4709: }
4710:
4711: sub str2array {
1.265 albertel 4712: my ($string)=@_;
4713: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
4714: return @$array;
4715: }
4716:
4717: sub str2arrayref {
1.204 albertel 4718: my ($string) = @_;
1.265 albertel 4719: my @array;
4720:
4721: if($string !~ /^__ARRAY_REF__/) {
4722: if (! ($string eq '' || !defined($string))) {
4723: $array[0]='Array reference error';
4724: }
4725: return (\@array, $string);
4726: }
4727:
4728: $string =~ s/^__ARRAY_REF__//;
4729:
4730: while($string !~ /^__END_ARRAY_REF__/) {
4731: my $value='';
4732: if($string =~ /^__HASH_REF__/) {
4733: ($value, $string)=&str2hashref($string);
4734: if(defined($value->{'error'})) {
4735: $array[0] ='Array reference error';
4736: return (\@array, $string);
4737: }
4738: } elsif($string =~ /^__ARRAY_REF__/) {
4739: ($value, $string)=&str2arrayref($string);
4740: if($value->[0] eq 'Array reference error') {
4741: $array[0] ='Array reference error';
4742: return (\@array, $string);
4743: }
4744: } else {
4745: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
4746: }
4747: $string =~ s/^&//;
4748:
4749: push(@array, $value);
1.191 harris41 4750: }
1.265 albertel 4751:
4752: $string =~ s/^__END_ARRAY_REF__//;
4753:
4754: return (\@array, $string);
1.168 albertel 4755: }
4756:
1.167 albertel 4757: # -------------------------------------------------------------------Temp Store
4758:
1.168 albertel 4759: sub tmpreset {
4760: my ($symb,$namespace,$domain,$stuname) = @_;
4761: if (!$symb) {
4762: $symb=&symbread();
1.620 albertel 4763: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4764: }
4765: $symb=escape($symb);
4766:
1.620 albertel 4767: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 4768: $namespace=~s/\//\_/g;
4769: $namespace=~s/\W//g;
4770:
1.620 albertel 4771: if (!$domain) { $domain=$env{'user.domain'}; }
4772: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4773: if ($domain eq 'public' && $stuname eq 'public') {
4774: $stuname=$ENV{'REMOTE_ADDR'};
4775: }
1.1117 foxr 4776: my $path=LONCAPA::tempdir();
1.168 albertel 4777: my %hash;
4778: if (tie(%hash,'GDBM_File',
4779: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4780: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 4781: foreach my $key (keys(%hash)) {
1.180 albertel 4782: if ($key=~ /:$symb/) {
1.168 albertel 4783: delete($hash{$key});
4784: }
4785: }
4786: }
4787: }
4788:
1.167 albertel 4789: sub tmpstore {
1.168 albertel 4790: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4791:
4792: if (!$symb) {
4793: $symb=&symbread();
1.620 albertel 4794: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4795: }
4796: $symb=escape($symb);
4797:
4798: if (!$namespace) {
4799: # I don't think we would ever want to store this for a course.
4800: # it seems this will only be used if we don't have a course.
1.620 albertel 4801: #$namespace=$env{'request.course.id'};
1.168 albertel 4802: #if (!$namespace) {
1.620 albertel 4803: $namespace=$env{'request.state'};
1.168 albertel 4804: #}
4805: }
4806: $namespace=~s/\//\_/g;
4807: $namespace=~s/\W//g;
1.620 albertel 4808: if (!$domain) { $domain=$env{'user.domain'}; }
4809: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4810: if ($domain eq 'public' && $stuname eq 'public') {
4811: $stuname=$ENV{'REMOTE_ADDR'};
4812: }
1.168 albertel 4813: my $now=time;
4814: my %hash;
1.1117 foxr 4815: my $path=LONCAPA::tempdir();
1.168 albertel 4816: if (tie(%hash,'GDBM_File',
4817: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4818: &GDBM_WRCREAT(),0640)) {
1.168 albertel 4819: $hash{"version:$symb"}++;
4820: my $version=$hash{"version:$symb"};
4821: my $allkeys='';
4822: foreach my $key (keys(%$storehash)) {
4823: $allkeys.=$key.':';
1.591 albertel 4824: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 4825: }
4826: $hash{"$version:$symb:timestamp"}=$now;
4827: $allkeys.='timestamp';
4828: $hash{"$version:keys:$symb"}=$allkeys;
4829: if (untie(%hash)) {
4830: return 'ok';
4831: } else {
4832: return "error:$!";
4833: }
4834: } else {
4835: return "error:$!";
4836: }
4837: }
1.167 albertel 4838:
1.168 albertel 4839: # -----------------------------------------------------------------Temp Restore
1.167 albertel 4840:
1.168 albertel 4841: sub tmprestore {
4842: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 4843:
1.168 albertel 4844: if (!$symb) {
4845: $symb=&symbread();
1.620 albertel 4846: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4847: }
4848: $symb=escape($symb);
4849:
1.620 albertel 4850: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 4851:
1.620 albertel 4852: if (!$domain) { $domain=$env{'user.domain'}; }
4853: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4854: if ($domain eq 'public' && $stuname eq 'public') {
4855: $stuname=$ENV{'REMOTE_ADDR'};
4856: }
1.168 albertel 4857: my %returnhash;
4858: $namespace=~s/\//\_/g;
4859: $namespace=~s/\W//g;
4860: my %hash;
1.1117 foxr 4861: my $path=LONCAPA::tempdir();
1.168 albertel 4862: if (tie(%hash,'GDBM_File',
4863: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4864: &GDBM_READER(),0640)) {
1.168 albertel 4865: my $version=$hash{"version:$symb"};
4866: $returnhash{'version'}=$version;
4867: my $scope;
4868: for ($scope=1;$scope<=$version;$scope++) {
4869: my $vkeys=$hash{"$scope:keys:$symb"};
4870: my @keys=split(/:/,$vkeys);
4871: my $key;
4872: $returnhash{"$scope:keys"}=$vkeys;
4873: foreach $key (@keys) {
1.591 albertel 4874: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
4875: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 4876: }
4877: }
1.168 albertel 4878: if (!(untie(%hash))) {
4879: return "error:$!";
4880: }
4881: } else {
4882: return "error:$!";
4883: }
4884: return %returnhash;
1.167 albertel 4885: }
4886:
1.9 www 4887: # ----------------------------------------------------------------------- Store
4888:
4889: sub store {
1.1269 raeburn 4890: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 4891: my $home='';
4892:
1.168 albertel 4893: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4894:
1.213 www 4895: $symb=&symbclean($symb);
1.122 albertel 4896: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 4897:
1.620 albertel 4898: if (!$domain) { $domain=$env{'user.domain'}; }
4899: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 4900:
4901: &devalidate($symb,$stuname,$domain);
1.109 www 4902:
4903: $symb=escape($symb);
1.187 www 4904: if (!$namespace) {
1.620 albertel 4905: unless ($namespace=$env{'request.course.id'}) {
1.187 www 4906: return '';
4907: }
4908: }
1.620 albertel 4909: if (!$home) { $home=$env{'user.home'}; }
1.447 www 4910:
4911: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4912: $$storehash{'host'}=$perlvar{'lonHostID'};
4913:
1.12 www 4914: my $namevalue='';
1.800 albertel 4915: foreach my $key (keys(%$storehash)) {
4916: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 4917: }
1.12 www 4918: $namevalue=~s/\&$//;
1.187 www 4919: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1269 raeburn 4920: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9 www 4921: }
4922:
1.47 www 4923: # -------------------------------------------------------------- Critical Store
4924:
4925: sub cstore {
1.1269 raeburn 4926: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 4927: my $home='';
4928:
1.168 albertel 4929: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4930:
1.213 www 4931: $symb=&symbclean($symb);
1.122 albertel 4932: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 4933:
1.620 albertel 4934: if (!$domain) { $domain=$env{'user.domain'}; }
4935: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 4936:
4937: &devalidate($symb,$stuname,$domain);
1.109 www 4938:
4939: $symb=escape($symb);
1.187 www 4940: if (!$namespace) {
1.620 albertel 4941: unless ($namespace=$env{'request.course.id'}) {
1.187 www 4942: return '';
4943: }
4944: }
1.620 albertel 4945: if (!$home) { $home=$env{'user.home'}; }
1.447 www 4946:
4947: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4948: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 4949:
1.47 www 4950: my $namevalue='';
1.800 albertel 4951: foreach my $key (keys(%$storehash)) {
4952: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 4953: }
1.47 www 4954: $namevalue=~s/\&$//;
1.187 www 4955: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 4956: return critical
1.1269 raeburn 4957: ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47 www 4958: }
4959:
1.9 www 4960: # --------------------------------------------------------------------- Restore
4961:
4962: sub restore {
1.124 www 4963: my ($symb,$namespace,$domain,$stuname) = @_;
4964: my $home='';
4965:
1.168 albertel 4966: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4967:
1.122 albertel 4968: if (!$symb) {
1.1224 raeburn 4969: return if ($namespace eq 'courserequests');
4970: unless ($symb=escape(&symbread())) { return ''; }
1.122 albertel 4971: } else {
1.1224 raeburn 4972: unless ($namespace eq 'courserequests') {
4973: $symb=&escape(&symbclean($symb));
4974: }
1.122 albertel 4975: }
1.188 www 4976: if (!$namespace) {
1.620 albertel 4977: unless ($namespace=$env{'request.course.id'}) {
1.188 www 4978: return '';
4979: }
4980: }
1.620 albertel 4981: if (!$domain) { $domain=$env{'user.domain'}; }
4982: if (!$stuname) { $stuname=$env{'user.name'}; }
4983: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 4984: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
4985:
1.12 www 4986: my %returnhash=();
1.800 albertel 4987: foreach my $line (split(/\&/,$answer)) {
4988: my ($name,$value)=split(/\=/,$line);
1.591 albertel 4989: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 4990: }
1.75 www 4991: my $version;
4992: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 4993: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
4994: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 4995: }
1.75 www 4996: }
1.13 www 4997: return %returnhash;
1.34 www 4998: }
4999:
5000: # ---------------------------------------------------------- Course Description
1.1118 foxr 5001: #
5002: #
1.34 www 5003:
5004: sub coursedescription {
1.731 albertel 5005: my ($courseid,$args)=@_;
1.34 www 5006: $courseid=~s/^\///;
1.49 www 5007: $courseid=~s/\_/\//g;
1.34 www 5008: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 5009: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 5010: my $normalid=$cdomain.'_'.$cnum;
5011: # need to always cache even if we get errors otherwise we keep
5012: # trying and trying and trying to get the course description.
5013: my %envhash=();
5014: my %returnhash=();
1.731 albertel 5015:
5016: my $expiretime=600;
5017: if ($env{'request.course.id'} eq $normalid) {
5018: $expiretime=120;
5019: }
5020:
5021: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
5022: if (!$args->{'freshen_cache'}
5023: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
5024: foreach my $key (keys(%env)) {
5025: next if ($key !~ /^\Q$prefix\E(.*)/);
5026: my ($setting) = $1;
5027: $returnhash{$setting} = $env{$key};
5028: }
5029: return %returnhash;
5030: }
5031:
1.1118 foxr 5032: # get the data again
5033:
1.731 albertel 5034: if (!$args->{'one_time'}) {
5035: $envhash{'course.'.$normalid.'.last_cache'}=time;
5036: }
1.811 albertel 5037:
1.34 www 5038: if ($chome ne 'no_host') {
1.302 albertel 5039: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 5040: if (!exists($returnhash{'con_lost'})) {
1.1118 foxr 5041: my $username = $env{'user.name'}; # Defult username
5042: if(defined $args->{'user'}) {
5043: $username = $args->{'user'};
5044: }
1.129 albertel 5045: $returnhash{'home'}= $chome;
5046: $returnhash{'domain'} = $cdomain;
5047: $returnhash{'num'} = $cnum;
1.741 raeburn 5048: if (!defined($returnhash{'type'})) {
5049: $returnhash{'type'} = 'Course';
5050: }
1.130 albertel 5051: while (my ($name,$value) = each %returnhash) {
1.53 www 5052: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 5053: }
1.270 www 5054: $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117 foxr 5055: $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118 foxr 5056: $username.'_'.$cdomain.'_'.$cnum;
1.60 www 5057: $envhash{'course.'.$normalid.'.home'}=$chome;
5058: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
5059: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 5060: }
5061: }
1.731 albertel 5062: if (!$args->{'one_time'}) {
1.949 raeburn 5063: &appenv(\%envhash);
1.731 albertel 5064: }
1.302 albertel 5065: return %returnhash;
1.461 www 5066: }
5067:
1.1080 raeburn 5068: sub update_released_required {
5069: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
5070: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
5071: $cid = $env{'request.course.id'};
5072: $cdom = $env{'course.'.$cid.'.domain'};
5073: $cnum = $env{'course.'.$cid.'.num'};
5074: $chome = $env{'course.'.$cid.'.home'};
5075: }
5076: if ($needsrelease) {
5077: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
5078: my $needsupdate;
5079: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
5080: $needsupdate = 1;
5081: } else {
5082: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
5083: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
5084: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
5085: $needsupdate = 1;
5086: }
5087: }
5088: if ($needsupdate) {
5089: my %needshash = (
5090: 'internal.releaserequired' => $needsrelease,
5091: );
5092: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
5093: if ($putresult eq 'ok') {
5094: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
5095: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
5096: if (ref($crsinfo{$cid}) eq 'HASH') {
5097: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
5098: &courseidput($cdom,\%crsinfo,$chome,'notime');
5099: }
5100: }
5101: }
5102: }
5103: return;
5104: }
5105:
1.461 www 5106: # -------------------------------------------------See if a user is privileged
5107:
5108: sub privileged {
1.1219 raeburn 5109: my ($username,$domain,$possdomains,$possroles)=@_;
1.1170 droeschl 5110: my $now = time;
1.1219 raeburn 5111: my $roles;
5112: if (ref($possroles) eq 'ARRAY') {
5113: $roles = $possroles;
5114: } else {
5115: $roles = ['dc','su'];
5116: }
5117: if (ref($possdomains) eq 'ARRAY') {
5118: my %privileged = &privileged_by_domain($possdomains,$roles);
5119: foreach my $dom (@{$possdomains}) {
5120: if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
5121: (ref($privileged{$dom}) eq 'HASH')) {
5122: foreach my $role (@{$roles}) {
5123: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5124: if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
5125: my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
5126: return 1 unless (($end && $end < $now) ||
5127: ($start && $start > $now));
5128: }
5129: }
5130: }
5131: }
5132: }
5133: } else {
5134: my %rolesdump = &dump("roles", $domain, $username) or return 0;
5135: my $now = time;
1.1170 droeschl 5136:
1.1275 musolffc 5137: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170 droeschl 5138: my ($trole, $tend, $tstart) = split(/_/, $role);
1.1219 raeburn 5139: if (grep(/^\Q$trole\E$/,@{$roles})) {
1.1170 droeschl 5140: return 1 unless ($tend && $tend < $now)
1.1219 raeburn 5141: or ($tstart && $tstart > $now);
1.1170 droeschl 5142: }
1.1219 raeburn 5143: }
5144: }
5145: return 0;
5146: }
1.1170 droeschl 5147:
1.1219 raeburn 5148: sub privileged_by_domain {
5149: my ($domains,$roles) = @_;
5150: my %privileged = ();
5151: my $cachetime = 60*60*24;
5152: my $now = time;
5153: unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
5154: return %privileged;
5155: }
5156: foreach my $dom (@{$domains}) {
5157: next if (ref($privileged{$dom}) eq 'HASH');
5158: my $needroles;
5159: foreach my $role (@{$roles}) {
5160: my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
5161: if (defined($cached)) {
5162: if (ref($result) eq 'HASH') {
5163: $privileged{$dom}{$role} = $result;
5164: }
5165: } else {
5166: $needroles = 1;
5167: }
5168: }
5169: if ($needroles) {
5170: my %dompersonnel = &get_domain_roles($dom,$roles);
5171: $privileged{$dom} = {};
5172: foreach my $server (keys(%dompersonnel)) {
5173: if (ref($dompersonnel{$server}) eq 'HASH') {
5174: foreach my $item (keys(%{$dompersonnel{$server}})) {
5175: my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
5176: my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
5177: next if ($end && $end < $now);
5178: $privileged{$dom}{$trole}{$uname.':'.$udom} =
5179: $dompersonnel{$server}{$item};
5180: }
5181: }
5182: }
5183: if (ref($privileged{$dom}) eq 'HASH') {
5184: foreach my $role (@{$roles}) {
5185: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5186: &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
5187: } else {
5188: my %hash = ();
5189: &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
5190: }
5191: }
5192: }
5193: }
5194: }
5195: return %privileged;
1.9 www 5196: }
1.1 albertel 5197:
1.103 harris41 5198: # -------------------------------------------------------- Get user privileges
1.11 www 5199:
5200: sub rolesinit {
1.1169 droeschl 5201: my ($domain, $username) = @_;
5202: my %userroles = ('user.login.time' => time);
5203: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
5204:
5205: # firstaccess and timerinterval are related to timed maps/resources.
5206: # also, blocking can be triggered by an activating timer
5207: # it's saved in the user's %env.
5208: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
5209: my %timerinterval = &dump('timerinterval', $domain, $username);
5210: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
5211: %timerintchk, %timerintenv);
5212:
1.1162 raeburn 5213: foreach my $key (keys(%firstaccess)) {
1.1169 droeschl 5214: my ($cid, $rest) = split(/\0/, $key);
1.1162 raeburn 5215: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
5216: }
1.1169 droeschl 5217:
1.1162 raeburn 5218: foreach my $key (keys(%timerinterval)) {
5219: my ($cid,$rest) = split(/\0/,$key);
5220: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
5221: }
1.1169 droeschl 5222:
1.11 www 5223: my %allroles=();
1.1162 raeburn 5224: my %allgroups=();
1.11 www 5225:
1.1274 raeburn 5226: for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169 droeschl 5227: my $role = $rolesdump{$area};
5228: $area =~ s/\_\w\w$//;
5229:
5230: my ($trole, $tend, $tstart, $group_privs);
5231:
5232: if ($role =~ /^cr/) {
5233: # Custom role, defined by a user
5234: # e.g., user.role.cr/msu/smith/mynewrole
5235: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
5236: $trole = $1;
5237: ($tend, $tstart) = split('_', $2);
5238: } else {
5239: $trole = $role;
5240: }
5241: } elsif ($role =~ m|^gr/|) {
5242: # Role of member in a group, defined within a course/community
5243: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
5244: ($trole, $tend, $tstart) = split(/_/, $role);
5245: next if $tstart eq '-1';
5246: ($trole, $group_privs) = split(/\//, $trole);
5247: $group_privs = &unescape($group_privs);
5248: } else {
5249: # Just a normal role, defined in roles.tab
5250: ($trole, $tend, $tstart) = split(/_/,$role);
5251: }
5252:
5253: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
5254: $username);
5255: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
5256:
5257: # role expired or not available yet?
5258: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
5259: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
5260:
5261: next if $area eq '' or $trole eq '';
5262:
5263: my $spec = "$trole.$area";
5264: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
5265:
5266: if ($trole =~ /^cr\//) {
5267: # Custom role, defined by a user
5268: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5269: } elsif ($trole eq 'gr') {
5270: # Role of a member in a group, defined within a course/community
5271: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
5272: next;
5273: } else {
5274: # Normal role, defined in roles.tab
5275: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5276: }
5277:
5278: my $cid = $tdomain.'_'.$trest;
5279: unless ($firstaccchk{$cid}) {
5280: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
5281: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
5282: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
5283: $coursetimerstarts{$cid}{$item};
5284: }
5285: }
5286: $firstaccchk{$cid} = 1;
5287: }
5288: unless ($timerintchk{$cid}) {
5289: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
5290: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
5291: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
5292: $coursetimerintervals{$cid}{$item};
1.1162 raeburn 5293: }
1.12 www 5294: }
1.1169 droeschl 5295: $timerintchk{$cid} = 1;
1.191 harris41 5296: }
1.11 www 5297: }
1.1169 droeschl 5298:
5299: @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
5300: \%allroles, \%allgroups);
5301: $env{'user.adv'} = $userroles{'user.adv'};
5302:
1.1162 raeburn 5303: return (\%userroles,\%firstaccenv,\%timerintenv);
1.11 www 5304: }
5305:
1.567 raeburn 5306: sub set_arearole {
1.1215 raeburn 5307: my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
5308: unless ($nolog) {
1.567 raeburn 5309: # log the associated role with the area
1.1215 raeburn 5310: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
5311: }
1.743 albertel 5312: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 5313: }
5314:
5315: sub custom_roleprivs {
5316: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
5317: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1250 raeburn 5318: my $homsvr = &homeserver($rauthor,$rdomain);
1.838 albertel 5319: if (&hostname($homsvr) ne '') {
1.567 raeburn 5320: my ($rdummy,$roledef)=
5321: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
5322: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
5323: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
5324: if (defined($syspriv)) {
1.1043 raeburn 5325: if ($trest =~ /^$match_community$/) {
5326: $syspriv =~ s/bre\&S//;
5327: }
1.567 raeburn 5328: $$allroles{'cm./'}.=':'.$syspriv;
5329: $$allroles{$spec.'./'}.=':'.$syspriv;
5330: }
5331: if ($tdomain ne '') {
5332: if (defined($dompriv)) {
5333: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
5334: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
5335: }
5336: if (($trest ne '') && (defined($coursepriv))) {
5337: $$allroles{'cm.'.$area}.=':'.$coursepriv;
5338: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
5339: }
5340: }
5341: }
5342: }
5343: }
5344:
1.678 raeburn 5345: sub group_roleprivs {
5346: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
5347: my $access = 1;
5348: my $now = time;
5349: if (($tend!=0) && ($tend<$now)) { $access = 0; }
5350: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
5351: if ($access) {
1.811 albertel 5352: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 5353: $$allgroups{$course}{$group} .=':'.$group_privs;
5354: }
5355: }
1.567 raeburn 5356:
5357: sub standard_roleprivs {
5358: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
5359: if (defined($pr{$trole.':s'})) {
5360: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
5361: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
5362: }
5363: if ($tdomain ne '') {
5364: if (defined($pr{$trole.':d'})) {
5365: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5366: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5367: }
5368: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
5369: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
5370: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
5371: }
5372: }
5373: }
5374:
5375: sub set_userprivs {
1.1064 raeburn 5376: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 5377: my $author=0;
5378: my $adv=0;
1.678 raeburn 5379: my %grouproles = ();
5380: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 5381: my @groupkeys;
1.1000 raeburn 5382: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 5383: push(@groupkeys,$role);
5384: }
5385: if (ref($groups_roles) eq 'HASH') {
5386: foreach my $key (keys(%{$groups_roles})) {
5387: unless (grep(/^\Q$key\E$/,@groupkeys)) {
5388: push(@groupkeys,$key);
5389: }
5390: }
5391: }
5392: if (@groupkeys > 0) {
5393: foreach my $role (@groupkeys) {
5394: my ($trole,$area,$sec,$extendedarea);
5395: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
5396: $trole = $1;
5397: $area = $2;
5398: $sec = $3;
5399: $extendedarea = $area.$sec;
5400: if (exists($$allgroups{$area})) {
5401: foreach my $group (keys(%{$$allgroups{$area}})) {
5402: my $spec = $trole.'.'.$extendedarea;
5403: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 5404: $$allgroups{$area}{$group};
1.1064 raeburn 5405: }
1.678 raeburn 5406: }
5407: }
5408: }
5409: }
5410: }
1.800 albertel 5411: foreach my $group (keys(%grouproles)) {
5412: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 5413: }
1.800 albertel 5414: foreach my $role (keys(%{$allroles})) {
5415: my %thesepriv;
1.941 raeburn 5416: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 5417: foreach my $item (split(/:/,$$allroles{$role})) {
5418: if ($item ne '') {
5419: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 5420: if ($restrictions eq '') {
5421: $thesepriv{$privilege}='F';
5422: } elsif ($thesepriv{$privilege} ne 'F') {
5423: $thesepriv{$privilege}.=$restrictions;
5424: }
5425: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
5426: }
5427: }
5428: my $thesestr='';
1.1104 raeburn 5429: foreach my $priv (sort(keys(%thesepriv))) {
1.800 albertel 5430: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
5431: }
5432: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 5433: }
5434: return ($author,$adv);
5435: }
5436:
1.994 raeburn 5437: sub role_status {
1.1104 raeburn 5438: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 5439: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1250 raeburn 5440: my ($one,$two) = split(m{\./},$rolekey,2);
5441: (undef,undef,$$role) = split(/\./,$one,3);
1.994 raeburn 5442: unless (!defined($$role) || $$role eq '') {
1.1251 raeburn 5443: $$where = '/'.$two;
1.994 raeburn 5444: $$trolecode=$$role.'.'.$$where;
5445: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
5446: $$tstatus='is';
1.1104 raeburn 5447: if ($$tstart && $$tstart>$update) {
1.994 raeburn 5448: $$tstatus='future';
1.1034 raeburn 5449: if ($$tstart<$now) {
5450: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 5451: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 5452: my (%allroles,%allgroups,$group_privs,
5453: %groups_roles,@rolecodes);
1.1002 raeburn 5454: my %userroles = (
5455: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
5456: );
1.1064 raeburn 5457: @rolecodes = ('cm');
1.1002 raeburn 5458: my $spec=$$role.'.'.$$where;
5459: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
5460: if ($$role =~ /^cr\//) {
5461: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 5462: push(@rolecodes,'cr');
1.1002 raeburn 5463: } elsif ($$role eq 'gr') {
1.1064 raeburn 5464: push(@rolecodes,$$role);
1.1002 raeburn 5465: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
5466: $env{'user.name'});
1.1064 raeburn 5467: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 5468: (undef,my $group_privs) = split(/\//,$trole);
5469: $group_privs = &unescape($group_privs);
5470: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 5471: 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 5472: &get_groups_roles($tdomain,$trest,
5473: \%course_roles,\@rolecodes,
5474: \%groups_roles);
1.1002 raeburn 5475: } else {
1.1064 raeburn 5476: push(@rolecodes,$$role);
1.1002 raeburn 5477: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
5478: }
1.1064 raeburn 5479: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
5480: &appenv(\%userroles,\@rolecodes);
1.1002 raeburn 5481: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
5482: }
5483: }
1.1034 raeburn 5484: $$tstatus = 'is';
1.1002 raeburn 5485: }
1.994 raeburn 5486: }
5487: if ($$tend) {
1.1104 raeburn 5488: if ($$tend<$update) {
1.994 raeburn 5489: $$tstatus='expired';
5490: } elsif ($$tend<$now) {
5491: $$tstatus='will_not';
5492: }
5493: }
5494: }
5495: }
5496: }
5497:
1.1104 raeburn 5498: sub get_groups_roles {
5499: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
5500: return unless((ref($cdom_courseroles) eq 'HASH') &&
5501: (ref($rolecodes) eq 'ARRAY') &&
5502: (ref($groups_roles) eq 'HASH'));
5503: if (keys(%{$cdom_courseroles}) > 0) {
5504: my ($cnum) = ($rest =~ /^($match_courseid)/);
5505: if ($cdom ne '' && $cnum ne '') {
5506: foreach my $key (keys(%{$cdom_courseroles})) {
5507: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
5508: my $crsrole = $1;
5509: my $crssec = $2;
5510: if ($crsrole =~ /^cr/) {
5511: unless (grep(/^cr$/,@{$rolecodes})) {
5512: push(@{$rolecodes},'cr');
5513: }
5514: } else {
5515: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
5516: push(@{$rolecodes},$crsrole);
5517: }
5518: }
5519: my $rolekey = "$crsrole./$cdom/$cnum";
5520: if ($crssec ne '') {
5521: $rolekey .= "/$crssec";
5522: }
5523: $rolekey .= './';
5524: $groups_roles->{$rolekey} = $rolecodes;
5525: }
5526: }
5527: }
5528: }
5529: return;
5530: }
5531:
5532: sub delete_env_groupprivs {
5533: my ($where,$courseroles,$possroles) = @_;
5534: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
5535: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
5536: unless (ref($courseroles->{$udom}) eq 'HASH') {
5537: %{$courseroles->{$udom}} =
5538: &get_my_roles('','','userroles',['active'],
5539: $possroles,[$udom],1);
5540: }
5541: if (ref($courseroles->{$udom}) eq 'HASH') {
5542: foreach my $item (keys(%{$courseroles->{$udom}})) {
5543: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
5544: my $area = '/'.$cdom.'/'.$cnum;
5545: my $privkey = "user.priv.$crsrole.$area";
5546: if ($crssec ne '') {
5547: $privkey .= '/'.$crssec;
5548: }
5549: $privkey .= ".$area/$group";
5550: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
5551: }
5552: }
5553: return;
5554: }
5555:
1.994 raeburn 5556: sub check_adhoc_privs {
1.1104 raeburn 5557: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994 raeburn 5558: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1185 raeburn 5559: my $setprivs;
1.994 raeburn 5560: if ($env{$cckey}) {
5561: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104 raeburn 5562: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 5563: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088 raeburn 5564: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185 raeburn 5565: $setprivs = 1;
1.994 raeburn 5566: }
5567: } else {
1.1088 raeburn 5568: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185 raeburn 5569: $setprivs = 1;
1.994 raeburn 5570: }
1.1185 raeburn 5571: return $setprivs;
1.994 raeburn 5572: }
5573:
5574: sub set_adhoc_privileges {
5575: # role can be cc or ca
1.1088 raeburn 5576: my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994 raeburn 5577: my $area = '/'.$dcdom.'/'.$pickedcourse;
5578: my $spec = $role.'.'.$area;
5579: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1215 raeburn 5580: $env{'user.name'},1);
1.994 raeburn 5581: my %ccrole = ();
5582: &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
5583: my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
5584: &appenv(\%userroles,[$role,'cm']);
5585: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088 raeburn 5586: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
5587: &appenv( {'request.role' => $spec,
5588: 'request.role.domain' => $dcdom,
5589: 'request.course.sec' => ''
5590: }
5591: );
5592: my $tadv=0;
5593: if (&allowed('adv') eq 'F') { $tadv=1; }
5594: &appenv({'request.role.adv' => $tadv});
5595: }
1.994 raeburn 5596: }
5597:
1.12 www 5598: # --------------------------------------------------------------- get interface
5599:
5600: sub get {
1.131 albertel 5601: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 5602: my $items='';
1.800 albertel 5603: foreach my $item (@$storearr) {
5604: $items.=&escape($item).'&';
1.191 harris41 5605: }
1.12 www 5606: $items=~s/\&$//;
1.620 albertel 5607: if (!$udomain) { $udomain=$env{'user.domain'}; }
5608: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 5609: my $uhome=&homeserver($uname,$udomain);
5610:
1.133 albertel 5611: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 5612: my @pairs=split(/\&/,$rep);
1.273 albertel 5613: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
5614: return @pairs;
5615: }
1.15 www 5616: my %returnhash=();
1.42 www 5617: my $i=0;
1.800 albertel 5618: foreach my $item (@$storearr) {
5619: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 5620: $i++;
1.191 harris41 5621: }
1.15 www 5622: return %returnhash;
1.27 www 5623: }
5624:
5625: # --------------------------------------------------------------- del interface
5626:
5627: sub del {
1.133 albertel 5628: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 5629: my $items='';
1.800 albertel 5630: foreach my $item (@$storearr) {
5631: $items.=&escape($item).'&';
1.191 harris41 5632: }
1.984 neumanie 5633:
1.27 www 5634: $items=~s/\&$//;
1.620 albertel 5635: if (!$udomain) { $udomain=$env{'user.domain'}; }
5636: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 5637: my $uhome=&homeserver($uname,$udomain);
5638: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 5639: }
5640:
5641: # -------------------------------------------------------------- dump interface
5642:
1.1180 droeschl 5643: sub unserialize {
5644: my ($rep, $escapedkeys) = @_;
5645:
5646: return {} if $rep =~ /^error/;
5647:
5648: my %returnhash=();
1.1252 raeburn 5649: foreach my $item (split(/\&/,$rep)) {
1.1180 droeschl 5650: my ($key, $value) = split(/=/, $item, 2);
5651: $key = unescape($key) unless $escapedkeys;
5652: next if $key =~ /^error: 2 /;
1.1252 raeburn 5653: $returnhash{$key} = &thaw_unescape($value);
1.1180 droeschl 5654: }
5655: #return %returnhash;
5656: return \%returnhash;
5657: }
5658:
5659: # see Lond::dump_with_regexp
5660: # if $escapedkeys hash keys won't get unescaped.
1.15 www 5661: sub dump {
1.1180 droeschl 5662: my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755 albertel 5663: if (!$udomain) { $udomain=$env{'user.domain'}; }
5664: if (!$uname) { $uname=$env{'user.name'}; }
5665: my $uhome=&homeserver($uname,$udomain);
1.1167 droeschl 5666:
1.1266 raeburn 5667: if ($regexp) {
5668: $regexp=&escape($regexp);
5669: } else {
5670: $regexp='.';
5671: }
1.1180 droeschl 5672: if (grep { $_ eq $uhome } current_machine_ids()) {
5673: # user is hosted on this machine
1.1266 raeburn 5674: my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
1.1226 raeburn 5675: $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1180 droeschl 5676: return %{unserialize($reply, $escapedkeys)};
5677: }
1.1166 raeburn 5678: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755 albertel 5679: my @pairs=split(/\&/,$rep);
5680: my %returnhash=();
1.1098 foxr 5681: if (!($rep =~ /^error/ )) {
5682: foreach my $item (@pairs) {
5683: my ($key,$value)=split(/=/,$item,2);
1.1180 droeschl 5684: $key = unescape($key) unless $escapedkeys;
5685: #$key = &unescape($key);
1.1098 foxr 5686: next if ($key =~ /^error: 2 /);
5687: $returnhash{$key}=&thaw_unescape($value);
5688: }
1.755 albertel 5689: }
5690: return %returnhash;
1.407 www 5691: }
5692:
1.1098 foxr 5693:
1.717 albertel 5694: # --------------------------------------------------------- dumpstore interface
5695:
5696: sub dumpstore {
5697: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180 droeschl 5698: # same as dump but keys must be escaped. They may contain colon separated
5699: # lists of values that may themself contain colons (e.g. symbs).
5700: return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717 albertel 5701: }
5702:
1.407 www 5703: # -------------------------------------------------------------- keys interface
5704:
5705: sub getkeys {
5706: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 5707: if (!$udomain) { $udomain=$env{'user.domain'}; }
5708: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 5709: my $uhome=&homeserver($uname,$udomain);
5710: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
5711: my @keyarray=();
1.800 albertel 5712: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 5713: next if ($key =~ /^error: 2 /);
1.800 albertel 5714: push(@keyarray,&unescape($key));
1.407 www 5715: }
5716: return @keyarray;
1.318 matthew 5717: }
5718:
1.319 matthew 5719: # --------------------------------------------------------------- currentdump
5720: sub currentdump {
1.328 matthew 5721: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 5722: $courseid = $env{'request.course.id'} if (! defined($courseid));
5723: $sdom = $env{'user.domain'} if (! defined($sdom));
5724: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 5725: my $uhome = &homeserver($sname,$sdom);
1.1180 droeschl 5726: my $rep;
5727:
5728: if (grep { $_ eq $uhome } current_machine_ids()) {
5729: $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
5730: $courseid)));
5731: } else {
5732: $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
5733: }
5734:
1.318 matthew 5735: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 5736: #
1.318 matthew 5737: my %returnhash=();
1.319 matthew 5738: #
5739: if ($rep eq "unknown_cmd") {
5740: # an old lond will not know currentdump
5741: # Do a dump and make it look like a currentdump
1.822 albertel 5742: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 5743: return if ($tmp[0] =~ /^(error:|no_such_host)/);
5744: my %hash = @tmp;
5745: @tmp=();
1.424 matthew 5746: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 5747: } else {
5748: my @pairs=split(/\&/,$rep);
1.800 albertel 5749: foreach my $pair (@pairs) {
5750: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 5751: my ($symb,$param) = split(/:/,$key);
5752: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 5753: &thaw_unescape($value);
1.319 matthew 5754: }
1.191 harris41 5755: }
1.12 www 5756: return %returnhash;
1.424 matthew 5757: }
5758:
5759: sub convert_dump_to_currentdump{
5760: my %hash = %{shift()};
5761: my %returnhash;
5762: # Code ripped from lond, essentially. The only difference
5763: # here is the unescaping done by lonnet::dump(). Conceivably
5764: # we might run in to problems with parameter names =~ /^v\./
5765: while (my ($key,$value) = each(%hash)) {
5766: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 5767: $symb = &unescape($symb);
5768: $param = &unescape($param);
1.424 matthew 5769: next if ($v eq 'version' || $symb eq 'keys');
5770: next if (exists($returnhash{$symb}) &&
5771: exists($returnhash{$symb}->{$param}) &&
5772: $returnhash{$symb}->{'v.'.$param} > $v);
5773: $returnhash{$symb}->{$param}=$value;
5774: $returnhash{$symb}->{'v.'.$param}=$v;
5775: }
5776: #
5777: # Remove all of the keys in the hashes which keep track of
5778: # the version of the parameter.
5779: while (my ($symb,$param_hash) = each(%returnhash)) {
5780: # use a foreach because we are going to delete from the hash.
5781: foreach my $key (keys(%$param_hash)) {
5782: delete($param_hash->{$key}) if ($key =~ /^v\./);
5783: }
5784: }
5785: return \%returnhash;
1.12 www 5786: }
5787:
1.627 albertel 5788: # ------------------------------------------------------ critical inc interface
5789:
5790: sub cinc {
5791: return &inc(@_,'critical');
5792: }
5793:
1.449 matthew 5794: # --------------------------------------------------------------- inc interface
5795:
5796: sub inc {
1.627 albertel 5797: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 5798: if (!$udomain) { $udomain=$env{'user.domain'}; }
5799: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 5800: my $uhome=&homeserver($uname,$udomain);
5801: my $items='';
5802: if (! ref($store)) {
5803: # got a single value, so use that instead
5804: $items = &escape($store).'=&';
5805: } elsif (ref($store) eq 'SCALAR') {
5806: $items = &escape($$store).'=&';
5807: } elsif (ref($store) eq 'ARRAY') {
5808: $items = join('=&',map {&escape($_);} @{$store});
5809: } elsif (ref($store) eq 'HASH') {
5810: while (my($key,$value) = each(%{$store})) {
5811: $items.= &escape($key).'='.&escape($value).'&';
5812: }
5813: }
5814: $items=~s/\&$//;
1.627 albertel 5815: if ($critical) {
5816: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
5817: } else {
5818: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
5819: }
1.449 matthew 5820: }
5821:
1.12 www 5822: # --------------------------------------------------------------- put interface
5823:
5824: sub put {
1.134 albertel 5825: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 5826: if (!$udomain) { $udomain=$env{'user.domain'}; }
5827: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 5828: my $uhome=&homeserver($uname,$udomain);
1.12 www 5829: my $items='';
1.800 albertel 5830: foreach my $item (keys(%$storehash)) {
5831: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 5832: }
1.12 www 5833: $items=~s/\&$//;
1.134 albertel 5834: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 5835: }
5836:
1.631 albertel 5837: # ------------------------------------------------------------ newput interface
5838:
5839: sub newput {
5840: my ($namespace,$storehash,$udomain,$uname)=@_;
5841: if (!$udomain) { $udomain=$env{'user.domain'}; }
5842: if (!$uname) { $uname=$env{'user.name'}; }
5843: my $uhome=&homeserver($uname,$udomain);
5844: my $items='';
5845: foreach my $key (keys(%$storehash)) {
5846: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
5847: }
5848: $items=~s/\&$//;
5849: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
5850: }
5851:
5852: # --------------------------------------------------------- putstore interface
5853:
1.524 raeburn 5854: sub putstore {
1.1269 raeburn 5855: my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620 albertel 5856: if (!$udomain) { $udomain=$env{'user.domain'}; }
5857: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 5858: my $uhome=&homeserver($uname,$udomain);
5859: my $items='';
1.715 albertel 5860: foreach my $key (keys(%$storehash)) {
5861: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 5862: }
1.715 albertel 5863: $items=~s/\&$//;
1.716 albertel 5864: my $esc_symb=&escape($symb);
5865: my $esc_v=&escape($version);
1.715 albertel 5866: my $reply =
1.716 albertel 5867: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 5868: $uhome);
1.1269 raeburn 5869: if (($tolog) && ($reply eq 'ok')) {
5870: my $namevalue='';
5871: foreach my $key (keys(%{$storehash})) {
5872: $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
5873: }
5874: $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
5875: '&host='.&escape($perlvar{'lonHostID'}).
5876: '&version='.$esc_v.
5877: '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
5878: &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
5879: }
1.715 albertel 5880: if ($reply eq 'unknown_cmd') {
1.716 albertel 5881: # gfall back to way things use to be done
1.715 albertel 5882: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
5883: $uname);
1.524 raeburn 5884: }
1.715 albertel 5885: return $reply;
5886: }
5887:
5888: sub old_putstore {
1.716 albertel 5889: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
5890: if (!$udomain) { $udomain=$env{'user.domain'}; }
5891: if (!$uname) { $uname=$env{'user.name'}; }
5892: my $uhome=&homeserver($uname,$udomain);
5893: my %newstorehash;
1.800 albertel 5894: foreach my $item (keys(%$storehash)) {
5895: my $key = $version.':'.&escape($symb).':'.$item;
5896: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 5897: }
5898: my $items='';
5899: my %allitems = ();
1.800 albertel 5900: foreach my $item (keys(%newstorehash)) {
5901: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 5902: my $key = $1.':keys:'.$2;
5903: $allitems{$key} .= $3.':';
5904: }
1.800 albertel 5905: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 5906: }
1.800 albertel 5907: foreach my $item (keys(%allitems)) {
5908: $allitems{$item} =~ s/\:$//;
5909: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 5910: }
5911: $items=~s/\&$//;
5912: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 5913: }
5914:
1.47 www 5915: # ------------------------------------------------------ critical put interface
5916:
5917: sub cput {
1.134 albertel 5918: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 5919: if (!$udomain) { $udomain=$env{'user.domain'}; }
5920: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 5921: my $uhome=&homeserver($uname,$udomain);
1.47 www 5922: my $items='';
1.800 albertel 5923: foreach my $item (keys(%$storehash)) {
5924: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 5925: }
1.47 www 5926: $items=~s/\&$//;
1.134 albertel 5927: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 5928: }
5929:
5930: # -------------------------------------------------------------- eget interface
5931:
5932: sub eget {
1.133 albertel 5933: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 5934: my $items='';
1.800 albertel 5935: foreach my $item (@$storearr) {
5936: $items.=&escape($item).'&';
1.191 harris41 5937: }
1.12 www 5938: $items=~s/\&$//;
1.620 albertel 5939: if (!$udomain) { $udomain=$env{'user.domain'}; }
5940: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 5941: my $uhome=&homeserver($uname,$udomain);
5942: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 5943: my @pairs=split(/\&/,$rep);
5944: my %returnhash=();
1.42 www 5945: my $i=0;
1.800 albertel 5946: foreach my $item (@$storearr) {
5947: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 5948: $i++;
1.191 harris41 5949: }
1.12 www 5950: return %returnhash;
5951: }
5952:
1.667 albertel 5953: # ------------------------------------------------------------ tmpput interface
5954: sub tmpput {
1.802 raeburn 5955: my ($storehash,$server,$context)=@_;
1.667 albertel 5956: my $items='';
1.800 albertel 5957: foreach my $item (keys(%$storehash)) {
5958: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 5959: }
5960: $items=~s/\&$//;
1.802 raeburn 5961: if (defined($context)) {
5962: $items .= ':'.&escape($context);
5963: }
1.667 albertel 5964: return &reply("tmpput:$items",$server);
5965: }
5966:
5967: # ------------------------------------------------------------ tmpget interface
5968: sub tmpget {
1.688 albertel 5969: my ($token,$server)=@_;
5970: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5971: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 5972: my %returnhash;
5973: foreach my $item (split(/\&/,$rep)) {
5974: my ($key,$value)=split(/=/,$item);
1.951 raeburn 5975: next if ($key =~ /^error: 2 /);
1.667 albertel 5976: $returnhash{&unescape($key)}=&thaw_unescape($value);
5977: }
5978: return %returnhash;
5979: }
5980:
1.1113 raeburn 5981: # ------------------------------------------------------------ tmpdel interface
1.688 albertel 5982: sub tmpdel {
5983: my ($token,$server)=@_;
5984: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5985: return &reply("tmpdel:$token",$server);
5986: }
5987:
1.1198 raeburn 5988: # ------------------------------------------------------------ get_timebased_id
5989:
5990: sub get_timebased_id {
5991: my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
5992: $maxtries) = @_;
5993: my ($newid,$error,$dellock);
5994: unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
5995: return ('','ok','invalid call to get suffix');
5996: }
5997:
5998: # set defaults for any optional args for which values were not supplied
5999: if ($who eq '') {
6000: $who = $env{'user.name'}.':'.$env{'user.domain'};
6001: }
6002: if (!$locktries) {
6003: $locktries = 3;
6004: }
6005: if (!$maxtries) {
6006: $maxtries = 10;
6007: }
6008:
6009: if (($cdom eq '') || ($cnum eq '')) {
6010: if ($env{'request.course.id'}) {
6011: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6012: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6013: }
6014: if (($cdom eq '') || ($cnum eq '')) {
6015: return ('','ok','call to get suffix not in course context');
6016: }
6017: }
6018:
6019: # construct locking item
6020: my $lockhash = {
6021: $prefix."\0".'locked_'.$keyid => $who,
6022: };
6023: my $tries = 0;
6024:
6025: # attempt to get lock on nohist_$namespace file
6026: my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
6027: while (($gotlock ne 'ok') && $tries <$locktries) {
6028: $tries ++;
6029: sleep 1;
6030: $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
6031: }
6032:
6033: # attempt to get unique identifier, based on current timestamp
6034: if ($gotlock eq 'ok') {
6035: my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
6036: my $id = time;
6037: $newid = $id;
1.1268 raeburn 6038: if ($idtype eq 'addcode') {
6039: $newid .= &sixnum_code();
6040: }
1.1198 raeburn 6041: my $idtries = 0;
6042: while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
6043: if ($idtype eq 'concat') {
6044: $newid = $id.$idtries;
1.1268 raeburn 6045: } elsif ($idtype eq 'addcode') {
6046: $newid = $newid.&sixnum_code();
1.1198 raeburn 6047: } else {
6048: $newid ++;
6049: }
6050: $idtries ++;
6051: }
6052: if (!exists($inuse{$prefix."\0".$newid})) {
6053: my %new_item = (
6054: $prefix."\0".$newid => $who,
6055: );
6056: my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
6057: $cdom,$cnum);
6058: if ($putresult ne 'ok') {
6059: undef($newid);
6060: $error = 'error saving new item: '.$putresult;
6061: }
6062: } else {
1.1268 raeburn 6063: undef($newid);
1.1198 raeburn 6064: $error = ('error: no unique suffix available for the new item ');
6065: }
6066: # remove lock
6067: my @del_lock = ($prefix."\0".'locked_'.$keyid);
6068: $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
6069: } else {
6070: $error = "error: could not obtain lockfile\n";
6071: $dellock = 'ok';
1.1276 raeburn 6072: if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
6073: $dellock = 'nolock';
6074: }
1.1198 raeburn 6075: }
6076: return ($newid,$dellock,$error);
6077: }
6078:
1.1268 raeburn 6079: sub sixnum_code {
6080: my $code;
6081: for (0..6) {
6082: $code .= int( rand(9) );
6083: }
6084: return $code;
6085: }
6086:
1.765 albertel 6087: # -------------------------------------------------- portfolio access checking
6088:
6089: sub portfolio_access {
1.1270 raeburn 6090: my ($requrl,$clientip) = @_;
1.765 albertel 6091: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1270 raeburn 6092: my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814 raeburn 6093: if ($result) {
6094: my %setters;
6095: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6096: my ($startblock,$endblock) =
6097: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
6098: if ($startblock && $endblock) {
6099: return 'B';
6100: }
6101: } else {
6102: my ($startblock,$endblock) =
6103: &Apache::loncommon::blockcheck(\%setters,'port');
6104: if ($startblock && $endblock) {
6105: return 'B';
6106: }
6107: }
6108: }
1.765 albertel 6109: if ($result eq 'ok') {
1.766 albertel 6110: return 'F';
1.765 albertel 6111: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 6112: return 'A';
1.765 albertel 6113: }
1.766 albertel 6114: return '';
1.765 albertel 6115: }
6116:
6117: sub get_portfolio_access {
1.1270 raeburn 6118: my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767 albertel 6119:
6120: if (!ref($access_hash)) {
6121: my $current_perms = &get_portfile_permissions($udom,$unum);
6122: my %access_controls = &get_access_controls($current_perms,$group,
6123: $file_name);
6124: $access_hash = $access_controls{$file_name};
6125: }
6126:
1.1270 raeburn 6127: my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765 albertel 6128: my $now = time;
6129: if (ref($access_hash) eq 'HASH') {
6130: foreach my $key (keys(%{$access_hash})) {
6131: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
6132: if ($start > $now) {
6133: next;
6134: }
6135: if ($end && $end<$now) {
6136: next;
6137: }
6138: if ($scope eq 'public') {
6139: $public = $key;
6140: last;
6141: } elsif ($scope eq 'guest') {
6142: $guest = $key;
6143: } elsif ($scope eq 'domains') {
6144: push(@domains,$key);
6145: } elsif ($scope eq 'users') {
6146: push(@users,$key);
6147: } elsif ($scope eq 'course') {
6148: push(@courses,$key);
6149: } elsif ($scope eq 'group') {
6150: push(@groups,$key);
1.1270 raeburn 6151: } elsif ($scope eq 'ip') {
6152: push(@ips,$key);
1.765 albertel 6153: }
6154: }
6155: if ($public) {
6156: return 'ok';
1.1270 raeburn 6157: } elsif (@ips > 0) {
6158: my $allowed;
6159: foreach my $ipkey (@ips) {
6160: if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
6161: if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
6162: $allowed = 1;
6163: last;
6164: }
6165: }
6166: }
6167: if ($allowed) {
6168: return 'ok';
6169: }
1.765 albertel 6170: }
6171: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6172: if ($guest) {
6173: return $guest;
6174: }
6175: } else {
6176: if (@domains > 0) {
6177: foreach my $domkey (@domains) {
6178: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
6179: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
6180: return 'ok';
6181: }
6182: }
6183: }
6184: }
6185: if (@users > 0) {
6186: foreach my $userkey (@users) {
1.865 raeburn 6187: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
6188: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
6189: if (ref($item) eq 'HASH') {
6190: if (($item->{'uname'} eq $env{'user.name'}) &&
6191: ($item->{'udom'} eq $env{'user.domain'})) {
6192: return 'ok';
6193: }
6194: }
6195: }
6196: }
1.765 albertel 6197: }
6198: }
6199: my %roleshash;
6200: my @courses_and_groups = @courses;
6201: push(@courses_and_groups,@groups);
6202: if (@courses_and_groups > 0) {
6203: my (%allgroups,%allroles);
6204: my ($start,$end,$role,$sec,$group);
6205: foreach my $envkey (%env) {
1.1060 raeburn 6206: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6207: my $cid = $2.'_'.$3;
6208: if ($1 eq 'gr') {
6209: $group = $4;
6210: $allgroups{$cid}{$group} = $env{$envkey};
6211: } else {
6212: if ($4 eq '') {
6213: $sec = 'none';
6214: } else {
6215: $sec = $4;
6216: }
6217: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6218: }
1.811 albertel 6219: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6220: my $cid = $2.'_'.$3;
6221: if ($4 eq '') {
6222: $sec = 'none';
6223: } else {
6224: $sec = $4;
6225: }
6226: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6227: }
6228: }
6229: if (keys(%allroles) == 0) {
6230: return;
6231: }
6232: foreach my $key (@courses_and_groups) {
6233: my %content = %{$$access_hash{$key}};
6234: my $cnum = $content{'number'};
6235: my $cdom = $content{'domain'};
6236: my $cid = $cdom.'_'.$cnum;
6237: if (!exists($allroles{$cid})) {
6238: next;
6239: }
6240: foreach my $role_id (keys(%{$content{'roles'}})) {
6241: my @sections = @{$content{'roles'}{$role_id}{'section'}};
6242: my @groups = @{$content{'roles'}{$role_id}{'group'}};
6243: my @status = @{$content{'roles'}{$role_id}{'access'}};
6244: my @roles = @{$content{'roles'}{$role_id}{'role'}};
6245: foreach my $role (keys(%{$allroles{$cid}})) {
6246: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
6247: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
6248: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
6249: if (grep/^all$/,@sections) {
6250: return 'ok';
6251: } else {
6252: if (grep/^$sec$/,@sections) {
6253: return 'ok';
6254: }
6255: }
6256: }
6257: }
6258: if (keys(%{$allgroups{$cid}}) == 0) {
6259: if (grep/^none$/,@groups) {
6260: return 'ok';
6261: }
6262: } else {
6263: if (grep/^all$/,@groups) {
6264: return 'ok';
6265: }
6266: foreach my $group (keys(%{$allgroups{$cid}})) {
6267: if (grep/^$group$/,@groups) {
6268: return 'ok';
6269: }
6270: }
6271: }
6272: }
6273: }
6274: }
6275: }
6276: }
6277: if ($guest) {
6278: return $guest;
6279: }
6280: }
6281: }
6282: return;
6283: }
6284:
6285: sub course_group_datechecker {
6286: my ($dates,$now,$status) = @_;
6287: my ($start,$end) = split(/\./,$dates);
6288: if (!$start && !$end) {
6289: return 'ok';
6290: }
6291: if (grep/^active$/,@{$status}) {
6292: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
6293: return 'ok';
6294: }
6295: }
6296: if (grep/^previous$/,@{$status}) {
6297: if ($end > $now ) {
6298: return 'ok';
6299: }
6300: }
6301: if (grep/^future$/,@{$status}) {
6302: if ($start > $now) {
6303: return 'ok';
6304: }
6305: }
6306: return;
6307: }
6308:
6309: sub parse_portfolio_url {
6310: my ($url) = @_;
6311:
6312: my ($type,$udom,$unum,$group,$file_name);
6313:
1.823 albertel 6314: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 6315: $type = 1;
6316: $udom = $1;
6317: $unum = $2;
6318: $file_name = $3;
1.823 albertel 6319: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 6320: $type = 2;
6321: $udom = $1;
6322: $unum = $2;
6323: $group = $3;
6324: $file_name = $3.'/'.$4;
6325: }
6326: if (wantarray) {
6327: return ($type,$udom,$unum,$file_name,$group);
6328: }
6329: return $type;
6330: }
6331:
6332: sub is_portfolio_url {
6333: my ($url) = @_;
6334: return scalar(&parse_portfolio_url($url));
6335: }
6336:
1.798 raeburn 6337: sub is_portfolio_file {
6338: my ($file) = @_;
1.820 raeburn 6339: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 6340: return 1;
6341: }
6342: return;
6343: }
6344:
1.976 raeburn 6345: sub usertools_access {
1.1084 raeburn 6346: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 6347: my ($access,%tools);
6348: if ($context eq '') {
6349: $context = 'tools';
6350: }
6351: if ($context eq 'requestcourses') {
6352: %tools = (
6353: official => 1,
6354: unofficial => 1,
1.1006 raeburn 6355: community => 1,
1.1246 raeburn 6356: textbook => 1,
1.985 raeburn 6357: );
1.1183 raeburn 6358: } elsif ($context eq 'requestauthor') {
6359: %tools = (
6360: requestauthor => 1,
6361: );
1.985 raeburn 6362: } else {
6363: %tools = (
6364: aboutme => 1,
6365: blog => 1,
1.1177 raeburn 6366: webdav => 1,
1.985 raeburn 6367: portfolio => 1,
6368: );
6369: }
1.976 raeburn 6370: return if (!defined($tools{$tool}));
6371:
1.1242 raeburn 6372: if (($udom eq '') || ($uname eq '')) {
1.976 raeburn 6373: $udom = $env{'user.domain'};
6374: $uname = $env{'user.name'};
6375: }
6376:
1.978 raeburn 6377: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
6378: if ($action ne 'reload') {
1.985 raeburn 6379: if ($context eq 'requestcourses') {
6380: return $env{'environment.canrequest.'.$tool};
1.1183 raeburn 6381: } elsif ($context eq 'requestauthor') {
6382: return $env{'environment.canrequest.author'};
1.985 raeburn 6383: } else {
6384: return $env{'environment.availabletools.'.$tool};
6385: }
6386: }
1.976 raeburn 6387: }
6388:
1.1183 raeburn 6389: my ($toolstatus,$inststatus,$envkey);
6390: if ($context eq 'requestauthor') {
6391: $envkey = $context;
6392: } else {
6393: $envkey = $context.'.'.$tool;
6394: }
1.976 raeburn 6395:
1.985 raeburn 6396: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
6397: ($action ne 'reload')) {
1.1183 raeburn 6398: $toolstatus = $env{'environment.'.$envkey};
1.976 raeburn 6399: $inststatus = $env{'environment.inststatus'};
6400: } else {
1.1084 raeburn 6401: if (ref($userenvref) eq 'HASH') {
1.1183 raeburn 6402: $toolstatus = $userenvref->{$envkey};
1.1084 raeburn 6403: $inststatus = $userenvref->{'inststatus'};
6404: } else {
1.1183 raeburn 6405: my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
6406: $toolstatus = $userenv{$envkey};
1.1084 raeburn 6407: $inststatus = $userenv{'inststatus'};
6408: }
1.976 raeburn 6409: }
6410:
6411: if ($toolstatus ne '') {
6412: if ($toolstatus) {
6413: $access = 1;
6414: } else {
6415: $access = 0;
6416: }
6417: return $access;
6418: }
6419:
1.1084 raeburn 6420: my ($is_adv,%domdef);
6421: if (ref($is_advref) eq 'HASH') {
6422: $is_adv = $is_advref->{'is_adv'};
6423: } else {
6424: $is_adv = &is_advanced_user($udom,$uname);
6425: }
6426: if (ref($domdefref) eq 'HASH') {
6427: %domdef = %{$domdefref};
6428: } else {
6429: %domdef = &get_domain_defaults($udom);
6430: }
1.976 raeburn 6431: if (ref($domdef{$tool}) eq 'HASH') {
6432: if ($is_adv) {
6433: if ($domdef{$tool}{'_LC_adv'} ne '') {
6434: if ($domdef{$tool}{'_LC_adv'}) {
6435: $access = 1;
6436: } else {
6437: $access = 0;
6438: }
6439: return $access;
6440: }
6441: }
6442: if ($inststatus ne '') {
6443: my ($hasaccess,$hasnoaccess);
6444: foreach my $affiliation (split(/:/,$inststatus)) {
6445: if ($domdef{$tool}{$affiliation} ne '') {
6446: if ($domdef{$tool}{$affiliation}) {
6447: $hasaccess = 1;
6448: } else {
6449: $hasnoaccess = 1;
6450: }
6451: }
6452: }
6453: if ($hasaccess || $hasnoaccess) {
6454: if ($hasaccess) {
6455: $access = 1;
6456: } elsif ($hasnoaccess) {
6457: $access = 0;
6458: }
6459: return $access;
6460: }
6461: } else {
6462: if ($domdef{$tool}{'default'} ne '') {
6463: if ($domdef{$tool}{'default'}) {
6464: $access = 1;
6465: } elsif ($domdef{$tool}{'default'} == 0) {
6466: $access = 0;
6467: }
6468: return $access;
6469: }
6470: }
6471: } else {
1.1177 raeburn 6472: if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985 raeburn 6473: $access = 1;
6474: } else {
6475: $access = 0;
6476: }
1.976 raeburn 6477: return $access;
6478: }
6479: }
6480:
1.1050 raeburn 6481: sub is_course_owner {
6482: my ($cdom,$cnum,$udom,$uname) = @_;
6483: if (($udom eq '') || ($uname eq '')) {
6484: $udom = $env{'user.domain'};
6485: $uname = $env{'user.name'};
6486: }
6487: unless (($udom eq '') || ($uname eq '')) {
6488: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
6489: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
6490: return 1;
6491: } else {
6492: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
6493: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
6494: return 1;
6495: }
6496: }
6497: }
6498: }
6499: return;
6500: }
6501:
1.976 raeburn 6502: sub is_advanced_user {
6503: my ($udom,$uname) = @_;
1.1085 raeburn 6504: if ($udom ne '' && $uname ne '') {
6505: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128 raeburn 6506: if (wantarray) {
6507: return ($env{'user.adv'},$env{'user.author'});
6508: } else {
6509: return $env{'user.adv'};
6510: }
1.1085 raeburn 6511: }
6512: }
1.976 raeburn 6513: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
6514: my %allroles;
1.1128 raeburn 6515: my ($is_adv,$is_author);
1.976 raeburn 6516: foreach my $role (keys(%roleshash)) {
6517: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
6518: my $area = '/'.$tdomain.'/'.$trest;
6519: if ($sec ne '') {
6520: $area .= '/'.$sec;
6521: }
6522: if (($area ne '') && ($trole ne '')) {
6523: my $spec=$trole.'.'.$area;
6524: if ($trole =~ /^cr\//) {
6525: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
6526: } elsif ($trole ne 'gr') {
6527: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
6528: }
1.1128 raeburn 6529: if ($trole eq 'au') {
6530: $is_author = 1;
6531: }
1.976 raeburn 6532: }
6533: }
6534: foreach my $role (keys(%allroles)) {
6535: last if ($is_adv);
6536: foreach my $item (split(/:/,$allroles{$role})) {
6537: if ($item ne '') {
6538: my ($privilege,$restrictions)=split(/&/,$item);
6539: if ($privilege eq 'adv') {
6540: $is_adv = 1;
6541: last;
6542: }
6543: }
6544: }
6545: }
1.1128 raeburn 6546: if (wantarray) {
6547: return ($is_adv,$is_author);
6548: }
1.976 raeburn 6549: return $is_adv;
6550: }
1.798 raeburn 6551:
1.1035 raeburn 6552: sub check_can_request {
1.1036 raeburn 6553: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 6554: my $canreq = 0;
6555: my ($types,$typename) = &Apache::loncommon::course_types();
6556: my @options = ('approval','validate','autolimit');
6557: my $optregex = join('|',@options);
6558: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
6559: foreach my $type (@{$types}) {
6560: if (&usertools_access($env{'user.name'},
6561: $env{'user.domain'},
6562: $type,undef,'requestcourses')) {
6563: $canreq ++;
1.1036 raeburn 6564: if (ref($request_domains) eq 'HASH') {
6565: push(@{$request_domains->{$type}},$env{'user.domain'});
6566: }
1.1035 raeburn 6567: if ($dom eq $env{'user.domain'}) {
6568: $can_request->{$type} = 1;
6569: }
6570: }
6571: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
6572: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
6573: if (@curr > 0) {
1.1036 raeburn 6574: foreach my $item (@curr) {
6575: if (ref($request_domains) eq 'HASH') {
6576: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
6577: if ($otherdom ne '') {
6578: if (ref($request_domains->{$type}) eq 'ARRAY') {
6579: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
6580: push(@{$request_domains->{$type}},$otherdom);
6581: }
6582: } else {
6583: push(@{$request_domains->{$type}},$otherdom);
6584: }
6585: }
6586: }
6587: }
6588: unless($dom eq $env{'user.domain'}) {
6589: $canreq ++;
1.1035 raeburn 6590: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
6591: $can_request->{$type} = 1;
6592: }
6593: }
6594: }
6595: }
6596: }
6597: }
6598: return $canreq;
6599: }
6600:
1.341 www 6601: # ---------------------------------------------- Custom access rule evaluation
6602:
6603: sub customaccess {
6604: my ($priv,$uri)=@_;
1.807 albertel 6605: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 6606: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 6607: $udom = &LONCAPA::clean_domain($udom);
6608: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 6609: my $access=0;
1.800 albertel 6610: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 6611: my ($effect,$realm,$role,$type)=split(/\:/,$right);
6612: if ($type eq 'user') {
6613: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 6614: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 6615: if ($tdom) {
6616: if ($tdom ne $env{'user.domain'}) { next; }
6617: }
1.896 albertel 6618: if ($tuname) {
6619: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 6620: }
6621: $access=($effect eq 'allow');
6622: last;
6623: }
6624: } else {
6625: if ($role) {
6626: if ($role ne $urole) { next; }
6627: }
6628: foreach my $scope (split(/\s*\,\s*/,$realm)) {
6629: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
6630: if ($tdom) {
6631: if ($tdom ne $udom) { next; }
6632: }
6633: if ($tcrs) {
6634: if ($tcrs ne $ucrs) { next; }
6635: }
6636: if ($tsec) {
6637: if ($tsec ne $usec) { next; }
6638: }
6639: $access=($effect eq 'allow');
6640: last;
6641: }
6642: if ($realm eq '' && $role eq '') {
6643: $access=($effect eq 'allow');
6644: }
1.402 bowersj2 6645: }
1.341 www 6646: }
6647: return $access;
6648: }
6649:
1.103 harris41 6650: # ------------------------------------------------- Check for a user privilege
1.12 www 6651:
6652: sub allowed {
1.1281 raeburn 6653: my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
1.705 albertel 6654: my $ver_orguri=$uri;
1.439 www 6655: $uri=&deversion($uri);
1.152 www 6656: my $orguri=$uri;
1.52 www 6657: $uri=&declutter($uri);
1.809 raeburn 6658:
1.810 raeburn 6659: if ($priv eq 'evb') {
6660: # Evade communication block restrictions for specified role in a course
6661: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
6662: return $1;
6663: } else {
6664: return;
6665: }
6666: }
6667:
1.620 albertel 6668: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 6669: # Free bre access to adm and meta resources
1.775 albertel 6670: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 6671: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
6672: && ($priv eq 'bre')) {
1.14 www 6673: return 'F';
1.159 www 6674: }
6675:
1.545 banghart 6676: # Free bre access to user's own portfolio contents
1.714 raeburn 6677: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 6678: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 6679: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 6680: my %setters;
6681: my ($startblock,$endblock) =
6682: &Apache::loncommon::blockcheck(\%setters,'port');
6683: if ($startblock && $endblock) {
6684: return 'B';
6685: } else {
6686: return 'F';
6687: }
1.545 banghart 6688: }
6689:
1.762 raeburn 6690: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 6691: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
6692: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
6693: if (exists($env{'request.course.id'})) {
6694: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6695: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6696: if (($domain eq $cdom) && ($name eq $cnum)) {
6697: my $courseprivid=$env{'request.course.id'};
6698: $courseprivid=~s/\_/\//;
6699: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
6700: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
6701: return $1;
1.762 raeburn 6702: } else {
6703: if ($env{'request.course.sec'}) {
6704: $courseprivid.='/'.$env{'request.course.sec'};
6705: }
6706: if ($env{'user.priv.'.$env{'request.role'}.'./'.
6707: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
6708: return $2;
6709: }
1.714 raeburn 6710: }
6711: }
6712: }
6713: }
6714:
1.159 www 6715: # Free bre to public access
6716:
6717: if ($priv eq 'bre') {
1.238 www 6718: my $copyright=&metadata($uri,'copyright');
1.620 albertel 6719: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 6720: return 'F';
6721: }
1.238 www 6722: if ($copyright eq 'priv') {
6723: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 6724: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 6725: return '';
6726: }
6727: }
6728: if ($copyright eq 'domain') {
6729: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 6730: unless (($env{'user.domain'} eq $1) ||
6731: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 6732: return '';
6733: }
1.262 matthew 6734: }
1.620 albertel 6735: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 6736: # Library role, so allow browsing of resources in this domain.
6737: return 'F';
1.238 www 6738: }
1.341 www 6739: if ($copyright eq 'custom') {
6740: unless (&customaccess($priv,$uri)) { return ''; }
6741: }
1.14 www 6742: }
1.264 matthew 6743: # Domain coordinator is trying to create a course
1.620 albertel 6744: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 6745: # uri is the requested domain in this case.
6746: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 6747: # a role of dc for the domain in question.
1.620 albertel 6748: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 6749: }
1.29 www 6750:
1.52 www 6751: my $thisallowed='';
6752: my $statecond=0;
6753: my $courseprivid='';
6754:
1.1039 raeburn 6755: my $ownaccess;
1.1043 raeburn 6756: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 6757: if (($priv eq 'bro') && ($env{'user.author'})) {
6758: if ($uri eq '') {
6759: $ownaccess = 1;
6760: } else {
6761: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
6762: my $udom = $env{'user.domain'};
6763: my $uname = $env{'user.name'};
6764: if ($uri =~ m{^\Q$udom\E/?$}) {
6765: $ownaccess = 1;
1.1040 raeburn 6766: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 6767: unless ($uri =~ m{\.\./}) {
6768: $ownaccess = 1;
6769: }
6770: } elsif (($udom ne 'public') && ($uname ne 'public')) {
6771: my $now = time;
6772: if ($uri =~ m{^([^/]+)/?$}) {
6773: my $adom = $1;
6774: foreach my $key (keys(%env)) {
1.1042 raeburn 6775: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 6776: my ($start,$end) = split('.',$env{$key});
6777: if (($now >= $start) && (!$end || $end < $now)) {
6778: $ownaccess = 1;
6779: last;
6780: }
6781: }
6782: }
6783: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
6784: my $adom = $1;
6785: my $aname = $2;
1.1042 raeburn 6786: foreach my $role ('ca','aa') {
6787: if ($env{"user.role.$role./$adom/$aname"}) {
6788: my ($start,$end) =
6789: split('.',$env{"user.role.$role./$adom/$aname"});
6790: if (($now >= $start) && (!$end || $end < $now)) {
6791: $ownaccess = 1;
6792: last;
6793: }
1.1039 raeburn 6794: }
6795: }
6796: }
6797: }
6798: }
6799: }
6800: }
6801:
1.52 www 6802: # Course
6803:
1.620 albertel 6804: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6805: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6806: $thisallowed.=$1;
6807: }
1.52 www 6808: }
1.29 www 6809:
1.52 www 6810: # Domain
6811:
1.620 albertel 6812: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 6813: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6814: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6815: $thisallowed.=$1;
6816: }
1.12 www 6817: }
1.52 www 6818:
1.1141 raeburn 6819: # User who is not author or co-author might still be able to edit
6820: # resource of an author in the domain (e.g., if Domain Coordinator).
6821: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
6822: (&allowed('mdc',$env{'request.course.id'}))) {
6823: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
6824: $thisallowed.=$1;
6825: }
6826: }
6827:
1.52 www 6828: # Course: uri itself is a course
1.66 www 6829: my $courseuri=$uri;
6830: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 6831: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 6832:
1.620 albertel 6833: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 6834: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6835: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6836: $thisallowed.=$1;
6837: }
1.12 www 6838: }
1.29 www 6839:
1.665 albertel 6840: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 6841: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 6842: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 6843: $thisallowed='';
1.671 raeburn 6844: my ($match)=&is_on_map($uri);
6845: if ($match) {
6846: if ($env{'user.priv.'.$env{'request.role'}.'./'}
6847: =~/\Q$priv\E\&([^\:]*)/) {
1.1281 raeburn 6848: my $value = $1;
6849: if ($noblockcheck) {
6850: $thisallowed.=$value;
1.1162 raeburn 6851: } else {
1.1281 raeburn 6852: my @blockers = &has_comm_blocking($priv,$symb,$uri);
6853: if (@blockers > 0) {
6854: $thisallowed = 'B';
6855: } else {
6856: $thisallowed.=$value;
6857: }
1.1162 raeburn 6858: }
1.671 raeburn 6859: }
6860: } else {
1.705 albertel 6861: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 6862: if ($refuri) {
6863: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 6864: $thisallowed='F';
1.671 raeburn 6865: } else {
6866: $refuri=&declutter($refuri);
6867: my ($match) = &is_on_map($refuri);
6868: if ($match) {
1.1281 raeburn 6869: if ($noblockcheck) {
6870: $thisallowed='F';
1.1162 raeburn 6871: } else {
1.1281 raeburn 6872: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
6873: if (@blockers > 0) {
6874: $thisallowed = 'B';
6875: } else {
6876: $thisallowed='F';
6877: }
1.1162 raeburn 6878: }
1.671 raeburn 6879: }
1.669 raeburn 6880: }
1.671 raeburn 6881: }
6882: }
1.314 www 6883: }
1.492 albertel 6884:
1.766 albertel 6885: if ($priv eq 'bre'
6886: && $thisallowed ne 'F'
6887: && $thisallowed ne '2'
6888: && &is_portfolio_url($uri)) {
1.1270 raeburn 6889: $thisallowed = &portfolio_access($uri,$clientip);
1.766 albertel 6890: }
1.1250 raeburn 6891:
1.52 www 6892: # Full access at system, domain or course-wide level? Exit.
1.29 www 6893: if ($thisallowed=~/F/) {
6894: return 'F';
6895: }
6896:
1.52 www 6897: # If this is generating or modifying users, exit with special codes
1.29 www 6898:
1.643 www 6899: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
6900: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 6901: my ($audom,$auname)=split('/',$uri);
1.643 www 6902: # no author name given, so this just checks on the general right to make a co-author in this domain
6903: unless ($auname) { return $thisallowed; }
6904: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 6905: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
6906: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
6907: ($audom ne $env{'request.role.domain'}))) { return ''; }
6908: }
1.52 www 6909: return $thisallowed;
6910: }
6911: #
1.103 harris41 6912: # Gathered so far: system, domain and course wide privileges
1.52 www 6913: #
6914: # Course: See if uri or referer is an individual resource that is part of
6915: # the course
6916:
1.620 albertel 6917: if ($env{'request.course.id'}) {
1.232 www 6918:
1.620 albertel 6919: $courseprivid=$env{'request.course.id'};
6920: if ($env{'request.course.sec'}) {
6921: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 6922: }
6923: $courseprivid=~s/\_/\//;
6924: my $checkreferer=1;
1.232 www 6925: my ($match,$cond)=&is_on_map($uri);
6926: if ($match) {
6927: $statecond=$cond;
1.620 albertel 6928: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 6929: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6930: my $value = $1;
6931: if ($priv eq 'bre') {
1.1281 raeburn 6932: if ($noblockcheck) {
6933: $thisallowed.=$value;
1.1162 raeburn 6934: } else {
1.1281 raeburn 6935: my @blockers = &has_comm_blocking($priv,$symb,$uri);
6936: if (@blockers > 0) {
6937: $thisallowed = 'B';
6938: } else {
6939: $thisallowed.=$value;
6940: }
1.1162 raeburn 6941: }
6942: } else {
6943: $thisallowed.=$value;
6944: }
1.52 www 6945: $checkreferer=0;
6946: }
1.29 www 6947: }
1.83 www 6948:
1.148 www 6949: if ($checkreferer) {
1.620 albertel 6950: my $refuri=$env{'httpref.'.$orguri};
1.148 www 6951: unless ($refuri) {
1.800 albertel 6952: foreach my $key (keys(%env)) {
6953: if ($key=~/^httpref\..*\*/) {
6954: my $pattern=$key;
1.156 www 6955: $pattern=~s/^httpref\.\/res\///;
1.148 www 6956: $pattern=~s/\*/\[\^\/\]\+/g;
6957: $pattern=~s/\//\\\//g;
1.152 www 6958: if ($orguri=~/$pattern/) {
1.800 albertel 6959: $refuri=$env{$key};
1.148 www 6960: }
6961: }
1.191 harris41 6962: }
1.148 www 6963: }
1.232 www 6964:
1.148 www 6965: if ($refuri) {
1.152 www 6966: $refuri=&declutter($refuri);
1.232 www 6967: my ($match,$cond)=&is_on_map($refuri);
6968: if ($match) {
6969: my $refstatecond=$cond;
1.620 albertel 6970: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 6971: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6972: my $value = $1;
6973: if ($priv eq 'bre') {
1.1281 raeburn 6974: if ($noblockcheck) {
6975: $thisallowed.=$value;
1.1162 raeburn 6976: } else {
1.1281 raeburn 6977: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
6978: if (@blockers > 0) {
6979: $thisallowed = 'B';
6980: } else {
6981: $thisallowed.=$value;
6982: }
1.1162 raeburn 6983: }
6984: } else {
6985: $thisallowed.=$value;
6986: }
1.53 www 6987: $uri=$refuri;
6988: $statecond=$refstatecond;
1.52 www 6989: }
6990: }
1.148 www 6991: }
1.29 www 6992: }
1.52 www 6993: }
1.29 www 6994:
1.52 www 6995: #
1.103 harris41 6996: # Gathered now: all privileges that could apply, and condition number
1.52 www 6997: #
6998: #
6999: # Full or no access?
7000: #
1.29 www 7001:
1.52 www 7002: if ($thisallowed=~/F/) {
7003: return 'F';
7004: }
1.29 www 7005:
1.52 www 7006: unless ($thisallowed) {
7007: return '';
7008: }
1.29 www 7009:
1.52 www 7010: # Restrictions exist, deal with them
7011: #
7012: # C:according to course preferences
7013: # R:according to resource settings
7014: # L:unless locked
7015: # X:according to user session state
7016: #
7017:
7018: # Possibly locked functionality, check all courses
1.54 www 7019: # Locks might take effect only after 10 minutes cache expiration for other
7020: # courses, and 2 minutes for current course
1.52 www 7021:
7022: my $envkey;
7023: if ($thisallowed=~/L/) {
1.1000 raeburn 7024: foreach $envkey (keys(%env)) {
1.54 www 7025: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
7026: my $courseid=$2;
7027: my $roleid=$1.'.'.$2;
1.92 www 7028: $courseid=~s/^\///;
1.54 www 7029: my $expiretime=600;
1.620 albertel 7030: if ($env{'request.role'} eq $roleid) {
1.54 www 7031: $expiretime=120;
7032: }
7033: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
7034: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 7035: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 7036: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 7037: }
1.620 albertel 7038: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
7039: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
7040: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
7041: &log($env{'user.domain'},$env{'user.name'},
7042: $env{'user.home'},
1.57 www 7043: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 7044: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 7045: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 7046: return '';
7047: }
7048: }
1.620 albertel 7049: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
7050: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
7051: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
7052: &log($env{'user.domain'},$env{'user.name'},
7053: $env{'user.home'},
1.57 www 7054: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 7055: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 7056: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 7057: return '';
7058: }
7059: }
7060: }
1.29 www 7061: }
1.52 www 7062: }
7063:
7064: #
7065: # Rest of the restrictions depend on selected course
7066: #
7067:
1.620 albertel 7068: unless ($env{'request.course.id'}) {
1.766 albertel 7069: if ($thisallowed eq 'A') {
7070: return 'A';
1.814 raeburn 7071: } elsif ($thisallowed eq 'B') {
7072: return 'B';
1.766 albertel 7073: } else {
7074: return '1';
7075: }
1.52 www 7076: }
1.29 www 7077:
1.52 www 7078: #
7079: # Now user is definitely in a course
7080: #
1.53 www 7081:
7082:
7083: # Course preferences
7084:
7085: if ($thisallowed=~/C/) {
1.620 albertel 7086: my $rolecode=(split(/\./,$env{'request.role'}))[0];
7087: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
7088: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 7089: =~/\Q$rolecode\E/) {
1.1103 raeburn 7090: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7091: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
7092: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
7093: $env{'request.course.id'});
7094: }
1.237 www 7095: return '';
7096: }
7097:
1.620 albertel 7098: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 7099: =~/\Q$unamedom\E/) {
1.1103 raeburn 7100: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7101: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
7102: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
7103: $env{'request.course.id'});
7104: }
1.54 www 7105: return '';
7106: }
1.53 www 7107: }
7108:
7109: # Resource preferences
7110:
7111: if ($thisallowed=~/R/) {
1.620 albertel 7112: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 7113: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103 raeburn 7114: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7115: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
7116: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
7117: }
7118: return '';
1.54 www 7119: }
1.53 www 7120: }
1.30 www 7121:
1.246 www 7122: # Restricted by state or randomout?
1.30 www 7123:
1.52 www 7124: if ($thisallowed=~/X/) {
1.620 albertel 7125: if ($env{'acc.randomout'}) {
1.579 albertel 7126: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 7127: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 7128: return '';
7129: }
1.247 www 7130: }
7131: if (&condval($statecond)) {
1.52 www 7132: return '2';
7133: } else {
7134: return '';
7135: }
7136: }
1.30 www 7137:
1.766 albertel 7138: if ($thisallowed eq 'A') {
7139: return 'A';
1.814 raeburn 7140: } elsif ($thisallowed eq 'B') {
7141: return 'B';
1.766 albertel 7142: }
1.52 www 7143: return 'F';
1.232 www 7144: }
1.1162 raeburn 7145:
1.1192 raeburn 7146: # ------------------------------------------- Check construction space access
7147:
7148: sub constructaccess {
7149: my ($url,$setpriv)=@_;
7150:
7151: # We do not allow editing of previous versions of files
7152: if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
7153:
7154: # Get username and domain from URL
7155: my ($ownername,$ownerdomain,$ownerhome);
7156:
7157: ($ownerdomain,$ownername) =
7158: ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
7159:
7160: # The URL does not really point to any authorspace, forget it
7161: unless (($ownername) && ($ownerdomain)) { return ''; }
7162:
7163: # Now we need to see if the user has access to the authorspace of
7164: # $ownername at $ownerdomain
7165:
7166: if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
7167: # Real author for this?
7168: $ownerhome = $env{'user.home'};
7169: if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
7170: return ($ownername,$ownerdomain,$ownerhome);
7171: }
7172: } else {
7173: # Co-author for this?
7174: if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
7175: exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
7176: $ownerhome = &homeserver($ownername,$ownerdomain);
7177: return ($ownername,$ownerdomain,$ownerhome);
7178: }
7179: }
7180:
7181: # We don't have any access right now. If we are not possibly going to do anything about this,
7182: # we might as well leave
7183: unless ($setpriv) { return ''; }
7184:
7185: # Backdoor access?
7186: my $allowed=&allowed('eco',$ownerdomain);
7187: # Nope
7188: unless ($allowed) { return ''; }
7189: # Looks like we may have access, but could be locked by the owner of the construction space
7190: if ($allowed eq 'U') {
7191: my %blocked=&get('environment',['domcoord.author'],
7192: $ownerdomain,$ownername);
7193: # Is blocked by owner
7194: if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
7195: }
7196: if (($allowed eq 'F') || ($allowed eq 'U')) {
7197: # Grant temporary access
7198: my $then=$env{'user.login.time'};
1.1209 raeburn 7199: my $update=$env{'user.update.time'};
1.1192 raeburn 7200: if (!$update) { $update = $then; }
7201: my $refresh=$env{'user.refresh.time'};
7202: if (!$refresh) { $refresh = $update; }
7203: my $now = time;
7204: &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
7205: $now,'ca','constructaccess');
7206: $ownerhome = &homeserver($ownername,$ownerdomain);
7207: return($ownername,$ownerdomain,$ownerhome);
7208: }
7209: # No business here
7210: return '';
7211: }
7212:
1.1282 raeburn 7213: # ----------------------------------------------------------- Content Blocking
7214:
7215: {
7216: # Caches for faster Course Contents display where content blocking
7217: # is in operation (i.e., interval param set) for timed quiz.
7218: #
7219: # User for whom data are being temporarily cached.
7220: my $cacheduser='';
7221: # Cached blockers for this user (a hash of blocking items).
7222: my %cachedblockers=();
7223: # When the data were last cached.
7224: my $cachedlast='';
7225:
7226: sub load_all_blockers {
7227: my ($uname,$udom,$blocks)=@_;
7228: if (($uname ne '') && ($udom ne '')) {
7229: if (($cacheduser eq $uname.':'.$udom) &&
7230: (abs($cachedlast-time)<5)) {
7231: return;
7232: }
7233: }
7234: $cachedlast=time;
7235: $cacheduser=$uname.':'.$udom;
7236: %cachedblockers = &get_commblock_resources($blocks);
7237: }
7238:
1.1162 raeburn 7239: sub get_comm_blocks {
7240: my ($cdom,$cnum) = @_;
7241: if ($cdom eq '' || $cnum eq '') {
7242: return unless ($env{'request.course.id'});
7243: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7244: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7245: }
7246: my %commblocks;
7247: my $hashid=$cdom.'_'.$cnum;
7248: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
7249: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
7250: %commblocks = %{$blocksref};
7251: } else {
7252: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
7253: my $cachetime = 600;
7254: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
7255: }
7256: return %commblocks;
7257: }
7258:
1.1282 raeburn 7259: sub get_commblock_resources {
7260: my ($blocks) = @_;
7261: my %blockers = ();
7262: return %blockers unless ($env{'request.course.id'});
7263: return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162 raeburn 7264: my %commblocks;
7265: if (ref($blocks) eq 'HASH') {
7266: %commblocks = %{$blocks};
7267: } else {
7268: %commblocks = &get_comm_blocks();
7269: }
1.1282 raeburn 7270: return %blockers unless (keys(%commblocks) > 0);
7271: my $navmap = Apache::lonnavmaps::navmap->new();
7272: return %blockers unless (ref($navmap));
1.1162 raeburn 7273: my $now = time;
7274: foreach my $block (keys(%commblocks)) {
7275: if ($block =~ /^(\d+)____(\d+)$/) {
7276: my ($start,$end) = ($1,$2);
7277: if ($start <= $now && $end >= $now) {
7278: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7279: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
7280: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1282 raeburn 7281: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
7282: $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162 raeburn 7283: }
7284: }
7285: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1282 raeburn 7286: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
7287: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162 raeburn 7288: }
7289: }
7290: }
7291: }
7292: }
7293: } elsif ($block =~ /^firstaccess____(.+)$/) {
7294: my $item = $1;
1.1163 raeburn 7295: my @to_test;
1.1162 raeburn 7296: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7297: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1282 raeburn 7298: my @interval;
7299: my $type = 'map';
7300: if ($item eq 'course') {
7301: $type = 'course';
7302: @interval=&EXT("resource.0.interval");
7303: } else {
7304: if ($item =~ /___\d+___/) {
7305: $type = 'resource';
7306: @interval=&EXT("resource.0.interval",$item);
7307: if (ref($navmap)) {
7308: my $res = $navmap->getBySymb($item);
7309: push(@to_test,$res);
7310: }
1.1162 raeburn 7311: } else {
1.1282 raeburn 7312: my $mapsymb = &symbread($item,1);
7313: if ($mapsymb) {
7314: if (ref($navmap)) {
7315: my $mapres = $navmap->getBySymb($mapsymb);
7316: @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
7317: foreach my $res (@to_test) {
7318: my $symb = $res->symb();
7319: next if ($symb eq $mapsymb);
7320: if ($symb ne '') {
7321: @interval=&EXT("resource.0.interval",$symb);
7322: if ($interval[1] eq 'map') {
7323: last;
1.1162 raeburn 7324: }
7325: }
7326: }
7327: }
7328: }
7329: }
1.1282 raeburn 7330: }
7331: if ($interval[0] =~ /^\d+$/) {
7332: my $first_access;
7333: if ($type eq 'resource') {
7334: $first_access=&get_first_access($interval[1],$item);
7335: } elsif ($type eq 'map') {
7336: $first_access=&get_first_access($interval[1],undef,$item);
7337: } else {
7338: $first_access=&get_first_access($interval[1]);
7339: }
7340: if ($first_access) {
7341: my $timesup = $first_access+$interval[0];
7342: if ($timesup > $now) {
7343: my $activeblock;
7344: foreach my $res (@to_test) {
1.1283 raeburn 7345: if ($res->answerable()) {
1.1282 raeburn 7346: $activeblock = 1;
7347: last;
7348: }
7349: }
7350: if ($activeblock) {
7351: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
7352: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
7353: $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
7354: }
7355: }
7356: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
7357: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
7358: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163 raeburn 7359: }
1.1162 raeburn 7360: }
7361: }
7362: }
7363: }
7364: }
7365: }
7366: }
7367: }
7368: }
1.1282 raeburn 7369: return %blockers;
1.1162 raeburn 7370: }
7371:
1.1282 raeburn 7372: sub has_comm_blocking {
7373: my ($priv,$symb,$uri,$blocks) = @_;
7374: my @blockers;
7375: return unless ($env{'request.course.id'});
7376: return unless ($priv eq 'bre');
7377: return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
7378: return if ($env{'request.state'} eq 'construct');
7379: &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
7380: return unless (keys(%cachedblockers) > 0);
7381: my (%possibles,@symbs);
7382: if (!$symb) {
7383: $symb = &symbread($uri,1,1,1,\%possibles);
1.1162 raeburn 7384: }
1.1282 raeburn 7385: if ($symb) {
7386: @symbs = ($symb);
7387: } elsif (keys(%possibles)) {
7388: @symbs = keys(%possibles);
7389: }
7390: my $noblock;
7391: foreach my $symb (@symbs) {
7392: last if ($noblock);
7393: my ($map,$resid,$resurl)=&decode_symb($symb);
7394: foreach my $block (keys(%cachedblockers)) {
7395: if ($block =~ /^firstaccess____(.+)$/) {
7396: my $item = $1;
7397: if (($item eq $map) || ($item eq $symb)) {
7398: $noblock = 1;
7399: last;
7400: }
7401: }
7402: if (ref($cachedblockers{$block}) eq 'HASH') {
7403: if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
7404: if ($cachedblockers{$block}{'resources'}{$symb}) {
7405: unless (grep(/^\Q$block\E$/,@blockers)) {
7406: push(@blockers,$block);
7407: }
7408: }
7409: }
1.1162 raeburn 7410: }
1.1282 raeburn 7411: if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
7412: if ($cachedblockers{$block}{'maps'}{$map}) {
7413: unless (grep(/^\Q$block\E$/,@blockers)) {
7414: push(@blockers,$block);
7415: }
7416: }
1.1162 raeburn 7417: }
7418: }
7419: }
1.1282 raeburn 7420: return if ($noblock);
7421: return @blockers;
7422: }
1.1162 raeburn 7423: }
7424:
1.1282 raeburn 7425: # -------------------------------- Deversion and split uri into path an filename
7426:
1.1133 foxr 7427: #
1.1282 raeburn 7428: # Removes the version from a URI and
1.1133 foxr 7429: # splits it in to its filename and path to the filename.
7430: # Seems like File::Basename could have done this more clearly.
7431: # Parameters:
7432: # $uri - input URI
7433: # Returns:
7434: # Two element list consisting of
7435: # $pathname - the URI up to and excluding the trailing /
7436: # $filename - The part of the URI following the last /
7437: # NOTE:
7438: # Another realization of this is simply:
7439: # use File::Basename;
7440: # ...
7441: # $uri = shift;
7442: # $filename = basename($uri);
7443: # $path = dirname($uri);
7444: # return ($filename, $path);
7445: #
7446: # The implementation below is probably faster however.
7447: #
1.710 albertel 7448: sub split_uri_for_cond {
7449: my $uri=&deversion(&declutter(shift));
7450: my @uriparts=split(/\//,$uri);
7451: my $filename=pop(@uriparts);
7452: my $pathname=join('/',@uriparts);
7453: return ($pathname,$filename);
7454: }
1.232 www 7455: # --------------------------------------------------- Is a resource on the map?
7456:
7457: sub is_on_map {
1.710 albertel 7458: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 7459: #Trying to find the conditional for the file
1.620 albertel 7460: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 7461: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 7462: if ($match) {
1.289 bowersj2 7463: return (1,$1);
7464: } else {
1.434 www 7465: return (0,0);
1.289 bowersj2 7466: }
1.12 www 7467: }
7468:
1.427 www 7469: # --------------------------------------------------------- Get symb from alias
7470:
7471: sub get_symb_from_alias {
7472: my $symb=shift;
7473: my ($map,$resid,$url)=&decode_symb($symb);
7474: # Already is a symb
7475: if ($url) { return $symb; }
7476: # Must be an alias
7477: my $aliassymb='';
7478: my %bighash;
1.620 albertel 7479: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 7480: &GDBM_READER(),0640)) {
7481: my $rid=$bighash{'mapalias_'.$symb};
7482: if ($rid) {
7483: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 7484: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
7485: $resid,$bighash{'src_'.$rid});
1.427 www 7486: }
7487: untie %bighash;
7488: }
7489: return $aliassymb;
7490: }
7491:
1.12 www 7492: # ----------------------------------------------------------------- Define Role
7493:
7494: sub definerole {
7495: if (allowed('mcr','/')) {
7496: my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800 albertel 7497: foreach my $role (split(':',$sysrole)) {
7498: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7499: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
7500: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
7501: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 7502: return "refused:s:$crole&$cqual";
7503: }
7504: }
1.191 harris41 7505: }
1.800 albertel 7506: foreach my $role (split(':',$domrole)) {
7507: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7508: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
7509: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
7510: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 7511: return "refused:d:$crole&$cqual";
7512: }
7513: }
1.191 harris41 7514: }
1.800 albertel 7515: foreach my $role (split(':',$courole)) {
7516: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7517: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
7518: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
7519: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 7520: return "refused:c:$crole&$cqual";
7521: }
7522: }
1.191 harris41 7523: }
1.620 albertel 7524: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
7525: "$env{'user.domain'}:$env{'user.name'}:".
1.21 www 7526: "rolesdef_$rolename=".
7527: escape($sysrole.'_'.$domrole.'_'.$courole);
1.620 albertel 7528: return reply($command,$env{'user.home'});
1.12 www 7529: } else {
7530: return 'refused';
7531: }
1.105 harris41 7532: }
7533:
7534: # ---------------- Make a metadata query against the network of library servers
7535:
7536: sub metadata_query {
1.1237 raeburn 7537: my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120 harris41 7538: my %rhash;
1.845 albertel 7539: my %libserv = &all_library();
1.244 matthew 7540: my @server_list = (defined($server_array) ? @$server_array
7541: : keys(%libserv) );
7542: for my $server (@server_list) {
1.1237 raeburn 7543: my $domains = '';
7544: if (ref($domains_hash) eq 'HASH') {
7545: $domains = $domains_hash->{$server};
7546: }
1.118 harris41 7547: unless ($custom or $customshow) {
1.1237 raeburn 7548: my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118 harris41 7549: $rhash{$server}=$reply;
7550: }
7551: else {
7552: my $reply=&reply("querysend:".&escape($query).':'.
1.1237 raeburn 7553: &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118 harris41 7554: $server);
7555: $rhash{$server}=$reply;
7556: }
1.112 harris41 7557: }
1.118 harris41 7558: return \%rhash;
1.240 www 7559: }
7560:
7561: # ----------------------------------------- Send log queries and wait for reply
7562:
7563: sub log_query {
7564: my ($uname,$udom,$query,%filters)=@_;
7565: my $uhome=&homeserver($uname,$udom);
7566: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 7567: my $uhost=&hostname($uhome);
1.800 albertel 7568: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 7569: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
7570: $uhome);
1.479 albertel 7571: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 7572: return get_query_reply($queryid);
7573: }
7574:
1.818 raeburn 7575: # -------------------------- Update MySQL table for portfolio file
7576:
7577: sub update_portfolio_table {
1.821 raeburn 7578: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 7579: if ($group ne '') {
7580: $file_name =~s /^\Q$group\E//;
7581: }
1.818 raeburn 7582: my $homeserver = &homeserver($uname,$udom);
7583: my $queryid=
1.821 raeburn 7584: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
7585: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 7586: my $reply = &get_query_reply($queryid);
7587: return $reply;
7588: }
7589:
1.899 raeburn 7590: # -------------------------- Update MySQL allusers table
7591:
7592: sub update_allusers_table {
7593: my ($uname,$udom,$names) = @_;
7594: my $homeserver = &homeserver($uname,$udom);
7595: my $queryid=
7596: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
7597: 'lastname='.&escape($names->{'lastname'}).'%%'.
7598: 'firstname='.&escape($names->{'firstname'}).'%%'.
7599: 'middlename='.&escape($names->{'middlename'}).'%%'.
7600: 'generation='.&escape($names->{'generation'}).'%%'.
7601: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
7602: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 7603: return;
1.899 raeburn 7604: }
7605:
1.508 raeburn 7606: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 7607:
7608: sub fetch_enrollment_query {
1.511 raeburn 7609: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508 raeburn 7610: my $homeserver;
1.547 raeburn 7611: my $maxtries = 1;
1.508 raeburn 7612: if ($context eq 'automated') {
7613: $homeserver = $perlvar{'lonHostID'};
1.547 raeburn 7614: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 7615: } else {
7616: $homeserver = &homeserver($cnum,$dom);
7617: }
1.838 albertel 7618: my $host=&hostname($homeserver);
1.506 raeburn 7619: my $cmd = '';
1.1000 raeburn 7620: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 7621: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 7622: }
7623: $cmd =~ s/%%$//;
7624: $cmd = &escape($cmd);
7625: my $query = 'fetchenrollment';
1.620 albertel 7626: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 7627: unless ($queryid=~/^\Q$host\E\_/) {
7628: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
7629: return 'error: '.$queryid;
7630: }
1.506 raeburn 7631: my $reply = &get_query_reply($queryid);
1.547 raeburn 7632: my $tries = 1;
7633: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
7634: $reply = &get_query_reply($queryid);
7635: $tries ++;
7636: }
1.526 raeburn 7637: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 7638: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 7639: } else {
1.901 albertel 7640: my @responses = split(/:/,$reply);
1.515 raeburn 7641: if ($homeserver eq $perlvar{'lonHostID'}) {
1.800 albertel 7642: foreach my $line (@responses) {
7643: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 7644: $$replyref{$key} = $value;
7645: }
7646: } else {
1.1117 foxr 7647: my $pathname = LONCAPA::tempdir();
1.800 albertel 7648: foreach my $line (@responses) {
7649: my ($key,$value) = split(/=/,$line);
1.506 raeburn 7650: $$replyref{$key} = $value;
7651: if ($value > 0) {
1.800 albertel 7652: foreach my $item (@{$$affiliatesref{$key}}) {
7653: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 7654: my $destname = $pathname.'/'.$filename;
7655: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 7656: if ($xml_classlist =~ /^error/) {
7657: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
7658: } else {
1.506 raeburn 7659: if ( open(FILE,">$destname") ) {
7660: print FILE &unescape($xml_classlist);
7661: close(FILE);
1.526 raeburn 7662: } else {
7663: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 7664: }
7665: }
7666: }
7667: }
7668: }
7669: }
7670: return 'ok';
7671: }
7672: return 'error';
7673: }
7674:
1.242 www 7675: sub get_query_reply {
7676: my $queryid=shift;
1.1117 foxr 7677: my $replyfile=LONCAPA::tempdir().$queryid;
1.240 www 7678: my $reply='';
7679: for (1..100) {
7680: sleep 2;
7681: if (-e $replyfile.'.end') {
1.448 albertel 7682: if (open(my $fh,$replyfile)) {
1.904 albertel 7683: $reply = join('',<$fh>);
7684: close($fh);
1.240 www 7685: } else { return 'error: reply_file_error'; }
1.242 www 7686: return &unescape($reply);
7687: }
1.240 www 7688: }
1.242 www 7689: return 'timeout:'.$queryid;
1.240 www 7690: }
7691:
7692: sub courselog_query {
1.241 www 7693: #
7694: # possible filters:
7695: # url: url or symb
7696: # username
7697: # domain
7698: # action: view, submit, grade
7699: # start: timestamp
7700: # end: timestamp
7701: #
1.240 www 7702: my (%filters)=@_;
1.620 albertel 7703: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 7704: if ($filters{'url'}) {
7705: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
7706: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
7707: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
7708: }
1.620 albertel 7709: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
7710: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 7711: return &log_query($cname,$cdom,'courselog',%filters);
7712: }
7713:
7714: sub userlog_query {
1.858 raeburn 7715: #
7716: # possible filters:
7717: # action: log check role
7718: # start: timestamp
7719: # end: timestamp
7720: #
1.240 www 7721: my ($uname,$udom,%filters)=@_;
7722: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 7723: }
7724:
1.506 raeburn 7725: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
7726:
7727: sub auto_run {
1.508 raeburn 7728: my ($cnum,$cdom) = @_;
1.876 raeburn 7729: my $response = 0;
7730: my $settings;
7731: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
7732: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
7733: $settings = $domconfig{'autoenroll'};
7734: if ($settings->{'run'} eq '1') {
7735: $response = 1;
7736: }
7737: } else {
1.934 raeburn 7738: my $homeserver;
7739: if (&is_course($cdom,$cnum)) {
7740: $homeserver = &homeserver($cnum,$cdom);
7741: } else {
7742: $homeserver = &domain($cdom,'primary');
7743: }
7744: if ($homeserver ne 'no_host') {
7745: $response = &reply('autorun:'.$cdom,$homeserver);
7746: }
1.876 raeburn 7747: }
1.506 raeburn 7748: return $response;
7749: }
1.776 albertel 7750:
1.506 raeburn 7751: sub auto_get_sections {
1.508 raeburn 7752: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 7753: my $homeserver;
7754: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7755: $homeserver = &homeserver($cnum,$cdom);
7756: }
7757: if (!defined($homeserver)) {
7758: if ($cdom =~ /^$match_domain$/) {
7759: $homeserver = &domain($cdom,'primary');
7760: }
7761: }
7762: my @secs;
7763: if (defined($homeserver)) {
7764: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
7765: unless ($response eq 'refused') {
7766: @secs = split(/:/,$response);
7767: }
1.506 raeburn 7768: }
7769: return @secs;
7770: }
1.776 albertel 7771:
1.506 raeburn 7772: sub auto_new_course {
1.1099 raeburn 7773: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 7774: my $homeserver = &homeserver($cnum,$cdom);
1.1099 raeburn 7775: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 7776: return $response;
7777: }
1.776 albertel 7778:
1.506 raeburn 7779: sub auto_validate_courseID {
1.508 raeburn 7780: my ($cnum,$cdom,$inst_course_id) = @_;
7781: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 7782: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 7783: return $response;
7784: }
1.776 albertel 7785:
1.1007 raeburn 7786: sub auto_validate_instcode {
1.1020 raeburn 7787: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 7788: my ($homeserver,$response);
7789: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7790: $homeserver = &homeserver($cnum,$cdom);
7791: }
7792: if (!defined($homeserver)) {
7793: if ($cdom =~ /^$match_domain$/) {
7794: $homeserver = &domain($cdom,'primary');
7795: }
7796: }
1.1065 raeburn 7797: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
7798: &escape($instcode).':'.&escape($owner),$homeserver));
1.1216 raeburn 7799: my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
7800: return ($outcome,$description,$defaultcredits);
1.1007 raeburn 7801: }
7802:
1.506 raeburn 7803: sub auto_create_password {
1.873 raeburn 7804: my ($cnum,$cdom,$authparam,$udom) = @_;
7805: my ($homeserver,$response);
1.506 raeburn 7806: my $create_passwd = 0;
7807: my $authchk = '';
1.873 raeburn 7808: if ($udom =~ /^$match_domain$/) {
7809: $homeserver = &domain($udom,'primary');
7810: }
7811: if ($homeserver eq '') {
7812: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7813: $homeserver = &homeserver($cnum,$cdom);
7814: }
7815: }
7816: if ($homeserver eq '') {
7817: $authchk = 'nodomain';
1.506 raeburn 7818: } else {
1.873 raeburn 7819: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
7820: if ($response eq 'refused') {
7821: $authchk = 'refused';
7822: } else {
1.901 albertel 7823: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 7824: }
1.506 raeburn 7825: }
7826: return ($authparam,$create_passwd,$authchk);
7827: }
7828:
1.706 raeburn 7829: sub auto_photo_permission {
7830: my ($cnum,$cdom,$students) = @_;
7831: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 7832: my ($outcome,$perm_reqd,$conditions) =
7833: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 7834: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7835: return (undef,undef);
7836: }
1.706 raeburn 7837: return ($outcome,$perm_reqd,$conditions);
7838: }
7839:
7840: sub auto_checkphotos {
7841: my ($uname,$udom,$pid) = @_;
7842: my $homeserver = &homeserver($uname,$udom);
7843: my ($result,$resulttype);
7844: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 7845: &escape($uname).':'.&escape($pid),
7846: $homeserver));
1.709 albertel 7847: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7848: return (undef,undef);
7849: }
1.706 raeburn 7850: if ($outcome) {
7851: ($result,$resulttype) = split(/:/,$outcome);
7852: }
7853: return ($result,$resulttype);
7854: }
7855:
7856: sub auto_photochoice {
7857: my ($cnum,$cdom) = @_;
7858: my $homeserver = &homeserver($cnum,$cdom);
7859: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 7860: &escape($cdom),
7861: $homeserver)));
1.709 albertel 7862: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7863: return (undef,undef);
7864: }
1.706 raeburn 7865: return ($update,$comment);
7866: }
7867:
7868: sub auto_photoupdate {
7869: my ($affiliatesref,$dom,$cnum,$photo) = @_;
7870: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 7871: my $host=&hostname($homeserver);
1.706 raeburn 7872: my $cmd = '';
7873: my $maxtries = 1;
1.800 albertel 7874: foreach my $affiliate (keys(%{$affiliatesref})) {
7875: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 7876: }
7877: $cmd =~ s/%%$//;
7878: $cmd = &escape($cmd);
7879: my $query = 'institutionalphotos';
7880: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
7881: unless ($queryid=~/^\Q$host\E\_/) {
7882: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
7883: return 'error: '.$queryid;
7884: }
7885: my $reply = &get_query_reply($queryid);
7886: my $tries = 1;
7887: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
7888: $reply = &get_query_reply($queryid);
7889: $tries ++;
7890: }
7891: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
7892: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
7893: } else {
7894: my @responses = split(/:/,$reply);
7895: my $outcome = shift(@responses);
7896: foreach my $item (@responses) {
7897: my ($key,$value) = split(/=/,$item);
7898: $$photo{$key} = $value;
7899: }
7900: return $outcome;
7901: }
7902: return 'error';
7903: }
7904:
1.521 raeburn 7905: sub auto_instcode_format {
1.793 albertel 7906: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
7907: $cat_order) = @_;
1.521 raeburn 7908: my $courses = '';
1.772 raeburn 7909: my @homeservers;
1.521 raeburn 7910: if ($caller eq 'global') {
1.841 albertel 7911: my %servers = &get_servers($codedom,'library');
7912: foreach my $tryserver (keys(%servers)) {
7913: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7914: push(@homeservers,$tryserver);
7915: }
1.584 raeburn 7916: }
1.1022 raeburn 7917: } elsif ($caller eq 'requests') {
7918: if ($codedom =~ /^$match_domain$/) {
7919: my $chome = &domain($codedom,'primary');
7920: unless ($chome eq 'no_host') {
7921: push(@homeservers,$chome);
7922: }
7923: }
1.521 raeburn 7924: } else {
1.772 raeburn 7925: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 7926: }
1.793 albertel 7927: foreach my $code (keys(%{$instcodes})) {
7928: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 7929: }
7930: chop($courses);
1.772 raeburn 7931: my $ok_response = 0;
7932: my $response;
7933: while (@homeservers > 0 && $ok_response == 0) {
7934: my $server = shift(@homeservers);
7935: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
7936: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
7937: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 7938: split(/:/,$response);
1.772 raeburn 7939: %{$codes} = (%{$codes},&str2hash($codes_str));
7940: push(@{$codetitles},&str2array($codetitles_str));
7941: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
7942: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
7943: $ok_response = 1;
7944: }
7945: }
7946: if ($ok_response) {
1.521 raeburn 7947: return 'ok';
1.772 raeburn 7948: } else {
7949: return $response;
1.521 raeburn 7950: }
7951: }
7952:
1.792 raeburn 7953: sub auto_instcode_defaults {
7954: my ($domain,$returnhash,$code_order) = @_;
7955: my @homeservers;
1.841 albertel 7956:
7957: my %servers = &get_servers($domain,'library');
7958: foreach my $tryserver (keys(%servers)) {
7959: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7960: push(@homeservers,$tryserver);
7961: }
1.792 raeburn 7962: }
1.841 albertel 7963:
1.792 raeburn 7964: my $response;
1.841 albertel 7965: foreach my $server (@homeservers) {
1.792 raeburn 7966: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 7967: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
7968:
7969: foreach my $pair (split(/\&/,$response)) {
7970: my ($name,$value)=split(/\=/,$pair);
7971: if ($name eq 'code_order') {
7972: @{$code_order} = split(/\&/,&unescape($value));
7973: } else {
7974: $returnhash->{&unescape($name)}=&unescape($value);
7975: }
7976: }
7977: return 'ok';
1.792 raeburn 7978: }
1.841 albertel 7979:
7980: return $response;
1.1003 raeburn 7981: }
7982:
7983: sub auto_possible_instcodes {
1.1007 raeburn 7984: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
7985: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
7986: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
7987: return;
7988: }
1.1003 raeburn 7989: my (@homeservers,$uhome);
7990: if (defined(&domain($domain,'primary'))) {
7991: $uhome=&domain($domain,'primary');
7992: push(@homeservers,&domain($domain,'primary'));
7993: } else {
7994: my %servers = &get_servers($domain,'library');
7995: foreach my $tryserver (keys(%servers)) {
7996: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7997: push(@homeservers,$tryserver);
7998: }
7999: }
8000: }
8001: my $response;
8002: foreach my $server (@homeservers) {
8003: $response=&reply('autopossibleinstcodes:'.$domain,$server);
8004: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 8005: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
8006: split(':',$response);
8007: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
8008: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 8009: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 8010: my ($name,$value)=split('=',$item);
8011: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 8012: }
8013: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 8014: my ($name,$value)=split('=',$item);
8015: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 8016: }
8017: return 'ok';
8018: }
8019: return $response;
8020: }
1.792 raeburn 8021:
1.1010 raeburn 8022: sub auto_courserequest_checks {
8023: my ($dom) = @_;
1.1020 raeburn 8024: my ($homeserver,%validations);
8025: if ($dom =~ /^$match_domain$/) {
8026: $homeserver = &domain($dom,'primary');
8027: }
8028: unless ($homeserver eq 'no_host') {
8029: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
8030: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
8031: my @items = split(/&/,$response);
8032: foreach my $item (@items) {
8033: my ($key,$value) = split('=',$item);
8034: $validations{&unescape($key)} = &thaw_unescape($value);
8035: }
8036: }
8037: }
1.1010 raeburn 8038: return %validations;
8039: }
8040:
1.1020 raeburn 8041: sub auto_courserequest_validation {
1.1255 raeburn 8042: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020 raeburn 8043: my ($homeserver,$response);
8044: if ($dom =~ /^$match_domain$/) {
8045: $homeserver = &domain($dom,'primary');
8046: }
1.1255 raeburn 8047: unless ($homeserver eq 'no_host') {
8048: my $customdata;
8049: if (ref($custominfo) eq 'HASH') {
8050: $customdata = &freeze_escape($custominfo);
8051: }
1.1020 raeburn 8052: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 8053: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1255 raeburn 8054: ':'.&escape($instcode).':'.&escape($instseclist).':'.
8055: $customdata,$homeserver));
1.1020 raeburn 8056: }
8057: return $response;
8058: }
8059:
1.777 albertel 8060: sub auto_validate_class_sec {
1.918 raeburn 8061: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 8062: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 8063: my $ownerlist;
8064: if (ref($owners) eq 'ARRAY') {
8065: $ownerlist = join(',',@{$owners});
8066: } else {
8067: $ownerlist = $owners;
8068: }
1.773 raeburn 8069: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 8070: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 8071: return $response;
8072: }
8073:
1.1248 raeburn 8074: sub auto_crsreq_update {
8075: my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1257 raeburn 8076: $code,$accessstart,$accessend,$inbound) = @_;
1.1248 raeburn 8077: my ($homeserver,%crsreqresponse);
8078: if ($cdom =~ /^$match_domain$/) {
8079: $homeserver = &domain($cdom,'primary');
8080: }
8081: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
8082: my $info;
8083: if (ref($inbound) eq 'HASH') {
8084: $info = &freeze_escape($inbound);
8085: }
8086: my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
8087: ':'.&escape($action).':'.&escape($ownername).':'.
8088: &escape($ownerdomain).':'.&escape($fullname).':'.
1.1257 raeburn 8089: &escape($title).':'.&escape($code).':'.
8090: &escape($accessstart).':'.&escape($accessend).':'.$info,
8091: $homeserver);
1.1248 raeburn 8092: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
8093: my @items = split(/&/,$response);
8094: foreach my $item (@items) {
8095: my ($key,$value) = split('=',$item);
8096: $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
8097: }
8098: }
8099: }
8100: return \%crsreqresponse;
8101: }
8102:
1.679 raeburn 8103: # ------------------------------------------------------- Course Group routines
8104:
8105: sub get_coursegroups {
1.809 raeburn 8106: my ($cdom,$cnum,$group,$namespace) = @_;
8107: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 8108: }
8109:
1.679 raeburn 8110: sub modify_coursegroup {
8111: my ($cdom,$cnum,$groupsettings) = @_;
8112: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
8113: }
8114:
1.809 raeburn 8115: sub toggle_coursegroup_status {
8116: my ($cdom,$cnum,$group,$action) = @_;
8117: my ($from_namespace,$to_namespace);
8118: if ($action eq 'delete') {
8119: $from_namespace = 'coursegroups';
8120: $to_namespace = 'deleted_groups';
8121: } else {
8122: $from_namespace = 'deleted_groups';
8123: $to_namespace = 'coursegroups';
8124: }
8125: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 8126: if (my $tmp = &error(%curr_group)) {
8127: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
8128: return ('read error',$tmp);
8129: } else {
8130: my %savedsettings = %curr_group;
1.809 raeburn 8131: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 8132: my $deloutcome;
8133: if ($result eq 'ok') {
1.809 raeburn 8134: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 8135: } else {
8136: return ('write error',$result);
8137: }
8138: if ($deloutcome eq 'ok') {
8139: return 'ok';
8140: } else {
8141: return ('delete error',$deloutcome);
8142: }
8143: }
8144: }
8145:
1.679 raeburn 8146: sub modify_group_roles {
1.957 raeburn 8147: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 8148: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
8149: my $role = 'gr/'.&escape($userprivs);
8150: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 8151: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 8152: if ($result eq 'ok') {
8153: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
8154: }
1.679 raeburn 8155: return $result;
8156: }
8157:
8158: sub modify_coursegroup_membership {
8159: my ($cdom,$cnum,$membership) = @_;
8160: my $result = &put('groupmembership',$membership,$cdom,$cnum);
8161: return $result;
8162: }
8163:
1.682 raeburn 8164: sub get_active_groups {
8165: my ($udom,$uname,$cdom,$cnum) = @_;
8166: my $now = time;
8167: my %groups = ();
8168: foreach my $key (keys(%env)) {
1.811 albertel 8169: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 8170: my ($start,$end) = split(/\./,$env{$key});
8171: if (($end!=0) && ($end<$now)) { next; }
8172: if (($start!=0) && ($start>$now)) { next; }
8173: if ($1 eq $cdom && $2 eq $cnum) {
8174: $groups{$3} = $env{$key} ;
8175: }
8176: }
8177: }
8178: return %groups;
8179: }
8180:
1.683 raeburn 8181: sub get_group_membership {
8182: my ($cdom,$cnum,$group) = @_;
8183: return(&dump('groupmembership',$cdom,$cnum,$group));
8184: }
8185:
8186: sub get_users_groups {
8187: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 8188: my @usersgroups;
1.683 raeburn 8189: my $cachetime=1800;
8190:
8191: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 8192: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
8193: if (defined($cached)) {
1.734 albertel 8194: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 8195: } else {
8196: $grouplist = '';
1.816 raeburn 8197: my $courseurl = &courseid_to_courseurl($courseid);
1.1166 raeburn 8198: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 8199: my $access_end = $env{'course.'.$courseid.
8200: '.default_enrollment_end_date'};
8201: my $now = time;
8202: foreach my $key (keys(%roleshash)) {
8203: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
8204: my $group = $1;
8205: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
8206: my $start = $2;
8207: my $end = $1;
8208: if ($start == -1) { next; } # deleted from group
8209: if (($start!=0) && ($start>$now)) { next; }
8210: if (($end!=0) && ($end<$now)) {
8211: if ($access_end && $access_end < $now) {
8212: if ($access_end - $end < 86400) {
8213: push(@usersgroups,$group);
1.733 raeburn 8214: }
8215: }
1.817 raeburn 8216: next;
1.733 raeburn 8217: }
1.817 raeburn 8218: push(@usersgroups,$group);
1.683 raeburn 8219: }
8220: }
8221: }
1.817 raeburn 8222: @usersgroups = &sort_course_groups($courseid,@usersgroups);
8223: $grouplist = join(':',@usersgroups);
8224: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 8225: }
1.733 raeburn 8226: return @usersgroups;
1.683 raeburn 8227: }
8228:
8229: sub devalidate_getgroups_cache {
8230: my ($udom,$uname,$cdom,$cnum)=@_;
8231: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 8232:
1.683 raeburn 8233: my $hashid="$udom:$uname:$courseid";
8234: &devalidate_cache_new('getgroups',$hashid);
8235: }
8236:
1.12 www 8237: # ------------------------------------------------------------------ Plain Text
8238:
8239: sub plaintext {
1.988 raeburn 8240: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 8241: if ($short =~ m{^cr/}) {
1.758 albertel 8242: return (split('/',$short))[-1];
8243: }
1.742 raeburn 8244: if (!defined($cid)) {
8245: $cid = $env{'request.course.id'};
8246: }
8247: my %rolenames = (
1.1008 raeburn 8248: Course => 'std',
8249: Community => 'alt1',
1.742 raeburn 8250: );
1.1037 raeburn 8251: if ($cid ne '') {
8252: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
8253: unless ($forcedefault) {
8254: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
8255: &Apache::lonlocal::mt_escape(\$roletext);
8256: return &Apache::lonlocal::mt($roletext);
8257: }
8258: }
8259: }
8260: if ((defined($type)) && (defined($rolenames{$type})) &&
8261: (defined($rolenames{$type})) &&
8262: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 8263: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 8264: } elsif ($cid ne '') {
8265: my $crstype = $env{'course.'.$cid.'.type'};
8266: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
8267: (defined($prp{$short}{$rolenames{$crstype}}))) {
8268: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
8269: }
1.742 raeburn 8270: }
1.1037 raeburn 8271: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 8272: }
8273:
8274: # ----------------------------------------------------------------- Assign Role
8275:
8276: sub assignrole {
1.957 raeburn 8277: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
8278: $context)=@_;
1.21 www 8279: my $mrole;
8280: if ($role =~ /^cr\//) {
1.393 www 8281: my $cwosec=$url;
1.811 albertel 8282: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 8283: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 8284: my $refused = 1;
8285: if ($context eq 'requestcourses') {
8286: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
8287: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
8288: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
8289: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8290: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8291: if ($crsenv{'internal.courseowner'} eq
8292: $env{'user.name'}.':'.$env{'user.domain'}) {
8293: $refused = '';
8294: }
8295: }
8296: }
8297: }
8298: }
8299: if ($refused) {
8300: &logthis('Refused custom assignrole: '.
8301: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
8302: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
8303: return 'refused';
8304: }
1.104 www 8305: }
1.21 www 8306: $mrole='cr';
1.678 raeburn 8307: } elsif ($role =~ /^gr\//) {
8308: my $cwogrp=$url;
1.811 albertel 8309: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 8310: unless (&allowed('mdg',$cwogrp)) {
8311: &logthis('Refused group assignrole: '.
8312: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
8313: $env{'user.name'}.' at '.$env{'user.domain'});
8314: return 'refused';
8315: }
8316: $mrole='gr';
1.21 www 8317: } else {
1.82 www 8318: my $cwosec=$url;
1.811 albertel 8319: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 8320: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
8321: my $refused;
8322: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
8323: if (!(&allowed('c'.$role,$url))) {
8324: $refused = 1;
8325: }
8326: } else {
8327: $refused = 1;
8328: }
1.947 raeburn 8329: if ($refused) {
1.1045 raeburn 8330: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8331: if (!$selfenroll && $context eq 'course') {
8332: my %crsenv;
8333: if ($role eq 'cc' || $role eq 'co') {
8334: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8335: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
8336: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
8337: if ($crsenv{'internal.courseowner'} eq
8338: $env{'user.name'}.':'.$env{'user.domain'}) {
8339: $refused = '';
8340: }
8341: }
8342: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
8343: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
8344: if ($crsenv{'internal.courseowner'} eq
8345: $env{'user.name'}.':'.$env{'user.domain'}) {
8346: $refused = '';
8347: }
8348: }
8349: }
8350: }
8351: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 8352: $refused = '';
1.1017 raeburn 8353: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 8354: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 8355: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 8356: my $wrongcc;
8357: if ($cnum =~ /^$match_community$/) {
8358: $wrongcc = 1 if ($role eq 'cc');
8359: } else {
8360: $wrongcc = 1 if ($role eq 'co');
8361: }
8362: unless ($wrongcc) {
8363: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8364: if ($crsenv{'internal.courseowner'} eq
8365: $env{'user.name'}.':'.$env{'user.domain'}) {
8366: $refused = '';
8367: }
1.1017 raeburn 8368: }
8369: }
1.1183 raeburn 8370: } elsif ($context eq 'requestauthor') {
8371: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
8372: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
8373: if ($env{'environment.requestauthor'} eq 'automatic') {
8374: $refused = '';
8375: } else {
8376: my %domdefaults = &get_domain_defaults($udom);
8377: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
8378: my $checkbystatus;
8379: if ($env{'user.adv'}) {
8380: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
8381: if ($disposition eq 'automatic') {
8382: $refused = '';
8383: } elsif ($disposition eq '') {
8384: $checkbystatus = 1;
8385: }
8386: } else {
8387: $checkbystatus = 1;
8388: }
8389: if ($checkbystatus) {
8390: if ($env{'environment.inststatus'}) {
8391: my @inststatuses = split(/,/,$env{'environment.inststatus'});
8392: foreach my $type (@inststatuses) {
8393: if (($type ne '') &&
8394: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
8395: $refused = '';
8396: }
8397: }
8398: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
8399: $refused = '';
8400: }
8401: }
8402: }
8403: }
8404: }
1.1017 raeburn 8405: }
8406: if ($refused) {
1.947 raeburn 8407: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
8408: ' '.$role.' '.$end.' '.$start.' by '.
8409: $env{'user.name'}.' at '.$env{'user.domain'});
8410: return 'refused';
8411: }
1.932 raeburn 8412: }
1.1131 raeburn 8413: } elsif ($role eq 'au') {
8414: if ($url ne '/'.$udom.'/') {
8415: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
8416: ' to assign author role for '.$uname.':'.$udom.
8417: ' in domain: '.$url.' refused (wrong domain).');
8418: return 'refused';
8419: }
1.104 www 8420: }
1.21 www 8421: $mrole=$role;
8422: }
1.620 albertel 8423: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 8424: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 8425: if ($end) { $command.='_'.$end; }
1.21 www 8426: if ($start) {
8427: if ($end) {
1.81 www 8428: $command.='_'.$start;
1.21 www 8429: } else {
1.81 www 8430: $command.='_0_'.$start;
1.21 www 8431: }
8432: }
1.739 raeburn 8433: my $origstart = $start;
8434: my $origend = $end;
1.957 raeburn 8435: my $delflag;
1.357 www 8436: # actually delete
8437: if ($deleteflag) {
1.373 www 8438: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 8439: # modify command to delete the role
1.620 albertel 8440: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 8441: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 8442: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 8443: # set start and finish to negative values for userrolelog
8444: $start=-1;
8445: $end=-1;
1.957 raeburn 8446: $delflag = 1;
1.357 www 8447: }
8448: }
8449: # send command
1.349 www 8450: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 8451: # log new user role if status is ok
1.349 www 8452: if ($answer eq 'ok') {
1.663 raeburn 8453: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.1184 raeburn 8454: if (($role eq 'cc') || ($role eq 'in') ||
8455: ($role eq 'ep') || ($role eq 'ad') ||
8456: ($role eq 'ta') || ($role eq 'st') ||
8457: ($role=~/^cr/) || ($role eq 'gr') ||
8458: ($role eq 'co')) {
1.1200 raeburn 8459: # for course roles, perform group memberships changes triggered by role change.
8460: unless ($role =~ /^gr/) {
8461: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
8462: $origstart,$selfenroll,$context);
8463: }
1.1184 raeburn 8464: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8465: $selfenroll,$context);
8466: } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
8467: ($role eq 'au') || ($role eq 'dc')) {
8468: &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8469: $context);
8470: } elsif (($role eq 'ca') || ($role eq 'aa')) {
8471: &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8472: $context);
8473: }
1.1053 raeburn 8474: if ($role eq 'cc') {
8475: &autoupdate_coowners($url,$end,$start,$uname,$udom);
8476: }
1.349 www 8477: }
8478: return $answer;
1.169 harris41 8479: }
8480:
1.1053 raeburn 8481: sub autoupdate_coowners {
8482: my ($url,$end,$start,$uname,$udom) = @_;
8483: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
8484: if (($cdom ne '') && ($cnum ne '')) {
8485: my $now = time;
8486: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
8487: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
8488: my %coursehash = &coursedescription($cdom.'_'.$cnum);
8489: my $instcode = $coursehash{'internal.coursecode'};
8490: if ($instcode ne '') {
1.1056 raeburn 8491: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
8492: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 8493: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 8494: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
8495: if ($result eq 'valid') {
8496: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 8497: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
8498: push(@newcoowners,$coowner);
8499: }
8500: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
8501: push(@newcoowners,$uname.':'.$udom);
8502: }
8503: @newcoowners = sort(@newcoowners);
8504: } else {
8505: push(@newcoowners,$uname.':'.$udom);
8506: }
8507: } else {
8508: if ($coursehash{'internal.co-owners'}) {
8509: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
8510: unless ($coowner eq $uname.':'.$udom) {
8511: push(@newcoowners,$coowner);
8512: }
8513: }
8514: unless (@newcoowners > 0) {
8515: $delcoowners = 1;
8516: $coowners = '';
8517: }
8518: }
8519: }
8520: if (@newcoowners || $delcoowners) {
8521: &store_coowners($cdom,$cnum,$coursehash{'home'},
8522: $delcoowners,@newcoowners);
8523: }
8524: }
8525: }
8526: }
8527: }
8528: }
8529: }
8530:
8531: sub store_coowners {
8532: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
8533: my $cid = $cdom.'_'.$cnum;
8534: my ($coowners,$delresult,$putresult);
8535: if (@newcoowners) {
8536: $coowners = join(',',@newcoowners);
8537: my %coownershash = (
8538: 'internal.co-owners' => $coowners,
8539: );
8540: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
8541: if ($putresult eq 'ok') {
8542: if ($env{'course.'.$cid.'.num'} eq $cnum) {
8543: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
8544: }
8545: }
8546: }
8547: if ($delcoowners) {
8548: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
8549: if ($delresult eq 'ok') {
8550: if ($env{'course.'.$cid.'.internal.co-owners'}) {
8551: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
8552: }
8553: }
8554: }
8555: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
8556: my %crsinfo =
8557: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
8558: if (ref($crsinfo{$cid}) eq 'HASH') {
8559: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
8560: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
8561: }
8562: }
8563: }
8564:
1.169 harris41 8565: # -------------------------------------------------- Modify user authentication
1.197 www 8566: # Overrides without validation
8567:
1.169 harris41 8568: sub modifyuserauth {
8569: my ($udom,$uname,$umode,$upass)=@_;
8570: my $uhome=&homeserver($uname,$udom);
1.197 www 8571: unless (&allowed('mau',$udom)) { return 'refused'; }
8572: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 8573: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
8574: ' in domain '.$env{'request.role.domain'});
1.169 harris41 8575: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
8576: &escape($upass),$uhome);
1.620 albertel 8577: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 8578: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
8579: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
8580: &log($udom,,$uname,$uhome,
1.620 albertel 8581: 'Authentication changed by '.$env{'user.domain'}.', '.
8582: $env{'user.name'}.', '.$umode.
1.197 www 8583: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 8584: unless ($reply eq 'ok') {
1.197 www 8585: &logthis('Authentication mode error: '.$reply);
1.169 harris41 8586: return 'error: '.$reply;
8587: }
1.170 harris41 8588: return 'ok';
1.80 www 8589: }
8590:
1.81 www 8591: # --------------------------------------------------------------- Modify a user
1.80 www 8592:
1.81 www 8593: sub modifyuser {
1.206 matthew 8594: my ($udom, $uname, $uid,
8595: $umode, $upass, $first,
8596: $middle, $last, $gene,
1.1058 raeburn 8597: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 8598: $udom= &LONCAPA::clean_domain($udom);
8599: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 8600: my $showcandelete = 'none';
8601: if (ref($candelete) eq 'ARRAY') {
8602: if (@{$candelete} > 0) {
8603: $showcandelete = join(', ',@{$candelete});
8604: }
8605: }
1.81 www 8606: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 8607: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 8608: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 8609: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
8610: ' desiredhome not specified').
1.620 albertel 8611: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
8612: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 8613: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 8614: my $newuser;
8615: if ($uhome eq 'no_host') {
8616: $newuser = 1;
8617: }
1.80 www 8618: # ----------------------------------------------------------------- Create User
1.406 albertel 8619: if (($uhome eq 'no_host') &&
8620: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 8621: my $unhome='';
1.844 albertel 8622: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 8623: $unhome = $desiredhome;
1.620 albertel 8624: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
8625: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 8626: } else { # load balancing routine for determining $unhome
1.81 www 8627: my $loadm=10000000;
1.841 albertel 8628: my %servers = &get_servers($udom,'library');
8629: foreach my $tryserver (keys(%servers)) {
8630: my $answer=reply('load',$tryserver);
8631: if (($answer=~/\d+/) && ($answer<$loadm)) {
8632: $loadm=$answer;
8633: $unhome=$tryserver;
8634: }
1.80 www 8635: }
8636: }
8637: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 8638: return 'error: unable to find a home server for '.$uname.
8639: ' in domain '.$udom;
1.80 www 8640: }
8641: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
8642: &escape($upass),$unhome);
8643: unless ($reply eq 'ok') {
8644: return 'error: '.$reply;
8645: }
1.230 stredwic 8646: $uhome=&homeserver($uname,$udom,'true');
1.80 www 8647: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 8648: return 'error: unable verify users home machine.';
1.80 www 8649: }
1.209 matthew 8650: } # End of creation of new user
1.80 www 8651: # ---------------------------------------------------------------------- Add ID
8652: if ($uid) {
8653: $uid=~tr/A-Z/a-z/;
8654: my %uidhash=&idrget($udom,$uname);
1.196 www 8655: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
8656: && (!$forceid)) {
1.80 www 8657: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 8658: return 'error: user id "'.$uid.'" does not match '.
8659: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 8660: }
8661: } else {
8662: &idput($udom,($uname => $uid));
8663: }
8664: }
8665: # -------------------------------------------------------------- Add names, etc
1.313 matthew 8666: my @tmp=&get('environment',
1.899 raeburn 8667: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 8668: 'permanentemail','inststatus'],
1.134 albertel 8669: $udom,$uname);
1.1075 raeburn 8670: my (%names,%oldnames);
1.313 matthew 8671: if ($tmp[0] =~ m/^error:.*/) {
8672: %names=();
8673: } else {
8674: %names = @tmp;
1.1075 raeburn 8675: %oldnames = %names;
1.313 matthew 8676: }
1.388 www 8677: #
1.1058 raeburn 8678: # If name, email and/or uid are blank (e.g., because an uploaded file
8679: # of users did not contain them), do not overwrite existing values
8680: # unless field is in $candelete array ref.
8681: #
8682:
8683: my @fields = ('firstname','middlename','lastname','generation',
8684: 'permanentemail','id');
8685: my %newvalues;
8686: if (ref($candelete) eq 'ARRAY') {
8687: foreach my $field (@fields) {
8688: if (grep(/^\Q$field\E$/,@{$candelete})) {
8689: if ($field eq 'firstname') {
8690: $names{$field} = $first;
8691: } elsif ($field eq 'middlename') {
8692: $names{$field} = $middle;
8693: } elsif ($field eq 'lastname') {
8694: $names{$field} = $last;
8695: } elsif ($field eq 'generation') {
8696: $names{$field} = $gene;
8697: } elsif ($field eq 'permanentemail') {
8698: $names{$field} = $email;
8699: } elsif ($field eq 'id') {
8700: $names{$field} = $uid;
8701: }
8702: }
8703: }
8704: }
1.388 www 8705: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 8706: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 8707: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 8708: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 8709: if ($email) {
8710: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 8711: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 8712: }
1.899 raeburn 8713: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 8714: if (defined($inststatus)) {
8715: $names{'inststatus'} = '';
8716: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
8717: if (ref($usertypes) eq 'HASH') {
8718: my @okstatuses;
8719: foreach my $item (split(/:/,$inststatus)) {
8720: if (defined($usertypes->{$item})) {
8721: push(@okstatuses,$item);
8722: }
8723: }
8724: if (@okstatuses) {
8725: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
8726: }
8727: }
8728: }
1.1075 raeburn 8729: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 8730: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 8731: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 8732: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
8733: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
8734: } else {
8735: $logmsg .= ' during self creation';
8736: }
1.1075 raeburn 8737: my $changed;
8738: if ($newuser) {
8739: $changed = 1;
8740: } else {
8741: foreach my $field (@fields) {
8742: if ($names{$field} ne $oldnames{$field}) {
8743: $changed = 1;
8744: last;
8745: }
8746: }
8747: }
8748: unless ($changed) {
8749: $logmsg = 'No changes in user information needed for: '.$logmsg;
8750: &logthis($logmsg);
8751: return 'ok';
8752: }
8753: my $reply = &put('environment', \%names, $udom,$uname);
8754: if ($reply ne 'ok') {
8755: return 'error: '.$reply;
8756: }
1.1087 raeburn 8757: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
8758: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
8759: }
1.1075 raeburn 8760: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
8761: &devalidate_cache_new('namescache',$uname.':'.$udom);
8762: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 8763: &logthis($logmsg);
1.134 albertel 8764: return 'ok';
1.80 www 8765: }
8766:
1.81 www 8767: # -------------------------------------------------------------- Modify student
1.80 www 8768:
1.81 www 8769: sub modifystudent {
8770: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 8771: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1216 raeburn 8772: $selfenroll,$context,$inststatus,$credits)=@_;
1.455 albertel 8773: if (!$cid) {
1.620 albertel 8774: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 8775: return 'not_in_class';
8776: }
1.80 www 8777: }
8778: # --------------------------------------------------------------- Make the user
1.81 www 8779: my $reply=&modifyuser
1.209 matthew 8780: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 8781: $desiredhome,$email,$inststatus);
1.80 www 8782: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 8783: # This will cause &modify_student_enrollment to get the uid from the
1.1235 raeburn 8784: # student's environment
1.297 matthew 8785: $uid = undef if (!$forceid);
1.455 albertel 8786: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1216 raeburn 8787: $gene,$usec,$end,$start,$type,$locktype,
8788: $cid,$selfenroll,$context,$credits);
1.297 matthew 8789: return $reply;
8790: }
8791:
8792: sub modify_student_enrollment {
1.1216 raeburn 8793: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
8794: $locktype,$cid,$selfenroll,$context,$credits) = @_;
1.455 albertel 8795: my ($cdom,$cnum,$chome);
8796: if (!$cid) {
1.620 albertel 8797: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 8798: return 'not_in_class';
8799: }
1.620 albertel 8800: $cdom=$env{'course.'.$cid.'.domain'};
8801: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 8802: } else {
8803: ($cdom,$cnum)=split(/_/,$cid);
8804: }
1.620 albertel 8805: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 8806: if (!$chome) {
1.457 raeburn 8807: $chome=&homeserver($cnum,$cdom);
1.297 matthew 8808: }
1.455 albertel 8809: if (!$chome) { return 'unknown_course'; }
1.297 matthew 8810: # Make sure the user exists
1.81 www 8811: my $uhome=&homeserver($uname,$udom);
8812: if (($uhome eq '') || ($uhome eq 'no_host')) {
8813: return 'error: no such user';
8814: }
1.297 matthew 8815: # Get student data if we were not given enough information
8816: if (!defined($first) || $first eq '' ||
8817: !defined($last) || $last eq '' ||
8818: !defined($uid) || $uid eq '' ||
8819: !defined($middle) || $middle eq '' ||
8820: !defined($gene) || $gene eq '') {
1.294 matthew 8821: # They did not supply us with enough data to enroll the student, so
8822: # we need to pick up more information.
1.297 matthew 8823: my %tmp = &get('environment',
1.294 matthew 8824: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 8825: ,$udom,$uname);
8826:
1.800 albertel 8827: #foreach my $key (keys(%tmp)) {
8828: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 8829: #}
1.294 matthew 8830: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
8831: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
8832: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 8833: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 8834: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
8835: }
1.556 albertel 8836: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148 raeburn 8837: my $user = "$uname:$udom";
8838: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487 albertel 8839: my $reply=cput('classlist',
1.1148 raeburn 8840: {$user =>
1.1216 raeburn 8841: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits) },
1.487 albertel 8842: $cdom,$cnum);
1.1148 raeburn 8843: if (($reply eq 'ok') || ($reply eq 'delayed')) {
8844: &devalidate_getsection_cache($udom,$uname,$cid);
8845: } else {
1.81 www 8846: return 'error: '.$reply;
8847: }
1.297 matthew 8848: # Add student role to user
1.83 www 8849: my $uurl='/'.$cid;
1.81 www 8850: $uurl=~s/\_/\//g;
8851: if ($usec) {
8852: $uurl.='/'.$usec;
8853: }
1.1148 raeburn 8854: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
8855: $selfenroll,$context);
8856: if ($result ne 'ok') {
8857: if ($old_entry{$user} ne '') {
8858: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
8859: } else {
8860: $reply = &del('classlist',[$user],$cdom,$cnum);
8861: }
8862: }
8863: return $result;
1.21 www 8864: }
8865:
1.556 albertel 8866: sub format_name {
8867: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
8868: my $name;
8869: if ($first ne 'lastname') {
8870: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
8871: } else {
8872: if ($lastname=~/\S/) {
8873: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
8874: $name=~s/\s+,/,/;
8875: } else {
8876: $name.= $firstname.' '.$middlename.' '.$generation;
8877: }
8878: }
8879: $name=~s/^\s+//;
8880: $name=~s/\s+$//;
8881: $name=~s/\s+/ /g;
8882: return $name;
8883: }
8884:
1.84 www 8885: # ------------------------------------------------- Write to course preferences
8886:
8887: sub writecoursepref {
8888: my ($courseid,%prefs)=@_;
8889: $courseid=~s/^\///;
8890: $courseid=~s/\_/\//g;
8891: my ($cdomain,$cnum)=split(/\//,$courseid);
8892: my $chome=homeserver($cnum,$cdomain);
8893: if (($chome eq '') || ($chome eq 'no_host')) {
8894: return 'error: no such course';
8895: }
8896: my $cstring='';
1.800 albertel 8897: foreach my $pref (keys(%prefs)) {
8898: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 8899: }
1.84 www 8900: $cstring=~s/\&$//;
8901: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
8902: }
8903:
8904: # ---------------------------------------------------------- Make/modify course
8905:
8906: sub createcourse {
1.741 raeburn 8907: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 8908: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 8909: $url=&declutter($url);
8910: my $cid='';
1.1028 raeburn 8911: if ($context eq 'requestcourses') {
8912: my $can_create = 0;
8913: my ($ownername,$ownerdom) = split(':',$course_owner);
8914: if ($udom eq $ownerdom) {
8915: if (&usertools_access($ownername,$ownerdom,$category,undef,
8916: $context)) {
8917: $can_create = 1;
8918: }
8919: } else {
8920: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
8921: $category);
8922: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
8923: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
8924: if (@curr > 0) {
8925: my @options = qw(approval validate autolimit);
8926: my $optregex = join('|',@options);
8927: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
8928: $can_create = 1;
8929: }
8930: }
8931: }
8932: }
8933: if ($can_create) {
8934: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
8935: unless (&allowed('ccc',$udom)) {
8936: return 'refused';
8937: }
1.1017 raeburn 8938: }
8939: } else {
8940: return 'refused';
8941: }
1.1028 raeburn 8942: } elsif (!&allowed('ccc',$udom)) {
8943: return 'refused';
1.84 www 8944: }
1.1011 raeburn 8945: # --------------------------------------------------------------- Get Unique ID
8946: my $uname;
8947: if ($cnum =~ /^$match_courseid$/) {
8948: my $chome=&homeserver($cnum,$udom,'true');
8949: if (($chome eq '') || ($chome eq 'no_host')) {
8950: $uname = $cnum;
8951: } else {
1.1038 raeburn 8952: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 8953: }
8954: } else {
1.1038 raeburn 8955: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 8956: }
8957: return $uname if ($uname =~ /^error/);
8958: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 8959: if (!defined($course_server)) {
8960: if (defined(&domain($udom,'primary'))) {
8961: $course_server = &domain($udom,'primary');
8962: } else {
8963: $course_server = $env{'user.home'};
8964: }
8965: }
8966: my %host_servers =
8967: &Apache::lonnet::get_servers($udom,'library');
8968: unless ($host_servers{$course_server}) {
8969: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 8970: }
1.84 www 8971: # ------------------------------------------------------------- Make the course
8972: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 8973: $course_server);
1.84 www 8974: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 8975: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 8976: if (($uhome eq '') || ($uhome eq 'no_host')) {
8977: return 'error: no such course';
8978: }
1.271 www 8979: # ----------------------------------------------------------------- Course made
1.516 raeburn 8980: # log existence
1.1029 raeburn 8981: my $now = time;
1.918 raeburn 8982: my $newcourse = {
8983: $udom.'_'.$uname => {
1.921 raeburn 8984: description => $description,
8985: inst_code => $inst_code,
8986: owner => $course_owner,
8987: type => $crstype,
1.1029 raeburn 8988: creator => $env{'user.name'}.':'.
8989: $env{'user.domain'},
8990: created => $now,
8991: context => $context,
1.918 raeburn 8992: },
8993: };
1.921 raeburn 8994: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 8995: # set toplevel url
1.271 www 8996: my $topurl=$url;
8997: unless ($nonstandard) {
8998: # ------------------------------------------ For standard courses, make top url
8999: my $mapurl=&clutter($url);
1.278 www 9000: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 9001: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 9002: <map>
9003: <resource id="1" type="start"></resource>
9004: <resource id="2" src="$mapurl"></resource>
9005: <resource id="3" type="finish"></resource>
9006: <link index="1" from="1" to="2"></link>
9007: <link index="2" from="2" to="3"></link>
9008: </map>
9009: ENDINITMAP
9010: $topurl=&declutter(
1.638 albertel 9011: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 9012: );
9013: }
9014: # ----------------------------------------------------------- Write preferences
1.84 www 9015: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 9016: ('description' => $description,
9017: 'url' => $topurl,
9018: 'internal.creator' => $env{'user.name'}.':'.
9019: $env{'user.domain'},
9020: 'internal.created' => $now,
9021: 'internal.creationcontext' => $context)
9022: );
1.84 www 9023: return '/'.$udom.'/'.$uname;
9024: }
9025:
1.1011 raeburn 9026: # ------------------------------------------------------------------- Create ID
9027: sub generate_coursenum {
1.1038 raeburn 9028: my ($udom,$crstype) = @_;
1.1011 raeburn 9029: my $domdesc = &domain($udom);
9030: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 9031: my $first;
9032: if ($crstype eq 'Community') {
9033: $first = '0';
9034: } else {
9035: $first = int(1+rand(9));
9036: }
9037: my $uname=$first.
1.1011 raeburn 9038: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
9039: substr($$.time,0,5).unpack("H8",pack("I32",time)).
9040: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
9041: # ----------------------------------------------- Make sure that does not exist
9042: my $uhome=&homeserver($uname,$udom,'true');
9043: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 9044: if ($crstype eq 'Community') {
9045: $first = '0';
9046: } else {
9047: $first = int(1+rand(9));
9048: }
9049: $uname=$first.
1.1011 raeburn 9050: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
9051: substr($$.time,0,5).unpack("H8",pack("I32",time)).
9052: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
9053: $uhome=&homeserver($uname,$udom,'true');
9054: unless (($uhome eq '') || ($uhome eq 'no_host')) {
9055: return 'error: unable to generate unique course-ID';
9056: }
9057: }
9058: return $uname;
9059: }
9060:
1.813 albertel 9061: sub is_course {
1.1167 droeschl 9062: my ($cdom, $cnum) = scalar(@_) == 1 ?
9063: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
9064:
9065: return unless $cdom and $cnum;
9066:
9067: my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
9068: '.');
9069:
1.1219 raeburn 9070: return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167 droeschl 9071: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813 albertel 9072: }
9073:
1.1015 raeburn 9074: sub store_userdata {
9075: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 9076: my $result;
1.1016 raeburn 9077: if ($datakey ne '') {
1.1013 raeburn 9078: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 9079: if ($udom eq '' || $uname eq '') {
9080: $udom = $env{'user.domain'};
9081: $uname = $env{'user.name'};
9082: }
9083: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 9084: if (($uhome eq '') || ($uhome eq 'no_host')) {
9085: $result = 'error: no_host';
9086: } else {
9087: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
9088: $storehash->{'host'} = $perlvar{'lonHostID'};
9089:
9090: my $namevalue='';
9091: foreach my $key (keys(%{$storehash})) {
9092: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
9093: }
9094: $namevalue=~s/\&$//;
1.1224 raeburn 9095: unless ($namespace eq 'courserequests') {
9096: $datakey = &escape($datakey);
9097: }
1.1105 raeburn 9098: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
9099: $namevalue,$uhome);
1.1013 raeburn 9100: }
9101: } else {
9102: $result = 'error: data to store was not a hash reference';
9103: }
9104: } else {
9105: $result= 'error: invalid requestkey';
9106: }
9107: return $result;
9108: }
9109:
1.21 www 9110: # ---------------------------------------------------------- Assign Custom Role
9111:
9112: sub assigncustomrole {
1.957 raeburn 9113: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9114: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 9115: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 9116: }
9117:
9118: # ----------------------------------------------------------------- Revoke Role
9119:
9120: sub revokerole {
1.957 raeburn 9121: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9122: my $now=time;
1.965 raeburn 9123: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 9124: }
9125:
9126: # ---------------------------------------------------------- Revoke Custom Role
9127:
9128: sub revokecustomrole {
1.957 raeburn 9129: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9130: my $now=time;
1.357 www 9131: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 9132: $deleteflag,$selfenroll,$context);
1.17 www 9133: }
9134:
1.533 banghart 9135: # ------------------------------------------------------------ Disk usage
1.535 albertel 9136: sub diskusage {
1.955 raeburn 9137: my ($udom,$uname,$directorypath,$getpropath)=@_;
9138: $directorypath =~ s/\/$//;
9139: my $listing=&reply('du2:'.&escape($directorypath).':'
9140: .&escape($getpropath).':'.&escape($uname).':'
9141: .&escape($udom),homeserver($uname,$udom));
9142: if ($listing eq 'unknown_cmd') {
9143: if ($getpropath) {
9144: $directorypath = &propath($udom,$uname).'/'.$directorypath;
9145: }
9146: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
9147: }
1.514 albertel 9148: return $listing;
1.512 banghart 9149: }
9150:
1.566 banghart 9151: sub is_locked {
1.1096 raeburn 9152: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 9153: my @check;
9154: my $is_locked;
1.1093 raeburn 9155: push (@check,$file_name);
1.613 albertel 9156: my %locked = &get('file_permissions',\@check,
1.620 albertel 9157: $env{'user.domain'},$env{'user.name'});
1.615 albertel 9158: my ($tmp)=keys(%locked);
9159: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 9160:
1.566 banghart 9161: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 9162: $is_locked = 'false';
9163: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 9164: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 9165: $is_locked = 'true';
1.1096 raeburn 9166: if (ref($which) eq 'ARRAY') {
9167: push(@{$which},$entry);
9168: } else {
9169: last;
9170: }
1.745 raeburn 9171: }
9172: }
1.566 banghart 9173: } else {
9174: $is_locked = 'false';
9175: }
1.1093 raeburn 9176: return $is_locked;
1.566 banghart 9177: }
9178:
1.759 albertel 9179: sub declutter_portfile {
9180: my ($file) = @_;
1.833 albertel 9181: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 9182: return $file;
9183: }
9184:
1.559 banghart 9185: # ------------------------------------------------------------- Mark as Read Only
9186:
9187: sub mark_as_readonly {
9188: my ($domain,$user,$files,$what) = @_;
1.613 albertel 9189: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 9190: my ($tmp)=keys(%current_permissions);
9191: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 9192: foreach my $file (@{$files}) {
1.759 albertel 9193: $file = &declutter_portfile($file);
1.561 banghart 9194: push(@{$current_permissions{$file}},$what);
1.559 banghart 9195: }
1.613 albertel 9196: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 9197: return;
9198: }
9199:
1.572 banghart 9200: # ------------------------------------------------------------Save Selected Files
9201:
9202: sub save_selected_files {
9203: my ($user, $path, @files) = @_;
9204: my $filename = $user."savedfiles";
1.573 banghart 9205: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 9206: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 9207: foreach my $file (@files) {
1.620 albertel 9208: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 9209: }
9210: foreach my $file (@other_files) {
1.574 banghart 9211: print (OUT $file."\n");
1.572 banghart 9212: }
1.574 banghart 9213: close (OUT);
1.572 banghart 9214: return 'ok';
9215: }
9216:
1.574 banghart 9217: sub clear_selected_files {
9218: my ($user) = @_;
9219: my $filename = $user."savedfiles";
1.1117 foxr 9220: open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574 banghart 9221: print (OUT undef);
9222: close (OUT);
9223: return ("ok");
9224: }
9225:
1.572 banghart 9226: sub files_in_path {
9227: my ($user, $path) = @_;
9228: my $filename = $user."savedfiles";
9229: my %return_files;
1.1117 foxr 9230: open (IN, '<'.LONCAPA::tempdir().$filename);
1.573 banghart 9231: while (my $line_in = <IN>) {
1.574 banghart 9232: chomp ($line_in);
9233: my @paths_and_file = split (m!/!, $line_in);
9234: my $file_part = pop (@paths_and_file);
9235: my $path_part = join ('/', @paths_and_file);
1.573 banghart 9236: $path_part.='/';
9237: my $path_and_file = $path_part.$file_part;
9238: if ($path_part eq $path) {
9239: $return_files{$file_part}= 'selected';
9240: }
9241: }
1.574 banghart 9242: close (IN);
9243: return (\%return_files);
1.572 banghart 9244: }
9245:
9246: # called in portfolio select mode, to show files selected NOT in current directory
9247: sub files_not_in_path {
9248: my ($user, $path) = @_;
9249: my $filename = $user."savedfiles";
9250: my @return_files;
9251: my $path_part;
1.1117 foxr 9252: open(IN, '<'.LONCAPA::.$filename);
1.800 albertel 9253: while (my $line = <IN>) {
1.572 banghart 9254: #ok, I know it's clunky, but I want it to work
1.800 albertel 9255: my @paths_and_file = split(m|/|, $line);
9256: my $file_part = pop(@paths_and_file);
9257: chomp($file_part);
9258: my $path_part = join('/', @paths_and_file);
1.572 banghart 9259: $path_part .= '/';
9260: my $path_and_file = $path_part.$file_part;
9261: if ($path_part ne $path) {
1.800 albertel 9262: push(@return_files, ($path_and_file));
1.572 banghart 9263: }
9264: }
1.800 albertel 9265: close(OUT);
1.574 banghart 9266: return (@return_files);
1.572 banghart 9267: }
9268:
1.1273 raeburn 9269: #------------------------------Submitted/Handedback Portfolio Files Versioning
9270:
9271: sub portfiles_versioning {
9272: my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
9273: my $portfolio_root = '/userfiles/portfolio';
9274: return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
9275: foreach my $file (@{$portfiles}) {
9276: &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
9277: my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
9278: my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
9279: my $getpropath = 1;
9280: my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
9281: $stu_name,$getpropath);
9282: my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
9283: my $new_answer =
9284: &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
9285: if ($new_answer ne 'problem getting file') {
9286: push(@{$versioned_portfiles}, $directory.$new_answer);
9287: &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
9288: [$symb,$env{'request.course.id'},'graded']);
9289: }
9290: }
9291: }
9292:
9293: sub get_next_version {
9294: my ($answer_name, $answer_ext, $dir_list) = @_;
9295: my $version;
9296: if (ref($dir_list) eq 'ARRAY') {
9297: foreach my $row (@{$dir_list}) {
9298: my ($file) = split(/\&/,$row,2);
9299: my ($file_name,$file_version,$file_ext) =
9300: &file_name_version_ext($file);
9301: if (($file_name eq $answer_name) &&
9302: ($file_ext eq $answer_ext)) {
9303: # gets here if filename and extension match,
9304: # regardless of version
9305: if ($file_version ne '') {
9306: # a versioned file is found so save it for later
9307: if ($file_version > $version) {
9308: $version = $file_version;
9309: }
9310: }
9311: }
9312: }
9313: }
9314: $version ++;
9315: return($version);
9316: }
9317:
9318: sub version_selected_portfile {
9319: my ($domain,$stu_name,$directory,$file_name,$version) = @_;
9320: my ($answer_name,$answer_ver,$answer_ext) =
9321: &file_name_version_ext($file_name);
9322: my $new_answer;
9323: $env{'form.copy'} =
9324: &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
9325: if($env{'form.copy'} eq '-1') {
9326: $new_answer = 'problem getting file';
9327: } else {
9328: $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
9329: my $copy_result =
9330: &finishuserfileupload($stu_name,$domain,'copy',
9331: '/portfolio'.$directory.$new_answer);
9332: }
9333: undef($env{'form.copy'});
9334: return ($new_answer);
9335: }
9336:
9337: sub file_name_version_ext {
9338: my ($file)=@_;
9339: my @file_parts = split(/\./, $file);
9340: my ($name,$version,$ext);
9341: if (@file_parts > 1) {
9342: $ext=pop(@file_parts);
9343: if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
9344: $version=pop(@file_parts);
9345: }
9346: $name=join('.',@file_parts);
9347: } else {
9348: $name=join('.',@file_parts);
9349: }
9350: return($name,$version,$ext);
9351: }
9352:
1.745 raeburn 9353: #----------------------------------------------Get portfolio file permissions
1.629 banghart 9354:
1.745 raeburn 9355: sub get_portfile_permissions {
9356: my ($domain,$user) = @_;
1.613 albertel 9357: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 9358: my ($tmp)=keys(%current_permissions);
9359: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 9360: return \%current_permissions;
9361: }
9362:
9363: #---------------------------------------------Get portfolio file access controls
9364:
1.749 raeburn 9365: sub get_access_controls {
1.745 raeburn 9366: my ($current_permissions,$group,$file) = @_;
1.769 albertel 9367: my %access;
9368: my $real_file = $file;
9369: $file =~ s/\.meta$//;
1.745 raeburn 9370: if (defined($file)) {
1.749 raeburn 9371: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
9372: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 9373: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 9374: }
9375: }
1.745 raeburn 9376: } else {
1.749 raeburn 9377: foreach my $key (keys(%{$current_permissions})) {
9378: if ($key =~ /\0accesscontrol$/) {
9379: if (defined($group)) {
9380: if ($key !~ m-^\Q$group\E/-) {
9381: next;
9382: }
9383: }
9384: my ($fullpath) = split(/\0/,$key);
9385: if (ref($$current_permissions{$key}) eq 'HASH') {
9386: foreach my $control (keys(%{$$current_permissions{$key}})) {
9387: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
9388: }
9389: }
9390: }
9391: }
9392: }
9393: return %access;
9394: }
9395:
9396: sub modify_access_controls {
9397: my ($file_name,$changes,$domain,$user)=@_;
9398: my ($outcome,$deloutcome);
9399: my %store_permissions;
9400: my %new_values;
9401: my %new_control;
9402: my %translation;
9403: my @deletions = ();
9404: my $now = time;
9405: if (exists($$changes{'activate'})) {
9406: if (ref($$changes{'activate'}) eq 'HASH') {
9407: my @newitems = sort(keys(%{$$changes{'activate'}}));
9408: my $numnew = scalar(@newitems);
9409: for (my $i=0; $i<$numnew; $i++) {
9410: my $newkey = $newitems[$i];
9411: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 9412: if ($newkey =~ /^\d+:/) {
9413: $newkey =~ s/^(\d+)/$newid/;
9414: $translation{$1} = $newid;
9415: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
9416: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
9417: $translation{$1} = $newid;
9418: }
1.749 raeburn 9419: $new_values{$file_name."\0".$newkey} =
9420: $$changes{'activate'}{$newitems[$i]};
9421: $new_control{$newkey} = $now;
9422: }
9423: }
9424: }
9425: my %todelete;
9426: my %changed_items;
9427: foreach my $action ('delete','update') {
9428: if (exists($$changes{$action})) {
9429: if (ref($$changes{$action}) eq 'HASH') {
9430: foreach my $key (keys(%{$$changes{$action}})) {
9431: my ($itemnum) = ($key =~ /^([^:]+):/);
9432: if ($action eq 'delete') {
9433: $todelete{$itemnum} = 1;
9434: } else {
9435: $changed_items{$itemnum} = $key;
9436: }
9437: }
1.745 raeburn 9438: }
9439: }
1.749 raeburn 9440: }
9441: # get lock on access controls for file.
9442: my $lockhash = {
9443: $file_name."\0".'locked_access_records' => $env{'user.name'}.
9444: ':'.$env{'user.domain'},
9445: };
9446: my $tries = 0;
9447: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9448:
9449: while (($gotlock ne 'ok') && $tries <3) {
9450: $tries ++;
9451: sleep 1;
9452: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9453: }
9454: if ($gotlock eq 'ok') {
9455: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
9456: my ($tmp)=keys(%curr_permissions);
9457: if ($tmp=~/^error:/) { undef(%curr_permissions); }
9458: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
9459: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
9460: if (ref($curr_controls) eq 'HASH') {
9461: foreach my $control_item (keys(%{$curr_controls})) {
9462: my ($itemnum) = ($control_item =~ /^([^:]+):/);
9463: if (defined($todelete{$itemnum})) {
9464: push(@deletions,$file_name."\0".$control_item);
9465: } else {
9466: if (defined($changed_items{$itemnum})) {
9467: $new_control{$changed_items{$itemnum}} = $now;
9468: push(@deletions,$file_name."\0".$control_item);
9469: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
9470: } else {
9471: $new_control{$control_item} = $$curr_controls{$control_item};
9472: }
9473: }
1.745 raeburn 9474: }
9475: }
9476: }
1.970 raeburn 9477: my ($group);
9478: if (&is_course($domain,$user)) {
9479: ($group,my $file) = split(/\//,$file_name,2);
9480: }
1.749 raeburn 9481: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
9482: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
9483: $outcome = &put('file_permissions',\%new_values,$domain,$user);
9484: # remove lock
9485: my @del_lock = ($file_name."\0".'locked_access_records');
9486: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 9487: my $sqlresult =
1.970 raeburn 9488: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 9489: $group);
1.749 raeburn 9490: } else {
9491: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 9492: }
1.749 raeburn 9493: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 9494: }
9495:
1.827 raeburn 9496: sub make_public_indefinitely {
1.1271 raeburn 9497: my (@requrl) = @_;
9498: return &automated_portfile_access('public',\@requrl);
9499: }
9500:
9501: sub automated_portfile_access {
9502: my ($accesstype,$addsref,$delsref,$info) = @_;
1.1273 raeburn 9503: unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
9504: return 'invalid';
9505: }
1.1271 raeburn 9506: my %urls;
9507: if (ref($addsref) eq 'ARRAY') {
9508: foreach my $requrl (@{$addsref}) {
9509: if (&is_portfolio_url($requrl)) {
9510: unless (exists($urls{$requrl})) {
9511: $urls{$requrl} = 'add';
9512: }
9513: }
9514: }
9515: }
9516: if (ref($delsref) eq 'ARRAY') {
9517: foreach my $requrl (@{$delsref}) {
9518: if (&is_portfolio_url($requrl)) {
9519: unless (exists($urls{$requrl})) {
9520: $urls{$requrl} = 'delete';
9521: }
9522: }
9523: }
9524: }
9525: unless (keys(%urls)) {
9526: return 'invalid';
9527: }
9528: my $ip;
9529: if ($accesstype eq 'ip') {
9530: if (ref($info) eq 'HASH') {
9531: if ($info->{'ip'} ne '') {
9532: $ip = $info->{'ip'};
9533: }
9534: }
9535: if ($ip eq '') {
9536: return 'invalid';
9537: }
9538: }
9539: my $errors;
1.827 raeburn 9540: my $now = time;
1.1271 raeburn 9541: my %current_perms;
9542: foreach my $requrl (sort(keys(%urls))) {
9543: my $action;
9544: if ($urls{$requrl} eq 'add') {
9545: $action = 'activate';
9546: } else {
9547: $action = 'none';
9548: }
9549: my $aclnum = 0;
1.827 raeburn 9550: my (undef,$udom,$unum,$file_name,$group) =
9551: &parse_portfolio_url($requrl);
1.1271 raeburn 9552: unless (exists($current_perms{$unum.':'.$udom})) {
9553: $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
9554: }
9555: my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
1.827 raeburn 9556: $group,$file_name);
9557: foreach my $key (keys(%{$access_controls{$file_name}})) {
9558: my ($num,$scope,$end,$start) =
9559: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
1.1271 raeburn 9560: if ($scope eq $accesstype) {
9561: if (($start <= $now) && ($end == 0)) {
9562: if ($accesstype eq 'ip') {
9563: if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
9564: if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
9565: if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
9566: if ($urls{$requrl} eq 'add') {
9567: $action = 'none';
9568: last;
9569: } else {
9570: $action = 'delete';
9571: $aclnum = $num;
9572: last;
9573: }
9574: }
9575: }
9576: }
9577: } elsif ($accesstype eq 'public') {
9578: if ($urls{$requrl} eq 'add') {
9579: $action = 'none';
9580: last;
9581: } else {
9582: $action = 'delete';
9583: $aclnum = $num;
9584: last;
9585: }
9586: }
9587: } elsif ($accesstype eq 'public') {
1.827 raeburn 9588: $action = 'update';
9589: $aclnum = $num;
1.1271 raeburn 9590: last;
1.827 raeburn 9591: }
9592: }
9593: }
9594: if ($action eq 'none') {
1.1271 raeburn 9595: next;
1.827 raeburn 9596: } else {
9597: my %changes;
9598: my $newend = 0;
9599: my $newstart = $now;
1.1271 raeburn 9600: my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
1.827 raeburn 9601: $changes{$action}{$newkey} = {
1.1271 raeburn 9602: type => $accesstype,
1.827 raeburn 9603: time => {
9604: start => $newstart,
9605: end => $newend,
9606: },
9607: };
1.1271 raeburn 9608: if ($accesstype eq 'ip') {
9609: $changes{$action}{$newkey}{'ip'} = [$ip];
9610: }
1.827 raeburn 9611: my ($outcome,$deloutcome,$new_values,$translation) =
9612: &modify_access_controls($file_name,\%changes,$udom,$unum);
1.1271 raeburn 9613: unless ($outcome eq 'ok') {
9614: $errors .= $outcome.' ';
9615: }
1.827 raeburn 9616: }
1.1271 raeburn 9617: }
9618: if ($errors) {
9619: $errors =~ s/\s$//;
9620: return $errors;
1.827 raeburn 9621: } else {
1.1271 raeburn 9622: return 'ok';
1.827 raeburn 9623: }
9624: }
9625:
1.745 raeburn 9626: #------------------------------------------------------Get Marked as Read Only
9627:
9628: sub get_marked_as_readonly {
9629: my ($domain,$user,$what,$group) = @_;
9630: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 9631: my @readonly_files;
1.629 banghart 9632: my $cmp1=$what;
9633: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 9634: while (my ($file_name,$value) = each(%{$current_permissions})) {
9635: if (defined($group)) {
9636: if ($file_name !~ m-^\Q$group\E/-) {
9637: next;
9638: }
9639: }
1.561 banghart 9640: if (ref($value) eq "ARRAY"){
9641: foreach my $stored_what (@{$value}) {
1.629 banghart 9642: my $cmp2=$stored_what;
1.759 albertel 9643: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 9644: $cmp2=join('',@{$stored_what});
1.745 raeburn 9645: }
1.629 banghart 9646: if ($cmp1 eq $cmp2) {
1.561 banghart 9647: push(@readonly_files, $file_name);
1.745 raeburn 9648: last;
1.563 banghart 9649: } elsif (!defined($what)) {
9650: push(@readonly_files, $file_name);
1.745 raeburn 9651: last;
1.561 banghart 9652: }
9653: }
1.745 raeburn 9654: }
1.561 banghart 9655: }
9656: return @readonly_files;
9657: }
1.577 banghart 9658: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 9659:
1.577 banghart 9660: sub get_marked_as_readonly_hash {
1.745 raeburn 9661: my ($current_permissions,$group,$what) = @_;
1.577 banghart 9662: my %readonly_files;
1.745 raeburn 9663: while (my ($file_name,$value) = each(%{$current_permissions})) {
9664: if (defined($group)) {
9665: if ($file_name !~ m-^\Q$group\E/-) {
9666: next;
9667: }
9668: }
1.577 banghart 9669: if (ref($value) eq "ARRAY"){
9670: foreach my $stored_what (@{$value}) {
1.745 raeburn 9671: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 9672: foreach my $lock_descriptor(@{$stored_what}) {
9673: if ($lock_descriptor eq 'graded') {
9674: $readonly_files{$file_name} = 'graded';
9675: } elsif ($lock_descriptor eq 'handback') {
9676: $readonly_files{$file_name} = 'handback';
9677: } else {
9678: if (!exists($readonly_files{$file_name})) {
9679: $readonly_files{$file_name} = 'locked';
9680: }
9681: }
1.745 raeburn 9682: }
1.750 banghart 9683: }
1.577 banghart 9684: }
9685: }
9686: }
9687: return %readonly_files;
9688: }
1.559 banghart 9689: # ------------------------------------------------------------ Unmark as Read Only
9690:
9691: sub unmark_as_readonly {
1.629 banghart 9692: # unmarks $file_name (if $file_name is defined), or all files locked by $what
9693: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 9694: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 9695: $file_name = &declutter_portfile($file_name);
1.634 albertel 9696: my $symb_crs = $what;
9697: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 9698: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 9699: my ($tmp)=keys(%current_permissions);
9700: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 9701: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 9702: foreach my $file (@readonly_files) {
1.759 albertel 9703: my $clean_file = &declutter_portfile($file);
9704: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 9705: my $current_locks = $current_permissions{$file};
1.563 banghart 9706: my @new_locks;
9707: my @del_keys;
9708: if (ref($current_locks) eq "ARRAY"){
9709: foreach my $locker (@{$current_locks}) {
1.632 albertel 9710: my $compare=$locker;
1.749 raeburn 9711: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 9712: $compare=join('',@{$locker});
1.746 raeburn 9713: if ($compare ne $symb_crs) {
9714: push(@new_locks, $locker);
9715: }
1.563 banghart 9716: }
9717: }
1.650 albertel 9718: if (scalar(@new_locks) > 0) {
1.563 banghart 9719: $current_permissions{$file} = \@new_locks;
9720: } else {
9721: push(@del_keys, $file);
1.613 albertel 9722: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 9723: delete($current_permissions{$file});
1.563 banghart 9724: }
9725: }
1.561 banghart 9726: }
1.613 albertel 9727: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 9728: return;
9729: }
1.512 banghart 9730:
1.17 www 9731: # ------------------------------------------------------------ Directory lister
9732:
9733: sub dirlist {
1.955 raeburn 9734: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 9735: $uri=~s/^\///;
9736: $uri=~s/\/$//;
1.253 stredwic 9737: my ($udom, $uname);
1.955 raeburn 9738: if ($getuserdir) {
1.253 stredwic 9739: $udom = $userdomain;
9740: $uname = $username;
1.955 raeburn 9741: } else {
9742: (undef,$udom,$uname)=split(/\//,$uri);
9743: if(defined($userdomain)) {
9744: $udom = $userdomain;
9745: }
9746: if(defined($username)) {
9747: $uname = $username;
9748: }
1.253 stredwic 9749: }
1.955 raeburn 9750: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 9751:
1.955 raeburn 9752: $dirRoot = $perlvar{'lonDocRoot'};
9753: if (defined($getpropath)) {
9754: $dirRoot = &propath($udom,$uname);
1.253 stredwic 9755: $dirRoot =~ s/\/$//;
1.955 raeburn 9756: } elsif (defined($getuserdir)) {
9757: my $subdir=$uname.'__';
9758: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
9759: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
9760: ."/$udom/$subdir/$uname";
9761: } elsif (defined($alternateRoot)) {
9762: $dirRoot = $alternateRoot;
1.751 banghart 9763: }
1.253 stredwic 9764:
9765: if($udom) {
9766: if($uname) {
1.1135 raeburn 9767: my $uhome = &homeserver($uname,$udom);
1.1136 raeburn 9768: if ($uhome eq 'no_host') {
9769: return ([],'no_host');
9770: }
1.955 raeburn 9771: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 9772: .$getuserdir.':'.&escape($dirRoot)
1.1135 raeburn 9773: .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955 raeburn 9774: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 9775: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955 raeburn 9776: } else {
9777: @listing_results = map { &unescape($_); } split(/:/,$listing);
9778: }
1.605 matthew 9779: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 9780: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605 matthew 9781: @listing_results = split(/:/,$listing);
9782: } else {
9783: @listing_results = map { &unescape($_); } split(/:/,$listing);
9784: }
1.1135 raeburn 9785: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
1.1136 raeburn 9786: ($listing eq 'rejected') || ($listing eq 'refused') ||
9787: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
9788: return ([],$listing);
9789: } else {
9790: return (\@listing_results);
1.1135 raeburn 9791: }
1.955 raeburn 9792: } elsif(!$alternateRoot) {
1.1136 raeburn 9793: my (%allusers,%listerror);
1.841 albertel 9794: my %servers = &get_servers($udom,'library');
1.955 raeburn 9795: foreach my $tryserver (keys(%servers)) {
9796: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
9797: &escape($udom),$tryserver);
9798: if ($listing eq 'unknown_cmd') {
9799: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
9800: $udom, $tryserver);
9801: } else {
9802: @listing_results = map { &unescape($_); } split(/:/,$listing);
9803: }
1.841 albertel 9804: if ($listing eq 'unknown_cmd') {
9805: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
9806: $udom, $tryserver);
9807: @listing_results = split(/:/,$listing);
9808: } else {
9809: @listing_results =
9810: map { &unescape($_); } split(/:/,$listing);
9811: }
1.1136 raeburn 9812: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
9813: ($listing eq 'rejected') || ($listing eq 'refused') ||
9814: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
9815: $listerror{$tryserver} = $listing;
9816: } else {
1.841 albertel 9817: foreach my $line (@listing_results) {
9818: my ($entry) = split(/&/,$line,2);
9819: $allusers{$entry} = 1;
9820: }
9821: }
1.253 stredwic 9822: }
1.1136 raeburn 9823: my @alluserslist=();
1.800 albertel 9824: foreach my $user (sort(keys(%allusers))) {
1.1136 raeburn 9825: push(@alluserslist,$user.'&user');
1.253 stredwic 9826: }
1.1136 raeburn 9827: return (\@alluserslist);
1.253 stredwic 9828: } else {
1.1136 raeburn 9829: return ([],'missing username');
1.253 stredwic 9830: }
1.955 raeburn 9831: } elsif(!defined($getpropath)) {
1.1136 raeburn 9832: my $path = $perlvar{'lonDocRoot'}.'/res/';
9833: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
9834: return (\@all_domains);
1.955 raeburn 9835: } else {
1.1136 raeburn 9836: return ([],'missing domain');
1.275 stredwic 9837: }
9838: }
9839:
9840: # --------------------------------------------- GetFileTimestamp
9841: # This function utilizes dirlist and returns the date stamp for
9842: # when it was last modified. It will also return an error of -1
9843: # if an error occurs
9844:
9845: sub GetFileTimestamp {
1.955 raeburn 9846: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 9847: $studentDomain = &LONCAPA::clean_domain($studentDomain);
9848: $studentName = &LONCAPA::clean_username($studentName);
1.1136 raeburn 9849: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
9850: undef,$getuserdir);
9851: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
9852: return -1;
9853: }
9854: if (ref($fileref) eq 'ARRAY') {
9855: my @stats = split('&',$fileref->[0]);
1.375 matthew 9856: # @stats contains first the filename, then the stat output
9857: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 9858: } else {
9859: return -1;
1.253 stredwic 9860: }
1.26 www 9861: }
9862:
1.712 albertel 9863: sub stat_file {
9864: my ($uri) = @_;
1.787 albertel 9865: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 9866:
1.955 raeburn 9867: my ($udom,$uname,$file);
1.712 albertel 9868: if ($uri =~ m-^/(uploaded|editupload)/-) {
9869: ($udom,$uname,$file) =
1.811 albertel 9870: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 9871: $file = 'userfiles/'.$file;
9872: }
9873: if ($uri =~ m-^/res/-) {
9874: ($udom,$uname) =
1.807 albertel 9875: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 9876: $file = $uri;
9877: }
9878:
9879: if (!$udom || !$uname || !$file) {
9880: # unable to handle the uri
9881: return ();
9882: }
1.956 raeburn 9883: my $getpropath;
9884: if ($file =~ /^userfiles\//) {
9885: $getpropath = 1;
9886: }
1.1136 raeburn 9887: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
9888: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
9889: return ();
9890: } else {
9891: if (ref($listref) eq 'ARRAY') {
9892: my @stats = split('&',$listref->[0]);
9893: shift(@stats); #filename is first
9894: return @stats;
9895: }
1.712 albertel 9896: }
9897: return ();
9898: }
9899:
1.26 www 9900: # -------------------------------------------------------- Value of a Condition
9901:
1.713 albertel 9902: # gets the value of a specific preevaluated condition
9903: # stored in the string $env{user.state.<cid>}
9904: # or looks up a condition reference in the bighash and if if hasn't
9905: # already been evaluated recurses into docondval to get the value of
9906: # the condition, then memoizing it to
9907: # $env{user.state.<cid>.<condition>}
1.40 www 9908: sub directcondval {
9909: my $number=shift;
1.620 albertel 9910: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 9911: &Apache::lonuserstate::evalstate();
9912: }
1.713 albertel 9913: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
9914: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
9915: } elsif ($number =~ /^_/) {
9916: my $sub_condition;
9917: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
9918: &GDBM_READER(),0640)) {
9919: $sub_condition=$bighash{'conditions'.$number};
9920: untie(%bighash);
9921: }
9922: my $value = &docondval($sub_condition);
1.949 raeburn 9923: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 9924: return $value;
9925: }
1.620 albertel 9926: if ($env{'user.state.'.$env{'request.course.id'}}) {
9927: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 9928: } else {
9929: return 2;
9930: }
9931: }
9932:
1.713 albertel 9933: # get the collection of conditions for this resource
1.26 www 9934: sub condval {
9935: my $condidx=shift;
1.54 www 9936: my $allpathcond='';
1.713 albertel 9937: foreach my $cond (split(/\|/,$condidx)) {
9938: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
9939: $allpathcond.=
9940: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
9941: }
1.191 harris41 9942: }
1.54 www 9943: $allpathcond=~s/\|$//;
1.713 albertel 9944: return &docondval($allpathcond);
9945: }
9946:
9947: #evaluates an expression of conditions
9948: sub docondval {
9949: my ($allpathcond) = @_;
9950: my $result=0;
9951: if ($env{'request.course.id'}
9952: && defined($allpathcond)) {
9953: my $operand='|';
9954: my @stack;
9955: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
9956: if ($chunk eq '(') {
9957: push @stack,($operand,$result);
9958: } elsif ($chunk eq ')') {
9959: my $before=pop @stack;
9960: if (pop @stack eq '&') {
9961: $result=$result>$before?$before:$result;
9962: } else {
9963: $result=$result>$before?$result:$before;
9964: }
9965: } elsif (($chunk eq '&') || ($chunk eq '|')) {
9966: $operand=$chunk;
9967: } else {
9968: my $new=directcondval($chunk);
9969: if ($operand eq '&') {
9970: $result=$result>$new?$new:$result;
9971: } else {
9972: $result=$result>$new?$result:$new;
9973: }
9974: }
9975: }
1.26 www 9976: }
9977: return $result;
1.421 albertel 9978: }
9979:
9980: # ---------------------------------------------------- Devalidate courseresdata
9981:
9982: sub devalidatecourseresdata {
9983: my ($coursenum,$coursedomain)=@_;
9984: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 9985: &devalidate_cache_new('courseres',$hashid);
1.28 www 9986: }
9987:
1.763 www 9988:
1.200 www 9989: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 9990: #
9991: # Parameters:
9992: # $coursenum - Number of the course.
9993: # $coursedomain - Domain at which the course was created.
9994: # Returns:
9995: # A hash of the course parameters along (I think) with timestamps
9996: # and version info.
1.877 foxr 9997:
1.624 albertel 9998: sub get_courseresdata {
9999: my ($coursenum,$coursedomain)=@_;
1.200 www 10000: my $coursehom=&homeserver($coursenum,$coursedomain);
10001: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 10002: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 10003: my %dumpreply;
1.417 albertel 10004: unless (defined($cached)) {
1.624 albertel 10005: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 10006: $result=\%dumpreply;
1.251 albertel 10007: my ($tmp) = keys(%dumpreply);
10008: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 10009: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 10010: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
10011: return $tmp;
1.416 albertel 10012: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 10013: $result=undef;
1.599 albertel 10014: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 10015: }
10016: }
1.624 albertel 10017: return $result;
10018: }
10019:
1.633 albertel 10020: sub devalidateuserresdata {
10021: my ($uname,$udom)=@_;
10022: my $hashid="$udom:$uname";
10023: &devalidate_cache_new('userres',$hashid);
10024: }
10025:
1.624 albertel 10026: sub get_userresdata {
10027: my ($uname,$udom)=@_;
10028: #most student don\'t have any data set, check if there is some data
10029: if (&EXT_cache_status($udom,$uname)) { return undef; }
10030:
10031: my $hashid="$udom:$uname";
10032: my ($result,$cached)=&is_cached_new('userres',$hashid);
10033: if (!defined($cached)) {
10034: my %resourcedata=&dump('resourcedata',$udom,$uname);
10035: $result=\%resourcedata;
10036: &do_cache_new('userres',$hashid,$result,600);
10037: }
10038: my ($tmp)=keys(%$result);
10039: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
10040: return $result;
10041: }
10042: #error 2 occurs when the .db doesn't exist
10043: if ($tmp!~/error: 2 /) {
1.672 albertel 10044: &logthis("<font color=\"blue\">WARNING:".
1.624 albertel 10045: " Trying to get resource data for ".
10046: $uname." at ".$udom.": ".
10047: $tmp."</font>");
10048: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 10049: #&EXT_cache_set($udom,$uname);
10050: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 10051: undef($tmp); # not really an error so don't send it back
1.624 albertel 10052: }
10053: return $tmp;
10054: }
1.879 foxr 10055: #----------------------------------------------- resdata - return resource data
10056: # Purpose:
10057: # Return resource data for either users or for a course.
10058: # Parameters:
10059: # $name - Course/user name.
10060: # $domain - Name of the domain the user/course is registered on.
10061: # $type - Type of thing $name is (must be 'course' or 'user'
10062: # @which - Array of names of resources desired.
10063: # Returns:
10064: # The value of the first reasource in @which that is found in the
10065: # resource hash.
10066: # Exceptional Conditions:
10067: # If the $type passed in is not valid (not the string 'course' or
10068: # 'user', an undefined reference is returned.
10069: # If none of the resources are found, an undef is returned
1.624 albertel 10070: sub resdata {
10071: my ($name,$domain,$type,@which)=@_;
10072: my $result;
10073: if ($type eq 'course') {
10074: $result=&get_courseresdata($name,$domain);
10075: } elsif ($type eq 'user') {
10076: $result=&get_userresdata($name,$domain);
10077: }
10078: if (!ref($result)) { return $result; }
1.251 albertel 10079: foreach my $item (@which) {
1.927 albertel 10080: if (defined($result->{$item->[0]})) {
10081: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 10082: }
1.250 albertel 10083: }
1.291 albertel 10084: return undef;
1.200 www 10085: }
10086:
1.1236 raeburn 10087: sub get_numsuppfiles {
10088: my ($cnum,$cdom,$ignorecache)=@_;
10089: my $hashid=$cnum.':'.$cdom;
10090: my ($suppcount,$cached);
10091: unless ($ignorecache) {
10092: ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
10093: }
10094: unless (defined($cached)) {
10095: my $chome=&homeserver($cnum,$cdom);
10096: unless ($chome eq 'no_host') {
10097: ($suppcount,my $errors) = (0,0);
10098: my $suppmap = 'supplemental.sequence';
10099: ($suppcount,$errors) =
10100: &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
10101: }
10102: &do_cache_new('suppcount',$hashid,$suppcount,600);
10103: }
10104: return $suppcount;
10105: }
10106:
1.379 matthew 10107: #
10108: # EXT resource caching routines
10109: #
10110:
10111: sub clear_EXT_cache_status {
1.383 albertel 10112: &delenv('cache.EXT.');
1.379 matthew 10113: }
10114:
10115: sub EXT_cache_status {
10116: my ($target_domain,$target_user) = @_;
1.383 albertel 10117: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 10118: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 10119: # We know already the user has no data
10120: return 1;
10121: } else {
10122: return 0;
10123: }
10124: }
10125:
10126: sub EXT_cache_set {
10127: my ($target_domain,$target_user) = @_;
1.383 albertel 10128: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 10129: #&appenv({$cachename => time});
1.379 matthew 10130: }
10131:
1.28 www 10132: # --------------------------------------------------------- Value of a Variable
1.58 www 10133: sub EXT {
1.715 albertel 10134:
1.1228 raeburn 10135: my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68 www 10136: unless ($varname) { return ''; }
1.218 albertel 10137: #get real user name/domain, courseid and symb
10138: my $courseid;
1.359 albertel 10139: my $publicuser;
1.427 www 10140: if ($symbparm) {
10141: $symbparm=&get_symb_from_alias($symbparm);
10142: }
1.218 albertel 10143: if (!($uname && $udom)) {
1.790 albertel 10144: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 10145: if (!$symbparm) { $symbparm=$cursymb; }
10146: } else {
1.620 albertel 10147: $courseid=$env{'request.course.id'};
1.218 albertel 10148: }
1.48 www 10149: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
10150: my $rest;
1.320 albertel 10151: if (defined($therest[0])) {
1.48 www 10152: $rest=join('.',@therest);
10153: } else {
10154: $rest='';
10155: }
1.320 albertel 10156:
1.57 www 10157: my $qualifierrest=$qualifier;
10158: if ($rest) { $qualifierrest.='.'.$rest; }
10159: my $spacequalifierrest=$space;
10160: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 10161: if ($realm eq 'user') {
1.48 www 10162: # --------------------------------------------------------------- user.resource
10163: if ($space eq 'resource') {
1.651 albertel 10164: if ( (defined($Apache::lonhomework::parsing_a_problem)
10165: || defined($Apache::lonhomework::parsing_a_task))
10166: &&
1.744 albertel 10167: ($symbparm eq &symbread()) ) {
10168: # if we are in the middle of processing the resource the
10169: # get the value we are planning on committing
10170: if (defined($Apache::lonhomework::results{$qualifierrest})) {
10171: return $Apache::lonhomework::results{$qualifierrest};
10172: } else {
10173: return $Apache::lonhomework::history{$qualifierrest};
10174: }
1.335 albertel 10175: } else {
1.359 albertel 10176: my %restored;
1.620 albertel 10177: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 10178: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
10179: } else {
10180: %restored=&restore($symbparm,$courseid,$udom,$uname);
10181: }
1.335 albertel 10182: return $restored{$qualifierrest};
10183: }
1.48 www 10184: # ----------------------------------------------------------------- user.access
10185: } elsif ($space eq 'access') {
1.218 albertel 10186: # FIXME - not supporting calls for a specific user
1.48 www 10187: return &allowed($qualifier,$rest);
10188: # ------------------------------------------ user.preferences, user.environment
10189: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 10190: if (($uname eq $env{'user.name'}) &&
10191: ($udom eq $env{'user.domain'})) {
10192: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 10193: } else {
1.359 albertel 10194: my %returnhash;
10195: if (!$publicuser) {
10196: %returnhash=&userenvironment($udom,$uname,
10197: $qualifierrest);
10198: }
1.218 albertel 10199: return $returnhash{$qualifierrest};
10200: }
1.48 www 10201: # ----------------------------------------------------------------- user.course
10202: } elsif ($space eq 'course') {
1.218 albertel 10203: # FIXME - not supporting calls for a specific user
1.620 albertel 10204: return $env{join('.',('request.course',$qualifier))};
1.48 www 10205: # ------------------------------------------------------------------- user.role
10206: } elsif ($space eq 'role') {
1.218 albertel 10207: # FIXME - not supporting calls for a specific user
1.620 albertel 10208: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 10209: if ($qualifier eq 'value') {
10210: return $role;
10211: } elsif ($qualifier eq 'extent') {
10212: return $where;
10213: }
10214: # ----------------------------------------------------------------- user.domain
10215: } elsif ($space eq 'domain') {
1.218 albertel 10216: return $udom;
1.48 www 10217: # ------------------------------------------------------------------- user.name
10218: } elsif ($space eq 'name') {
1.218 albertel 10219: return $uname;
1.48 www 10220: # ---------------------------------------------------- Any other user namespace
1.29 www 10221: } else {
1.359 albertel 10222: my %reply;
10223: if (!$publicuser) {
10224: %reply=&get($space,[$qualifierrest],$udom,$uname);
10225: }
10226: return $reply{$qualifierrest};
1.48 www 10227: }
1.236 www 10228: } elsif ($realm eq 'query') {
10229: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 10230: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
10231: [$spacequalifierrest]);
1.620 albertel 10232: return $env{'form.'.$spacequalifierrest};
1.236 www 10233: } elsif ($realm eq 'request') {
1.48 www 10234: # ------------------------------------------------------------- request.browser
10235: if ($space eq 'browser') {
1.1145 bisitz 10236: return $env{'browser.'.$qualifier};
1.57 www 10237: # ------------------------------------------------------------ request.filename
10238: } else {
1.620 albertel 10239: return $env{'request.'.$spacequalifierrest};
1.29 www 10240: }
1.28 www 10241: } elsif ($realm eq 'course') {
1.48 www 10242: # ---------------------------------------------------------- course.description
1.620 albertel 10243: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 10244: } elsif ($realm eq 'resource') {
1.165 www 10245:
1.620 albertel 10246: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 10247: if (!$symbparm) { $symbparm=&symbread(); }
10248: }
1.693 albertel 10249:
1.1232 raeburn 10250: if ($qualifier eq '') {
10251: if ($space eq 'title') {
10252: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
10253: return &gettitle($symbparm);
10254: }
1.693 albertel 10255:
1.1232 raeburn 10256: if ($space eq 'map') {
10257: my ($map) = &decode_symb($symbparm);
10258: return &symbread($map);
10259: }
10260: if ($space eq 'maptitle') {
10261: my ($map) = &decode_symb($symbparm);
10262: return &gettitle($map);
10263: }
10264: if ($space eq 'filename') {
10265: if ($symbparm) {
10266: return &clutter((&decode_symb($symbparm))[2]);
10267: }
10268: return &hreflocation('',$env{'request.filename'});
1.905 albertel 10269: }
1.1232 raeburn 10270:
1.1233 raeburn 10271: if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
10272: if ($space eq 'visibleparts') {
10273: my $navmap = Apache::lonnavmaps::navmap->new();
10274: my $item;
10275: if (ref($navmap)) {
10276: my $res = $navmap->getBySymb($symbparm);
10277: my $parts = $res->parts();
10278: if (ref($parts) eq 'ARRAY') {
10279: $item = join(',',@{$parts});
10280: }
10281: undef($navmap);
1.1232 raeburn 10282: }
1.1233 raeburn 10283: return $item;
1.1232 raeburn 10284: }
10285: }
10286: }
1.693 albertel 10287:
10288: my ($section, $group, @groups);
1.593 albertel 10289: my ($courselevelm,$courselevel);
1.1228 raeburn 10290: if (($courseid eq '') && ($cid)) {
10291: $courseid = $cid;
10292: }
10293: if (($symbparm && $courseid) &&
10294: (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165 www 10295:
1.218 albertel 10296: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 10297:
1.60 www 10298: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 10299: my $symbp=$symbparm;
1.735 albertel 10300: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 10301:
10302: my $symbparm=$symbp.'.'.$spacequalifierrest;
10303: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
10304:
1.620 albertel 10305: if (($env{'user.name'} eq $uname) &&
10306: ($env{'user.domain'} eq $udom)) {
10307: $section=$env{'request.course.sec'};
1.733 raeburn 10308: @groups = split(/:/,$env{'request.course.groups'});
10309: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 10310: } else {
1.539 albertel 10311: if (! defined($usection)) {
1.551 albertel 10312: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 10313: } else {
10314: $section = $usection;
10315: }
1.733 raeburn 10316: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 10317: }
10318:
10319: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
10320: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
10321: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
10322:
1.593 albertel 10323: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 10324: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 10325: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 10326:
1.60 www 10327: # ----------------------------------------------------------- first, check user
1.624 albertel 10328:
10329: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 10330: ([$courselevelr,'resource'],
10331: [$courselevelm,'map' ],
10332: [$courselevel, 'course' ]));
1.931 albertel 10333: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 10334:
1.594 albertel 10335: # ------------------------------------------------ second, check some of course
1.684 raeburn 10336: my $coursereply;
1.691 raeburn 10337: if (@groups > 0) {
10338: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
10339: $mapparm,$spacequalifierrest);
1.927 albertel 10340: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 10341: }
1.96 www 10342:
1.684 raeburn 10343: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 10344: $env{'course.'.$courseid.'.domain'},
10345: 'course',
10346: ([$seclevelr, 'resource'],
10347: [$seclevelm, 'map' ],
10348: [$seclevel, 'course' ],
10349: [$courselevelr,'resource']));
10350: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 10351:
1.60 www 10352: # ------------------------------------------------------ third, check map parms
1.218 albertel 10353: my %parmhash=();
10354: my $thisparm='';
10355: if (tie(%parmhash,'GDBM_File',
1.620 albertel 10356: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 10357: &GDBM_READER(),0640)) {
1.218 albertel 10358: $thisparm=$parmhash{$symbparm};
10359: untie(%parmhash);
10360: }
1.927 albertel 10361: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 10362: }
1.594 albertel 10363: # ------------------------------------------ fourth, look in resource metadata
1.71 www 10364:
1.218 albertel 10365: $spacequalifierrest=~s/\./\_/;
1.282 albertel 10366: my $filename;
10367: if (!$symbparm) { $symbparm=&symbread(); }
10368: if ($symbparm) {
1.409 www 10369: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 10370: } else {
1.620 albertel 10371: $filename=$env{'request.filename'};
1.282 albertel 10372: }
10373: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 10374: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 10375: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 10376: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 10377:
1.927 albertel 10378: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 10379: if ($symbparm && defined($courseid) &&
1.620 albertel 10380: $courseid eq $env{'request.course.id'}) {
1.624 albertel 10381: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
10382: $env{'course.'.$courseid.'.domain'},
10383: 'course',
1.927 albertel 10384: ([$courselevelm,'map' ],
10385: [$courselevel, 'course']));
10386: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 10387: }
1.145 www 10388: # ------------------------------------------------------------------ Cascade up
1.218 albertel 10389: unless ($space eq '0') {
1.336 albertel 10390: my @parts=split(/_/,$space);
10391: my $id=pop(@parts);
10392: my $part=join('_',@parts);
10393: if ($part eq '') { $part='0'; }
1.927 albertel 10394: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 10395: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 10396: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 10397: }
1.395 albertel 10398: if ($recurse) { return undef; }
10399: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 10400: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 10401: # ---------------------------------------------------- Any other user namespace
10402: } elsif ($realm eq 'environment') {
10403: # ----------------------------------------------------------------- environment
1.620 albertel 10404: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
10405: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 10406: } else {
1.770 albertel 10407: if ($uname eq 'anonymous' && $udom eq '') {
10408: return '';
10409: }
1.219 albertel 10410: my %returnhash=&userenvironment($udom,$uname,
10411: $spacequalifierrest);
10412: return $returnhash{$spacequalifierrest};
10413: }
1.28 www 10414: } elsif ($realm eq 'system') {
1.48 www 10415: # ----------------------------------------------------------------- system.time
10416: if ($space eq 'time') {
10417: return time;
10418: }
1.696 albertel 10419: } elsif ($realm eq 'server') {
10420: # ----------------------------------------------------------------- system.time
10421: if ($space eq 'name') {
10422: return $ENV{'SERVER_NAME'};
10423: }
1.28 www 10424: }
1.48 www 10425: return '';
1.61 www 10426: }
10427:
1.927 albertel 10428: sub get_reply {
10429: my ($reply_value) = @_;
1.940 raeburn 10430: if (ref($reply_value) eq 'ARRAY') {
10431: if (wantarray) {
10432: return @$reply_value;
10433: }
10434: return $reply_value->[0];
10435: } else {
10436: return $reply_value;
1.927 albertel 10437: }
10438: }
10439:
1.691 raeburn 10440: sub check_group_parms {
10441: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
10442: my @groupitems = ();
10443: my $resultitem;
1.927 albertel 10444: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 10445: foreach my $group (@{$groups}) {
10446: foreach my $level (@levels) {
1.927 albertel 10447: my $item = $courseid.'.['.$group.'].'.$level->[0];
10448: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 10449: }
10450: }
10451: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
10452: $env{'course.'.$courseid.'.domain'},
10453: 'course',@groupitems);
10454: return $coursereply;
10455: }
10456:
10457: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 10458: my ($courseid,@groups) = @_;
10459: @groups = sort(@groups);
1.691 raeburn 10460: return @groups;
10461: }
10462:
1.395 albertel 10463: sub packages_tab_default {
10464: my ($uri,$varname)=@_;
10465: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 10466:
10467: my (@extension,@specifics,$do_default);
10468: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 10469: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 10470: if ($pack_type eq 'default') {
10471: $do_default=1;
10472: } elsif ($pack_type eq 'extension') {
10473: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 10474: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 10475: # only look at packages defaults for packages that this id is
1.738 albertel 10476: push(@specifics,[$package,$pack_type,$pack_part]);
10477: }
10478: }
10479: # first look for a package that matches the requested part id
10480: foreach my $package (@specifics) {
10481: my (undef,$pack_type,$pack_part)=@{$package};
10482: next if ($pack_part ne $part);
10483: if (defined($packagetab{"$pack_type&$name&default"})) {
10484: return $packagetab{"$pack_type&$name&default"};
10485: }
10486: }
10487: # look for any possible matching non extension_ package
10488: foreach my $package (@specifics) {
10489: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 10490: if (defined($packagetab{"$pack_type&$name&default"})) {
10491: return $packagetab{"$pack_type&$name&default"};
10492: }
1.585 albertel 10493: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 10494: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
10495: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 10496: }
10497: }
1.738 albertel 10498: # look for any posible extension_ match
10499: foreach my $package (@extension) {
10500: my ($package,$pack_type)=@{$package};
10501: if (defined($packagetab{"$pack_type&$name&default"})) {
10502: return $packagetab{"$pack_type&$name&default"};
10503: }
10504: if (defined($packagetab{$package."&$name&default"})) {
10505: return $packagetab{$package."&$name&default"};
10506: }
10507: }
10508: # look for a global default setting
10509: if ($do_default && defined($packagetab{"default&$name&default"})) {
10510: return $packagetab{"default&$name&default"};
10511: }
1.395 albertel 10512: return undef;
10513: }
10514:
1.334 albertel 10515: sub add_prefix_and_part {
10516: my ($prefix,$part)=@_;
10517: my $keyroot;
10518: if (defined($prefix) && $prefix !~ /^__/) {
10519: # prefix that has a part already
10520: $keyroot=$prefix;
10521: } elsif (defined($prefix)) {
10522: # prefix that is missing a part
10523: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
10524: } else {
10525: # no prefix at all
10526: if (defined($part)) { $keyroot='_'.$part; }
10527: }
10528: return $keyroot;
10529: }
10530:
1.71 www 10531: # ---------------------------------------------------------------- Get metadata
10532:
1.599 albertel 10533: my %metaentry;
1.1070 www 10534: my %importedpartids;
1.71 www 10535: sub metadata {
1.176 www 10536: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 10537: $uri=&declutter($uri);
1.288 albertel 10538: # if it is a non metadata possible uri return quickly
1.529 albertel 10539: if (($uri eq '') ||
10540: (($uri =~ m|^/*adm/|) &&
1.1217 raeburn 10541: ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108 raeburn 10542: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 10543: return undef;
10544: }
1.1261 raeburn 10545: if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv})
1.924 albertel 10546: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 10547: return undef;
1.288 albertel 10548: }
1.73 www 10549: my $filename=$uri;
10550: $uri=~s/\.meta$//;
1.172 www 10551: #
10552: # Is the metadata already cached?
1.177 www 10553: # Look at timestamp of caching
1.172 www 10554: # Everything is cached by the main uri, libraries are never directly cached
10555: #
1.428 albertel 10556: if (!defined($liburi)) {
1.599 albertel 10557: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 10558: if (defined($cached)) { return $result->{':'.$what}; }
10559: }
10560: {
1.1069 www 10561: # Imported parts would go here
1.1070 www 10562: my %importedids=();
10563: my @origfileimportpartids=();
1.1069 www 10564: my $importedparts=0;
1.172 www 10565: #
10566: # Is this a recursive call for a library?
10567: #
1.599 albertel 10568: # if (! exists($metacache{$uri})) {
10569: # $metacache{$uri}={};
10570: # }
1.924 albertel 10571: my $cachetime = 60*60;
1.171 www 10572: if ($liburi) {
10573: $liburi=&declutter($liburi);
10574: $filename=$liburi;
1.401 bowersj2 10575: } else {
1.599 albertel 10576: &devalidate_cache_new('meta',$uri);
10577: undef(%metaentry);
1.401 bowersj2 10578: }
1.140 www 10579: my %metathesekeys=();
1.73 www 10580: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 10581: my $metastring;
1.1140 www 10582: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929 albertel 10583: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 10584: $metastring =
1.929 albertel 10585: &Apache::lonnet::ssi_body($which,
1.924 albertel 10586: ('grade_target' => 'meta'));
10587: $cachetime = 1; # only want this cached in the child not long term
1.1108 raeburn 10588: } elsif (($uri !~ m -^(editupload)/-) &&
10589: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 10590: my $file=&filelocation('',&clutter($filename));
1.599 albertel 10591: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 10592: $metastring=&getfile($file);
1.489 albertel 10593: }
1.208 albertel 10594: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 10595: my $token;
1.140 www 10596: undef %metathesekeys;
1.71 www 10597: while ($token=$parser->get_token) {
1.339 albertel 10598: if ($token->[0] eq 'S') {
10599: if (defined($token->[2]->{'package'})) {
1.172 www 10600: #
10601: # This is a package - get package info
10602: #
1.339 albertel 10603: my $package=$token->[2]->{'package'};
10604: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10605: if (defined($token->[2]->{'id'})) {
10606: $keyroot.='_'.$token->[2]->{'id'};
10607: }
1.599 albertel 10608: if ($metaentry{':packages'}) {
10609: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 10610: } else {
1.599 albertel 10611: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 10612: }
1.736 albertel 10613: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 10614: my $part=$keyroot;
10615: $part=~s/^\_//;
1.736 albertel 10616: if ($pack_entry=~/^\Q$package\E\&/ ||
10617: $pack_entry=~/^\Q$package\E_0\&/) {
10618: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 10619: # ignore package.tab specified default values
10620: # here &package_tab_default() will fetch those
10621: if ($subp eq 'default') { next; }
1.736 albertel 10622: my $value=$packagetab{$pack_entry};
1.432 albertel 10623: my $unikey;
10624: if ($pack =~ /_0$/) {
10625: $unikey='parameter_0_'.$name;
10626: $part=0;
10627: } else {
10628: $unikey='parameter'.$keyroot.'_'.$name;
10629: }
1.339 albertel 10630: if ($subp eq 'display') {
10631: $value.=' [Part: '.$part.']';
10632: }
1.599 albertel 10633: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 10634: $metathesekeys{$unikey}=1;
1.599 albertel 10635: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10636: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 10637: }
1.599 albertel 10638: if (defined($metaentry{':'.$unikey.'.default'})) {
10639: $metaentry{':'.$unikey}=
10640: $metaentry{':'.$unikey.'.default'};
1.356 albertel 10641: }
1.339 albertel 10642: }
10643: }
10644: } else {
1.172 www 10645: #
10646: # This is not a package - some other kind of start tag
1.339 albertel 10647: #
10648: my $entry=$token->[1];
1.1068 www 10649: my $unikey='';
1.175 www 10650:
1.339 albertel 10651: if ($entry eq 'import') {
1.175 www 10652: #
10653: # Importing a library here
1.339 albertel 10654: #
1.1067 www 10655: my $location=$parser->get_text('/import');
10656: my $dir=$filename;
10657: $dir=~s|[^/]*$||;
10658: $location=&filelocation($dir,$location);
1.1069 www 10659:
1.1068 www 10660: my $importmode=$token->[2]->{'importmode'};
10661: if ($importmode eq 'problem') {
1.1069 www 10662: # Import as problem/response
1.1068 www 10663: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10664: } elsif ($importmode eq 'part') {
10665: # Import as part(s)
1.1069 www 10666: $importedparts=1;
10667: # We need to get the original file and the imported file to get the part order correct
10668: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
10669: # Load and inspect original file
1.1070 www 10670: if ($#origfileimportpartids<0) {
10671: undef(%importedpartids);
10672: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
10673: my $origfile=&getfile($origfilelocation);
10674: @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10675: }
10676:
1.1069 www 10677: # Load and inspect imported file
10678: my $impfile=&getfile($location);
10679: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10680: if ($#impfilepartids>=0) {
10681: # This problem had parts
1.1070 www 10682: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 10683: } else {
10684: # Importing by turning a single problem into a problem part
10685: # It gets the import-tags ID as part-ID
10686: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 10687: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 10688: }
1.1068 www 10689: } else {
10690: # Normal import
10691: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10692: if (defined($token->[2]->{'id'})) {
10693: $unikey.='_'.$token->[2]->{'id'};
10694: }
1.1067 www 10695: }
10696:
1.339 albertel 10697: if ($depthcount<20) {
1.736 albertel 10698: my $metadata =
10699: &metadata($uri,'keys', $location,$unikey,
10700: $depthcount+1);
10701: foreach my $meta (split(',',$metadata)) {
10702: $metaentry{':'.$meta}=$metaentry{':'.$meta};
10703: $metathesekeys{$meta}=1;
1.339 albertel 10704: }
1.1068 www 10705:
10706: }
1.1067 www 10707: } else {
10708: #
10709: # Not importing, some other kind of non-package, non-library start tag
10710: #
10711: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
10712: if (defined($token->[2]->{'id'})) {
10713: $unikey.='_'.$token->[2]->{'id'};
10714: }
1.339 albertel 10715: if (defined($token->[2]->{'name'})) {
10716: $unikey.='_'.$token->[2]->{'name'};
10717: }
10718: $metathesekeys{$unikey}=1;
1.736 albertel 10719: foreach my $param (@{$token->[3]}) {
10720: $metaentry{':'.$unikey.'.'.$param} =
10721: $token->[2]->{$param};
1.339 albertel 10722: }
10723: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 10724: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 10725: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
10726: # only ws inside the tag, and not in default, so use default
10727: # as value
1.599 albertel 10728: $metaentry{':'.$unikey}=$default;
1.908 albertel 10729: } elsif ( $internaltext =~ /\S/ ) {
10730: # something interesting inside the tag
10731: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 10732: } else {
1.908 albertel 10733: # no interesting values, don't set a default
1.339 albertel 10734: }
1.172 www 10735: # end of not-a-package not-a-library import
1.339 albertel 10736: }
1.172 www 10737: # end of not-a-package start tag
1.339 albertel 10738: }
1.172 www 10739: # the next is the end of "start tag"
1.339 albertel 10740: }
10741: }
1.483 albertel 10742: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 10743: $extension = lc($extension);
10744: if ($extension eq 'htm') { $extension='html'; }
10745:
1.737 albertel 10746: foreach my $key (keys(%packagetab)) {
1.483 albertel 10747: #no specific packages #how's our extension
10748: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 10749: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 10750: \%metathesekeys);
10751: }
1.883 albertel 10752:
10753: if (!exists($metaentry{':packages'})
10754: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 10755: foreach my $key (keys(%packagetab)) {
1.483 albertel 10756: #no specific packages well let's get default then
10757: if ($key!~/^default&/) { next; }
1.488 albertel 10758: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 10759: \%metathesekeys);
10760: }
10761: }
1.338 www 10762: # are there custom rights to evaluate
1.599 albertel 10763: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 10764:
1.338 www 10765: #
10766: # Importing a rights file here
1.339 albertel 10767: #
10768: unless ($depthcount) {
1.599 albertel 10769: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 10770: my $dir=$filename;
10771: $dir=~s|[^/]*$||;
10772: $location=&filelocation($dir,$location);
1.736 albertel 10773: my $rights_metadata =
10774: &metadata($uri,'keys',$location,'_rights',
10775: $depthcount+1);
10776: foreach my $rights (split(',',$rights_metadata)) {
10777: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
10778: $metathesekeys{$rights}=1;
1.339 albertel 10779: }
10780: }
10781: }
1.737 albertel 10782: # uniqifiy package listing
10783: my %seen;
10784: my @uniq_packages =
10785: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
10786: $metaentry{':packages'} = join(',',@uniq_packages);
10787:
1.1070 www 10788: if ($importedparts) {
10789: # We had imported parts and need to rebuild partorder
10790: $metaentry{':partorder'}='';
10791: $metathesekeys{'partorder'}=1;
10792: for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
10793: if ($origfileimportpartids[$index] eq 'part') {
10794: # original part, part of the problem
10795: $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
10796: } else {
10797: # we have imported parts at this position
10798: $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
10799: }
10800: }
10801: $metaentry{':partorder'}=~s/^\,//;
10802: }
10803:
1.737 albertel 10804: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 10805: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1274 raeburn 10806: $metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924 albertel 10807: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 10808: # this is the end of "was not already recently cached
1.71 www 10809: }
1.599 albertel 10810: return $metaentry{':'.$what};
1.261 albertel 10811: }
10812:
1.488 albertel 10813: sub metadata_create_package_def {
1.483 albertel 10814: my ($uri,$key,$package,$metathesekeys)=@_;
10815: my ($pack,$name,$subp)=split(/\&/,$key);
10816: if ($subp eq 'default') { next; }
10817:
1.599 albertel 10818: if (defined($metaentry{':packages'})) {
10819: $metaentry{':packages'}.=','.$package;
1.483 albertel 10820: } else {
1.599 albertel 10821: $metaentry{':packages'}=$package;
1.483 albertel 10822: }
10823: my $value=$packagetab{$key};
10824: my $unikey;
10825: $unikey='parameter_0_'.$name;
1.599 albertel 10826: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 10827: $$metathesekeys{$unikey}=1;
1.599 albertel 10828: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10829: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 10830: }
1.599 albertel 10831: if (defined($metaentry{':'.$unikey.'.default'})) {
10832: $metaentry{':'.$unikey}=
10833: $metaentry{':'.$unikey.'.default'};
1.483 albertel 10834: }
10835: }
10836:
1.261 albertel 10837: sub metadata_generate_part0 {
10838: my ($metadata,$metacache,$uri) = @_;
10839: my %allnames;
1.737 albertel 10840: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 10841: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 10842: my $part=$$metacache{':'.$metakey.'.part'};
10843: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 10844: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 10845: $allnames{$name}=$part;
10846: }
10847: }
10848: }
10849: foreach my $name (keys(%allnames)) {
10850: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 10851: my $key=":parameter_0_$name";
1.261 albertel 10852: $$metacache{"$key.part"}='0';
10853: $$metacache{"$key.name"}=$name;
1.428 albertel 10854: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 10855: $allnames{$name}.'_'.$name.
10856: '.type'};
1.428 albertel 10857: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 10858: '.display'};
1.644 www 10859: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 10860: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 10861: $$metacache{"$key.display"}=$olddis;
10862: }
1.71 www 10863: }
10864:
1.764 albertel 10865: # ------------------------------------------------------ Devalidate title cache
10866:
10867: sub devalidate_title_cache {
10868: my ($url)=@_;
10869: if (!$env{'request.course.id'}) { return; }
10870: my $symb=&symbread($url);
10871: if (!$symb) { return; }
10872: my $key=$env{'request.course.id'}."\0".$symb;
10873: &devalidate_cache_new('title',$key);
10874: }
10875:
1.1014 droeschl 10876: # ------------------------------------------------- Get the title of a course
10877:
10878: sub current_course_title {
10879: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
10880: }
1.301 www 10881: # ------------------------------------------------- Get the title of a resource
10882:
10883: sub gettitle {
10884: my $urlsymb=shift;
10885: my $symb=&symbread($urlsymb);
1.534 albertel 10886: if ($symb) {
1.620 albertel 10887: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 10888: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 10889: if (defined($cached)) {
10890: return $result;
10891: }
1.534 albertel 10892: my ($map,$resid,$url)=&decode_symb($symb);
10893: my $title='';
1.907 albertel 10894: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
10895: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
10896: } else {
10897: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10898: &GDBM_READER(),0640)) {
10899: my $mapid=$bighash{'map_pc_'.&clutter($map)};
10900: $title=$bighash{'title_'.$mapid.'.'.$resid};
10901: untie(%bighash);
10902: }
1.534 albertel 10903: }
10904: $title=~s/\&colon\;/\:/gs;
10905: if ($title) {
1.1159 www 10906: # Remember both $symb and $title for dynamic metadata
10907: $accesshash{$symb.'___crstitle'}=$title;
1.1161 www 10908: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159 www 10909: # Cache this title and then return it
1.599 albertel 10910: return &do_cache_new('title',$key,$title,600);
1.534 albertel 10911: }
10912: $urlsymb=$url;
10913: }
10914: my $title=&metadata($urlsymb,'title');
10915: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
10916: return $title;
1.301 www 10917: }
1.613 albertel 10918:
1.614 albertel 10919: sub get_slot {
10920: my ($which,$cnum,$cdom)=@_;
10921: if (!$cnum || !$cdom) {
1.790 albertel 10922: (undef,my $courseid)=&whichuser();
1.620 albertel 10923: $cdom=$env{'course.'.$courseid.'.domain'};
10924: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 10925: }
1.703 albertel 10926: my $key=join("\0",'slots',$cdom,$cnum,$which);
10927: my %slotinfo;
10928: if (exists($remembered{$key})) {
10929: $slotinfo{$which} = $remembered{$key};
10930: } else {
10931: %slotinfo=&get('slots',[$which],$cdom,$cnum);
10932: &Apache::lonhomework::showhash(%slotinfo);
10933: my ($tmp)=keys(%slotinfo);
10934: if ($tmp=~/^error:/) { return (); }
10935: $remembered{$key} = $slotinfo{$which};
10936: }
1.616 albertel 10937: if (ref($slotinfo{$which}) eq 'HASH') {
10938: return %{$slotinfo{$which}};
10939: }
10940: return $slotinfo{$which};
1.614 albertel 10941: }
1.1150 raeburn 10942:
10943: sub get_reservable_slots {
10944: my ($cnum,$cdom,$uname,$udom) = @_;
10945: my $now = time;
10946: my $reservable_info;
10947: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
10948: if (exists($remembered{$key})) {
10949: $reservable_info = $remembered{$key};
10950: } else {
10951: my %resv;
10952: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
10953: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
10954: $reservable_info = \%resv;
10955: $remembered{$key} = $reservable_info;
10956: }
10957: return $reservable_info;
10958: }
10959:
10960: sub get_course_slots {
10961: my ($cnum,$cdom) = @_;
10962: my $hashid=$cnum.':'.$cdom;
10963: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
10964: if (defined($cached)) {
10965: if (ref($result) eq 'HASH') {
10966: return %{$result};
10967: }
10968: } else {
10969: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
10970: my ($tmp) = keys(%slots);
10971: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1219 raeburn 10972: &do_cache_new('allslots',$hashid,\%slots,600);
1.1150 raeburn 10973: return %slots;
10974: }
10975: }
10976: return;
10977: }
10978:
10979: sub devalidate_slots_cache {
10980: my ($cnum,$cdom)=@_;
10981: my $hashid=$cnum.':'.$cdom;
10982: &devalidate_cache_new('allslots',$hashid);
10983: }
10984:
1.1181 raeburn 10985: sub get_coursechange {
10986: my ($cdom,$cnum) = @_;
10987: if ($cdom eq '' || $cnum eq '') {
10988: return unless ($env{'request.course.id'});
10989: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10990: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10991: }
10992: my $hashid=$cdom.'_'.$cnum;
10993: my ($change,$cached)=&is_cached_new('crschange',$hashid);
10994: if ((defined($cached)) && ($change ne '')) {
10995: return $change;
10996: } else {
10997: my %crshash;
10998: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
10999: if ($crshash{'internal.contentchange'} eq '') {
11000: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
11001: if ($change eq '') {
11002: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
11003: $change = $crshash{'internal.created'};
11004: }
11005: } else {
11006: $change = $crshash{'internal.contentchange'};
11007: }
11008: my $cachetime = 600;
11009: &do_cache_new('crschange',$hashid,$change,$cachetime);
11010: }
11011: return $change;
11012: }
11013:
11014: sub devalidate_coursechange_cache {
11015: my ($cnum,$cdom)=@_;
11016: my $hashid=$cnum.':'.$cdom;
11017: &devalidate_cache_new('crschange',$hashid);
11018: }
11019:
1.31 www 11020: # ------------------------------------------------- Update symbolic store links
11021:
11022: sub symblist {
11023: my ($mapname,%newhash)=@_;
1.438 www 11024: $mapname=&deversion(&declutter($mapname));
1.31 www 11025: my %hash;
1.620 albertel 11026: if (($env{'request.course.fn'}) && (%newhash)) {
11027: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 11028: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 11029: foreach my $url (keys(%newhash)) {
1.711 albertel 11030: next if ($url eq 'last_known'
11031: && $env{'form.no_update_last_known'});
11032: $hash{declutter($url)}=&encode_symb($mapname,
11033: $newhash{$url}->[1],
11034: $newhash{$url}->[0]);
1.191 harris41 11035: }
1.31 www 11036: if (untie(%hash)) {
11037: return 'ok';
11038: }
11039: }
11040: }
11041: return 'error';
1.212 www 11042: }
11043:
11044: # --------------------------------------------------------------- Verify a symb
11045:
11046: sub symbverify {
1.1190 raeburn 11047: my ($symb,$thisurl,$encstate)=@_;
1.510 www 11048: my $thisfn=$thisurl;
1.439 www 11049: $thisfn=&declutter($thisfn);
1.215 www 11050: # direct jump to resource in page or to a sequence - will construct own symbs
11051: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
11052: # check URL part
1.409 www 11053: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 11054:
1.431 www 11055: unless ($url eq $thisfn) { return 0; }
1.213 www 11056:
1.216 www 11057: $symb=&symbclean($symb);
1.510 www 11058: $thisurl=&deversion($thisurl);
1.439 www 11059: $thisfn=&deversion($thisfn);
1.213 www 11060:
11061: my %bighash;
11062: my $okay=0;
1.431 www 11063:
1.620 albertel 11064: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 11065: &GDBM_READER(),0640)) {
1.1204 raeburn 11066: my $noclutter;
1.1032 raeburn 11067: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
11068: $thisurl =~ s/\?.+$//;
1.1204 raeburn 11069: if ($map =~ m{^uploaded/.+\.page$}) {
11070: $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
11071: $thisurl =~ s{^\Qhttp://https://\E}{https://};
11072: $noclutter = 1;
11073: }
11074: }
11075: my $ids;
11076: if ($noclutter) {
11077: $ids=$bighash{'ids_'.$thisurl};
11078: } else {
11079: $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032 raeburn 11080: }
1.1102 raeburn 11081: unless ($ids) {
11082: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
11083: $ids=$bighash{$idkey};
1.216 www 11084: }
11085: if ($ids) {
11086: # ------------------------------------------------------------------- Has ID(s)
1.1202 raeburn 11087: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
1.1203 raeburn 11088: $symb =~ s/\?.+$//;
1.1202 raeburn 11089: }
1.800 albertel 11090: foreach my $id (split(/\,/,$ids)) {
11091: my ($mapid,$resid)=split(/\./,$id);
1.216 www 11092: if (
11093: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190 raeburn 11094: eq $symb) {
11095: if (ref($encstate)) {
11096: $$encstate = $bighash{'encrypted_'.$id};
11097: }
1.620 albertel 11098: if (($env{'request.role.adv'}) ||
1.1101 raeburn 11099: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
11100: ($thisurl eq '/adm/navmaps')) {
1.1190 raeburn 11101: $okay=1;
1.1202 raeburn 11102: last;
1.582 albertel 11103: }
11104: }
1.216 www 11105: }
11106: }
1.213 www 11107: untie(%bighash);
11108: }
11109: return $okay;
1.31 www 11110: }
11111:
1.210 www 11112: # --------------------------------------------------------------- Clean-up symb
11113:
11114: sub symbclean {
11115: my $symb=shift;
1.568 albertel 11116: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 11117: # remove version from map
11118: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 11119:
1.210 www 11120: # remove version from URL
11121: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 11122:
1.507 www 11123: # remove wrapper
11124:
1.510 www 11125: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 11126: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 11127: return $symb;
1.409 www 11128: }
11129:
11130: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 11131:
11132: sub encode_symb {
11133: my ($map,$resid,$url)=@_;
11134: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
11135: }
1.409 www 11136:
11137: sub decode_symb {
1.568 albertel 11138: my $symb=shift;
11139: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
11140: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 11141: return (&fixversion($map),$resid,&fixversion($url));
11142: }
11143:
11144: sub fixversion {
11145: my $fn=shift;
1.609 banghart 11146: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 11147: my %bighash;
11148: my $uri=&clutter($fn);
1.620 albertel 11149: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 11150: # is this cached?
1.599 albertel 11151: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 11152: if (defined($cached)) { return $result; }
11153: # unfortunately not cached, or expired
1.620 albertel 11154: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 11155: &GDBM_READER(),0640)) {
11156: if ($bighash{'version_'.$uri}) {
11157: my $version=$bighash{'version_'.$uri};
1.444 www 11158: unless (($version eq 'mostrecent') ||
11159: ($version==&getversion($uri))) {
1.440 www 11160: $uri=~s/\.(\w+)$/\.$version\.$1/;
11161: }
11162: }
11163: untie %bighash;
1.413 www 11164: }
1.599 albertel 11165: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 11166: }
11167:
11168: sub deversion {
11169: my $url=shift;
11170: $url=~s/\.\d+\.(\w+)$/\.$1/;
11171: return $url;
1.210 www 11172: }
11173:
1.31 www 11174: # ------------------------------------------------------ Return symb list entry
11175:
11176: sub symbread {
1.1282 raeburn 11177: my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
1.1265 raeburn 11178: my $cache_str='request.symbread.cached.'.$thisfn;
1.1282 raeburn 11179: if (defined($env{$cache_str})) {
11180: if ($ignorecachednull) {
11181: return $env{$cache_str} unless ($env{$cache_str} eq '');
11182: } else {
11183: return $env{$cache_str};
11184: }
11185: }
1.242 www 11186: # no filename provided? try from environment
1.1265 raeburn 11187: unless ($thisfn) {
1.620 albertel 11188: if ($env{'request.symb'}) {
11189: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 11190: }
1.620 albertel 11191: $thisfn=$env{'request.filename'};
1.44 www 11192: }
1.569 albertel 11193: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 11194: # is that filename actually a symb? Verify, clean, and return
11195: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 11196: if (&symbverify($thisfn,$1)) {
1.620 albertel 11197: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 11198: }
1.242 www 11199: }
1.44 www 11200: $thisfn=declutter($thisfn);
1.31 www 11201: my %hash;
1.37 www 11202: my %bighash;
11203: my $syval='';
1.620 albertel 11204: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 11205: my $targetfn = $thisfn;
1.609 banghart 11206: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 11207: $targetfn = 'adm/wrapper/'.$thisfn;
11208: }
1.687 albertel 11209: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
11210: $targetfn=$1;
11211: }
1.620 albertel 11212: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 11213: &GDBM_READER(),0640)) {
1.481 raeburn 11214: $syval=$hash{$targetfn};
1.37 www 11215: untie(%hash);
11216: }
11217: # ---------------------------------------------------------- There was an entry
11218: if ($syval) {
1.601 albertel 11219: #unless ($syval=~/\_\d+$/) {
1.620 albertel 11220: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 11221: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 11222: #return $env{$cache_str}='';
1.601 albertel 11223: #}
11224: #$syval.=$1;
11225: #}
1.37 www 11226: } else {
11227: # ------------------------------------------------------- Was not in symb table
1.620 albertel 11228: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 11229: &GDBM_READER(),0640)) {
1.37 www 11230: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 11231: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 11232: unless ($ids) {
11233: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 11234: }
11235: unless ($ids) {
11236: # alias?
11237: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 11238: }
1.37 www 11239: if ($ids) {
11240: # ------------------------------------------------------------------- Has ID(s)
11241: my @possibilities=split(/\,/,$ids);
1.39 www 11242: if ($#possibilities==0) {
11243: # ----------------------------------------------- There is only one possibility
1.37 www 11244: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 11245: $syval=&encode_symb($bighash{'map_id_'.$mapid},
11246: $resid,$thisfn);
1.1282 raeburn 11247: if (ref($possibles) eq 'HASH') {
11248: $possibles->{$syval} = 1;
11249: }
11250: if ($checkforblock) {
11251: my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
11252: if (@blockers) {
11253: $syval = '';
11254: return;
11255: }
11256: }
11257: } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39 www 11258: # ------------------------------------------ There is more than one possibility
11259: my $realpossible=0;
1.800 albertel 11260: foreach my $id (@possibilities) {
11261: my $file=$bighash{'src_'.$id};
1.1282 raeburn 11262: my $canaccess;
11263: if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
11264: $canaccess = 1;
11265: } else {
11266: $canaccess = &allowed('bre',$file);
11267: }
11268: if ($canaccess) {
11269: my ($mapid,$resid)=split(/\./,$id);
11270: if ($bighash{'map_type_'.$mapid} ne 'page') {
11271: my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
11272: $resid,$thisfn);
11273: if (ref($possibles) eq 'HASH') {
11274: $possibles->{$syval} = 1;
11275: }
11276: if ($checkforblock) {
11277: my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
11278: unless (@blockers > 0) {
11279: $syval = $poss_syval;
11280: $realpossible++;
11281: }
11282: } else {
11283: $syval = $poss_syval;
11284: $realpossible++;
11285: }
11286: }
1.39 www 11287: }
1.191 harris41 11288: }
1.39 www 11289: if ($realpossible!=1) { $syval=''; }
1.249 www 11290: } else {
11291: $syval='';
1.37 www 11292: }
11293: }
1.1282 raeburn 11294: untie(%bighash);
1.481 raeburn 11295: }
1.31 www 11296: }
1.62 www 11297: if ($syval) {
1.620 albertel 11298: return $env{$cache_str}=$syval;
1.62 www 11299: }
1.31 www 11300: }
1.949 raeburn 11301: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 11302: return $env{$cache_str}='';
1.31 www 11303: }
11304:
11305: # ---------------------------------------------------------- Return random seed
11306:
1.32 www 11307: sub numval {
11308: my $txt=shift;
11309: $txt=~tr/A-J/0-9/;
11310: $txt=~tr/a-j/0-9/;
11311: $txt=~tr/K-T/0-9/;
11312: $txt=~tr/k-t/0-9/;
11313: $txt=~tr/U-Z/0-5/;
11314: $txt=~tr/u-z/0-5/;
11315: $txt=~s/\D//g;
1.564 albertel 11316: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 11317: return int($txt);
1.368 albertel 11318: }
11319:
1.484 albertel 11320: sub numval2 {
11321: my $txt=shift;
11322: $txt=~tr/A-J/0-9/;
11323: $txt=~tr/a-j/0-9/;
11324: $txt=~tr/K-T/0-9/;
11325: $txt=~tr/k-t/0-9/;
11326: $txt=~tr/U-Z/0-5/;
11327: $txt=~tr/u-z/0-5/;
11328: $txt=~s/\D//g;
11329: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
11330: my $total;
11331: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 11332: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 11333: return int($total);
11334: }
11335:
1.575 albertel 11336: sub numval3 {
11337: use integer;
11338: my $txt=shift;
11339: $txt=~tr/A-J/0-9/;
11340: $txt=~tr/a-j/0-9/;
11341: $txt=~tr/K-T/0-9/;
11342: $txt=~tr/k-t/0-9/;
11343: $txt=~tr/U-Z/0-5/;
11344: $txt=~tr/u-z/0-5/;
11345: $txt=~s/\D//g;
11346: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
11347: my $total;
11348: foreach my $val (@txts) { $total+=$val; }
11349: if ($_64bit) { $total=(($total<<32)>>32); }
11350: return $total;
11351: }
11352:
1.675 albertel 11353: sub digest {
11354: my ($data)=@_;
11355: my $digest=&Digest::MD5::md5($data);
11356: my ($a,$b,$c,$d)=unpack("iiii",$digest);
11357: my ($e,$f);
11358: {
11359: use integer;
11360: $e=($a+$b);
11361: $f=($c+$d);
11362: if ($_64bit) {
11363: $e=(($e<<32)>>32);
11364: $f=(($f<<32)>>32);
11365: }
11366: }
11367: if (wantarray) {
11368: return ($e,$f);
11369: } else {
11370: my $g;
11371: {
11372: use integer;
11373: $g=($e+$f);
11374: if ($_64bit) {
11375: $g=(($g<<32)>>32);
11376: }
11377: }
11378: return $g;
11379: }
11380: }
11381:
1.368 albertel 11382: sub latest_rnd_algorithm_id {
1.675 albertel 11383: return '64bit5';
1.366 albertel 11384: }
1.32 www 11385:
1.503 albertel 11386: sub get_rand_alg {
11387: my ($courseid)=@_;
1.790 albertel 11388: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 11389: if ($courseid) {
1.620 albertel 11390: return $env{"course.$courseid.rndseed"};
1.503 albertel 11391: }
11392: return &latest_rnd_algorithm_id();
11393: }
11394:
1.562 albertel 11395: sub validCODE {
11396: my ($CODE)=@_;
11397: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
11398: return 0;
11399: }
11400:
1.491 albertel 11401: sub getCODE {
1.620 albertel 11402: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 11403: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
11404: defined($Apache::lonhomework::parsing_a_task) ) &&
11405: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 11406: return $Apache::lonhomework::history{'resource.CODE'};
11407: }
11408: return undef;
11409: }
1.1133 foxr 11410: #
11411: # Determines the random seed for a specific context:
11412: #
11413: # parameters:
11414: # symb - in course context the symb for the seed.
11415: # course_id - The course id of the form domain_coursenum.
11416: # domain - Domain for the user.
11417: # course - Course for the user.
11418: # cenv - environment of the course.
11419: #
11420: # NOTE:
11421: # All parameters are picked out of the environment if missing
11422: # or not defined.
11423: # If a symb cannot be determined the current time is used instead.
11424: #
11425: # For a given well defined symb, courside, domain, username,
11426: # and course environment, the seed is reproducible.
11427: #
1.31 www 11428: sub rndseed {
1.1133 foxr 11429: my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790 albertel 11430: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 11431: if (!defined($symb)) {
1.366 albertel 11432: unless ($symb=$wsymb) { return time; }
11433: }
1.1146 foxr 11434: if (!defined $courseid) {
11435: $courseid=$wcourseid;
11436: }
11437: if (!defined $domain) { $domain=$wdomain; }
11438: if (!defined $username) { $username=$wusername }
1.1133 foxr 11439:
11440: my $which;
11441: if (defined($cenv->{'rndseed'})) {
11442: $which = $cenv->{'rndseed'};
11443: } else {
11444: $which =&get_rand_alg($courseid);
11445: }
1.491 albertel 11446: if (defined(&getCODE())) {
1.1133 foxr 11447:
1.675 albertel 11448: if ($which eq '64bit5') {
11449: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
11450: } elsif ($which eq '64bit4') {
1.575 albertel 11451: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
11452: } else {
11453: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
11454: }
1.675 albertel 11455: } elsif ($which eq '64bit5') {
11456: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 11457: } elsif ($which eq '64bit4') {
11458: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 11459: } elsif ($which eq '64bit3') {
11460: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 11461: } elsif ($which eq '64bit2') {
11462: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 11463: } elsif ($which eq '64bit') {
11464: return &rndseed_64bit($symb,$courseid,$domain,$username);
11465: }
11466: return &rndseed_32bit($symb,$courseid,$domain,$username);
11467: }
11468:
11469: sub rndseed_32bit {
11470: my ($symb,$courseid,$domain,$username)=@_;
11471: {
11472: use integer;
11473: my $symbchck=unpack("%32C*",$symb) << 27;
11474: my $symbseed=numval($symb) << 22;
11475: my $namechck=unpack("%32C*",$username) << 17;
11476: my $nameseed=numval($username) << 12;
11477: my $domainseed=unpack("%32C*",$domain) << 7;
11478: my $courseseed=unpack("%32C*",$courseid);
11479: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 11480: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11481: #&logthis("rndseed :$num:$symb");
1.564 albertel 11482: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 11483: return $num;
11484: }
11485: }
11486:
11487: sub rndseed_64bit {
11488: my ($symb,$courseid,$domain,$username)=@_;
11489: {
11490: use integer;
11491: my $symbchck=unpack("%32S*",$symb) << 21;
11492: my $symbseed=numval($symb) << 10;
11493: my $namechck=unpack("%32S*",$username);
11494:
11495: my $nameseed=numval($username) << 21;
11496: my $domainseed=unpack("%32S*",$domain) << 10;
11497: my $courseseed=unpack("%32S*",$courseid);
11498:
11499: my $num1=$symbchck+$symbseed+$namechck;
11500: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11501: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11502: #&logthis("rndseed :$num:$symb");
1.564 albertel 11503: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 11504: return "$num1,$num2";
1.155 albertel 11505: }
1.366 albertel 11506: }
11507:
1.443 albertel 11508: sub rndseed_64bit2 {
11509: my ($symb,$courseid,$domain,$username)=@_;
11510: {
11511: use integer;
11512: # strings need to be an even # of cahracters long, it it is odd the
11513: # last characters gets thrown away
11514: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11515: my $symbseed=numval($symb) << 10;
11516: my $namechck=unpack("%32S*",$username.' ');
11517:
11518: my $nameseed=numval($username) << 21;
1.501 albertel 11519: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11520: my $courseseed=unpack("%32S*",$courseid.' ');
11521:
11522: my $num1=$symbchck+$symbseed+$namechck;
11523: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11524: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11525: #&logthis("rndseed :$num:$symb");
1.803 albertel 11526: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 11527: return "$num1,$num2";
11528: }
11529: }
11530:
11531: sub rndseed_64bit3 {
11532: my ($symb,$courseid,$domain,$username)=@_;
11533: {
11534: use integer;
11535: # strings need to be an even # of cahracters long, it it is odd the
11536: # last characters gets thrown away
11537: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11538: my $symbseed=numval2($symb) << 10;
11539: my $namechck=unpack("%32S*",$username.' ');
11540:
11541: my $nameseed=numval2($username) << 21;
1.443 albertel 11542: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11543: my $courseseed=unpack("%32S*",$courseid.' ');
11544:
11545: my $num1=$symbchck+$symbseed+$namechck;
11546: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11547: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11548: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 11549: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 11550:
1.503 albertel 11551: return "$num1:$num2";
1.443 albertel 11552: }
11553: }
11554:
1.575 albertel 11555: sub rndseed_64bit4 {
11556: my ($symb,$courseid,$domain,$username)=@_;
11557: {
11558: use integer;
11559: # strings need to be an even # of cahracters long, it it is odd the
11560: # last characters gets thrown away
11561: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11562: my $symbseed=numval3($symb) << 10;
11563: my $namechck=unpack("%32S*",$username.' ');
11564:
11565: my $nameseed=numval3($username) << 21;
11566: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11567: my $courseseed=unpack("%32S*",$courseid.' ');
11568:
11569: my $num1=$symbchck+$symbseed+$namechck;
11570: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11571: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11572: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 11573: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 11574:
1.575 albertel 11575: return "$num1:$num2";
11576: }
11577: }
11578:
1.675 albertel 11579: sub rndseed_64bit5 {
11580: my ($symb,$courseid,$domain,$username)=@_;
11581: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
11582: return "$num1:$num2";
11583: }
11584:
1.366 albertel 11585: sub rndseed_CODE_64bit {
11586: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 11587: {
1.366 albertel 11588: use integer;
1.443 albertel 11589: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 11590: my $symbseed=numval2($symb);
1.491 albertel 11591: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11592: my $CODEseed=numval(&getCODE());
1.443 albertel 11593: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 11594: my $num1=$symbseed+$CODEchck;
11595: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 11596: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11597: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 11598: if ($_64bit) { $num1=(($num1<<32)>>32); }
11599: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 11600: return "$num1:$num2";
1.366 albertel 11601: }
11602: }
11603:
1.575 albertel 11604: sub rndseed_CODE_64bit4 {
11605: my ($symb,$courseid,$domain,$username)=@_;
11606: {
11607: use integer;
11608: my $symbchck=unpack("%32S*",$symb.' ') << 16;
11609: my $symbseed=numval3($symb);
11610: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11611: my $CODEseed=numval3(&getCODE());
11612: my $courseseed=unpack("%32S*",$courseid.' ');
11613: my $num1=$symbseed+$CODEchck;
11614: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 11615: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11616: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 11617: if ($_64bit) { $num1=(($num1<<32)>>32); }
11618: if ($_64bit) { $num2=(($num2<<32)>>32); }
11619: return "$num1:$num2";
11620: }
11621: }
11622:
1.675 albertel 11623: sub rndseed_CODE_64bit5 {
11624: my ($symb,$courseid,$domain,$username)=@_;
11625: my $code = &getCODE();
11626: my ($num1,$num2)=&digest("$symb,$courseid,$code");
11627: return "$num1:$num2";
11628: }
11629:
1.366 albertel 11630: sub setup_random_from_rndseed {
11631: my ($rndseed)=@_;
1.503 albertel 11632: if ($rndseed =~/([,:])/) {
1.1262 raeburn 11633: my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
11634: if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
11635: &Math::Random::random_set_seed_from_phrase($rndseed);
11636: } else {
11637: &Math::Random::random_set_seed($num1,$num2);
11638: }
1.366 albertel 11639: } else {
11640: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 11641: }
1.36 albertel 11642: }
11643:
1.474 albertel 11644: sub latest_receipt_algorithm_id {
1.835 albertel 11645: return 'receipt3';
1.474 albertel 11646: }
11647:
1.480 www 11648: sub recunique {
11649: my $fucourseid=shift;
11650: my $unique;
1.835 albertel 11651: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
11652: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 11653: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 11654: } else {
11655: $unique=$perlvar{'lonReceipt'};
11656: }
11657: return unpack("%32C*",$unique);
11658: }
11659:
11660: sub recprefix {
11661: my $fucourseid=shift;
11662: my $prefix;
1.835 albertel 11663: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
11664: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 11665: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 11666: } else {
11667: $prefix=$perlvar{'lonHostID'};
11668: }
11669: return unpack("%32C*",$prefix);
11670: }
11671:
1.76 www 11672: sub ireceipt {
1.474 albertel 11673: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 11674:
11675: my $return =&recprefix($fucourseid).'-';
11676:
11677: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
11678: $env{'request.state'} eq 'construct') {
11679: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
11680: return $return;
11681: }
11682:
1.76 www 11683: my $cuname=unpack("%32C*",$funame);
11684: my $cudom=unpack("%32C*",$fudom);
11685: my $cucourseid=unpack("%32C*",$fucourseid);
11686: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 11687: my $cunique=&recunique($fucourseid);
1.474 albertel 11688: my $cpart=unpack("%32S*",$part);
1.835 albertel 11689: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
11690:
1.790 albertel 11691: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 11692:
11693: $return.= ($cunique%$cuname+
11694: $cunique%$cudom+
11695: $cusymb%$cuname+
11696: $cusymb%$cudom+
11697: $cucourseid%$cuname+
11698: $cucourseid%$cudom+
11699: $cpart%$cuname+
11700: $cpart%$cudom);
11701: } else {
11702: $return.= ($cunique%$cuname+
11703: $cunique%$cudom+
11704: $cusymb%$cuname+
11705: $cusymb%$cudom+
11706: $cucourseid%$cuname+
11707: $cucourseid%$cudom);
11708: }
11709: return $return;
1.76 www 11710: }
11711:
11712: sub receipt {
1.474 albertel 11713: my ($part)=@_;
1.790 albertel 11714: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 11715: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 11716: }
1.260 ng 11717:
1.790 albertel 11718: sub whichuser {
11719: my ($passedsymb)=@_;
11720: my ($symb,$courseid,$domain,$name,$publicuser);
11721: if (defined($env{'form.grade_symb'})) {
11722: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
11723: my $allowed=&allowed('vgr',$tmp_courseid);
11724: if (!$allowed &&
11725: exists($env{'request.course.sec'}) &&
11726: $env{'request.course.sec'} !~ /^\s*$/) {
11727: $allowed=&allowed('vgr',$tmp_courseid.
11728: '/'.$env{'request.course.sec'});
11729: }
11730: if ($allowed) {
11731: ($symb)=&get_env_multiple('form.grade_symb');
11732: $courseid=$tmp_courseid;
11733: ($domain)=&get_env_multiple('form.grade_domain');
11734: ($name)=&get_env_multiple('form.grade_username');
11735: return ($symb,$courseid,$domain,$name,$publicuser);
11736: }
11737: }
11738: if (!$passedsymb) {
11739: $symb=&symbread();
11740: } else {
11741: $symb=$passedsymb;
11742: }
11743: $courseid=$env{'request.course.id'};
11744: $domain=$env{'user.domain'};
11745: $name=$env{'user.name'};
11746: if ($name eq 'public' && $domain eq 'public') {
11747: if (!defined($env{'form.username'})) {
11748: $env{'form.username'}.=time.rand(10000000);
11749: }
11750: $name.=$env{'form.username'};
11751: }
11752: return ($symb,$courseid,$domain,$name,$publicuser);
11753:
11754: }
11755:
1.36 albertel 11756: # ------------------------------------------------------------ Serves up a file
1.472 albertel 11757: # returns either the contents of the file or
11758: # -1 if the file doesn't exist
1.481 raeburn 11759: #
11760: # if the target is a file that was uploaded via DOCS,
11761: # a check will be made to see if a current copy exists on the local server,
11762: # if it does this will be served, otherwise a copy will be retrieved from
11763: # the home server for the course and stored in /home/httpd/html/userfiles on
11764: # the local server.
1.472 albertel 11765:
1.36 albertel 11766: sub getfile {
1.538 albertel 11767: my ($file) = @_;
1.609 banghart 11768: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 11769: &repcopy($file);
11770: return &readfile($file);
11771: }
11772:
11773: sub repcopy_userfile {
11774: my ($file)=@_;
1.1142 raeburn 11775: my $londocroot = $perlvar{'lonDocRoot'};
11776: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164 raeburn 11777: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538 albertel 11778: my ($cdom,$cnum,$filename) =
1.811 albertel 11779: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 11780: my $uri="/uploaded/$cdom/$cnum/$filename";
11781: if (-e "$file") {
1.828 www 11782: # we already have a local copy, check it out
1.538 albertel 11783: my @fileinfo = stat($file);
1.828 www 11784: my $rtncode;
11785: my $info;
1.538 albertel 11786: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 11787: if ($lwpresp ne 'ok') {
1.828 www 11788: # there is no such file anymore, even though we had a local copy
1.482 albertel 11789: if ($rtncode eq '404') {
1.538 albertel 11790: unlink($file);
1.482 albertel 11791: }
11792: return -1;
11793: }
11794: if ($info < $fileinfo[9]) {
1.828 www 11795: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 11796: return 'ok';
1.828 www 11797: } else {
11798: # the file is outdated, get rid of it
11799: unlink($file);
1.482 albertel 11800: }
1.828 www 11801: }
11802: # one way or the other, at this point, we don't have the file
11803: # construct the correct path for the file
11804: my @parts = ($cdom,$cnum);
11805: if ($filename =~ m|^(.+)/[^/]+$|) {
11806: push @parts, split(/\//,$1);
11807: }
11808: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
11809: foreach my $part (@parts) {
11810: $path .= '/'.$part;
11811: if (!-e $path) {
11812: mkdir($path,0770);
1.482 albertel 11813: }
11814: }
1.828 www 11815: # now the path exists for sure
11816: # get a user agent
11817: my $ua=new LWP::UserAgent;
11818: my $transferfile=$file.'.in.transfer';
11819: # FIXME: this should flock
11820: if (-e $transferfile) { return 'ok'; }
11821: my $request;
11822: $uri=~s/^\///;
1.980 raeburn 11823: my $homeserver = &homeserver($cnum,$cdom);
11824: my $protocol = $protocol{$homeserver};
11825: $protocol = 'http' if ($protocol ne 'https');
11826: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 11827: my $response=$ua->request($request,$transferfile);
11828: # did it work?
11829: if ($response->is_error()) {
11830: unlink($transferfile);
11831: &logthis("Userfile repcopy failed for $uri");
11832: return -1;
11833: }
11834: # worked, rename the transfer file
11835: rename($transferfile,$file);
1.607 raeburn 11836: return 'ok';
1.481 raeburn 11837: }
11838:
1.517 albertel 11839: sub tokenwrapper {
11840: my $uri=shift;
1.980 raeburn 11841: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 11842: $uri=~s|^/||;
1.620 albertel 11843: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 11844: my $token=$1;
1.552 albertel 11845: my (undef,$udom,$uname,$file)=split('/',$uri,4);
11846: if ($udom && $uname && $file) {
11847: $file=~s|(\?\.*)*$||;
1.949 raeburn 11848: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 11849: my $homeserver = &homeserver($uname,$udom);
11850: my $protocol = $protocol{$homeserver};
11851: $protocol = 'http' if ($protocol ne 'https');
11852: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 11853: (($uri=~/\?/)?'&':'?').'token='.$token.
11854: '&tokenissued='.$perlvar{'lonHostID'};
11855: } else {
11856: return '/adm/notfound.html';
11857: }
11858: }
11859:
1.828 www 11860: # call with reqtype HEAD: get last modification time
11861: # call with reqtype GET: get the file contents
11862: # Do not call this with reqtype GET for large files! It loads everything into memory
11863: #
1.481 raeburn 11864: sub getuploaded {
11865: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
11866: $uri=~s/^\///;
1.980 raeburn 11867: my $homeserver = &homeserver($cnum,$cdom);
11868: my $protocol = $protocol{$homeserver};
11869: $protocol = 'http' if ($protocol ne 'https');
11870: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 11871: my $ua=new LWP::UserAgent;
11872: my $request=new HTTP::Request($reqtype,$uri);
11873: my $response=$ua->request($request);
11874: $$rtncode = $response->code;
1.482 albertel 11875: if (! $response->is_success()) {
11876: return 'failed';
11877: }
11878: if ($reqtype eq 'HEAD') {
1.486 www 11879: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 11880: } elsif ($reqtype eq 'GET') {
11881: $$info = $response->content;
1.472 albertel 11882: }
1.482 albertel 11883: return 'ok';
1.36 albertel 11884: }
11885:
1.481 raeburn 11886: sub readfile {
11887: my $file = shift;
11888: if ( (! -e $file ) || ($file eq '') ) { return -1; };
11889: my $fh;
11890: open($fh,"<$file");
11891: my $a='';
1.800 albertel 11892: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 11893: return $a;
11894: }
11895:
1.36 albertel 11896: sub filelocation {
1.590 banghart 11897: my ($dir,$file) = @_;
11898: my $location;
11899: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 11900:
11901: if ($file =~ m-^/adm/-) {
11902: $file=~s-^/adm/wrapper/-/-;
11903: $file=~s-^/adm/coursedocs/showdoc/-/-;
11904: }
1.882 albertel 11905:
1.1139 www 11906: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956 raeburn 11907: $location = $file;
1.609 banghart 11908: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 11909: my ($udom,$uname,$filename)=
1.811 albertel 11910: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 11911: my $home=&homeserver($uname,$udom);
11912: my $is_me=0;
11913: my @ids=¤t_machine_ids();
11914: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
11915: if ($is_me) {
1.1117 foxr 11916: $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 11917: } else {
11918: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
11919: $udom.'/'.$uname.'/'.$filename;
11920: }
1.882 albertel 11921: } elsif ($file =~ m-^/adm/-) {
11922: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 11923: } else {
11924: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139 www 11925: $file=~s:^/(res|priv)/:/:;
11926: my $space=$1;
1.590 banghart 11927: if ( !( $file =~ m:^/:) ) {
11928: $location = $dir. '/'.$file;
11929: } else {
1.1142 raeburn 11930: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590 banghart 11931: }
1.59 albertel 11932: }
1.590 banghart 11933: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 11934: while ($location=~m{/\.\./}) {
11935: if ($location =~ m{/[^/]+/\.\./}) {
11936: $location=~ s{/[^/]+/\.\./}{/}g;
11937: } else {
11938: $location=~ s{/\.\./}{/}g;
11939: }
11940: } #remove dir/..
1.590 banghart 11941: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
11942: return $location;
1.46 www 11943: }
1.36 albertel 11944:
1.46 www 11945: sub hreflocation {
11946: my ($dir,$file)=@_;
1.980 raeburn 11947: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 11948: $file=filelocation($dir,$file);
1.700 albertel 11949: } elsif ($file=~m-^/adm/-) {
11950: $file=~s-^/adm/wrapper/-/-;
11951: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 11952: }
11953: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
11954: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
11955: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143 raeburn 11956: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
11957: {/uploaded/$1/$2/}x;
1.46 www 11958: }
1.913 albertel 11959: if ($file=~ m{^/userfiles/}) {
11960: $file =~ s{^/userfiles/}{/uploaded/};
11961: }
1.462 albertel 11962: return $file;
1.465 albertel 11963: }
11964:
1.1139 www 11965:
11966:
11967:
11968:
1.465 albertel 11969: sub current_machine_domains {
1.853 albertel 11970: return &machine_domains(&hostname($perlvar{'lonHostID'}));
11971: }
11972:
11973: sub machine_domains {
11974: my ($hostname) = @_;
1.465 albertel 11975: my @domains;
1.838 albertel 11976: my %hostname = &all_hostnames();
1.465 albertel 11977: while( my($id, $name) = each(%hostname)) {
1.467 matthew 11978: # &logthis("-$id-$name-$hostname-");
1.465 albertel 11979: if ($hostname eq $name) {
1.844 albertel 11980: push(@domains,&host_domain($id));
1.465 albertel 11981: }
11982: }
11983: return @domains;
11984: }
11985:
11986: sub current_machine_ids {
1.853 albertel 11987: return &machine_ids(&hostname($perlvar{'lonHostID'}));
11988: }
11989:
11990: sub machine_ids {
11991: my ($hostname) = @_;
11992: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 11993: my @ids;
1.888 albertel 11994: my %name_to_host = &all_names();
1.889 albertel 11995: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
11996: return @{ $name_to_host{$hostname} };
11997: }
11998: return;
1.31 www 11999: }
12000:
1.824 raeburn 12001: sub additional_machine_domains {
12002: my @domains;
12003: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
12004: while( my $line = <$fh>) {
12005: $line =~ s/\s//g;
12006: push(@domains,$line);
12007: }
12008: return @domains;
12009: }
12010:
12011: sub default_login_domain {
12012: my $domain = $perlvar{'lonDefDomain'};
12013: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
12014: foreach my $posdom (¤t_machine_domains(),
12015: &additional_machine_domains()) {
12016: if (lc($posdom) eq lc($testdomain)) {
12017: $domain=$posdom;
12018: last;
12019: }
12020: }
12021: return $domain;
12022: }
12023:
1.31 www 12024: # ------------------------------------------------------------- Declutters URLs
12025:
12026: sub declutter {
12027: my $thisfn=shift;
1.569 albertel 12028: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1261 raeburn 12029: unless ($thisfn=~m{^/home/httpd/html/priv/}) {
12030: $thisfn=~s{^/home/httpd/html}{};
12031: }
1.31 www 12032: $thisfn=~s/^\///;
1.697 albertel 12033: $thisfn=~s|^adm/wrapper/||;
12034: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 12035: $thisfn=~s/^res\///;
1.1172 bisitz 12036: $thisfn=~s/^priv\///;
1.1032 raeburn 12037: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
12038: $thisfn=~s/\?.+$//;
12039: }
1.268 www 12040: return $thisfn;
12041: }
12042:
12043: # ------------------------------------------------------------- Clutter up URLs
12044:
12045: sub clutter {
12046: my $thisfn='/'.&declutter(shift);
1.887 albertel 12047: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 12048: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 12049: $thisfn='/res'.$thisfn;
12050: }
1.1031 raeburn 12051: if ($thisfn !~m|^/adm|) {
12052: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 12053: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 12054: } else {
12055: my ($ext) = ($thisfn =~ /\.(\w+)$/);
12056: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 12057: if ($embstyle eq 'ssi'
12058: || ($embstyle eq 'hdn')
12059: || ($embstyle eq 'rat')
12060: || ($embstyle eq 'prv')
12061: || ($embstyle eq 'ign')) {
12062: #do nothing with these
12063: } elsif (($embstyle eq 'img')
1.695 albertel 12064: || ($embstyle eq 'emb')
12065: || ($embstyle eq 'wrp')) {
12066: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 12067: } elsif ($embstyle eq 'unk'
12068: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 12069: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 12070: } else {
1.718 www 12071: # &logthis("Got a blank emb style");
1.695 albertel 12072: }
1.694 albertel 12073: }
12074: }
1.31 www 12075: return $thisfn;
1.12 www 12076: }
12077:
1.787 albertel 12078: sub clutter_with_no_wrapper {
12079: my $uri = &clutter(shift);
12080: if ($uri =~ m-^/adm/-) {
12081: $uri =~ s-^/adm/wrapper/-/-;
12082: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
12083: }
12084: return $uri;
12085: }
12086:
1.557 albertel 12087: sub freeze_escape {
12088: my ($value)=@_;
12089: if (ref($value)) {
12090: $value=&nfreeze($value);
12091: return '__FROZEN__'.&escape($value);
12092: }
12093: return &escape($value);
12094: }
12095:
1.11 www 12096:
1.557 albertel 12097: sub thaw_unescape {
12098: my ($value)=@_;
12099: if ($value =~ /^__FROZEN__/) {
12100: substr($value,0,10,undef);
12101: $value=&unescape($value);
12102: return &thaw($value);
12103: }
12104: return &unescape($value);
12105: }
12106:
1.436 albertel 12107: sub correct_line_ends {
12108: my ($result)=@_;
12109: $$result =~s/\r\n/\n/mg;
12110: $$result =~s/\r/\n/mg;
1.415 albertel 12111: }
1.1 albertel 12112: # ================================================================ Main Program
12113:
1.184 www 12114: sub goodbye {
1.204 albertel 12115: &logthis("Starting Shut down");
1.443 albertel 12116: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 12117: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 12118: #converted
1.599 albertel 12119: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 12120: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
12121: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
12122: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 12123: #1.1 only
1.870 albertel 12124: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
12125: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
12126: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
12127: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
12128: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 12129: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
12130: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 12131: &flushcourselogs();
12132: &logthis("Shutting down");
12133: }
12134:
1.852 albertel 12135: sub get_dns {
1.1210 raeburn 12136: my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869 albertel 12137: if (!$ignore_cache) {
12138: my ($content,$cached)=
12139: &Apache::lonnet::is_cached_new('dns',$url);
12140: if ($cached) {
1.1210 raeburn 12141: &$func($content,$hashref);
1.869 albertel 12142: return;
12143: }
12144: }
12145:
12146: my %alldns;
1.852 albertel 12147: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
12148: foreach my $dns (<$config>) {
12149: next if ($dns !~ /^\^(\S*)/x);
1.979 raeburn 12150: my $line = $1;
12151: my ($host,$protocol) = split(/:/,$line);
12152: if ($protocol ne 'https') {
12153: $protocol = 'http';
12154: }
12155: $alldns{$host} = $protocol;
1.869 albertel 12156: }
12157: while (%alldns) {
1.1263 raeburn 12158: my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852 albertel 12159: my $ua=new LWP::UserAgent;
1.1134 raeburn 12160: $ua->timeout(30);
1.979 raeburn 12161: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 12162: my $response=$ua->request($request);
1.979 raeburn 12163: delete($alldns{$dns});
1.852 albertel 12164: next if ($response->is_error());
12165: my @content = split("\n",$response->content);
1.1210 raeburn 12166: unless ($nocache) {
1.1219 raeburn 12167: &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1210 raeburn 12168: }
12169: &$func(\@content,$hashref);
1.869 albertel 12170: return;
1.852 albertel 12171: }
12172: close($config);
1.871 albertel 12173: my $which = (split('/',$url))[3];
12174: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
12175: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 12176: my @content = <$config>;
1.1210 raeburn 12177: &$func(\@content,$hashref);
12178: return;
12179: }
12180:
12181: # ------------------------------------------------------Get DNS checksums file
1.1211 raeburn 12182: sub parse_dns_checksums_tab {
1.1210 raeburn 12183: my ($lines,$hashref) = @_;
1.1264 raeburn 12184: my $lonhost = $perlvar{'lonHostID'};
12185: my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1210 raeburn 12186: my $loncaparev = &get_server_loncaparev($machine_dom);
1.1264 raeburn 12187: my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
12188: my $webconfdir = '/etc/httpd/conf';
12189: if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
12190: $webconfdir = '/etc/apache2';
12191: } elsif ($distro =~ /^sles(\d+)$/) {
12192: if ($1 >= 10) {
12193: $webconfdir = '/etc/apache2';
12194: }
12195: } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
12196: if ($1 >= 10.0) {
12197: $webconfdir = '/etc/apache2';
12198: }
12199: }
1.1210 raeburn 12200: my ($release,$timestamp) = split(/\-/,$loncaparev);
12201: my (%chksum,%revnum);
12202: if (ref($lines) eq 'ARRAY') {
12203: chomp(@{$lines});
1.1238 raeburn 12204: my $version = shift(@{$lines});
12205: if ($version eq $release) {
1.1210 raeburn 12206: foreach my $line (@{$lines}) {
1.1238 raeburn 12207: my ($file,$version,$shasum) = split(/,/,$line);
1.1264 raeburn 12208: if ($file =~ m{^/etc/httpd/conf}) {
12209: if ($webconfdir eq '/etc/apache2') {
12210: $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
12211: }
12212: }
1.1238 raeburn 12213: $chksum{$file} = $shasum;
12214: $revnum{$file} = $version;
1.1210 raeburn 12215: }
12216: if (ref($hashref) eq 'HASH') {
12217: %{$hashref} = (
12218: sums => \%chksum,
12219: versions => \%revnum,
12220: );
12221: }
12222: }
12223: }
1.869 albertel 12224: return;
1.852 albertel 12225: }
1.1210 raeburn 12226:
12227: sub fetch_dns_checksums {
1.1238 raeburn 12228: my %checksums;
12229: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1260 raeburn 12230: my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1238 raeburn 12231: my ($release,$timestamp) = split(/\-/,$loncaparev);
12232: &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1211 raeburn 12233: \%checksums);
1.1210 raeburn 12234: return \%checksums;
12235: }
12236:
1.327 albertel 12237: # ------------------------------------------------------------ Read domain file
12238: {
1.852 albertel 12239: my $loaded;
1.846 albertel 12240: my %domain;
12241:
1.852 albertel 12242: sub parse_domain_tab {
12243: my ($lines) = @_;
12244: foreach my $line (@$lines) {
12245: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 12246:
1.846 albertel 12247: chomp($line);
1.852 albertel 12248: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 12249: my %this_domain;
12250: foreach my $field ('description', 'auth_def', 'auth_arg_def',
12251: 'lang_def', 'city', 'longi', 'lati',
12252: 'primary') {
12253: $this_domain{$field} = shift(@elements);
12254: }
12255: $domain{$name} = \%this_domain;
1.852 albertel 12256: }
12257: }
1.864 albertel 12258:
12259: sub reset_domain_info {
12260: undef($loaded);
12261: undef(%domain);
12262: }
12263:
1.852 albertel 12264: sub load_domain_tab {
1.869 albertel 12265: my ($ignore_cache) = @_;
12266: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852 albertel 12267: my $fh;
12268: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
12269: my @lines = <$fh>;
12270: &parse_domain_tab(\@lines);
1.448 albertel 12271: }
1.852 albertel 12272: close($fh);
12273: $loaded = 1;
1.327 albertel 12274: }
1.846 albertel 12275:
12276: sub domain {
1.852 albertel 12277: &load_domain_tab() if (!$loaded);
12278:
1.846 albertel 12279: my ($name,$what) = @_;
12280: return if ( !exists($domain{$name}) );
12281:
12282: if (!$what) {
12283: return $domain{$name}{'description'};
12284: }
12285: return $domain{$name}{$what};
12286: }
1.974 raeburn 12287:
12288: sub domain_info {
12289: &load_domain_tab() if (!$loaded);
12290: return %domain;
12291: }
12292:
1.327 albertel 12293: }
12294:
12295:
1.1 albertel 12296: # ------------------------------------------------------------- Read hosts file
12297: {
1.838 albertel 12298: my %hostname;
1.844 albertel 12299: my %hostdom;
1.845 albertel 12300: my %libserv;
1.852 albertel 12301: my $loaded;
1.888 albertel 12302: my %name_to_host;
1.1074 raeburn 12303: my %internetdom;
1.1107 raeburn 12304: my %LC_dns_serv;
1.852 albertel 12305:
12306: sub parse_hosts_tab {
12307: my ($file) = @_;
12308: foreach my $configline (@$file) {
12309: next if ($configline =~ /^(\#|\s*$ )/x);
1.1107 raeburn 12310: chomp($configline);
12311: if ($configline =~ /^\^/) {
12312: if ($configline =~ /^\^([\w.\-]+)/) {
12313: $LC_dns_serv{$1} = 1;
12314: }
12315: next;
12316: }
1.1074 raeburn 12317: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 12318: $name=~s/\s//g;
12319: if ($id && $domain && $role && $name) {
12320: $hostname{$id}=$name;
1.888 albertel 12321: push(@{$name_to_host{$name}}, $id);
1.852 albertel 12322: $hostdom{$id}=$domain;
12323: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 12324: if (defined($protocol)) {
12325: if ($protocol eq 'https') {
12326: $protocol{$id} = $protocol;
12327: } else {
12328: $protocol{$id} = 'http';
12329: }
1.968 raeburn 12330: } else {
1.969 raeburn 12331: $protocol{$id} = 'http';
1.968 raeburn 12332: }
1.1074 raeburn 12333: if (defined($intdom)) {
12334: $internetdom{$id} = $intdom;
12335: }
1.852 albertel 12336: }
12337: }
12338: }
1.864 albertel 12339:
12340: sub reset_hosts_info {
1.897 albertel 12341: &purge_remembered();
1.864 albertel 12342: &reset_domain_info();
12343: &reset_hosts_ip_info();
1.892 albertel 12344: undef(%name_to_host);
1.864 albertel 12345: undef(%hostname);
12346: undef(%hostdom);
12347: undef(%libserv);
12348: undef($loaded);
12349: }
1.1 albertel 12350:
1.852 albertel 12351: sub load_hosts_tab {
1.869 albertel 12352: my ($ignore_cache) = @_;
12353: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852 albertel 12354: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
12355: my @config = <$config>;
12356: &parse_hosts_tab(\@config);
12357: close($config);
12358: $loaded=1;
1.1 albertel 12359: }
1.852 albertel 12360:
1.838 albertel 12361: sub hostname {
1.852 albertel 12362: &load_hosts_tab() if (!$loaded);
12363:
1.838 albertel 12364: my ($lonid) = @_;
12365: return $hostname{$lonid};
12366: }
1.845 albertel 12367:
1.838 albertel 12368: sub all_hostnames {
1.852 albertel 12369: &load_hosts_tab() if (!$loaded);
12370:
1.838 albertel 12371: return %hostname;
12372: }
1.845 albertel 12373:
1.888 albertel 12374: sub all_names {
12375: &load_hosts_tab() if (!$loaded);
12376:
12377: return %name_to_host;
12378: }
12379:
1.974 raeburn 12380: sub all_host_domain {
12381: &load_hosts_tab() if (!$loaded);
12382: return %hostdom;
12383: }
12384:
1.845 albertel 12385: sub is_library {
1.852 albertel 12386: &load_hosts_tab() if (!$loaded);
12387:
1.845 albertel 12388: return exists($libserv{$_[0]});
12389: }
12390:
12391: sub all_library {
1.852 albertel 12392: &load_hosts_tab() if (!$loaded);
12393:
1.845 albertel 12394: return %libserv;
12395: }
12396:
1.1062 droeschl 12397: sub unique_library {
12398: #2x reverse removes all hostnames that appear more than once
12399: my %unique = reverse &all_library();
12400: return reverse %unique;
12401: }
12402:
1.841 albertel 12403: sub get_servers {
1.852 albertel 12404: &load_hosts_tab() if (!$loaded);
12405:
1.841 albertel 12406: my ($domain,$type) = @_;
12407: my %possible_hosts = ($type eq 'library') ? %libserv
12408: : %hostname;
12409: my %result;
1.842 albertel 12410: if (ref($domain) eq 'ARRAY') {
12411: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 12412: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 12413: $result{$host} = $hostname;
12414: }
12415: }
12416: } else {
12417: while ( my ($host,$hostname) = each(%possible_hosts)) {
12418: if ($hostdom{$host} eq $domain) {
12419: $result{$host} = $hostname;
12420: }
1.841 albertel 12421: }
12422: }
12423: return %result;
12424: }
1.845 albertel 12425:
1.1062 droeschl 12426: sub get_unique_servers {
12427: my %unique = reverse &get_servers(@_);
12428: return reverse %unique;
12429: }
12430:
1.844 albertel 12431: sub host_domain {
1.852 albertel 12432: &load_hosts_tab() if (!$loaded);
12433:
1.844 albertel 12434: my ($lonid) = @_;
12435: return $hostdom{$lonid};
12436: }
12437:
1.841 albertel 12438: sub all_domains {
1.852 albertel 12439: &load_hosts_tab() if (!$loaded);
12440:
1.841 albertel 12441: my %seen;
12442: my @uniq = grep(!$seen{$_}++, values(%hostdom));
12443: return @uniq;
12444: }
1.1074 raeburn 12445:
12446: sub internet_dom {
12447: &load_hosts_tab() if (!$loaded);
12448:
12449: my ($lonid) = @_;
12450: return $internetdom{$lonid};
12451: }
1.1107 raeburn 12452:
12453: sub is_LC_dns {
12454: &load_hosts_tab() if (!$loaded);
12455:
12456: my ($hostname) = @_;
12457: return exists($LC_dns_serv{$hostname});
12458: }
12459:
1.1 albertel 12460: }
12461:
1.847 albertel 12462: {
12463: my %iphost;
1.856 albertel 12464: my %name_to_ip;
12465: my %lonid_to_ip;
1.869 albertel 12466:
1.847 albertel 12467: sub get_hosts_from_ip {
12468: my ($ip) = @_;
12469: my %iphosts = &get_iphost();
12470: if (ref($iphosts{$ip})) {
12471: return @{$iphosts{$ip}};
12472: }
12473: return;
1.839 albertel 12474: }
1.864 albertel 12475:
12476: sub reset_hosts_ip_info {
12477: undef(%iphost);
12478: undef(%name_to_ip);
12479: undef(%lonid_to_ip);
12480: }
1.856 albertel 12481:
12482: sub get_host_ip {
12483: my ($lonid) = @_;
12484: if (exists($lonid_to_ip{$lonid})) {
12485: return $lonid_to_ip{$lonid};
12486: }
12487: my $name=&hostname($lonid);
12488: my $ip = gethostbyname($name);
12489: return if (!$ip || length($ip) ne 4);
12490: $ip=inet_ntoa($ip);
12491: $name_to_ip{$name} = $ip;
12492: $lonid_to_ip{$lonid} = $ip;
12493: return $ip;
12494: }
1.847 albertel 12495:
12496: sub get_iphost {
1.869 albertel 12497: my ($ignore_cache) = @_;
1.894 albertel 12498:
1.869 albertel 12499: if (!$ignore_cache) {
12500: if (%iphost) {
12501: return %iphost;
12502: }
12503: my ($ip_info,$cached)=
12504: &Apache::lonnet::is_cached_new('iphost','iphost');
12505: if ($cached) {
12506: %iphost = %{$ip_info->[0]};
12507: %name_to_ip = %{$ip_info->[1]};
12508: %lonid_to_ip = %{$ip_info->[2]};
12509: return %iphost;
12510: }
12511: }
1.894 albertel 12512:
12513: # get yesterday's info for fallback
12514: my %old_name_to_ip;
12515: my ($ip_info,$cached)=
12516: &Apache::lonnet::is_cached_new('iphost','iphost');
12517: if ($cached) {
12518: %old_name_to_ip = %{$ip_info->[1]};
12519: }
12520:
1.888 albertel 12521: my %name_to_host = &all_names();
12522: foreach my $name (keys(%name_to_host)) {
1.847 albertel 12523: my $ip;
12524: if (!exists($name_to_ip{$name})) {
12525: $ip = gethostbyname($name);
12526: if (!$ip || length($ip) ne 4) {
1.894 albertel 12527: if (defined($old_name_to_ip{$name})) {
12528: $ip = $old_name_to_ip{$name};
12529: &logthis("Can't find $name defaulting to old $ip");
12530: } else {
12531: &logthis("Name $name no IP found");
12532: next;
12533: }
12534: } else {
12535: $ip=inet_ntoa($ip);
1.847 albertel 12536: }
12537: $name_to_ip{$name} = $ip;
12538: } else {
12539: $ip = $name_to_ip{$name};
1.653 albertel 12540: }
1.888 albertel 12541: foreach my $id (@{ $name_to_host{$name} }) {
12542: $lonid_to_ip{$id} = $ip;
12543: }
12544: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 12545: }
1.1219 raeburn 12546: &do_cache_new('iphost','iphost',
12547: [\%iphost,\%name_to_ip,\%lonid_to_ip],
12548: 48*60*60);
1.869 albertel 12549:
1.847 albertel 12550: return %iphost;
1.598 albertel 12551: }
12552:
1.992 raeburn 12553: #
12554: # Given a DNS returns the loncapa host name for that DNS
12555: #
12556: sub host_from_dns {
12557: my ($dns) = @_;
12558: my @hosts;
12559: my $ip;
12560:
1.993 raeburn 12561: if (exists($name_to_ip{$dns})) {
1.992 raeburn 12562: $ip = $name_to_ip{$dns};
12563: }
12564: if (!$ip) {
12565: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
12566: if (length($ip) == 4) {
12567: $ip = &IO::Socket::inet_ntoa($ip);
12568: }
12569: }
12570: if ($ip) {
12571: @hosts = get_hosts_from_ip($ip);
12572: return $hosts[0];
12573: }
12574: return undef;
1.986 foxr 12575: }
1.992 raeburn 12576:
1.1074 raeburn 12577: sub get_internet_names {
12578: my ($lonid) = @_;
12579: return if ($lonid eq '');
12580: my ($idnref,$cached)=
12581: &Apache::lonnet::is_cached_new('internetnames',$lonid);
12582: if ($cached) {
12583: return $idnref;
12584: }
12585: my $ip = &get_host_ip($lonid);
12586: my @hosts = &get_hosts_from_ip($ip);
12587: my %iphost = &get_iphost();
12588: my (@idns,%seen);
12589: foreach my $id (@hosts) {
12590: my $dom = &host_domain($id);
12591: my $prim_id = &domain($dom,'primary');
12592: my $prim_ip = &get_host_ip($prim_id);
12593: next if ($seen{$prim_ip});
12594: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
12595: foreach my $id (@{$iphost{$prim_ip}}) {
12596: my $intdom = &internet_dom($id);
12597: unless (grep(/^\Q$intdom\E$/,@idns)) {
12598: push(@idns,$intdom);
12599: }
12600: }
12601: }
12602: $seen{$prim_ip} = 1;
12603: }
1.1219 raeburn 12604: return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074 raeburn 12605: }
12606:
1.986 foxr 12607: }
12608:
1.1079 raeburn 12609: sub all_loncaparevs {
1.1249 raeburn 12610: 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 12611: }
12612:
1.1227 raeburn 12613: # ---------------------------------------------------------- Read loncaparev table
12614: {
12615: sub load_loncaparevs {
12616: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
12617: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
12618: while (my $configline=<$config>) {
12619: chomp($configline);
12620: my ($hostid,$loncaparev)=split(/:/,$configline);
12621: $loncaparevs{$hostid}=$loncaparev;
12622: }
12623: close($config);
12624: }
12625: }
12626: }
12627: }
12628:
12629: # ---------------------------------------------------------- Read serverhostID table
12630: {
12631: sub load_serverhomeIDs {
12632: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
12633: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
12634: while (my $configline=<$config>) {
12635: chomp($configline);
12636: my ($name,$id)=split(/:/,$configline);
12637: $serverhomeIDs{$name}=$id;
12638: }
12639: close($config);
12640: }
12641: }
12642: }
12643: }
12644:
12645:
1.862 albertel 12646: BEGIN {
12647:
12648: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
12649: unless ($readit) {
12650: {
12651: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
12652: %perlvar = (%perlvar,%{$configvars});
12653: }
12654:
12655:
1.1 albertel 12656: # ------------------------------------------------------ Read spare server file
12657: {
1.448 albertel 12658: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 12659:
12660: while (my $configline=<$config>) {
12661: chomp($configline);
1.284 matthew 12662: if ($configline) {
1.784 albertel 12663: my ($host,$type) = split(':',$configline,2);
1.785 albertel 12664: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 12665: push(@{ $spareid{$type} }, $host);
1.1 albertel 12666: }
12667: }
1.448 albertel 12668: close($config);
1.1 albertel 12669: }
1.11 www 12670: # ------------------------------------------------------------ Read permissions
12671: {
1.448 albertel 12672: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 12673:
12674: while (my $configline=<$config>) {
1.448 albertel 12675: chomp($configline);
12676: if ($configline) {
12677: my ($role,$perm)=split(/ /,$configline);
12678: if ($perm ne '') { $pr{$role}=$perm; }
12679: }
1.11 www 12680: }
1.448 albertel 12681: close($config);
1.11 www 12682: }
12683:
12684: # -------------------------------------------- Read plain texts for permissions
12685: {
1.448 albertel 12686: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 12687:
12688: while (my $configline=<$config>) {
1.448 albertel 12689: chomp($configline);
12690: if ($configline) {
1.742 raeburn 12691: my ($short,@plain)=split(/:/,$configline);
12692: %{$prp{$short}} = ();
12693: if (@plain > 0) {
12694: $prp{$short}{'std'} = $plain[0];
12695: for (my $i=1; $i<@plain; $i++) {
12696: $prp{$short}{'alt'.$i} = $plain[$i];
12697: }
12698: }
1.448 albertel 12699: }
1.135 www 12700: }
1.448 albertel 12701: close($config);
1.135 www 12702: }
12703:
12704: # ---------------------------------------------------------- Read package table
12705: {
1.448 albertel 12706: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 12707:
12708: while (my $configline=<$config>) {
1.483 albertel 12709: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 12710: chomp($configline);
12711: my ($short,$plain)=split(/:/,$configline);
12712: my ($pack,$name)=split(/\&/,$short);
12713: if ($plain ne '') {
12714: $packagetab{$pack.'&'.$name.'&name'}=$name;
12715: $packagetab{$short}=$plain;
12716: }
1.11 www 12717: }
1.448 albertel 12718: close($config);
1.329 matthew 12719: }
12720:
1.1073 raeburn 12721: # ---------------------------------------------------------- Read loncaparev table
1.1227 raeburn 12722:
12723: &load_loncaparevs();
1.1073 raeburn 12724:
1.1074 raeburn 12725: # ---------------------------------------------------------- Read serverhostID table
12726:
1.1227 raeburn 12727: &load_serverhomeIDs();
12728:
12729: # ---------------------------------------------------------- Read releaseslist XML
1.1079 raeburn 12730: {
12731: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
12732: if (-e $file) {
12733: my $parser = HTML::LCParser->new($file);
12734: while (my $token = $parser->get_token()) {
12735: if ($token->[0] eq 'S') {
12736: my $item = $token->[1];
12737: my $name = $token->[2]{'name'};
12738: my $value = $token->[2]{'value'};
1.1285 raeburn 12739: my $valuematch = $token->[2]{'valuematch'};
12740: if ($item ne '' && $name ne '' && ($value ne '' || $valuematch ne '')) {
1.1079 raeburn 12741: my $release = $parser->get_text();
12742: $release =~ s/(^\s*|\s*$ )//gx;
1.1285 raeburn 12743: $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch} = $release;
1.1079 raeburn 12744: }
12745: }
12746: }
12747: }
1.1073 raeburn 12748: }
12749:
1.1138 raeburn 12750: # ---------------------------------------------------------- Read managers table
12751: {
12752: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
12753: if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
12754: while (my $configline=<$config>) {
12755: chomp($configline);
12756: next if ($configline =~ /^\#/);
12757: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
12758: $managerstab{$configline} = 1;
12759: }
12760: }
12761: close($config);
12762: }
12763: }
12764: }
12765:
1.329 matthew 12766: # ------------- set up temporary directory
12767: {
1.1117 foxr 12768: $tmpdir = LONCAPA::tempdir();
1.329 matthew 12769:
1.11 www 12770: }
12771:
1.794 albertel 12772: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
12773: 'compress_threshold'=> 20_000,
12774: });
1.185 www 12775:
1.281 www 12776: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 12777: $dumpcount=0;
1.958 www 12778: $locknum=0;
1.22 www 12779:
1.163 harris41 12780: &logtouch();
1.672 albertel 12781: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 12782: $readit=1;
1.564 albertel 12783: {
12784: use integer;
12785: my $test=(2**32)+1;
1.568 albertel 12786: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 12787: &logthis(" Detected 64bit platform ($_64bit)");
12788: }
1.195 www 12789: }
1.1 albertel 12790: }
1.179 www 12791:
1.1 albertel 12792: 1;
1.191 harris41 12793: __END__
12794:
1.243 albertel 12795: =pod
12796:
1.191 harris41 12797: =head1 NAME
12798:
1.243 albertel 12799: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 12800:
12801: =head1 SYNOPSIS
12802:
1.243 albertel 12803: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 12804:
12805: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
12806:
1.243 albertel 12807: Common parameters:
12808:
12809: =over 4
12810:
12811: =item *
12812:
12813: $uname : an internal username (if $cname expecting a course Id specifically)
12814:
12815: =item *
12816:
12817: $udom : a domain (if $cdom expecting a course's domain specifically)
12818:
12819: =item *
12820:
12821: $symb : a resource instance identifier
12822:
12823: =item *
12824:
12825: $namespace : the name of a .db file that contains the data needed or
12826: being set.
12827:
12828: =back
12829:
1.394 bowersj2 12830: =head1 OVERVIEW
1.191 harris41 12831:
1.394 bowersj2 12832: lonnet provides subroutines which interact with the
12833: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
12834: about classes, users, and resources.
1.243 albertel 12835:
12836: For many of these objects you can also use this to store data about
12837: them or modify them in various ways.
1.191 harris41 12838:
1.394 bowersj2 12839: =head2 Symbs
1.191 harris41 12840:
1.394 bowersj2 12841: To identify a specific instance of a resource, LON-CAPA uses symbols
12842: or "symbs"X<symb>. These identifiers are built from the URL of the
12843: map, the resource number of the resource in the map, and the URL of
12844: the resource itself. The latter is somewhat redundant, but might help
12845: if maps change.
12846:
12847: An example is
12848:
12849: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
12850:
12851: The respective map entry is
12852:
12853: <resource id="19" src="/res/msu/korte/tests/part12.problem"
12854: title="Problem 2">
12855: </resource>
12856:
12857: Symbs are used by the random number generator, as well as to store and
12858: restore data specific to a certain instance of for example a problem.
12859:
12860: =head2 Storing And Retrieving Data
12861:
12862: X<store()>X<cstore()>X<restore()>Three of the most important functions
12863: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
12864: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
12865: is is the non-critical message twin of cstore. These functions are for
12866: handlers to store a perl hash to a user's permanent data space in an
12867: easy manner, and to retrieve it again on another call. It is expected
12868: that a handler would use this once at the beginning to retrieve data,
12869: and then again once at the end to send only the new data back.
12870:
12871: The data is stored in the user's data directory on the user's
12872: homeserver under the ID of the course.
12873:
12874: The hash that is returned by restore will have all of the previous
12875: value for all of the elements of the hash.
12876:
12877: Example:
12878:
12879: #creating a hash
12880: my %hash;
12881: $hash{'foo'}='bar';
12882:
12883: #storing it
12884: &Apache::lonnet::cstore(\%hash);
12885:
12886: #changing a value
12887: $hash{'foo'}='notbar';
12888:
12889: #adding a new value
12890: $hash{'bar'}='foo';
12891: &Apache::lonnet::cstore(\%hash);
12892:
12893: #retrieving the hash
12894: my %history=&Apache::lonnet::restore();
12895:
12896: #print the hash
12897: foreach my $key (sort(keys(%history))) {
12898: print("\%history{$key} = $history{$key}");
12899: }
12900:
12901: Will print out:
1.191 harris41 12902:
1.394 bowersj2 12903: %history{1:foo} = bar
12904: %history{1:keys} = foo:timestamp
12905: %history{1:timestamp} = 990455579
12906: %history{2:bar} = foo
12907: %history{2:foo} = notbar
12908: %history{2:keys} = foo:bar:timestamp
12909: %history{2:timestamp} = 990455580
12910: %history{bar} = foo
12911: %history{foo} = notbar
12912: %history{timestamp} = 990455580
12913: %history{version} = 2
12914:
12915: Note that the special hash entries C<keys>, C<version> and
12916: C<timestamp> were added to the hash. C<version> will be equal to the
12917: total number of versions of the data that have been stored. The
12918: C<timestamp> attribute will be the UNIX time the hash was
12919: stored. C<keys> is available in every historical section to list which
12920: keys were added or changed at a specific historical revision of a
12921: hash.
12922:
12923: B<Warning>: do not store the hash that restore returns directly. This
12924: will cause a mess since it will restore the historical keys as if the
12925: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 12926:
1.394 bowersj2 12927: Calling convention:
1.191 harris41 12928:
1.1225 raeburn 12929: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1269 raeburn 12930: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191 harris41 12931:
1.394 bowersj2 12932: For more detailed information, see lonnet specific documentation.
1.191 harris41 12933:
1.394 bowersj2 12934: =head1 RETURN MESSAGES
1.191 harris41 12935:
1.394 bowersj2 12936: =over 4
1.191 harris41 12937:
1.394 bowersj2 12938: =item * B<con_lost>: unable to contact remote host
1.191 harris41 12939:
1.394 bowersj2 12940: =item * B<con_delayed>: unable to contact remote host, message will be delivered
12941: when the connection is brought back up
1.191 harris41 12942:
1.394 bowersj2 12943: =item * B<con_failed>: unable to contact remote host and unable to save message
12944: for later delivery
1.191 harris41 12945:
1.967 bisitz 12946: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 12947:
1.394 bowersj2 12948: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 12949: that was requested
1.191 harris41 12950:
1.243 albertel 12951: =back
1.191 harris41 12952:
1.243 albertel 12953: =head1 PUBLIC SUBROUTINES
1.191 harris41 12954:
1.243 albertel 12955: =head2 Session Environment Functions
1.191 harris41 12956:
1.243 albertel 12957: =over 4
1.191 harris41 12958:
1.394 bowersj2 12959: =item *
12960: X<appenv()>
1.949 raeburn 12961: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 12962: the user envirnoment file, and will be restored for each access this
1.620 albertel 12963: user makes during this session, also modifies the %env for the current
1.949 raeburn 12964: process. Optional rolesarrayref - if defined contains a reference to an array
12965: of roles which are exempt from the restriction on modifying user.role entries
12966: in the user's environment.db and in %env.
1.191 harris41 12967:
12968: =item *
1.394 bowersj2 12969: X<delenv()>
1.987 raeburn 12970: B<delenv($delthis,$regexp)>: removes all items from the session
12971: environment file that begin with $delthis. If the
12972: optional second arg - $regexp - is true, $delthis is treated as a
12973: regular expression, otherwise \Q$delthis\E is used.
12974: The values are also deleted from the current processes %env.
1.191 harris41 12975:
1.795 albertel 12976: =item * get_env_multiple($name)
12977:
12978: gets $name from the %env hash, it seemlessly handles the cases where multiple
12979: values may be defined and end up as an array ref.
12980:
12981: returns an array of values
12982:
1.243 albertel 12983: =back
12984:
12985: =head2 User Information
1.191 harris41 12986:
1.243 albertel 12987: =over 4
1.191 harris41 12988:
12989: =item *
1.394 bowersj2 12990: X<queryauthenticate()>
12991: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 12992: authentication scheme
12993:
12994: =item *
1.394 bowersj2 12995: X<authenticate()>
1.1073 raeburn 12996: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 12997: authenticate user from domain's lib servers (first use the current
12998: one). C<$upass> should be the users password.
1.1073 raeburn 12999: $checkdefauth is optional (value is 1 if a check should be made to
13000: authenticate user using default authentication method, and allow
13001: account creation if username does not have account in the domain).
13002: $clientcancheckhost is optional (value is 1 if checking whether the
13003: server can host will occur on the client side in lonauth.pm).
1.191 harris41 13004:
13005: =item *
1.394 bowersj2 13006: X<homeserver()>
13007: B<homeserver($uname,$udom)>: find the server which has
13008: the user's directory and files (there must be only one), this caches
13009: the answer, and also caches if there is a borken connection.
1.191 harris41 13010:
13011: =item *
1.394 bowersj2 13012: X<idget()>
13013: B<idget($udom,@ids)>: find the usernames behind a list of IDs
13014: (IDs are a unique resource in a domain, there must be only 1 ID per
13015: username, and only 1 username per ID in a specific domain) (returns
13016: hash: id=>name,id=>name)
1.191 harris41 13017:
13018: =item *
1.394 bowersj2 13019: X<idrget()>
13020: B<idrget($udom,@unames)>: find the IDs behind a list of
13021: usernames (returns hash: name=>id,name=>id)
1.191 harris41 13022:
13023: =item *
1.394 bowersj2 13024: X<idput()>
13025: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 13026:
13027: =item *
1.394 bowersj2 13028: X<rolesinit()>
1.1169 droeschl 13029: B<rolesinit($udom,$username)>: get user privileges.
13030: returns user role, first access and timer interval hashes
1.243 albertel 13031:
13032: =item *
1.1171 droeschl 13033: X<privileged()>
13034: B<privileged($username,$domain)>: returns a true if user has a
13035: privileged and active role (i.e. su or dc), false otherwise.
13036:
13037: =item *
1.551 albertel 13038: X<getsection()>
13039: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 13040: course $cname, return section name/number or '' for "not in course"
13041: and '-1' for "no section"
13042:
13043: =item *
1.394 bowersj2 13044: X<userenvironment()>
13045: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 13046: passed in @what from the requested user's environment, returns a hash
13047:
1.858 raeburn 13048: =item *
13049: X<userlog_query()>
1.859 albertel 13050: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
13051: activity.log file. %filters defines filters applied when parsing the
13052: log file. These can be start or end timestamps, or the type of action
13053: - log to look for Login or Logout events, check for Checkin or
13054: Checkout, role for role selection. The response is in the form
13055: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
13056: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 13057:
1.243 albertel 13058: =back
13059:
13060: =head2 User Roles
13061:
13062: =over 4
13063:
13064: =item *
13065:
1.1284 raeburn 13066: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege;
13067: returns codes for allowed actions.
13068:
13069: The first argument is required, all others are optional.
13070:
13071: $priv is the privilege being checked.
13072: $uri contains additional information about what is being checked for access (e.g.,
13073: URL, course ID etc.).
13074: $symb is the unique resource instance identifier in a course; if needed,
13075: but not provided, it will be retrieved via a call to &symbread().
13076: $role is the role for which a priv is being checked (only used if priv is evb).
13077: $clientip is the user's IP address (only used when checking for access to portfolio
13078: files).
13079: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
13080: prevents recursive calls to &allowed.
13081:
1.243 albertel 13082: F: full access
13083: U,I,K: authentication modes (cxx only)
13084: '': forbidden
13085: 1: user needs to choose course
13086: 2: browse allowed
1.766 albertel 13087: A: passphrase authentication needed
1.1284 raeburn 13088: B: access temporarily blocked because of a blocking event in a course.
1.243 albertel 13089:
13090: =item *
13091:
1.1192 raeburn 13092: constructaccess($url,$setpriv) : check for access to construction space URL
13093:
13094: See if the owner domain and name in the URL match those in the
13095: expected environment. If so, return three element list
13096: ($ownername,$ownerdomain,$ownerhome).
13097:
13098: Otherwise return the null string.
13099:
13100: If second argument 'setpriv' is true, it assigns the privileges,
13101: and returns the same three element list, unless the owner has
13102: blocked "ad hoc" Domain Coordinator access to the Author Space,
13103: in which case the null string is returned.
13104:
13105: =item *
13106:
1.243 albertel 13107: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
13108: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
13109: and course level
13110:
13111: =item *
13112:
1.988 raeburn 13113: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
13114: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 13115: $type is Course (default) or Community.
1.988 raeburn 13116: If $forcedefault evaluates to true, text returned will be default
13117: text for $type. Otherwise, if this is a course, the text returned
13118: will be a custom name for the role (if defined in the course's
13119: environment). If no custom name is defined the default is returned.
13120:
1.832 raeburn 13121: =item *
13122:
1.1219 raeburn 13123: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858 raeburn 13124: All arguments are optional. Returns a hash of a roles, either for
13125: co-author/assistant author roles for a user's Construction Space
1.906 albertel 13126: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 13127: In the hash, keys are set to colon-separated $uname,$udom,$role, and
13128: (optionally) if $withsec is true, a fourth colon-separated item - $section.
13129: For each key, value is set to colon-separated start and end times for
13130: the role. If no username and domain are specified, will default to
1.934 raeburn 13131: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 13132: of role statuses (active, future or previous), roles
13133: (e.g., cc,in, st etc.) and domains of the roles which can be used
13134: to restrict the list of roles reported. If no array ref is
13135: provided for types, will default to return only active roles.
1.834 albertel 13136:
1.1195 raeburn 13137: =item *
13138:
13139: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196 raeburn 13140: user: $uname:$udom has a role in the course: $cdom_$cnum.
13141:
13142: Additional optional arguments are: $type (if role checking is to be restricted
13143: to certain user status types -- previous (expired roles), active (currently
1.1195 raeburn 13144: available roles) or future (roles available in the future), and
13145: $hideprivileged -- if true will not report course roles for users who
1.1219 raeburn 13146: have active Domain Coordinator role in course's domain or in additional
13147: domains (specified in 'Domains to check for privileged users' in course
13148: environment -- set via: Course Settings -> Classlists and staff listing).
13149:
13150: =item *
13151:
13152: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
13153: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
13154: $possdomains and $possroles are optional array refs -- to domains to check and
13155: roles to check. If $possdomains is not specified, a dump will be done of the
13156: users' roles.db to check for a dc or su role in any domain. This can be
13157: time consuming if &privileged is called repeatedly (e.g., when displaying a
13158: classlist), so in such cases, supplying a $possdomains array is preferred, as
13159: this then allows &privileged_by_domain() to be used, which caches the identity
13160: of privileged users, eliminating the need for repeated calls to &dump().
13161:
13162: =item *
13163:
13164: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
13165: where the outer hash keys are domains specified in the $possdomains array ref,
13166: next inner hash keys are privileged roles specified in the $roles array ref,
13167: and the innermost hash contains key = value pairs for username:domain = end:start
13168: for active or future "privileged" users with that role in that domain. To avoid
13169: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
13170: innerhash are cached using priv_$role and $dom as the identifiers.
1.1195 raeburn 13171:
1.243 albertel 13172: =back
13173:
13174: =head2 User Modification
13175:
13176: =over 4
13177:
13178: =item *
13179:
1.957 raeburn 13180: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 13181: user for the level given by URL. Optional start and end dates (leave empty
13182: string or zero for "no date")
1.191 harris41 13183:
13184: =item *
13185:
1.243 albertel 13186: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
13187: change a users, password, possible return values are: ok,
13188: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
13189: refused
1.191 harris41 13190:
13191: =item *
13192:
1.243 albertel 13193: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 13194:
13195: =item *
13196:
1.1058 raeburn 13197: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
13198: $forceid,$desiredhome,$email,$inststatus,$candelete) :
13199:
13200: will update user information (firstname,middlename,lastname,generation,
13201: permanentemail), and if forceid is true, student/employee ID also.
13202: A user's institutional affiliation(s) can also be updated.
13203: User information fields will not be overwritten with empty entries
13204: unless the field is included in the $candelete array reference.
13205: This array is included when a single user is modified via "Manage Users",
13206: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 13207:
13208: =item *
13209:
1.286 matthew 13210: modifystudent
13211:
1.957 raeburn 13212: modify a student's enrollment and identification information.
1.1235 raeburn 13213: The course id is resolved based on the current user's environment.
13214: This means the invoking user must be a course coordinator or otherwise
1.286 matthew 13215: associated with a course.
13216:
1.297 matthew 13217: This call is essentially a wrapper for lonnet::modifyuser and
13218: lonnet::modify_student_enrollment
1.286 matthew 13219:
13220: Inputs:
13221:
13222: =over 4
13223:
1.957 raeburn 13224: =item B<$udom> Student's loncapa domain
1.286 matthew 13225:
1.957 raeburn 13226: =item B<$uname> Student's loncapa login name
1.286 matthew 13227:
1.964 bisitz 13228: =item B<$uid> Student/Employee ID
1.286 matthew 13229:
1.957 raeburn 13230: =item B<$umode> Student's authentication mode
1.286 matthew 13231:
1.957 raeburn 13232: =item B<$upass> Student's password
1.286 matthew 13233:
1.957 raeburn 13234: =item B<$first> Student's first name
1.286 matthew 13235:
1.957 raeburn 13236: =item B<$middle> Student's middle name
1.286 matthew 13237:
1.957 raeburn 13238: =item B<$last> Student's last name
1.286 matthew 13239:
1.957 raeburn 13240: =item B<$gene> Student's generation
1.286 matthew 13241:
1.957 raeburn 13242: =item B<$usec> Student's section in course
1.286 matthew 13243:
13244: =item B<$end> Unix time of the roles expiration
13245:
13246: =item B<$start> Unix time of the roles start date
13247:
13248: =item B<$forceid> If defined, allow $uid to be changed
13249:
13250: =item B<$desiredhome> server to use as home server for student
13251:
1.957 raeburn 13252: =item B<$email> Student's permanent e-mail address
13253:
13254: =item B<$type> Type of enrollment (auto or manual)
13255:
1.963 raeburn 13256: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
13257:
13258: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 13259:
1.963 raeburn 13260: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 13261:
1.963 raeburn 13262: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 13263:
1.1216 raeburn 13264: =item B<$inststatus> institutional status of user - : separated string of escaped status types
13265:
13266: =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 13267:
1.286 matthew 13268: =back
1.297 matthew 13269:
13270: =item *
13271:
13272: modify_student_enrollment
13273:
1.1235 raeburn 13274: Change a student's enrollment status in a class. The environment variable
1.297 matthew 13275: 'role.request.course' must be defined for this function to proceed.
13276:
13277: Inputs:
13278:
13279: =over 4
13280:
1.1235 raeburn 13281: =item $udom, student's domain
1.297 matthew 13282:
1.1235 raeburn 13283: =item $uname, student's name
1.297 matthew 13284:
1.1235 raeburn 13285: =item $uid, student's user id
1.297 matthew 13286:
1.1235 raeburn 13287: =item $first, student's first name
1.297 matthew 13288:
13289: =item $middle
13290:
13291: =item $last
13292:
13293: =item $gene
13294:
13295: =item $usec
13296:
13297: =item $end
13298:
13299: =item $start
13300:
1.957 raeburn 13301: =item $type
13302:
13303: =item $locktype
13304:
13305: =item $cid
13306:
13307: =item $selfenroll
13308:
13309: =item $context
13310:
1.1216 raeburn 13311: =item $credits, number of credits student will earn from this class
13312:
1.297 matthew 13313: =back
13314:
1.191 harris41 13315:
13316: =item *
13317:
1.243 albertel 13318: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
13319: custom role; give a custom role to a user for the level given by URL. Specify
13320: name and domain of role author, and role name
1.191 harris41 13321:
13322: =item *
13323:
1.243 albertel 13324: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 13325:
13326: =item *
13327:
1.243 albertel 13328: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
13329:
13330: =back
13331:
13332: =head2 Course Infomation
13333:
13334: =over 4
1.191 harris41 13335:
13336: =item *
13337:
1.1118 foxr 13338: coursedescription($courseid,$options) : returns a hash of information about the
1.631 albertel 13339: specified course id, including all environment settings for the
13340: course, the description of the course will be in the hash under the
13341: key 'description'
1.191 harris41 13342:
1.1118 foxr 13343: $options is an optional parameter that if supplied is a hash reference that controls
13344: what how this function works. It has the following key/values:
13345:
13346: =over 4
13347:
13348: =item freshen_cache
13349:
13350: If defined, and the environment cache for the course is valid, it is
13351: returned in the returned hash.
13352:
13353: =item one_time
13354:
13355: If defined, the last cache time is set to _now_
13356:
13357: =item user
13358:
13359: If defined, the supplied username is used instead of the current user.
13360:
13361:
13362: =back
13363:
1.191 harris41 13364: =item *
13365:
1.624 albertel 13366: resdata($name,$domain,$type,@which) : request for current parameter
13367: setting for a specific $type, where $type is either 'course' or 'user',
13368: @what should be a list of parameters to ask about. This routine caches
1.1235 raeburn 13369: answers for 10 minutes.
1.243 albertel 13370:
1.877 foxr 13371: =item *
13372:
13373: get_courseresdata($courseid, $domain) : dump the entire course resource
13374: data base, returning a hash that is keyed by the resource name and has
13375: values that are the resource value. I believe that the timestamps and
13376: versions are also returned.
13377:
1.1236 raeburn 13378: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
13379: supplemental content area. This routine caches the number of files for
13380: 10 minutes.
13381:
1.243 albertel 13382: =back
13383:
13384: =head2 Course Modification
13385:
13386: =over 4
1.191 harris41 13387:
13388: =item *
13389:
1.243 albertel 13390: writecoursepref($courseid,%prefs) : write preferences (environment
13391: database) for a course
1.191 harris41 13392:
13393: =item *
13394:
1.1011 raeburn 13395: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
13396:
13397: =item *
13398:
1.1038 raeburn 13399: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 13400:
1.1167 droeschl 13401: =item *
13402:
13403: is_course($courseid), is_course($cdom, $cnum)
13404:
13405: Accepts either a combined $courseid (in the form of domain_courseid) or the
13406: two component version $cdom, $cnum. It checks if the specified course exists.
13407:
13408: Returns:
13409: undef if the course doesn't exist, otherwise
13410: in scalar context the combined courseid.
13411: in list context the two components of the course identifier, domain and
13412: courseid.
13413:
1.243 albertel 13414: =back
13415:
13416: =head2 Resource Subroutines
13417:
13418: =over 4
1.191 harris41 13419:
13420: =item *
13421:
1.243 albertel 13422: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 13423:
13424: =item *
13425:
1.243 albertel 13426: repcopy($filename) : subscribes to the requested file, and attempts to
13427: replicate from the owning library server, Might return
1.607 raeburn 13428: 'unavailable', 'not_found', 'forbidden', 'ok', or
13429: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 13430: resource. Expects the local filesystem pathname
13431: (/home/httpd/html/res/....)
13432:
13433: =back
13434:
13435: =head2 Resource Information
13436:
13437: =over 4
1.191 harris41 13438:
13439: =item *
13440:
1.1228 raeburn 13441: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates
13442: and returns the value of a variety of different possible values,
13443: $varname should be a request string, and the other parameters can be
13444: used to specify who and what one is asking about. Ordinarily, $cid
13445: does not need to be specified, as it is retrived from
13446: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
13447: within lonuserstate::loadmap() when initializing a course, before
13448: $env{'request.course.id'} has been set, so it needs to be provided
13449: in that one case.
1.243 albertel 13450:
13451: Possible values for $varname are environment.lastname (or other item
13452: from the envirnment hash), user.name (or someother aspect about the
13453: user), resource.0.maxtries (or some other part and parameter of a
13454: resource)
1.204 albertel 13455:
13456: =item *
13457:
1.243 albertel 13458: directcondval($number) : get current value of a condition; reads from a state
13459: string
1.204 albertel 13460:
13461: =item *
13462:
1.243 albertel 13463: condval($condidx) : value of condition index based on state
1.204 albertel 13464:
13465: =item *
13466:
1.243 albertel 13467: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
13468: resource's metadata, $what should be either a specific key, or either
13469: 'keys' (to get a list of possible keys) or 'packages' to get a list of
13470: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
13471:
13472: this function automatically caches all requests
1.191 harris41 13473:
13474: =item *
13475:
1.243 albertel 13476: metadata_query($query,$custom,$customshow) : make a metadata query against the
13477: network of library servers; returns file handle of where SQL and regex results
13478: will be stored for query
1.191 harris41 13479:
13480: =item *
13481:
1.1282 raeburn 13482: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
13483: return symbolic list entry (all arguments optional).
13484:
13485: Args: filename is the filename (including path) for the file for which a symb
13486: is required; donotrecurse, if true will prevent calls to allowed() being made
13487: to check access status if more than one resource was found in the bighash
13488: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
13489: a randompick); ignorecachednull, if true will prevent a symb of '' being
13490: returned if $env{$cache_str} is defined as ''; checkforblock if true will
13491: cause possible symbs to be checked to determine if they are subject to content
13492: blocking, if so they will not be included as possible symbs; possibles is a
13493: ref to a hash, which, as a side effect, will be populated with all possible
13494: symbs (content blocking not tested).
13495:
1.243 albertel 13496: returns the data handle
1.191 harris41 13497:
13498: =item *
13499:
1.1190 raeburn 13500: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
13501: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582 albertel 13502: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190 raeburn 13503: on failure, user must be in a course, as it assumes the existence of
13504: the course initial hash, and uses $env('request.course.id'}. The third
13505: arg is an optional reference to a scalar. If this arg is passed in the
13506: call to symbverify, it will be set to 1 if the symb has been set to be
13507: encrypted; otherwise it will be null.
1.191 harris41 13508:
13509: =item *
13510:
1.243 albertel 13511: symbclean($symb) : removes versions numbers from a symb, returns the
13512: cleaned symb
1.191 harris41 13513:
13514: =item *
13515:
1.243 albertel 13516: is_on_map($uri) : checks if the $uri is somewhere on the current
13517: course map, user must be in a course for it to work.
1.191 harris41 13518:
13519: =item *
13520:
1.243 albertel 13521: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 13522:
13523: =item *
13524:
1.243 albertel 13525: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
13526: a random seed, all arguments are optional, if they aren't sent it uses the
13527: environment to derive them. Note: if symb isn't sent and it can't get one
13528: from &symbread it will use the current time as its return value
1.191 harris41 13529:
13530: =item *
13531:
1.243 albertel 13532: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
13533: unfakeable, receipt
1.191 harris41 13534:
13535: =item *
13536:
1.620 albertel 13537: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 13538:
13539: =item *
13540:
1.243 albertel 13541: countacc($url) : count the number of accesses to a given URL
1.191 harris41 13542:
13543: =item *
13544:
1.243 albertel 13545: 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 13546:
13547: =item *
13548:
1.243 albertel 13549: 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 13550:
13551: =item *
13552:
1.243 albertel 13553: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 13554:
13555: =item *
13556:
1.243 albertel 13557: devalidate($symb) : devalidate temporary spreadsheet calculations,
13558: forcing spreadsheet to reevaluate the resource scores next time.
13559:
1.1195 raeburn 13560: =item *
13561:
1.1196 raeburn 13562: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
13563: when viewing in course context.
1.1195 raeburn 13564:
1.1196 raeburn 13565: input: six args -- filename (decluttered), course number, course domain,
13566: url, symb (if registered) and group (if this is a
13567: group item -- e.g., bulletin board, group page etc.).
1.1195 raeburn 13568:
1.1196 raeburn 13569: output: array of five scalars --
1.1195 raeburn 13570: $cfile -- url for file editing if editable on current server
13571: $home -- homeserver of resource (i.e., for author if published,
13572: or course if uploaded.).
13573: $switchserver -- 1 if server switch will be needed.
1.1196 raeburn 13574: $forceedit -- 1 if icon/link should be to go to edit mode
13575: $forceview -- 1 if icon/link should be to go to view mode
1.1195 raeburn 13576:
13577: =item *
13578:
13579: is_course_upload($file,$cnum,$cdom)
13580:
13581: Used in course context to determine if current file was uploaded to
13582: the course (i.e., would be found in /userfiles/docs on the course's
13583: homeserver.
13584:
13585: input: 3 args -- filename (decluttered), course number and course domain.
13586: output: boolean -- 1 if file was uploaded.
13587:
1.243 albertel 13588: =back
13589:
13590: =head2 Storing/Retreiving Data
13591:
13592: =over 4
1.191 harris41 13593:
13594: =item *
13595:
1.1269 raeburn 13596: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
13597: permanently for this url; hashref needs to be given and should be a \%hashname;
13598: the remaining args aren't required and if they aren't passed or are '' they will
13599: be derived from the env (with the exception of $laststore, which is an
13600: optional arg used when a user's submission is stored in grading).
13601: $laststore is $version=$timestamp, where $version is the most recent version
13602: number retrieved for the corresponding $symb in the $namespace db file, and
13603: $timestamp is the timestamp for that transaction (UNIX time).
13604: $laststore is currently only passed when cstore() is called by
13605: structuretags::finalize_storage().
1.191 harris41 13606:
13607: =item *
13608:
1.1269 raeburn 13609: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
13610: but uses critical subroutine
1.191 harris41 13611:
13612: =item *
13613:
1.243 albertel 13614: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
13615: all args are optional
1.191 harris41 13616:
13617: =item *
13618:
1.717 albertel 13619: dumpstore($namespace,$udom,$uname,$regexp,$range) :
13620: dumps the complete (or key matching regexp) namespace into a hash
13621: ($udom, $uname, $regexp, $range are optional) for a namespace that is
13622: normally &store()ed into
13623:
13624: $range should be either an integer '100' (give me the first 100
13625: matching records)
13626: or be two integers sperated by a - with no spaces
13627: '30-50' (give me the 30th through the 50th matching
13628: records)
13629:
13630:
13631: =item *
13632:
1.1269 raeburn 13633: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717 albertel 13634: replaces a &store() version of data with a replacement set of data
13635: for a particular resource in a namespace passed in the $storehash hash
1.1269 raeburn 13636: reference. If $tolog is true, the transaction is logged in the courselog
13637: with an action=PUTSTORE.
1.717 albertel 13638:
13639: =item *
13640:
1.243 albertel 13641: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
13642: works very similar to store/cstore, but all data is stored in a
13643: temporary location and can be reset using tmpreset, $storehash should
13644: be a hash reference, returns nothing on success
1.191 harris41 13645:
13646: =item *
13647:
1.243 albertel 13648: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
13649: similar to restore, but all data is stored in a temporary location and
13650: can be reset using tmpreset. Returns a hash of values on success,
13651: error string otherwise.
1.191 harris41 13652:
13653: =item *
13654:
1.243 albertel 13655: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
13656: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 13657:
13658: =item *
13659:
1.243 albertel 13660: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13661: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 13662:
13663: =item *
13664:
1.243 albertel 13665: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
13666: namesp ($udom and $uname are optional)
1.191 harris41 13667:
13668: =item *
13669:
1.702 albertel 13670: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 13671: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 13672: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 13673:
1.702 albertel 13674: $range should be either an integer '100' (give me the first 100
13675: matching records)
13676: or be two integers sperated by a - with no spaces
13677: '30-50' (give me the 30th through the 50th matching
13678: records)
1.449 matthew 13679: =item *
13680:
13681: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
13682: $store can be a scalar, an array reference, or if the amount to be
13683: incremented is > 1, a hash reference.
13684:
13685: ($udom and $uname are optional)
1.191 harris41 13686:
13687: =item *
13688:
1.243 albertel 13689: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
13690: ($udom and $uname are optional)
1.191 harris41 13691:
13692: =item *
13693:
1.243 albertel 13694: cput($namespace,$storehash,$udom,$uname) : critical put
13695: ($udom and $uname are optional)
1.191 harris41 13696:
13697: =item *
13698:
1.748 albertel 13699: newput($namespace,$storehash,$udom,$uname) :
13700:
13701: Attempts to store the items in the $storehash, but only if they don't
13702: currently exist, if this succeeds you can be certain that you have
13703: successfully created a new key value pair in the $namespace db.
13704:
13705:
13706: Args:
13707: $namespace: name of database to store values to
13708: $storehash: hashref to store to the db
13709: $udom: (optional) domain of user containing the db
13710: $uname: (optional) name of user caontaining the db
13711:
13712: Returns:
13713: 'ok' -> succeeded in storing all keys of $storehash
13714: 'key_exists: <key>' -> failed to anything out of $storehash, as at
13715: least <key> already existed in the db (other
13716: requested keys may also already exist)
1.967 bisitz 13717: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 13718: 'con_lost' -> unable to contact request server
13719: 'refused' -> action was not allowed by remote machine
13720:
13721:
13722: =item *
13723:
1.243 albertel 13724: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13725: reference filled in from namesp (encrypts the return communication)
13726: ($udom and $uname are optional)
1.191 harris41 13727:
13728: =item *
13729:
1.243 albertel 13730: log($udom,$name,$home,$message) : write to permanent log for user; use
13731: critical subroutine
13732:
1.806 raeburn 13733: =item *
13734:
1.860 raeburn 13735: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
13736: array reference filled in from namespace found in domain level on either
13737: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 13738:
13739: =item *
13740:
1.860 raeburn 13741: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
13742: domain level either on specified domain server ($uhome) or primary domain
13743: server ($udom and $uhome are optional)
1.806 raeburn 13744:
1.943 raeburn 13745: =item *
13746:
1.1240 raeburn 13747: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
13748: for: authentication, language, quotas, timezone, date locale, and portal URL in
13749: the target domain.
13750:
13751: May also include additional key => value pairs for the following groups:
13752:
13753: =over
13754:
13755: =item
13756: disk quotas (MB allocated by default to portfolios and authoring spaces).
13757:
13758: =over
13759:
13760: =item defaultquota, authorquota
13761:
13762: =back
13763:
13764: =item
13765: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
13766: portfolio for users).
13767:
13768: =over
13769:
13770: =item
13771: aboutme, blog, webdav, portfolio
13772:
13773: =back
13774:
13775: =item
13776: requestcourses: ability to request courses, and how requests are processed.
13777:
13778: =over
13779:
13780: =item
1.1246 raeburn 13781: official, unofficial, community, textbook
1.1240 raeburn 13782:
13783: =back
13784:
13785: =item
13786: inststatus: types of institutional affiliation, and order in which they are displayed.
13787:
13788: =over
13789:
13790: =item
1.1256 raeburn 13791: inststatustypes, inststatusorder, inststatusguest
1.1240 raeburn 13792:
13793: =back
13794:
13795: =item
13796: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
13797: for course's uploaded content.
13798:
13799: =over
13800:
13801: =item
1.1246 raeburn 13802: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
13803: communityquota, textbookquota
1.1240 raeburn 13804:
13805: =back
13806:
13807: =item
13808: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
13809: on your servers.
13810:
13811: =over
13812:
13813: =item
13814: remotesessions, hostedsessions
13815:
13816: =back
13817:
13818: =back
13819:
13820: In cases where a domain coordinator has never used the "Set Domain Configuration"
13821: utility to create a configuration.db file on a domain's primary library server
13822: only the following domain defaults: auth_def, auth_arg_def, lang_def
13823: -- corresponding values are authentication type (internal, krb4, krb5,
13824: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
13825: will be available. Values are retrieved from cache (if current), unless the
13826: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
13827: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
13828:
13829: Typical usage:
1.943 raeburn 13830:
1.1240 raeburn 13831: %domdefaults = &get_domain_defaults($target_domain);
1.943 raeburn 13832:
1.243 albertel 13833: =back
13834:
13835: =head2 Network Status Functions
13836:
13837: =over 4
1.191 harris41 13838:
13839: =item *
13840:
1.1137 raeburn 13841: dirlist() : return directory list based on URI (first arg).
13842:
13843: Inputs: 1 required, 5 optional.
13844:
13845: =over
13846:
13847: =item
13848: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
13849:
13850: =item
13851: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
13852:
13853: =item
13854: $username - username of user/course to be listed. Extracted from $uri if absent.
13855:
13856: =item
13857: $getpropath - boolean: 1 if prepend path using &propath().
13858:
13859: =item
13860: $getuserdir - boolean: 1 if prepend path for "userfiles".
13861:
13862: =item
13863: $alternateRoot - path to prepend in place of path from $uri.
13864:
13865: =back
13866:
13867: Returns: Array of up to two items.
13868:
13869: =over
13870:
13871: a reference to an array of files/subdirectories
13872:
13873: =over
13874:
13875: Each element in the array of files/subdirectories is a & separated list of
13876: item name and the result of running stat on the item. If dirlist was requested
13877: for a file instead of a directory, the item name will be ''. For a directory
13878: listing, if the item is a metadata file, the element will end &N&M
13879: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
13880: default copyright set (1).
13881:
13882: =back
13883:
13884: a scalar containing error condition (if encountered).
13885:
13886: =over
13887:
13888: =item
13889: no_host (no homeserver identified for $username:$domain).
13890:
13891: =item
13892: no_such_host (server contacted for listing not identified as valid host).
13893:
13894: =item
13895: con_lost (connection to remote server failed).
13896:
13897: =item
13898: refused (invalid $username:$domain received on lond side).
13899:
13900: =item
13901: no_such_dir (directory at specified path on lond side does not exist).
13902:
13903: =item
13904: empty (directory at specified path on lond side is empty).
13905:
13906: =over
13907:
13908: This is currently not encountered because the &ls3, &ls2,
13909: &ls (_handler) routines on the lond side do not filter out
13910: . and .. from a directory listing.
13911:
13912: =back
13913:
13914: =back
13915:
13916: =back
1.191 harris41 13917:
13918: =item *
13919:
1.243 albertel 13920: spareserver() : find server with least workload from spare.tab
13921:
1.986 foxr 13922:
13923: =item *
13924:
13925: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
13926: if there is no corresponding loncapa host.
13927:
1.243 albertel 13928: =back
13929:
1.986 foxr 13930:
1.243 albertel 13931: =head2 Apache Request
13932:
13933: =over 4
1.191 harris41 13934:
13935: =item *
13936:
1.243 albertel 13937: ssi($url,%hash) : server side include, does a complete request cycle on url to
13938: localhost, posts hash
13939:
13940: =back
13941:
13942: =head2 Data to String to Data
13943:
13944: =over 4
1.191 harris41 13945:
13946: =item *
13947:
1.243 albertel 13948: hash2str(%hash) : convert a hash into a string complete with escaping and '='
13949: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 13950:
13951: =item *
13952:
1.243 albertel 13953: hashref2str($hashref) : convert a hashref into a string complete with
13954: escaping and '=' and '&' separators, supports elements that are
13955: arrayrefs and hashrefs
1.191 harris41 13956:
13957: =item *
13958:
1.243 albertel 13959: arrayref2str($arrayref) : convert an arrayref into a string complete
13960: with escaping and '&' separators, supports elements that are arrayrefs
13961: and hashrefs
1.191 harris41 13962:
13963: =item *
13964:
1.243 albertel 13965: str2hash($string) : convert string to hash using unescaping and
13966: splitting on '=' and '&', supports elements that are arrayrefs and
13967: hashrefs
1.191 harris41 13968:
13969: =item *
13970:
1.243 albertel 13971: str2array($string) : convert string to hash using unescaping and
13972: splitting on '&', supports elements that are arrayrefs and hashrefs
13973:
13974: =back
13975:
13976: =head2 Logging Routines
13977:
13978:
13979: These routines allow one to make log messages in the lonnet.log and
13980: lonnet.perm logfiles.
1.191 harris41 13981:
1.1119 foxr 13982: =over 4
13983:
1.191 harris41 13984: =item *
13985:
1.243 albertel 13986: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 13987:
13988: =item *
13989:
1.243 albertel 13990: logthis() : append message to the normal lonnet.log file, it gets
13991: preiodically rolled over and deleted.
1.191 harris41 13992:
13993: =item *
13994:
1.243 albertel 13995: logperm() : append a permanent message to lonnet.perm.log, this log
13996: file never gets deleted by any automated portion of the system, only
13997: messages of critical importance should go in here.
13998:
1.1119 foxr 13999:
1.243 albertel 14000: =back
14001:
14002: =head2 General File Helper Routines
14003:
14004: =over 4
1.191 harris41 14005:
14006: =item *
14007:
1.481 raeburn 14008: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
14009: (a) files in /uploaded
14010: (i) If a local copy of the file exists -
14011: compares modification date of local copy with last-modified date for
14012: definitive version stored on home server for course. If local copy is
14013: stale, requests a new version from the home server and stores it.
14014: If the original has been removed from the home server, then local copy
14015: is unlinked.
14016: (ii) If local copy does not exist -
14017: requests the file from the home server and stores it.
14018:
14019: If $caller is 'uploadrep':
14020: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
14021: for request for files originally uploaded via DOCS.
14022: - returns 'ok' if fresh local copy now available, -1 otherwise.
14023:
14024: Otherwise:
14025: This indicates a call from the content generation phase of the request.
14026: - returns the entire contents of the file or -1.
14027:
14028: (b) files in /res
14029: - returns the entire contents of a file or -1;
14030: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 14031:
1.712 albertel 14032:
14033: =item *
14034:
14035: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
14036: reference
14037:
14038: returns either a stat() list of data about the file or an empty list
14039: if the file doesn't exist or couldn't find out about it (connection
14040: problems or user unknown)
14041:
1.191 harris41 14042: =item *
14043:
1.243 albertel 14044: filelocation($dir,$file) : returns file system location of a file
14045: based on URI; meant to be "fairly clean" absolute reference, $dir is a
14046: directory that relative $file lookups are to looked in ($dir of /a/dir
14047: and a file of ../bob will become /a/bob)
1.191 harris41 14048:
14049: =item *
14050:
14051: hreflocation($dir,$file) : returns file system location or a URL; same as
14052: filelocation except for hrefs
14053:
14054: =item *
14055:
1.1261 raeburn 14056: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
14057: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191 harris41 14058:
1.243 albertel 14059: =back
14060:
1.608 albertel 14061: =head2 Usererfile file routines (/uploaded*)
14062:
14063: =over 4
14064:
14065: =item *
14066:
14067: userfileupload(): main rotine for putting a file in a user or course's
14068: filespace, arguments are,
14069:
1.620 albertel 14070: formname - required - this is the name of the element in $env where the
1.608 albertel 14071: filename, and the contents of the file to create/modifed exist
1.620 albertel 14072: the filename is in $env{'form.'.$formname.'.filename'} and the
14073: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 14074: context - if coursedoc, store the file in the course of the active role
14075: of the current user;
14076: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
14077: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 14078: subdir - required - subdirectory to put the file in under ../userfiles/
14079: if undefined, it will be placed in "unknown"
14080:
14081: (This routine calls clean_filename() to remove any dangerous
14082: characters from the filename, and then calls finuserfileupload() to
14083: complete the transaction)
14084:
14085: returns either the url of the uploaded file (/uploaded/....) if successful
14086: and /adm/notfound.html if unsuccessful
14087:
14088: =item *
14089:
14090: clean_filename(): routine for cleaing a filename up for storage in
14091: userfile space, argument is:
14092:
14093: filename - proposed filename
14094:
14095: returns: the new clean filename
14096:
14097: =item *
14098:
1.1090 raeburn 14099: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 14100: userspace, probably shouldn't be called directly
14101:
14102: docuname: username or courseid of destination for the file
14103: docudom: domain of user/course of destination for the file
14104: formname: same as for userfileupload()
1.1090 raeburn 14105: fname: filename (including subdirectories) for the file
14106: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
14107: allfiles: reference to hash used to store objects found by parser
14108: codebase: reference to hash used for codebases of java objects found by parser
14109: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
14110: thumbheight: height (pixels) of thumbnail to be created for uploaded image
14111: resizewidth: width to be used to resize image using resizeImage from ImageMagick
14112: resizeheight: height to be used to resize image using resizeImage from ImageMagick
14113: context: if 'overwrite', will move the uploaded file from its temporary location to
14114: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 14115: mimetype: reference to scalar to accommodate mime type determined
14116: from File::MMagic if $parser = parse.
1.608 albertel 14117:
14118: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 14119: and /adm/notfound.html if unsuccessful (or an error message if context
14120: was 'overwrite').
14121:
1.608 albertel 14122:
14123: =item *
14124:
14125: renameuserfile(): renames an existing userfile to a new name
14126:
14127: Args:
14128: docuname: username or courseid of destination for the file
14129: docudom: domain of user/course of destination for the file
14130: old: current file name (including any subdirs under userfiles)
14131: new: desired file name (including any subdirs under userfiles)
14132:
14133: =item *
14134:
14135: mkdiruserfile(): creates a directory is a userfiles dir
14136:
14137: Args:
14138: docuname: username or courseid of destination for the file
14139: docudom: domain of user/course of destination for the file
14140: dir: dir to create (including any subdirs under userfiles)
14141:
14142: =item *
14143:
14144: removeuserfile(): removes a file that exists in userfiles
14145:
14146: Args:
14147: docuname: username or courseid of destination for the file
14148: docudom: domain of user/course of destination for the file
14149: fname: filname to delete (including any subdirs under userfiles)
14150:
14151: =item *
14152:
14153: removeuploadedurl(): convience function for removeuserfile()
14154:
14155: Args:
14156: url: a full /uploaded/... url to delete
14157:
1.747 albertel 14158: =item *
14159:
14160: get_portfile_permissions():
14161: Args:
14162: domain: domain of user or course contain the portfolio files
14163: user: name of user or num of course contain the portfolio files
14164: Returns:
14165: hashref of a dump of the proper file_permissions.db
14166:
14167:
14168: =item *
14169:
14170: get_access_controls():
14171:
14172: Args:
14173: current_permissions: the hash ref returned from get_portfile_permissions()
14174: group: (optional) the group you want the files associated with
14175: file: (optional) the file you want access info on
14176:
14177: Returns:
1.749 raeburn 14178: a hash (keys are file names) of hashes containing
14179: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
14180: values are XML containing access control settings (see below)
1.747 albertel 14181:
14182: Internal notes:
14183:
1.749 raeburn 14184: access controls are stored in file_permissions.db as key=value pairs.
14185: key -> path to file/file_name\0uniqueID:scope_end_start
14186: where scope -> public,guest,course,group,domains or users.
14187: end -> UNIX time for end of access (0 -> no end date)
14188: start -> UNIX time for start of access
14189:
14190: value -> XML description of access control
14191: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
14192: <start></start>
14193: <end></end>
14194:
14195: <password></password> for scope type = guest
14196:
14197: <domain></domain> for scope type = course or group
14198: <number></number>
14199: <roles id="">
14200: <role></role>
14201: <access></access>
14202: <section></section>
14203: <group></group>
14204: </roles>
14205:
14206: <dom></dom> for scope type = domains
14207:
14208: <users> for scope type = users
14209: <user>
14210: <uname></uname>
14211: <udom></udom>
14212: </user>
14213: </users>
14214: </scope>
14215:
14216: Access data is also aggregated for each file in an additional key=value pair:
14217: key -> path to file/file_name\0accesscontrol
14218: value -> reference to hash
14219: hash contains key = value pairs
14220: where key = uniqueID:scope_end_start
14221: value = UNIX time record was last updated
14222:
14223: Used to improve speed of look-ups of access controls for each file.
14224:
14225: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
14226:
1.1198 raeburn 14227: =item *
14228:
1.749 raeburn 14229: modify_access_controls():
14230:
14231: Modifies access controls for a portfolio file
14232: Args
14233: 1. file name
14234: 2. reference to hash of required changes,
14235: 3. domain
14236: 4. username
14237: where domain,username are the domain of the portfolio owner
14238: (either a user or a course)
14239:
14240: Returns:
14241: 1. result of additions or updates ('ok' or 'error', with error message).
14242: 2. result of deletions ('ok' or 'error', with error message).
14243: 3. reference to hash of any new or updated access controls.
14244: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
14245: key = integer (inbound ID)
1.1198 raeburn 14246: value = uniqueID
14247:
14248: =item *
14249:
14250: get_timebased_id():
14251:
14252: Attempts to get a unique timestamp-based suffix for use with items added to a
14253: course via the Course Editor (e.g., folders, composite pages,
14254: group bulletin boards).
14255:
14256: Args: (first three required; six others optional)
14257:
14258: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
14259: docssequence, or name of group
14260:
14261: 2. keyid (alphanumeric): name of temporary locking key in hash,
14262: e.g., num, boardids
14263:
14264: 3. namespace: name of gdbm file used to store suffixes already assigned;
14265: file will be named nohist_namespace.db
14266:
14267: 4. cdom: domain of course; default is current course domain from %env
14268:
14269: 5. cnum: course number; default is current course number from %env
14270:
14271: 6. idtype: set to concat if an additional digit is to be appended to the
14272: unix timestamp to form the suffix, if the plain timestamp is already
14273: in use. Default is to not do this, but simply increment the unix
14274: timestamp by 1 until a unique key is obtained.
14275:
14276: 7. who: holder of locking key; defaults to user:domain for user.
14277:
14278: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
14279: retrying); default is 3.
14280:
14281: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
14282:
14283: Returns:
14284:
14285: 1. suffix obtained (numeric)
14286:
14287: 2. result of deleting locking key (ok if deleted, or lock never obtained)
14288:
14289: 3. error: contains (localized) error message if an error occurred.
14290:
1.747 albertel 14291:
1.608 albertel 14292: =back
14293:
1.243 albertel 14294: =head2 HTTP Helper Routines
14295:
14296: =over 4
14297:
1.191 harris41 14298: =item *
14299:
14300: escape() : unpack non-word characters into CGI-compatible hex codes
14301:
14302: =item *
14303:
14304: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
14305:
1.243 albertel 14306: =back
14307:
14308: =head1 PRIVATE SUBROUTINES
14309:
14310: =head2 Underlying communication routines (Shouldn't call)
14311:
14312: =over 4
14313:
14314: =item *
14315:
14316: subreply() : tries to pass a message to lonc, returns con_lost if incapable
14317:
14318: =item *
14319:
14320: reply() : uses subreply to send a message to remote machine, logs all failures
14321:
14322: =item *
14323:
14324: critical() : passes a critical message to another server; if cannot
14325: get through then place message in connection buffer directory and
14326: returns con_delayed, if incapable of saving message, returns
14327: con_failed
14328:
14329: =item *
14330:
14331: reconlonc() : tries to reconnect lonc client processes.
14332:
14333: =back
14334:
14335: =head2 Resource Access Logging
14336:
14337: =over 4
14338:
14339: =item *
14340:
14341: flushcourselogs() : flush (save) buffer logs and access logs
14342:
14343: =item *
14344:
14345: courselog($what) : save message for course in hash
14346:
14347: =item *
14348:
14349: courseacclog($what) : save message for course using &courselog(). Perform
14350: special processing for specific resource types (problems, exams, quizzes, etc).
14351:
1.191 harris41 14352: =item *
14353:
14354: goodbye() : flush course logs and log shutting down; it is called in srm.conf
14355: as a PerlChildExitHandler
1.243 albertel 14356:
14357: =back
14358:
14359: =head2 Other
14360:
14361: =over 4
14362:
14363: =item *
14364:
14365: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 14366:
14367: =back
14368:
14369: =cut
1.877 foxr 14370:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>