Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1308
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1308 ! raeburn 4: # $Id: lonnet.pm,v 1.1307 2016/04/21 00:36:17 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.1289 damieng 95: use Time::HiRes qw( sleep 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.1288 damieng 108: my $max_connection_retries = 20; # 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.
1.1289 damieng 378: sleep(0.1);
1.549 foxr 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.1289 damieng 396: sleep(0.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: if ($lonid) {
1.1295 raeburn 426: my $hostname = &hostname($lonid);
1.891 albertel 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.1295 raeburn 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') {
1.1295 raeburn 472: &reconlonc($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: }
1.1288 damieng 489: sleep 1;
1.1 albertel 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);
1.1307 raeburn 1291: my $domneedscache;
1.1129 raeburn 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.1307 raeburn 1306: } else {
1307: $domneedscache = $dom_in_use;
1.1129 raeburn 1308: }
1309: }
1310: if (ref($result) eq 'HASH') {
1.1191 raeburn 1311: ($is_balancer,$currtargets,$currrules) =
1312: &check_balancer_result($result,@hosts);
1.1129 raeburn 1313: if ($is_balancer) {
1314: if (ref($currrules) eq 'HASH') {
1315: if ($homeintdom) {
1316: if ($uname ne '') {
1317: if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
1318: my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
1319: if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
1320: $rule_in_effect = $currrules->{'_LC_author'};
1321: } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
1322: $rule_in_effect = $currrules->{'_LC_adv'}
1323: }
1324: }
1325: if ($rule_in_effect eq '') {
1326: my %userenv = &userenvironment($udom,$uname,'inststatus');
1327: if ($userenv{'inststatus'} ne '') {
1328: my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
1329: my ($othertitle,$usertypes,$types) =
1330: &Apache::loncommon::sorted_inst_types($udom);
1331: if (ref($types) eq 'ARRAY') {
1332: foreach my $type (@{$types}) {
1333: if (grep(/^\Q$type\E$/,@statuses)) {
1334: if (exists($currrules->{$type})) {
1335: $rule_in_effect = $currrules->{$type};
1336: }
1337: }
1338: }
1339: }
1340: } else {
1341: if (exists($currrules->{'default'})) {
1342: $rule_in_effect = $currrules->{'default'};
1343: }
1344: }
1345: }
1346: } else {
1347: if (exists($currrules->{'default'})) {
1348: $rule_in_effect = $currrules->{'default'};
1349: }
1350: }
1351: } else {
1352: if ($currrules->{'_LC_external'} ne '') {
1353: $rule_in_effect = $currrules->{'_LC_external'};
1354: }
1355: }
1356: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1357: $uname,$udom);
1358: }
1359: }
1360: } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1239 raeburn 1361: ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129 raeburn 1362: unless (defined($cached)) {
1363: my %domconfig =
1364: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
1365: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1307 raeburn 1366: $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
1367: } else {
1368: $domneedscache = $serverhomedom;
1.1129 raeburn 1369: }
1370: }
1371: if (ref($result) eq 'HASH') {
1.1191 raeburn 1372: ($is_balancer,$currtargets,$currrules) =
1373: &check_balancer_result($result,@hosts);
1374: if ($is_balancer) {
1.1129 raeburn 1375: if (ref($currrules) eq 'HASH') {
1376: if ($currrules->{'_LC_internetdom'} ne '') {
1377: $rule_in_effect = $currrules->{'_LC_internetdom'};
1378: }
1379: }
1380: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1381: $uname,$udom);
1382: }
1383: } else {
1384: if ($perlvar{'lonBalancer'} eq 'yes') {
1385: $is_balancer = 1;
1386: $offloadto = &this_host_spares($dom_in_use);
1387: }
1.1307 raeburn 1388: unless (defined($cached)) {
1389: $domneedscache = $serverhomedom;
1390: }
1.1129 raeburn 1391: }
1392: } else {
1393: if ($perlvar{'lonBalancer'} eq 'yes') {
1394: $is_balancer = 1;
1395: $offloadto = &this_host_spares($dom_in_use);
1396: }
1.1307 raeburn 1397: unless (defined($cached)) {
1398: $domneedscache = $serverhomedom;
1399: }
1400: }
1401: if ($domneedscache) {
1402: &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129 raeburn 1403: }
1.1176 raeburn 1404: if ($is_balancer) {
1405: my $lowest_load = 30000;
1406: if (ref($offloadto) eq 'HASH') {
1407: if (ref($offloadto->{'primary'}) eq 'ARRAY') {
1408: foreach my $try_server (@{$offloadto->{'primary'}}) {
1409: ($otherserver,$lowest_load) =
1410: &compare_server_load($try_server,$otherserver,$lowest_load);
1411: }
1.1129 raeburn 1412: }
1.1176 raeburn 1413: my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129 raeburn 1414:
1.1176 raeburn 1415: if (!$found_server) {
1416: if (ref($offloadto->{'default'}) eq 'ARRAY') {
1417: foreach my $try_server (@{$offloadto->{'default'}}) {
1418: ($otherserver,$lowest_load) =
1419: &compare_server_load($try_server,$otherserver,$lowest_load);
1420: }
1421: }
1422: }
1423: } elsif (ref($offloadto) eq 'ARRAY') {
1424: if (@{$offloadto} == 1) {
1425: $otherserver = $offloadto->[0];
1426: } elsif (@{$offloadto} > 1) {
1427: foreach my $try_server (@{$offloadto}) {
1.1129 raeburn 1428: ($otherserver,$lowest_load) =
1429: &compare_server_load($try_server,$otherserver,$lowest_load);
1430: }
1431: }
1432: }
1.1176 raeburn 1433: if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
1434: $is_balancer = 0;
1435: if ($uname ne '' && $udom ne '') {
1436: if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1437:
1438: &appenv({'user.loadbalexempt' => $lonhost,
1439: 'user.loadbalcheck.time' => time});
1440: }
1.1129 raeburn 1441: }
1442: }
1443: }
1444: return ($is_balancer,$otherserver);
1445: }
1446:
1.1191 raeburn 1447: sub check_balancer_result {
1448: my ($result,@hosts) = @_;
1449: my ($is_balancer,$currtargets,$currrules);
1450: if (ref($result) eq 'HASH') {
1451: if ($result->{'lonhost'} ne '') {
1452: my $currbalancer = $result->{'lonhost'};
1453: if (grep(/^\Q$currbalancer\E$/,@hosts)) {
1454: $is_balancer = 1;
1455: $currtargets = $result->{'targets'};
1456: $currrules = $result->{'rules'};
1457: }
1458: } else {
1459: foreach my $key (keys(%{$result})) {
1460: if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
1461: (ref($result->{$key}) eq 'HASH')) {
1462: $is_balancer = 1;
1463: $currrules = $result->{$key}{'rules'};
1464: $currtargets = $result->{$key}{'targets'};
1465: last;
1466: }
1467: }
1468: }
1469: }
1470: return ($is_balancer,$currtargets,$currrules);
1471: }
1472:
1.1129 raeburn 1473: sub get_loadbalancer_targets {
1474: my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
1475: my $offloadto;
1.1175 raeburn 1476: if ($rule_in_effect eq 'none') {
1477: return [$perlvar{'lonHostID'}];
1478: } elsif ($rule_in_effect eq '') {
1.1129 raeburn 1479: $offloadto = $currtargets;
1480: } else {
1481: if ($rule_in_effect eq 'homeserver') {
1482: my $homeserver = &homeserver($uname,$udom);
1483: if ($homeserver ne 'no_host') {
1484: $offloadto = [$homeserver];
1485: }
1486: } elsif ($rule_in_effect eq 'externalbalancer') {
1487: my %domconfig =
1488: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1489: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1490: if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
1491: if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
1492: $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
1493: }
1494: }
1495: } else {
1.1178 raeburn 1496: my %servers = &internet_dom_servers($udom);
1.1129 raeburn 1497: my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
1498: if (&hostname($remotebalancer) ne '') {
1499: $offloadto = [$remotebalancer];
1500: }
1501: }
1502: } elsif (&hostname($rule_in_effect) ne '') {
1503: $offloadto = [$rule_in_effect];
1504: }
1505: }
1506: return $offloadto;
1507: }
1508:
1.1127 raeburn 1509: sub internet_dom_servers {
1510: my ($dom) = @_;
1511: my (%uniqservers,%servers);
1512: my $primaryserver = &hostname(&domain($dom,'primary'));
1513: my @machinedoms = &machine_domains($primaryserver);
1514: foreach my $mdom (@machinedoms) {
1515: my %currservers = %servers;
1516: my %server = &get_servers($mdom);
1517: %servers = (%currservers,%server);
1518: }
1519: my %by_hostname;
1520: foreach my $id (keys(%servers)) {
1521: push(@{$by_hostname{$servers{$id}}},$id);
1522: }
1523: foreach my $hostname (sort(keys(%by_hostname))) {
1524: if (@{$by_hostname{$hostname}} > 1) {
1525: my $match = 0;
1526: foreach my $id (@{$by_hostname{$hostname}}) {
1527: if (&host_domain($id) eq $dom) {
1528: $uniqservers{$id} = $hostname;
1529: $match = 1;
1530: }
1531: }
1532: unless ($match) {
1533: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1534: }
1535: } else {
1536: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1537: }
1538: }
1539: return %uniqservers;
1540: }
1541:
1.1 albertel 1542: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 1543:
1.599 albertel 1544: my %homecache;
1.1 albertel 1545: sub homeserver {
1.230 stredwic 1546: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 1547: my $index="$uname:$udom";
1.426 albertel 1548:
1.599 albertel 1549: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 1550:
1551: my %servers = &get_servers($udom,'library');
1552: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 1553: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 1554: exists($badServerCache{$tryserver}));
1.841 albertel 1555:
1556: my $answer=reply("home:$udom:$uname",$tryserver);
1557: if ($answer eq 'found') {
1558: delete($badServerCache{$tryserver});
1559: return $homecache{$index}=$tryserver;
1560: } elsif ($answer eq 'no_host') {
1561: $badServerCache{$tryserver}=1;
1562: }
1.1 albertel 1563: }
1564: return 'no_host';
1.70 www 1565: }
1566:
1.1300 raeburn 1567: # ----- Find the usernames behind a list of student/employee IDs or clicker IDs
1.70 www 1568:
1569: sub idget {
1.1300 raeburn 1570: my ($udom,$idsref,$namespace)=@_;
1.70 www 1571: my %returnhash=();
1.1300 raeburn 1572: my @ids=();
1573: if (ref($idsref) eq 'ARRAY') {
1574: @ids = @{$idsref};
1575: } else {
1576: return %returnhash;
1577: }
1578: if ($namespace eq '') {
1579: $namespace = 'ids';
1580: }
1.70 www 1581:
1.841 albertel 1582: my %servers = &get_servers($udom,'library');
1583: foreach my $tryserver (keys(%servers)) {
1.1299 raeburn 1584: my $idlist=join('&', map { &escape($_); } @ids);
1.1300 raeburn 1585: if ($namespace eq 'ids') {
1586: $idlist=~tr/A-Z/a-z/;
1587: }
1588: my $reply;
1589: if ($namespace eq 'ids') {
1590: $reply=&reply("idget:$udom:".$idlist,$tryserver);
1591: } else {
1592: $reply=&reply("getdom:$udom:$namespace:$idlist",$tryserver);
1593: }
1.841 albertel 1594: my @answer=();
1595: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1596: @answer=split(/\&/,$reply);
1597: } ;
1598: my $i;
1599: for ($i=0;$i<=$#ids;$i++) {
1600: if ($answer[$i]) {
1.1299 raeburn 1601: $returnhash{$ids[$i]}=&unescape($answer[$i]);
1.1300 raeburn 1602: }
1.841 albertel 1603: }
1.1300 raeburn 1604: }
1.70 www 1605: return %returnhash;
1606: }
1607:
1608: # ------------------------------------- Find the IDs behind a list of usernames
1609:
1610: sub idrget {
1611: my ($udom,@unames)=@_;
1612: my %returnhash=();
1.800 albertel 1613: foreach my $uname (@unames) {
1614: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 1615: }
1.70 www 1616: return %returnhash;
1617: }
1618:
1.1300 raeburn 1619: # Store away a list of names and associated student/employee IDs or clicker IDs
1.70 www 1620:
1621: sub idput {
1.1300 raeburn 1622: my ($udom,$idsref,$uhom,$namespace)=@_;
1.70 www 1623: my %servers=();
1.1300 raeburn 1624: my %ids=();
1625: my %byid = ();
1626: if (ref($idsref) eq 'HASH') {
1627: %ids=%{$idsref};
1628: }
1629: if ($namespace eq '') {
1630: $namespace = 'ids';
1631: }
1.800 albertel 1632: foreach my $uname (keys(%ids)) {
1633: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1.1300 raeburn 1634: if ($uhom eq '') {
1635: $uhom=&homeserver($uname,$udom);
1636: }
1.70 www 1637: if ($uhom ne 'no_host') {
1.800 albertel 1638: my $esc_unam=&escape($uname);
1.1300 raeburn 1639: if ($namespace eq 'ids') {
1640: my $id=&escape($ids{$uname});
1641: $id=~tr/A-Z/a-z/;
1642: my $esc_unam=&escape($uname);
1643: $servers{$uhom}.=$id.'='.$esc_unam.'&';
1.70 www 1644: } else {
1.1300 raeburn 1645: my @currids = split(/,/,$ids{$uname});
1646: foreach my $id (@currids) {
1647: $byid{$uhom}{$id} .= $uname.',';
1648: }
1649: }
1650: }
1651: }
1652: if ($namespace eq 'clickers') {
1653: foreach my $server (keys(%byid)) {
1654: if (ref($byid{$server}) eq 'HASH') {
1655: foreach my $id (keys(%{$byid{$server}})) {
1656: $byid{$server} =~ s/,$//;
1657: $servers{$uhom}.=&escape($id).'='.&escape($byid{$server}).'&';
1658: }
1.70 www 1659: }
1660: }
1.191 harris41 1661: }
1.800 albertel 1662: foreach my $server (keys(%servers)) {
1.1300 raeburn 1663: $servers{$server} =~ s/\&$//;
1664: if ($namespace eq 'ids') {
1665: &critical('idput:'.$udom.':'.$servers{$server},$server);
1666: } else {
1667: &critical('updateclickers:'.$udom.':add:'.$servers{$server},$server);
1668: }
1.191 harris41 1669: }
1.344 www 1670: }
1671:
1.1300 raeburn 1672: # ------------- Delete unwanted student/employee IDs or clicker IDs from domain
1.1231 raeburn 1673:
1674: sub iddel {
1.1300 raeburn 1675: my ($udom,$idshashref,$uhome,$namespace)=@_;
1.1231 raeburn 1676: my %result=();
1.1300 raeburn 1677: my %ids=();
1678: my %byid = ();
1679: if (ref($idshashref) eq 'HASH') {
1680: %ids=%{$idshashref};
1681: } else {
1.1231 raeburn 1682: return %result;
1683: }
1.1300 raeburn 1684: if ($namespace eq '') {
1685: $namespace = 'ids';
1686: }
1.1231 raeburn 1687: my %servers=();
1.1300 raeburn 1688: while (my ($id,$unamestr) = each(%ids)) {
1689: if ($namespace eq 'ids') {
1690: my $uhom = $uhome;
1691: if ($uhom eq '') {
1692: $uhom=&homeserver($unamestr,$udom);
1693: }
1694: if ($uhom ne 'no_host') {
1695: $servers{$uhom}.='&'.&escape($id);
1696: }
1697: } else {
1698: my @curritems = split(/,/,$ids{$id});
1699: foreach my $uname (@curritems) {
1700: my $uhom = $uhome;
1701: if ($uhom eq '') {
1702: $uhom=&homeserver($uname,$udom);
1703: }
1704: if ($uhom ne 'no_host') {
1705: $byid{$uhom}{$id} .= $uname.',';
1706: }
1707: }
1.1231 raeburn 1708: }
1.1300 raeburn 1709: }
1710: if ($namespace eq 'clickers') {
1711: foreach my $server (keys(%byid)) {
1712: if (ref($byid{$server}) eq 'HASH') {
1713: foreach my $id (keys(%{$byid{$server}})) {
1714: $byid{$server}{$id} =~ s/,$//;
1715: $servers{$server}.=&escape($id).'='.&escape($byid{$server}{$id}).'&';
1716: }
1.1231 raeburn 1717: }
1718: }
1719: }
1720: foreach my $server (keys(%servers)) {
1.1300 raeburn 1721: $servers{$server} =~ s/\&$//;
1722: if ($namespace eq 'ids') {
1723: $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
1724: } elsif ($namespace eq 'clickers') {
1725: $result{$server} = &critical('updateclickers:'.$udom.':del:'.$servers{$server},$server);
1726: }
1.1231 raeburn 1727: }
1728: return %result;
1729: }
1730:
1.1300 raeburn 1731: # ----- Update clicker ID-to-username look-ups in clickers.db on library server
1732:
1733: sub updateclickers {
1734: my ($udom,$action,$idshashref,$uhome,$critical) = @_;
1735: my %clickers;
1736: if (ref($idshashref) eq 'HASH') {
1737: %clickers=%{$idshashref};
1738: } else {
1739: return;
1740: }
1741: my $items='';
1742: foreach my $item (keys(%clickers)) {
1743: $items.=&escape($item).'='.&escape($clickers{$item}).'&';
1744: }
1745: $items=~s/\&$//;
1746: my $request = "updateclickers:$udom:$action:$items";
1747: if ($critical) {
1748: return &critical($request,$uhome);
1749: } else {
1750: return &reply($request,$uhome);
1751: }
1752: }
1753:
1.1023 raeburn 1754: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 1755: sub dump_dom {
1.1165 droeschl 1756: my ($namespace, $udom, $regexp) = @_;
1757:
1758: $udom ||= $env{'user.domain'};
1759:
1760: return () unless $udom;
1761:
1762: return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012 raeburn 1763: }
1764:
1.1023 raeburn 1765: # ------------------------------------------ get items from domain db files
1.806 raeburn 1766:
1767: sub get_dom {
1.860 raeburn 1768: my ($namespace,$storearr,$udom,$uhome)=@_;
1.1267 raeburn 1769: return if ($udom eq 'public');
1.806 raeburn 1770: my $items='';
1771: foreach my $item (@$storearr) {
1772: $items.=&escape($item).'&';
1773: }
1774: $items=~s/\&$//;
1.860 raeburn 1775: if (!$udom) {
1776: $udom=$env{'user.domain'};
1.1267 raeburn 1777: return if ($udom eq 'public');
1.860 raeburn 1778: if (defined(&domain($udom,'primary'))) {
1779: $uhome=&domain($udom,'primary');
1780: } else {
1.874 albertel 1781: undef($uhome);
1.860 raeburn 1782: }
1783: } else {
1784: if (!$uhome) {
1785: if (defined(&domain($udom,'primary'))) {
1786: $uhome=&domain($udom,'primary');
1787: }
1788: }
1789: }
1790: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1791: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866 raeburn 1792: my %returnhash;
1.875 albertel 1793: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 1794: return %returnhash;
1795: }
1.806 raeburn 1796: my @pairs=split(/\&/,$rep);
1797: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1798: return @pairs;
1799: }
1800: my $i=0;
1801: foreach my $item (@$storearr) {
1802: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1803: $i++;
1804: }
1805: return %returnhash;
1806: } else {
1.880 banghart 1807: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 1808: }
1809: }
1810:
1811: # -------------------------------------------- put items in domain db files
1812:
1813: sub put_dom {
1.860 raeburn 1814: my ($namespace,$storehash,$udom,$uhome)=@_;
1815: if (!$udom) {
1816: $udom=$env{'user.domain'};
1817: if (defined(&domain($udom,'primary'))) {
1818: $uhome=&domain($udom,'primary');
1819: } else {
1.874 albertel 1820: undef($uhome);
1.860 raeburn 1821: }
1822: } else {
1823: if (!$uhome) {
1824: if (defined(&domain($udom,'primary'))) {
1825: $uhome=&domain($udom,'primary');
1826: }
1827: }
1828: }
1829: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1830: my $items='';
1831: foreach my $item (keys(%$storehash)) {
1832: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1833: }
1834: $items=~s/\&$//;
1835: return &reply("putdom:$udom:$namespace:$items",$uhome);
1836: } else {
1.860 raeburn 1837: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 1838: }
1839: }
1840:
1.1023 raeburn 1841: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 1842: sub newput_dom {
1.1023 raeburn 1843: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 1844: my $result;
1845: if (!$udom) {
1846: $udom=$env{'user.domain'};
1847: }
1.1023 raeburn 1848: if ($udom) {
1849: my $uname = &get_domainconfiguser($udom);
1850: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 1851: }
1852: return $result;
1853: }
1854:
1.1023 raeburn 1855: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 1856: sub del_dom {
1.1023 raeburn 1857: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 1858: if (ref($storearr) eq 'ARRAY') {
1859: if (!$udom) {
1860: $udom=$env{'user.domain'};
1861: }
1.1023 raeburn 1862: if ($udom) {
1863: my $uname = &get_domainconfiguser($udom);
1864: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 1865: }
1866: }
1867: }
1868:
1.1023 raeburn 1869: # ----------------------------------construct domainconfig user for a domain
1870: sub get_domainconfiguser {
1871: my ($udom) = @_;
1872: return $udom.'-domainconfig';
1873: }
1874:
1.837 raeburn 1875: sub retrieve_inst_usertypes {
1876: my ($udom) = @_;
1877: my (%returnhash,@order);
1.989 raeburn 1878: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1879: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1880: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1256 raeburn 1881: return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989 raeburn 1882: } else {
1883: if (defined(&domain($udom,'primary'))) {
1884: my $uhome=&domain($udom,'primary');
1885: my $rep=&reply("inst_usertypes:$udom",$uhome);
1886: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1256 raeburn 1887: &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989 raeburn 1888: return (\%returnhash,\@order);
1889: }
1890: my ($hashitems,$orderitems) = split(/:/,$rep);
1891: my @pairs=split(/\&/,$hashitems);
1892: foreach my $item (@pairs) {
1893: my ($key,$value)=split(/=/,$item,2);
1894: $key = &unescape($key);
1895: next if ($key =~ /^error: 2 /);
1896: $returnhash{$key}=&thaw_unescape($value);
1897: }
1898: my @esc_order = split(/\&/,$orderitems);
1899: foreach my $item (@esc_order) {
1900: push(@order,&unescape($item));
1901: }
1902: } else {
1.1256 raeburn 1903: &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837 raeburn 1904: }
1.1256 raeburn 1905: return (\%returnhash,\@order);
1.837 raeburn 1906: }
1907: }
1908:
1.868 raeburn 1909: sub is_domainimage {
1910: my ($url) = @_;
1.1306 raeburn 1911: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
1.868 raeburn 1912: if (&domain($1) ne '') {
1913: return '1';
1914: }
1915: }
1916: return;
1917: }
1918:
1.899 raeburn 1919: sub inst_directory_query {
1920: my ($srch) = @_;
1921: my $udom = $srch->{'srchdomain'};
1922: my %results;
1923: my $homeserver = &domain($udom,'primary');
1.909 raeburn 1924: my $outcome;
1.899 raeburn 1925: if ($homeserver ne '') {
1.904 albertel 1926: my $queryid=&reply("querysend:instdirsearch:".
1927: &escape($srch->{'srchby'}).':'.
1928: &escape($srch->{'srchterm'}).':'.
1929: &escape($srch->{'srchtype'}),$homeserver);
1930: my $host=&hostname($homeserver);
1931: if ($queryid !~/^\Q$host\E\_/) {
1932: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1933: return;
1934: }
1935: my $response = &get_query_reply($queryid);
1936: my $maxtries = 5;
1937: my $tries = 1;
1938: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1939: $response = &get_query_reply($queryid);
1940: $tries ++;
1941: }
1942:
1943: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 1944: if ($response eq 'unavailable') {
1945: $outcome = $response;
1946: } else {
1947: $outcome = 'ok';
1948: my @matches = split(/\n/,$response);
1949: foreach my $match (@matches) {
1950: my ($key,$value) = split(/=/,$match);
1951: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1952: }
1.899 raeburn 1953: }
1954: }
1955: }
1.909 raeburn 1956: return ($outcome,%results);
1.899 raeburn 1957: }
1958:
1959: sub usersearch {
1960: my ($srch) = @_;
1961: my $dom = $srch->{'srchdomain'};
1962: my %results;
1963: my %libserv = &all_library();
1964: my $query = 'usersearch';
1965: foreach my $tryserver (keys(%libserv)) {
1966: if (&host_domain($tryserver) eq $dom) {
1967: my $host=&hostname($tryserver);
1968: my $queryid=
1.911 raeburn 1969: &reply("querysend:".&escape($query).':'.
1970: &escape($srch->{'srchby'}).':'.
1.899 raeburn 1971: &escape($srch->{'srchtype'}).':'.
1972: &escape($srch->{'srchterm'}),$tryserver);
1973: if ($queryid !~/^\Q$host\E\_/) {
1974: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 1975: next;
1.899 raeburn 1976: }
1977: my $reply = &get_query_reply($queryid);
1978: my $maxtries = 1;
1979: my $tries = 1;
1980: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1981: $reply = &get_query_reply($queryid);
1982: $tries ++;
1983: }
1984: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1985: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1986: } else {
1.911 raeburn 1987: my @matches;
1988: if ($reply =~ /\n/) {
1989: @matches = split(/\n/,$reply);
1990: } else {
1991: @matches = split(/\&/,$reply);
1992: }
1.899 raeburn 1993: foreach my $match (@matches) {
1994: my ($uname,$udom,%userhash);
1.911 raeburn 1995: foreach my $entry (split(/:/,$match)) {
1996: my ($key,$value) =
1997: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 1998: $userhash{$key} = $value;
1999: if ($key eq 'username') {
2000: $uname = $value;
2001: } elsif ($key eq 'domain') {
2002: $udom = $value;
1.911 raeburn 2003: }
1.899 raeburn 2004: }
2005: $results{$uname.':'.$udom} = \%userhash;
2006: }
2007: }
2008: }
2009: }
2010: return %results;
2011: }
2012:
1.912 raeburn 2013: sub get_instuser {
2014: my ($udom,$uname,$id) = @_;
2015: my $homeserver = &domain($udom,'primary');
2016: my ($outcome,%results);
2017: if ($homeserver ne '') {
2018: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
2019: &escape($id).':'.&escape($udom),$homeserver);
2020: my $host=&hostname($homeserver);
2021: if ($queryid !~/^\Q$host\E\_/) {
2022: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
2023: return;
2024: }
2025: my $response = &get_query_reply($queryid);
2026: my $maxtries = 5;
2027: my $tries = 1;
2028: while (($response=~/^timeout/) && ($tries < $maxtries)) {
2029: $response = &get_query_reply($queryid);
2030: $tries ++;
2031: }
2032: if (!&error($response) && $response ne 'refused') {
2033: if ($response eq 'unavailable') {
2034: $outcome = $response;
2035: } else {
2036: $outcome = 'ok';
2037: my @matches = split(/\n/,$response);
2038: foreach my $match (@matches) {
2039: my ($key,$value) = split(/=/,$match);
2040: $results{&unescape($key)} = &thaw_unescape($value);
2041: }
2042: }
2043: }
2044: }
2045: my %userinfo;
2046: if (ref($results{$uname}) eq 'HASH') {
2047: %userinfo = %{$results{$uname}};
2048: }
2049: return ($outcome,%userinfo);
2050: }
2051:
1.1290 raeburn 2052: sub get_multiple_instusers {
2053: my ($udom,$users,$caller) = @_;
2054: my ($outcome,$results);
2055: if (ref($users) eq 'HASH') {
2056: my $count = keys(%{$users});
2057: my $requested = &freeze_escape($users);
2058: my $homeserver = &domain($udom,'primary');
2059: if ($homeserver ne '') {
2060: my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
2061: my $host=&hostname($homeserver);
2062: if ($queryid !~/^\Q$host\E\_/) {
2063: &logthis('get_multiple_instusers invalid queryid: '.$queryid.
2064: ' for host: '.$homeserver.'in domain '.$udom);
2065: return ($outcome,$results);
2066: }
2067: my $response = &get_query_reply($queryid);
2068: my $maxtries = 5;
2069: if ($count > 100) {
2070: $maxtries = 1+int($count/20);
2071: }
2072: my $tries = 1;
2073: while (($response=~/^timeout/) && ($tries <= $maxtries)) {
2074: $response = &get_query_reply($queryid);
2075: $tries ++;
2076: }
2077: if ($response eq '') {
2078: $results = {};
2079: foreach my $key (keys(%{$users})) {
2080: my ($uname,$id);
2081: if ($caller eq 'id') {
2082: $id = $key;
2083: } else {
2084: $uname = $key;
2085: }
2086: my ($resp,%info) = &get_instuser($udom,$uname,$id);
1.1291 raeburn 2087: $outcome = $resp;
1.1290 raeburn 2088: if ($resp eq 'ok') {
2089: %{$results} = (%{$results}, %info);
2090: } else {
2091: last;
2092: }
2093: }
2094: } elsif(!&error($response) && ($response ne 'refused')) {
2095: if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
2096: $outcome = $response;
2097: } else {
1.1291 raeburn 2098: ($outcome,my $userdata) = split(/=/,$response,2);
1.1290 raeburn 2099: if ($outcome eq 'ok') {
2100: $results = &thaw_unescape($userdata);
2101: }
2102: }
2103: }
2104: }
2105: }
2106: return ($outcome,$results);
2107: }
2108:
1.912 raeburn 2109: sub inst_rulecheck {
1.923 raeburn 2110: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 2111: my %returnhash;
2112: if ($udom ne '') {
2113: if (ref($rules) eq 'ARRAY') {
2114: @{$rules} = map {&escape($_);} (@{$rules});
2115: my $rulestr = join(':',@{$rules});
2116: my $homeserver=&domain($udom,'primary');
2117: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 2118: my $response;
2119: if ($item eq 'username') {
2120: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
2121: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 2122: $homeserver));
1.923 raeburn 2123: } elsif ($item eq 'id') {
2124: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
2125: ':'.&escape($id).':'.$rulestr,
2126: $homeserver));
1.945 raeburn 2127: } elsif ($item eq 'selfcreate') {
2128: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 2129: &escape($udom).':'.&escape($uname).
2130: ':'.$rulestr,$homeserver));
1.923 raeburn 2131: }
1.912 raeburn 2132: if ($response ne 'refused') {
2133: my @pairs=split(/\&/,$response);
2134: foreach my $item (@pairs) {
2135: my ($key,$value)=split(/=/,$item,2);
2136: $key = &unescape($key);
2137: next if ($key =~ /^error: 2 /);
2138: $returnhash{$key}=&thaw_unescape($value);
2139: }
2140: }
2141: }
2142: }
2143: }
2144: return %returnhash;
2145: }
2146:
2147: sub inst_userrules {
1.923 raeburn 2148: my ($udom,$check) = @_;
1.912 raeburn 2149: my (%ruleshash,@ruleorder);
2150: if ($udom ne '') {
2151: my $homeserver=&domain($udom,'primary');
2152: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 2153: my $response;
2154: if ($check eq 'id') {
2155: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 2156: $homeserver);
1.943 raeburn 2157: } elsif ($check eq 'email') {
2158: $response=&reply('instemailrules:'.&escape($udom),
2159: $homeserver);
1.923 raeburn 2160: } else {
2161: $response=&reply('instuserrules:'.&escape($udom),
2162: $homeserver);
2163: }
1.912 raeburn 2164: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 2165: ($response ne 'unknown_cmd') &&
1.912 raeburn 2166: ($response ne 'no_such_host')) {
2167: my ($hashitems,$orderitems) = split(/:/,$response);
2168: my @pairs=split(/\&/,$hashitems);
2169: foreach my $item (@pairs) {
2170: my ($key,$value)=split(/=/,$item,2);
2171: $key = &unescape($key);
2172: next if ($key =~ /^error: 2 /);
2173: $ruleshash{$key}=&thaw_unescape($value);
2174: }
2175: my @esc_order = split(/\&/,$orderitems);
2176: foreach my $item (@esc_order) {
2177: push(@ruleorder,&unescape($item));
2178: }
2179: }
2180: }
2181: }
2182: return (\%ruleshash,\@ruleorder);
2183: }
2184:
1.976 raeburn 2185: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 2186:
2187: sub get_domain_defaults {
1.1240 raeburn 2188: my ($domain,$ignore_cache) = @_;
1.1242 raeburn 2189: return if (($domain eq '') || ($domain eq 'public'));
1.943 raeburn 2190: my $cachetime = 60*60*24;
1.1240 raeburn 2191: unless ($ignore_cache) {
2192: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
2193: if (defined($cached)) {
2194: if (ref($result) eq 'HASH') {
2195: return %{$result};
2196: }
1.943 raeburn 2197: }
2198: }
2199: my %domdefaults;
2200: my %domconfig =
1.989 raeburn 2201: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 2202: 'requestcourses','inststatus',
1.1183 raeburn 2203: 'coursedefaults','usersessions',
1.1258 raeburn 2204: 'requestauthor','selfenrollment',
2205: 'coursecategories'],$domain);
1.1305 raeburn 2206: my @coursetypes = ('official','unofficial','community','textbook','placement');
1.943 raeburn 2207: if (ref($domconfig{'defaults'}) eq 'HASH') {
2208: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
2209: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
2210: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 2211: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 2212: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147 raeburn 2213: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943 raeburn 2214: } else {
2215: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
2216: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
2217: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
2218: }
1.976 raeburn 2219: if (ref($domconfig{'quotas'}) eq 'HASH') {
2220: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
2221: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
2222: } else {
2223: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1229 raeburn 2224: }
1.1177 raeburn 2225: my @usertools = ('aboutme','blog','webdav','portfolio');
1.976 raeburn 2226: foreach my $item (@usertools) {
2227: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
2228: $domdefaults{$item} = $domconfig{'quotas'}{$item};
2229: }
2230: }
1.1229 raeburn 2231: if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
2232: $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
2233: }
1.976 raeburn 2234: }
1.985 raeburn 2235: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1305 raeburn 2236: foreach my $item ('official','unofficial','community','textbook','placement') {
1.985 raeburn 2237: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
2238: }
2239: }
1.1183 raeburn 2240: if (ref($domconfig{'requestauthor'}) eq 'HASH') {
2241: $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
2242: }
1.989 raeburn 2243: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1256 raeburn 2244: foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989 raeburn 2245: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
2246: }
2247: }
1.1047 raeburn 2248: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1230 raeburn 2249: $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
1.1277 raeburn 2250: $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
2251: $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
2252: if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
2253: $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
2254: }
1.1254 raeburn 2255: foreach my $type (@coursetypes) {
2256: if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
2257: unless ($type eq 'community') {
2258: $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
2259: }
2260: }
2261: if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
2262: $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
2263: }
1.1277 raeburn 2264: if ($domdefaults{'postsubmit'} eq 'on') {
2265: if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
2266: $domdefaults{$type.'postsubtimeout'} =
2267: $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
2268: }
2269: }
1.1230 raeburn 2270: }
1.1286 raeburn 2271: if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
2272: if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
2273: my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
2274: if (@clonecodes) {
2275: $domdefaults{'canclone'} = join('+',@clonecodes);
2276: }
2277: }
2278: } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
2279: $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
2280: }
1.1047 raeburn 2281: }
1.1073 raeburn 2282: if (ref($domconfig{'usersessions'}) eq 'HASH') {
2283: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
2284: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
2285: }
2286: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
2287: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
2288: }
1.1279 raeburn 2289: if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
2290: $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
2291: }
1.1073 raeburn 2292: }
1.1254 raeburn 2293: if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
2294: if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
2295: my @settings = ('types','registered','enroll_dates','access_dates','section',
2296: 'approval','limit');
2297: foreach my $type (@coursetypes) {
2298: if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
2299: my @mgrdc = ();
2300: foreach my $item (@settings) {
2301: if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
2302: push(@mgrdc,$item);
2303: }
2304: }
2305: if (@mgrdc) {
2306: $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
2307: }
2308: }
2309: }
2310: }
2311: if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
2312: foreach my $type (@coursetypes) {
2313: if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
2314: foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
2315: $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
2316: }
2317: }
2318: }
2319: }
2320: }
1.1258 raeburn 2321: if (ref($domconfig{'coursecategories'}) eq 'HASH') {
2322: $domdefaults{'catauth'} = 'std';
2323: $domdefaults{'catunauth'} = 'std';
2324: if ($domconfig{'coursecategories'}{'auth'}) {
2325: $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
2326: }
2327: if ($domconfig{'coursecategories'}{'unauth'}) {
2328: $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
2329: }
2330: }
1.1219 raeburn 2331: &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943 raeburn 2332: return %domdefaults;
2333: }
2334:
1.344 www 2335: # --------------------------------------------------- Assign a key to a student
2336:
2337: sub assign_access_key {
1.364 www 2338: #
2339: # a valid key looks like uname:udom#comments
2340: # comments are being appended
2341: #
1.498 www 2342: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
2343: $kdom=
1.620 albertel 2344: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 2345: $knum=
1.620 albertel 2346: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 2347: $cdom=
1.620 albertel 2348: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2349: $cnum=
1.620 albertel 2350: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2351: $udom=$env{'user.name'} unless (defined($udom));
2352: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 2353: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 2354: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 2355: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 2356: # assigned to this person
2357: # - this should not happen,
1.345 www 2358: # unless something went wrong
2359: # the first time around
2360: # ready to assign
1.364 www 2361: $logentry=$1.'; '.$logentry;
1.496 www 2362: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 2363: $kdom,$knum) eq 'ok') {
1.345 www 2364: # key now belongs to user
1.346 www 2365: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 2366: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 2367: &appenv({'environment.'.$envkey => $ckey});
1.345 www 2368: return 'ok';
2369: } else {
2370: return
2371: 'error: Count not permanently assign key, will need to be re-entered later.';
2372: }
2373: } else {
2374: return 'error: Could not assign key, try again later.';
2375: }
1.364 www 2376: } elsif (!$existing{$ckey}) {
1.345 www 2377: # the key does not exist
2378: return 'error: The key does not exist';
2379: } else {
2380: # the key is somebody else's
2381: return 'error: The key is already in use';
2382: }
1.344 www 2383: }
2384:
1.364 www 2385: # ------------------------------------------ put an additional comment on a key
2386:
2387: sub comment_access_key {
2388: #
2389: # a valid key looks like uname:udom#comments
2390: # comments are being appended
2391: #
2392: my ($ckey,$cdom,$cnum,$logentry)=@_;
2393: $cdom=
1.620 albertel 2394: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 2395: $cnum=
1.620 albertel 2396: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 2397: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2398: if ($existing{$ckey}) {
2399: $existing{$ckey}.='; '.$logentry;
2400: # ready to assign
1.367 www 2401: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 2402: $cdom,$cnum) eq 'ok') {
2403: return 'ok';
2404: } else {
2405: return 'error: Count not store comment.';
2406: }
2407: } else {
2408: # the key does not exist
2409: return 'error: The key does not exist';
2410: }
2411: }
2412:
1.344 www 2413: # ------------------------------------------------------ Generate a set of keys
2414:
2415: sub generate_access_keys {
1.364 www 2416: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 2417: $cdom=
1.620 albertel 2418: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2419: $cnum=
1.620 albertel 2420: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 2421: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 2422: unless (($cdom) && ($cnum)) { return 0; }
2423: if ($number>10000) { return 0; }
2424: sleep(2); # make sure don't get same seed twice
2425: srand(time()^($$+($$<<15))); # from "Programming Perl"
2426: my $total=0;
2427: for (my $i=1;$i<=$number;$i++) {
2428: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
2429: sprintf("%lx",int(100000*rand)).'-'.
2430: sprintf("%lx",int(100000*rand));
2431: $newkey=~s/1/g/g; # folks mix up 1 and l
2432: $newkey=~s/0/h/g; # and also 0 and O
2433: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
2434: if ($existing{$newkey}) {
2435: $i--;
2436: } else {
1.364 www 2437: if (&put('accesskeys',
2438: { $newkey => '# generated '.localtime().
1.620 albertel 2439: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 2440: '; '.$logentry },
2441: $cdom,$cnum) eq 'ok') {
1.344 www 2442: $total++;
2443: }
2444: }
2445: }
1.620 albertel 2446: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 2447: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
2448: return $total;
2449: }
2450:
2451: # ------------------------------------------------------- Validate an accesskey
2452:
2453: sub validate_access_key {
2454: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
2455: $cdom=
1.620 albertel 2456: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2457: $cnum=
1.620 albertel 2458: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2459: $udom=$env{'user.domain'} unless (defined($udom));
2460: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 2461: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 2462: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 2463: }
2464:
2465: # ------------------------------------- Find the section of student in a course
1.652 albertel 2466: sub devalidate_getsection_cache {
2467: my ($udom,$unam,$courseid)=@_;
2468: my $hashid="$udom:$unam:$courseid";
2469: &devalidate_cache_new('getsection',$hashid);
2470: }
1.298 matthew 2471:
1.815 albertel 2472: sub courseid_to_courseurl {
2473: my ($courseid) = @_;
2474: #already url style courseid
2475: return $courseid if ($courseid =~ m{^/});
2476:
2477: if (exists($env{'course.'.$courseid.'.num'})) {
2478: my $cnum = $env{'course.'.$courseid.'.num'};
2479: my $cdom = $env{'course.'.$courseid.'.domain'};
2480: return "/$cdom/$cnum";
2481: }
2482:
2483: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
2484: if (exists($courseinfo{'num'})) {
2485: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
2486: }
2487:
2488: return undef;
2489: }
2490:
1.298 matthew 2491: sub getsection {
2492: my ($udom,$unam,$courseid)=@_;
1.599 albertel 2493: my $cachetime=1800;
1.551 albertel 2494:
2495: my $hashid="$udom:$unam:$courseid";
1.599 albertel 2496: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 2497: if (defined($cached)) { return $result; }
2498:
1.298 matthew 2499: my %Pending;
2500: my %Expired;
2501: #
2502: # Each role can either have not started yet (pending), be active,
2503: # or have expired.
2504: #
2505: # If there is an active role, we are done.
2506: #
2507: # If there is more than one role which has not started yet,
2508: # choose the one which will start sooner
2509: # If there is one role which has not started yet, return it.
2510: #
2511: # If there is more than one expired role, choose the one which ended last.
2512: # If there is a role which has expired, return it.
2513: #
1.815 albertel 2514: $courseid = &courseid_to_courseurl($courseid);
1.1166 raeburn 2515: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817 raeburn 2516: foreach my $key (keys(%roleshash)) {
1.479 albertel 2517: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 2518: my $section=$1;
2519: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 2520: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 2521: my $now=time;
1.548 albertel 2522: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 2523: $Expired{$end}=$section;
2524: next;
2525: }
1.548 albertel 2526: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 2527: $Pending{$start}=$section;
2528: next;
2529: }
1.599 albertel 2530: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 2531: }
2532: #
2533: # Presumedly there will be few matching roles from the above
2534: # loop and the sorting time will be negligible.
2535: if (scalar(keys(%Pending))) {
2536: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 2537: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 2538: }
2539: if (scalar(keys(%Expired))) {
2540: my @sorted = sort {$a <=> $b} keys(%Expired);
2541: my $time = pop(@sorted);
1.599 albertel 2542: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 2543: }
1.599 albertel 2544: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 2545: }
1.70 www 2546:
1.599 albertel 2547: sub save_cache {
2548: &purge_remembered();
1.722 albertel 2549: #&Apache::loncommon::validate_page();
1.620 albertel 2550: undef(%env);
1.780 albertel 2551: undef($env_loaded);
1.599 albertel 2552: }
1.452 albertel 2553:
1.599 albertel 2554: my $to_remember=-1;
2555: my %remembered;
2556: my %accessed;
2557: my $kicks=0;
2558: my $hits=0;
1.849 albertel 2559: sub make_key {
2560: my ($name,$id) = @_;
1.872 albertel 2561: if (length($id) > 65
2562: && length(&escape($id)) > 200) {
2563: $id=length($id).':'.&Digest::MD5::md5_hex($id);
2564: }
1.849 albertel 2565: return &escape($name.':'.$id);
2566: }
2567:
1.599 albertel 2568: sub devalidate_cache_new {
2569: my ($name,$id,$debug) = @_;
2570: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849 albertel 2571: $id=&make_key($name,$id);
1.599 albertel 2572: $memcache->delete($id);
2573: delete($remembered{$id});
2574: delete($accessed{$id});
2575: }
2576:
2577: sub is_cached_new {
2578: my ($name,$id,$debug) = @_;
1.849 albertel 2579: $id=&make_key($name,$id);
1.599 albertel 2580: if (exists($remembered{$id})) {
1.1133 foxr 2581: if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
1.599 albertel 2582: $accessed{$id}=[&gettimeofday()];
2583: $hits++;
2584: return ($remembered{$id},1);
2585: }
2586: my $value = $memcache->get($id);
2587: if (!(defined($value))) {
2588: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 2589: return (undef,undef);
1.416 albertel 2590: }
1.599 albertel 2591: if ($value eq '__undef__') {
2592: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
2593: $value=undef;
2594: }
2595: &make_room($id,$value,$debug);
2596: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
2597: return ($value,1);
2598: }
2599:
2600: sub do_cache_new {
2601: my ($name,$id,$value,$time,$debug) = @_;
1.849 albertel 2602: $id=&make_key($name,$id);
1.599 albertel 2603: my $setvalue=$value;
2604: if (!defined($setvalue)) {
2605: $setvalue='__undef__';
2606: }
1.623 albertel 2607: if (!defined($time) ) {
2608: $time=600;
2609: }
1.599 albertel 2610: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 2611: my $result = $memcache->set($id,$setvalue,$time);
2612: if (! $result) {
1.872 albertel 2613: &logthis("caching of id -> $id failed");
1.910 albertel 2614: $memcache->disconnect_all();
1.872 albertel 2615: }
1.600 albertel 2616: # need to make a copy of $value
1.919 albertel 2617: &make_room($id,$value,$debug);
1.599 albertel 2618: return $value;
2619: }
2620:
2621: sub make_room {
2622: my ($id,$value,$debug)=@_;
1.919 albertel 2623:
2624: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
2625: : $value;
1.599 albertel 2626: if ($to_remember<0) { return; }
2627: $accessed{$id}=[&gettimeofday()];
2628: if (scalar(keys(%remembered)) <= $to_remember) { return; }
2629: my $to_kick;
2630: my $max_time=0;
2631: foreach my $other (keys(%accessed)) {
2632: if (&tv_interval($accessed{$other}) > $max_time) {
2633: $to_kick=$other;
2634: $max_time=&tv_interval($accessed{$other});
2635: }
2636: }
2637: delete($remembered{$to_kick});
2638: delete($accessed{$to_kick});
2639: $kicks++;
2640: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 2641: return;
2642: }
2643:
1.599 albertel 2644: sub purge_remembered {
1.604 albertel 2645: #&logthis("Tossing ".scalar(keys(%remembered)));
2646: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 2647: undef(%remembered);
2648: undef(%accessed);
1.428 albertel 2649: }
1.70 www 2650: # ------------------------------------- Read an entry from a user's environment
2651:
2652: sub userenvironment {
2653: my ($udom,$unam,@what)=@_;
1.976 raeburn 2654: my $items;
2655: foreach my $item (@what) {
2656: $items.=&escape($item).'&';
2657: }
2658: $items=~s/\&$//;
1.70 www 2659: my %returnhash=();
1.1009 raeburn 2660: my $uhome = &homeserver($unam,$udom);
2661: unless ($uhome eq 'no_host') {
2662: my @answer=split(/\&/,
2663: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 2664: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
2665: return %returnhash;
2666: }
1.1009 raeburn 2667: my $i;
2668: for ($i=0;$i<=$#what;$i++) {
2669: $returnhash{$what[$i]}=&unescape($answer[$i]);
2670: }
1.70 www 2671: }
2672: return %returnhash;
1.1 albertel 2673: }
2674:
1.617 albertel 2675: # ---------------------------------------------------------- Get a studentphoto
2676: sub studentphoto {
2677: my ($udom,$unam,$ext) = @_;
2678: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 2679: if (defined($env{'request.course.id'})) {
1.708 raeburn 2680: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 2681: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
2682: return(&retrievestudentphoto($udom,$unam,$ext));
2683: } else {
2684: my ($result,$perm_reqd)=
1.707 albertel 2685: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2686: if ($result eq 'ok') {
2687: if (!($perm_reqd eq 'yes')) {
2688: return(&retrievestudentphoto($udom,$unam,$ext));
2689: }
2690: }
2691: }
2692: }
2693: } else {
2694: my ($result,$perm_reqd) =
1.707 albertel 2695: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2696: if ($result eq 'ok') {
2697: if (!($perm_reqd eq 'yes')) {
2698: return(&retrievestudentphoto($udom,$unam,$ext));
2699: }
2700: }
2701: }
2702: return '/adm/lonKaputt/lonlogo_broken.gif';
2703: }
2704:
2705: sub retrievestudentphoto {
2706: my ($udom,$unam,$ext,$type) = @_;
2707: my $home=&Apache::lonnet::homeserver($unam,$udom);
2708: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
2709: if ($ret eq 'ok') {
2710: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
2711: if ($type eq 'thumbnail') {
2712: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
2713: }
2714: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
2715: return $tokenurl;
2716: } else {
2717: if ($type eq 'thumbnail') {
2718: return '/adm/lonKaputt/genericstudent_tn.gif';
2719: } else {
2720: return '/adm/lonKaputt/lonlogo_broken.gif';
2721: }
1.617 albertel 2722: }
2723: }
2724:
1.263 www 2725: # -------------------------------------------------------------------- New chat
2726:
2727: sub chatsend {
1.724 raeburn 2728: my ($newentry,$anon,$group)=@_;
1.620 albertel 2729: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
2730: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2731: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 2732: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 2733: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 2734: &escape($newentry)).':'.$group,$chome);
1.292 www 2735: }
2736:
2737: # ------------------------------------------ Find current version of a resource
2738:
2739: sub getversion {
2740: my $fname=&clutter(shift);
1.1189 raeburn 2741: unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292 www 2742: return ¤tversion(&filelocation('',$fname));
2743: }
2744:
2745: sub currentversion {
2746: my $fname=shift;
2747: my $author=$fname;
2748: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2749: my ($udom,$uname)=split(/\//,$author);
1.1112 www 2750: my $home=&homeserver($uname,$udom);
1.292 www 2751: if ($home eq 'no_host') {
2752: return -1;
2753: }
1.1112 www 2754: my $answer=&reply("currentversion:$fname",$home);
1.292 www 2755: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2756: return -1;
2757: }
1.1112 www 2758: return $answer;
1.263 www 2759: }
2760:
1.1111 www 2761: #
2762: # Return special version number of resource if set by override, empty otherwise
2763: #
2764: sub usedversion {
2765: my $fname=shift;
2766: unless ($fname) { $fname=$env{'request.uri'}; }
2767: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
2768: if ($urlversion) { return $urlversion; }
2769: return '';
2770: }
2771:
1.1 albertel 2772: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 2773:
1.1 albertel 2774: sub subscribe {
2775: my $fname=shift;
1.761 raeburn 2776: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 2777: $fname=~s/[\n\r]//g;
1.1 albertel 2778: my $author=$fname;
2779: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2780: my ($udom,$uname)=split(/\//,$author);
2781: my $home=homeserver($uname,$udom);
1.335 albertel 2782: if ($home eq 'no_host') {
2783: return 'not_found';
1.1 albertel 2784: }
2785: my $answer=reply("sub:$fname",$home);
1.64 www 2786: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2787: $answer.=' by '.$home;
2788: }
1.1 albertel 2789: return $answer;
2790: }
2791:
1.8 www 2792: # -------------------------------------------------------------- Replicate file
2793:
2794: sub repcopy {
2795: my $filename=shift;
1.23 www 2796: $filename=~s/\/+/\//g;
1.1142 raeburn 2797: my $londocroot = $perlvar{'lonDocRoot'};
2798: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164 raeburn 2799: if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142 raeburn 2800: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
2801: $filename=~m{^/*(uploaded|editupload)/}) {
1.538 albertel 2802: return &repcopy_userfile($filename);
2803: }
1.532 albertel 2804: $filename=~s/[\n\r]//g;
1.8 www 2805: my $transname="$filename.in.transfer";
1.828 www 2806: # FIXME: this should flock
1.607 raeburn 2807: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 2808: my $remoteurl=subscribe($filename);
1.64 www 2809: if ($remoteurl =~ /^con_lost by/) {
2810: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2811: return 'unavailable';
1.8 www 2812: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 2813: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 2814: return 'not_found';
1.64 www 2815: } elsif ($remoteurl =~ /^rejected by/) {
2816: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2817: return 'forbidden';
1.20 www 2818: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 2819: return 'ok';
1.8 www 2820: } else {
1.290 www 2821: my $author=$filename;
2822: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2823: my ($udom,$uname)=split(/\//,$author);
2824: my $home=homeserver($uname,$udom);
2825: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 2826: my @parts=split(/\//,$filename);
2827: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142 raeburn 2828: if ($path ne "$londocroot/res") {
1.8 www 2829: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 2830: return 'bad_request';
1.8 www 2831: }
2832: my $count;
2833: for ($count=5;$count<$#parts;$count++) {
2834: $path.="/$parts[$count]";
2835: if ((-e $path)!=1) {
2836: mkdir($path,0777);
2837: }
2838: }
2839: my $ua=new LWP::UserAgent;
2840: my $request=new HTTP::Request('GET',"$remoteurl");
2841: my $response=$ua->request($request,$transname);
2842: if ($response->is_error()) {
2843: unlink($transname);
2844: my $message=$response->status_line;
1.672 albertel 2845: &logthis("<font color=\"blue\">WARNING:"
1.12 www 2846: ." LWP get: $message: $filename</font>");
1.607 raeburn 2847: return 'unavailable';
1.8 www 2848: } else {
1.16 www 2849: if ($remoteurl!~/\.meta$/) {
2850: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2851: my $mresponse=$ua->request($mrequest,$filename.'.meta');
2852: if ($mresponse->is_error()) {
2853: unlink($filename.'.meta');
2854: &logthis(
1.672 albertel 2855: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 2856: }
2857: }
1.8 www 2858: rename($transname,$filename);
1.607 raeburn 2859: return 'ok';
1.8 www 2860: }
1.290 www 2861: }
1.8 www 2862: }
1.330 www 2863: }
2864:
2865: # ------------------------------------------------ Get server side include body
2866: sub ssi_body {
1.381 albertel 2867: my ($filelink,%form)=@_;
1.606 matthew 2868: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
2869: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
2870: }
1.953 www 2871: my $output='';
2872: my $response;
1.980 raeburn 2873: if ($filelink=~/^https?\:/) {
1.954 raeburn 2874: ($output,$response)=&externalssi($filelink);
1.953 www 2875: } else {
1.1004 droeschl 2876: $filelink .= $filelink=~/\?/ ? '&' : '?';
2877: $filelink .= 'inhibitmenu=yes';
1.953 www 2878: ($output,$response)=&ssi($filelink,%form);
2879: }
1.778 albertel 2880: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 2881: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 2882: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 2883: if (wantarray) {
2884: return ($output, $response);
2885: } else {
2886: return $output;
2887: }
1.8 www 2888: }
2889:
1.15 www 2890: # --------------------------------------------------------- Server Side Include
2891:
1.782 albertel 2892: sub absolute_url {
2893: my ($host_name) = @_;
2894: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
2895: if ($host_name eq '') {
2896: $host_name = $ENV{'SERVER_NAME'};
2897: }
2898: return $protocol.$host_name;
2899: }
2900:
1.942 foxr 2901: #
2902: # Server side include.
2903: # Parameters:
2904: # fn Possibly encrypted resource name/id.
2905: # form Hash that describes how the rendering should be done
2906: # and other things.
1.944 foxr 2907: # Returns:
1.950 raeburn 2908: # Scalar context: The content of the response.
2909: # Array context: 2 element list of the content and the full response object.
1.942 foxr 2910: #
1.15 www 2911: sub ssi {
2912:
1.944 foxr 2913: my ($fn,%form)=@_;
1.15 www 2914: my $ua=new LWP::UserAgent;
1.23 www 2915: my $request;
1.711 albertel 2916:
2917: $form{'no_update_last_known'}=1;
1.895 albertel 2918: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 2919: if (%form) {
1.782 albertel 2920: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1272 droeschl 2921: $request->content(join('&',map {
2922: my $name = escape($_);
2923: "$name=" . ( ref($form{$_}) eq 'ARRAY'
2924: ? join("&$name=", map {escape($_) } @{$form{$_}})
2925: : &escape($form{$_}) );
2926: } keys(%form)));
1.23 www 2927: } else {
1.782 albertel 2928: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 2929: }
2930:
1.15 www 2931: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1173 foxr 2932: my $response= $ua->request($request);
1.1182 foxr 2933: my $content = $response->content;
2934:
2935:
1.944 foxr 2936: if (wantarray) {
1.1173 foxr 2937: return ($content, $response);
1.944 foxr 2938: } else {
1.1173 foxr 2939: return $content;
1.942 foxr 2940: }
1.324 www 2941: }
2942:
2943: sub externalssi {
2944: my ($url)=@_;
2945: my $ua=new LWP::UserAgent;
2946: my $request=new HTTP::Request('GET',$url);
2947: my $response=$ua->request($request);
1.954 raeburn 2948: if (wantarray) {
2949: return ($response->content, $response);
2950: } else {
2951: return $response->content;
2952: }
1.15 www 2953: }
1.254 www 2954:
1.492 albertel 2955: # -------------------------------- Allow a /uploaded/ URI to be vouched for
2956:
2957: sub allowuploaded {
2958: my ($srcurl,$url)=@_;
2959: $url=&clutter(&declutter($url));
2960: my $dir=$url;
2961: $dir=~s/\/[^\/]+$//;
2962: my %httpref=();
2963: my $httpurl=&hreflocation('',$url);
2964: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 2965: &Apache::lonnet::appenv(\%httpref);
1.254 www 2966: }
1.477 raeburn 2967:
1.1193 raeburn 2968: #
2969: # Determine if the current user should be able to edit a particular resource,
2970: # when viewing in course context.
2971: # (a) When viewing resource used to determine if "Edit" item is included in
2972: # Functions.
2973: # (b) When displaying folder contents in course editor, used to determine if
2974: # "Edit" link will be displayed alongside resource.
2975: #
1.1196 raeburn 2976: # input: six args -- filename (decluttered), course number, course domain,
2977: # url, symb (if registered) and group (if this is a group
2978: # item -- e.g., bulletin board, group page etc.).
2979: # output: array of five scalars --
1.1193 raeburn 2980: # $cfile -- url for file editing if editable on current server
2981: # $home -- homeserver of resource (i.e., for author if published,
2982: # or course if uploaded.).
2983: # $switchserver -- 1 if server switch will be needed.
1.1196 raeburn 2984: # $forceedit -- 1 if icon/link should be to go to edit mode
2985: # $forceview -- 1 if icon/link should be to go to view mode
1.1193 raeburn 2986: #
2987:
2988: sub can_edit_resource {
1.1194 raeburn 2989: my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
2990: my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
2991: #
2992: # For aboutme pages user can only edit his/her own.
2993: #
1.1199 raeburn 2994: if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
1.1194 raeburn 2995: my ($sdom,$sname) = ($1,$2);
2996: if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
2997: $home = $env{'user.home'};
2998: $cfile = $resurl;
2999: if ($env{'form.forceedit'}) {
3000: $forceview = 1;
3001: } else {
3002: $forceedit = 1;
3003: }
3004: return ($cfile,$home,$switchserver,$forceedit,$forceview);
3005: } else {
3006: return;
3007: }
3008: }
3009:
3010: if ($env{'request.course.id'}) {
3011: my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
3012: if ($group ne '') {
3013: # if this is a group homepage or group bulletin board, check group privs
3014: my $allowed = 0;
1.1197 raeburn 3015: if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
3016: if ((&allowed('mdg',$env{'request.course.id'}.
1.1198 raeburn 3017: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
1.1194 raeburn 3018: (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
3019: $allowed = 1;
3020: }
1.1197 raeburn 3021: } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
3022: if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
3023: (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
1.1194 raeburn 3024: $allowed = 1;
3025: }
3026: }
3027: if ($allowed) {
3028: $home=&homeserver($cnum,$cdom);
3029: if ($env{'form.forceedit'}) {
3030: $forceview = 1;
3031: } else {
3032: $forceedit = 1;
3033: }
3034: $cfile = $resurl;
3035: } else {
3036: return;
3037: }
3038: } else {
1.1208 raeburn 3039: if ($resurl =~ m{^/?adm/viewclasslist$}) {
3040: unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
3041: return;
3042: }
3043: } elsif (!$crsedit) {
1.1194 raeburn 3044: #
3045: # No edit allowed where CC has switched to student role.
3046: #
3047: return;
3048: }
3049: }
3050: }
3051:
1.1193 raeburn 3052: if ($file ne '') {
3053: if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
1.1194 raeburn 3054: if (&is_course_upload($file,$cnum,$cdom)) {
3055: $uploaded = 1;
3056: $incourse = 1;
1.1193 raeburn 3057: if ($file =~/\.(htm|html|css|js|txt)$/) {
3058: $cfile = &hreflocation('',$file);
1.1201 raeburn 3059: if ($env{'form.forceedit'}) {
3060: $forceview = 1;
3061: } else {
3062: $forceedit = 1;
3063: }
1.1194 raeburn 3064: }
3065: } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
3066: $incourse = 1;
3067: if ($env{'form.forceedit'}) {
3068: $forceview = 1;
3069: } else {
3070: $forceedit = 1;
3071: }
3072: $cfile = $resurl;
3073: } elsif (($resurl ne '') && (&is_on_map($resurl))) {
3074: if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
3075: $incourse = 1;
3076: if ($env{'form.forceedit'}) {
3077: $forceview = 1;
3078: } else {
3079: $forceedit = 1;
3080: }
3081: $cfile = $resurl;
1.1199 raeburn 3082: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
1.1194 raeburn 3083: $incourse = 1;
3084: $cfile = $resurl.'/smpedit';
1.1199 raeburn 3085: } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
1.1194 raeburn 3086: $incourse = 1;
1.1199 raeburn 3087: if ($env{'form.forceedit'}) {
3088: $forceview = 1;
3089: } else {
3090: $forceedit = 1;
3091: }
3092: $cfile = $resurl;
1.1298 raeburn 3093: } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/exttools?$}) {
3094: $incourse = 1;
3095: if ($env{'form.forceedit'}) {
3096: $forceview = 1;
3097: } else {
3098: $forceedit = 1;
3099: }
3100: $cfile = $resurl;
1.1208 raeburn 3101: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3102: $incourse = 1;
3103: if ($env{'form.forceedit'}) {
3104: $forceview = 1;
3105: } else {
3106: $forceedit = 1;
3107: }
3108: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1194 raeburn 3109: }
3110: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
3111: my $template = '/res/lib/templates/simpleproblem.problem';
3112: if (&is_on_map($template)) {
3113: $incourse = 1;
3114: $forceview = 1;
3115: $cfile = $template;
1.1193 raeburn 3116: }
1.1199 raeburn 3117: } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
3118: $incourse = 1;
3119: if ($env{'form.forceedit'}) {
3120: $forceview = 1;
3121: } else {
3122: $forceedit = 1;
3123: }
3124: $cfile = $resurl;
1.1298 raeburn 3125: } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/exttools?$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
3126: $incourse = 1;
3127: if ($env{'form.forceedit'}) {
3128: $forceview = 1;
3129: } else {
3130: $forceedit = 1;
3131: }
3132: $cfile = $resurl;
1.1199 raeburn 3133: } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
3134: $incourse = 1;
3135: $forceview = 1;
3136: if ($symb) {
3137: my ($map,$id,$res)=&decode_symb($symb);
3138: $env{'request.symb'} = $symb;
3139: $cfile = &clutter($res);
3140: } else {
3141: $cfile = $env{'form.suppurl'};
1.1298 raeburn 3142: my $escfile = &unescape($cfile);
3143: if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/exttools?$}) {
3144: $cfile = '/adm/wrapper'.$escfile;
3145: } else {
3146: $escfile =~ s{^http://}{};
3147: $cfile = &escape("/adm/wrapper/ext/$escfile");
3148: }
1.1199 raeburn 3149: }
1.1234 raeburn 3150: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3151: if ($env{'form.forceedit'}) {
3152: $forceview = 1;
3153: } else {
3154: $forceedit = 1;
3155: }
3156: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1193 raeburn 3157: }
3158: }
1.1194 raeburn 3159: if ($uploaded || $incourse) {
3160: $home=&homeserver($cnum,$cdom);
1.1207 raeburn 3161: } elsif ($file !~ m{/$}) {
1.1193 raeburn 3162: $file=~s{^(priv/$match_domain/$match_username)}{/$1};
3163: $file=~s{^($match_domain/$match_username)}{/priv/$1};
3164: # Check that the user has permission to edit this resource
3165: my $setpriv = 1;
3166: my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
3167: if (defined($cfudom)) {
3168: $home=&homeserver($cfuname,$cfudom);
3169: $cfile=$file;
3170: }
3171: }
1.1194 raeburn 3172: if (($cfile ne '') && (!$incourse || $uploaded) &&
3173: (($home ne '') && ($home ne 'no_host'))) {
1.1193 raeburn 3174: my @ids=¤t_machine_ids();
3175: unless (grep(/^\Q$home\E$/,@ids)) {
3176: $switchserver=1;
3177: }
3178: }
3179: }
1.1194 raeburn 3180: return ($cfile,$home,$switchserver,$forceedit,$forceview);
1.1193 raeburn 3181: }
3182:
3183: sub is_course_upload {
3184: my ($file,$cnum,$cdom) = @_;
3185: my $uploadpath = &LONCAPA::propath($cdom,$cnum);
3186: $uploadpath =~ s{^\/}{};
1.1201 raeburn 3187: if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
3188: ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
1.1193 raeburn 3189: return 1;
3190: }
3191: return;
3192: }
3193:
1.1194 raeburn 3194: sub in_course {
1.1195 raeburn 3195: my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
3196: if ($hideprivileged) {
3197: my $skipuser;
1.1219 raeburn 3198: my %coursehash = &coursedescription($cdom.'_'.$cnum);
3199: my @possdoms = ($cdom);
3200: if ($coursehash{'checkforpriv'}) {
3201: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
3202: }
3203: if (&privileged($uname,$udom,\@possdoms)) {
1.1195 raeburn 3204: $skipuser = 1;
3205: if ($coursehash{'nothideprivileged'}) {
3206: foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3207: my $user;
3208: if ($item =~ /:/) {
3209: $user = $item;
3210: } else {
3211: $user = join(':',split(/[\@]/,$item));
3212: }
3213: if ($user eq $uname.':'.$udom) {
3214: undef($skipuser);
3215: last;
3216: }
3217: }
3218: }
3219: if ($skipuser) {
3220: return 0;
3221: }
3222: }
3223: }
1.1194 raeburn 3224: $type ||= 'any';
3225: if (!defined($cdom) || !defined($cnum)) {
3226: my $cid = $env{'request.course.id'};
3227: $cdom = $env{'course.'.$cid.'.domain'};
3228: $cnum = $env{'course.'.$cid.'.num'};
3229: }
3230: my $typesref;
1.1195 raeburn 3231: if (($type eq 'any') || ($type eq 'all')) {
1.1194 raeburn 3232: $typesref = ['active','previous','future'];
3233: } elsif ($type eq 'previous' || $type eq 'future') {
3234: $typesref = [$type];
3235: }
3236: my %roles = &get_my_roles($uname,$udom,'userroles',
3237: $typesref,undef,[$cdom]);
3238: my ($tmp) = keys(%roles);
3239: return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
3240: my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
3241: if (@course_roles > 0) {
3242: return 1;
3243: }
3244: return 0;
3245: }
3246:
1.478 albertel 3247: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 3248: # input: action, courseID, current domain, intended
1.637 raeburn 3249: # path to file, source of file, instruction to parse file for objects,
3250: # ref to hash for embedded objects,
3251: # ref to hash for codebase of java objects.
1.1095 raeburn 3252: # reference to scalar to accommodate mime type determined
3253: # from File::MMagic if $parser = parse.
1.637 raeburn 3254: #
1.485 raeburn 3255: # output: url to file (if action was uploaddoc),
3256: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 3257: #
1.478 albertel 3258: # Allows directory structure to be used within lonUsers/../userfiles/ for a
3259: # course.
1.477 raeburn 3260: #
1.478 albertel 3261: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3262: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
3263: # course's home server.
1.477 raeburn 3264: #
1.478 albertel 3265: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
3266: # be copied from $source (current location) to
3267: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3268: # and will then be copied to
3269: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
3270: # course's home server.
1.485 raeburn 3271: #
1.481 raeburn 3272: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 3273: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 3274: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3275: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
3276: # in course's home server.
1.637 raeburn 3277: #
1.477 raeburn 3278:
3279: sub process_coursefile {
1.1095 raeburn 3280: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
3281: $mimetype)=@_;
1.477 raeburn 3282: my $fetchresult;
1.638 albertel 3283: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 3284: if ($action eq 'propagate') {
1.638 albertel 3285: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
3286: $home);
1.481 raeburn 3287: } else {
1.477 raeburn 3288: my $fpath = '';
3289: my $fname = $file;
1.478 albertel 3290: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 3291: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 3292: my $filepath = &build_filepath($fpath);
1.481 raeburn 3293: if ($action eq 'copy') {
3294: if ($source eq '') {
3295: $fetchresult = 'no source file';
3296: return $fetchresult;
3297: } else {
3298: my $destination = $filepath.'/'.$fname;
3299: rename($source,$destination);
3300: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3301: $home);
1.481 raeburn 3302: }
3303: } elsif ($action eq 'uploaddoc') {
3304: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 3305: print $fh $env{'form.'.$source};
1.481 raeburn 3306: close($fh);
1.637 raeburn 3307: if ($parser eq 'parse') {
1.1024 raeburn 3308: my $mm = new File::MMagic;
1.1095 raeburn 3309: my $type = $mm->checktype_filename($filepath.'/'.$fname);
3310: if ($type eq 'text/html') {
1.1024 raeburn 3311: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
3312: unless ($parse_result eq 'ok') {
3313: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
3314: }
1.637 raeburn 3315: }
1.1095 raeburn 3316: if (ref($mimetype)) {
3317: $$mimetype = $type;
3318: }
1.637 raeburn 3319: }
1.477 raeburn 3320: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3321: $home);
1.481 raeburn 3322: if ($fetchresult eq 'ok') {
3323: return '/uploaded/'.$fpath.'/'.$fname;
3324: } else {
3325: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3326: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 3327: return '/adm/notfound.html';
3328: }
1.477 raeburn 3329: }
3330: }
1.485 raeburn 3331: unless ( $fetchresult eq 'ok') {
1.477 raeburn 3332: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3333: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 3334: }
3335: return $fetchresult;
3336: }
3337:
1.637 raeburn 3338: sub build_filepath {
3339: my ($fpath) = @_;
3340: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
3341: unless ($fpath eq '') {
3342: my @parts=split('/',$fpath);
3343: foreach my $part (@parts) {
3344: $filepath.= '/'.$part;
3345: if ((-e $filepath)!=1) {
3346: mkdir($filepath,0777);
3347: }
3348: }
3349: }
3350: return $filepath;
3351: }
3352:
3353: sub store_edited_file {
1.638 albertel 3354: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 3355: my $file = $primary_url;
3356: $file =~ s#^/uploaded/$docudom/$docuname/##;
3357: my $fpath = '';
3358: my $fname = $file;
3359: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
3360: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
3361: my $filepath = &build_filepath($fpath);
3362: open(my $fh,'>'.$filepath.'/'.$fname);
3363: print $fh $content;
3364: close($fh);
1.638 albertel 3365: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 3366: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3367: $home);
1.637 raeburn 3368: if ($$fetchresult eq 'ok') {
3369: return '/uploaded/'.$fpath.'/'.$fname;
3370: } else {
1.638 albertel 3371: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
3372: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 3373: return '/adm/notfound.html';
3374: }
3375: }
3376:
1.531 albertel 3377: sub clean_filename {
1.831 albertel 3378: my ($fname,$args)=@_;
1.315 www 3379: # Replace Windows backslashes by forward slashes
1.257 www 3380: $fname=~s/\\/\//g;
1.831 albertel 3381: if (!$args->{'keep_path'}) {
3382: # Get rid of everything but the actual filename
3383: $fname=~s/^.*\/([^\/]+)$/$1/;
3384: }
1.315 www 3385: # Replace spaces by underscores
3386: $fname=~s/\s+/\_/g;
3387: # Replace all other weird characters by nothing
1.831 albertel 3388: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 3389: # Replace all .\d. sequences with _\d. so they no longer look like version
3390: # numbers
3391: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 3392: return $fname;
3393: }
1.1051 raeburn 3394: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
3395: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
3396: # image with the same aspect ratio as the original, but with dimensions which do
3397: # not exceed $resizewidth and $resizeheight.
3398:
1.984 neumanie 3399: sub resizeImage {
1.1051 raeburn 3400: my ($img_path,$resizewidth,$resizeheight) = @_;
3401: my $ima = Image::Magick->new;
3402: my $resized;
3403: if (-e $img_path) {
3404: $ima->Read($img_path);
3405: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
3406: my $width = $ima->Get('width');
3407: my $height = $ima->Get('height');
3408: if ($width > $resizewidth) {
3409: my $factor = $width/$resizewidth;
3410: my $newheight = $height/$factor;
3411: $ima->Scale(width=>$resizewidth,height=>$newheight);
3412: $resized = 1;
3413: }
3414: }
3415: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
3416: my $width = $ima->Get('width');
3417: my $height = $ima->Get('height');
3418: if ($height > $resizeheight) {
3419: my $factor = $height/$resizeheight;
3420: my $newwidth = $width/$factor;
3421: $ima->Scale(width=>$newwidth,height=>$resizeheight);
3422: $resized = 1;
3423: }
3424: }
3425: if ($resized) {
3426: $ima->Write($img_path);
3427: }
3428: }
3429: return;
1.977 amueller 3430: }
3431:
1.608 albertel 3432: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 3433: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093 raeburn 3434: # the desired filename is in $env{"form.$formname.filename"}
1.1090 raeburn 3435: # $context - possible values: coursedoc, existingfile, overwrite,
3436: # canceloverwrite, or ''.
3437: # if 'coursedoc': upload to the current course
3438: # if 'existingfile': write file to tmp/overwrites directory
3439: # if 'canceloverwrite': delete file written to tmp/overwrites directory
3440: # $context is passed as argument to &finishuserfileupload
1.686 albertel 3441: # $subdir - directory in userfile to store the file into
1.858 raeburn 3442: # $parser - instruction to parse file for objects ($parser = parse)
3443: # $allfiles - reference to hash for embedded objects
3444: # $codebase - reference to hash for codebase of java objects
3445: # $desuname - username for permanent storage of uploaded file
3446: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 3447: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
3448: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 3449: # $resizewidth - width (pixels) to which to resize uploaded image
3450: # $resizeheight - height (pixels) to which to resize uploaded image
1.1095 raeburn 3451: # $mimetype - reference to scalar to accommodate mime type determined
1.1152 raeburn 3452: # from File::MMagic.
1.858 raeburn 3453: #
1.686 albertel 3454: # output: url of file in userspace, or error: <message>
3455: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 3456:
1.531 albertel 3457: sub userfileupload {
1.1090 raeburn 3458: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095 raeburn 3459: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531 albertel 3460: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 3461: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 3462: $fname=&clean_filename($fname);
1.1090 raeburn 3463: # See if there is anything left
1.257 www 3464: unless ($fname) { return 'error: no uploaded file'; }
1.1090 raeburn 3465: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
3466: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
3467: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
3468: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523 raeburn 3469: my $now = time;
1.1090 raeburn 3470: my $filepath;
1.1095 raeburn 3471: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090 raeburn 3472: $filepath = 'tmp/helprequests/'.$now;
3473: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
3474: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
3475: '_'.$env{'user.domain'}.'/pending';
3476: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
3477: my ($docuname,$docudom);
3478: if ($destudom) {
3479: $docudom = $destudom;
3480: } else {
3481: $docudom = $env{'user.domain'};
3482: }
3483: if ($destuname) {
3484: $docuname = $destuname;
3485: } else {
3486: $docuname = $env{'user.name'};
3487: }
3488: if (exists($env{'form.group'})) {
3489: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3490: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3491: }
3492: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
3493: if ($context eq 'canceloverwrite') {
3494: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
3495: if (-e $tempfile) {
3496: my @info = stat($tempfile);
3497: if ($info[9] eq $env{'form.timestamp'}) {
3498: unlink($tempfile);
3499: }
3500: }
3501: return;
1.523 raeburn 3502: }
3503: }
1.1090 raeburn 3504: # Create the directory if not present
1.741 raeburn 3505: my @parts=split(/\//,$filepath);
3506: my $fullpath = $perlvar{'lonDaemons'};
3507: for (my $i=0;$i<@parts;$i++) {
3508: $fullpath .= '/'.$parts[$i];
3509: if ((-e $fullpath)!=1) {
3510: mkdir($fullpath,0777);
3511: }
3512: }
3513: open(my $fh,'>'.$fullpath.'/'.$fname);
3514: print $fh $env{'form.'.$formname};
3515: close($fh);
1.1090 raeburn 3516: if ($context eq 'existingfile') {
3517: my @info = stat($fullpath.'/'.$fname);
3518: return ($fullpath.'/'.$fname,$info[9]);
3519: } else {
3520: return $fullpath.'/'.$fname;
3521: }
1.523 raeburn 3522: }
1.995 raeburn 3523: if ($subdir eq 'scantron') {
3524: $fname = 'scantron_orig_'.$fname;
1.1093 raeburn 3525: } else {
1.995 raeburn 3526: $fname="$subdir/$fname";
3527: }
1.1090 raeburn 3528: if ($context eq 'coursedoc') {
1.638 albertel 3529: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3530: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 3531: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 3532: return &finishuserfileupload($docuname,$docudom,
3533: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 3534: $codebase,$thumbwidth,$thumbheight,
1.1095 raeburn 3535: $resizewidth,$resizeheight,$context,$mimetype);
1.481 raeburn 3536: } else {
1.1218 raeburn 3537: if ($env{'form.folder'}) {
3538: $fname=$env{'form.folder'}.'/'.$fname;
3539: }
1.638 albertel 3540: return &process_coursefile('uploaddoc',$docuname,$docudom,
3541: $fname,$formname,$parser,
1.1095 raeburn 3542: $allfiles,$codebase,$mimetype);
1.481 raeburn 3543: }
1.719 banghart 3544: } elsif (defined($destuname)) {
3545: my $docuname=$destuname;
3546: my $docudom=$destudom;
1.860 raeburn 3547: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3548: $parser,$allfiles,$codebase,
1.1051 raeburn 3549: $thumbwidth,$thumbheight,
1.1095 raeburn 3550: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3551: } else {
1.638 albertel 3552: my $docuname=$env{'user.name'};
3553: my $docudom=$env{'user.domain'};
1.1220 raeburn 3554: if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714 raeburn 3555: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3556: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3557: }
1.860 raeburn 3558: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3559: $parser,$allfiles,$codebase,
1.1051 raeburn 3560: $thumbwidth,$thumbheight,
1.1095 raeburn 3561: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3562: }
1.271 www 3563: }
3564:
3565: sub finishuserfileupload {
1.860 raeburn 3566: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095 raeburn 3567: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477 raeburn 3568: my $path=$docudom.'/'.$docuname.'/';
1.258 www 3569: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 3570:
1.860 raeburn 3571: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 3572: $file=$fname;
3573: if ($fname=~m|/|) {
3574: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
3575: $path.=$fnamepath.'/';
3576: }
1.259 www 3577: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 3578: my $count;
3579: for ($count=4;$count<=$#parts;$count++) {
3580: $filepath.="/$parts[$count]";
3581: if ((-e $filepath)!=1) {
3582: mkdir($filepath,0777);
3583: }
3584: }
1.984 neumanie 3585:
1.258 www 3586: # Save the file
3587: {
1.701 albertel 3588: if (!open(FH,'>'.$filepath.'/'.$file)) {
3589: &logthis('Failed to create '.$filepath.'/'.$file);
3590: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
3591: return '/adm/notfound.html';
3592: }
1.1090 raeburn 3593: if ($context eq 'overwrite') {
1.1117 foxr 3594: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090 raeburn 3595: my $target = $filepath.'/'.$file;
3596: if (-e $source) {
3597: my @info = stat($source);
3598: if ($info[9] eq $env{'form.timestamp'}) {
3599: unless (&File::Copy::move($source,$target)) {
3600: &logthis('Failed to overwrite '.$filepath.'/'.$file);
3601: return "Moving from $source failed";
3602: }
3603: } else {
3604: return "Temporary file: $source had unexpected date/time for last modification";
3605: }
3606: } else {
3607: return "Temporary file: $source missing";
3608: }
3609: } elsif (!print FH ($env{'form.'.$formname})) {
1.701 albertel 3610: &logthis('Failed to write to '.$filepath.'/'.$file);
3611: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
3612: return '/adm/notfound.html';
3613: }
1.570 albertel 3614: close(FH);
1.1051 raeburn 3615: if ($resizewidth && $resizeheight) {
3616: my $mm = new File::MMagic;
3617: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
3618: if ($mime_type =~ m{^image/}) {
3619: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
3620: }
1.977 amueller 3621: }
1.258 www 3622: }
1.1152 raeburn 3623: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
3624: if (ref($mimetype)) {
3625: if ($$mimetype eq '') {
3626: my $mm = new File::MMagic;
3627: my $type = $mm->checktype_filename($filepath.'/'.$file);
3628: $$mimetype = $type;
3629: }
3630: }
3631: }
1.637 raeburn 3632: if ($parser eq 'parse') {
1.1152 raeburn 3633: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024 raeburn 3634: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
3635: $allfiles,$codebase);
3636: unless ($parse_result eq 'ok') {
3637: &logthis('Failed to parse '.$filepath.$file.
3638: ' for embedded media: '.$parse_result);
3639: }
1.637 raeburn 3640: }
3641: }
1.860 raeburn 3642: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
3643: my $input = $filepath.'/'.$file;
3644: my $output = $filepath.'/'.'tn-'.$file;
3645: my $thumbsize = $thumbwidth.'x'.$thumbheight;
3646: system("convert -sample $thumbsize $input $output");
3647: if (-e $filepath.'/'.'tn-'.$file) {
3648: $fetchthumb = 1;
3649: }
3650: }
1.858 raeburn 3651:
1.259 www 3652: # Notify homeserver to grep it
3653: #
1.984 neumanie 3654: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 3655: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 3656: if ($fetchresult eq 'ok') {
1.860 raeburn 3657: if ($fetchthumb) {
3658: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
3659: if ($thumbresult ne 'ok') {
3660: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
3661: $docuhome.': '.$thumbresult);
3662: }
3663: }
1.259 www 3664: #
1.258 www 3665: # Return the URL to it
1.494 albertel 3666: return '/uploaded/'.$path.$file;
1.263 www 3667: } else {
1.494 albertel 3668: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
3669: ': '.$fetchresult);
1.263 www 3670: return '/adm/notfound.html';
1.858 raeburn 3671: }
1.493 albertel 3672: }
3673:
1.637 raeburn 3674: sub extract_embedded_items {
1.961 raeburn 3675: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 3676: my @state = ();
1.1164 raeburn 3677: my (%lastids,%related,%shockwave,%flashvars);
1.637 raeburn 3678: my %javafiles = (
3679: codebase => '',
3680: code => '',
3681: archive => ''
3682: );
3683: my %mediafiles = (
3684: src => '',
3685: movie => '',
3686: );
1.648 raeburn 3687: my $p;
3688: if ($content) {
3689: $p = HTML::LCParser->new($content);
3690: } else {
1.961 raeburn 3691: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 3692: }
1.641 albertel 3693: while (my $t=$p->get_token()) {
1.640 albertel 3694: if ($t->[0] eq 'S') {
3695: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 3696: push(@state, $tagname);
1.648 raeburn 3697: if (lc($tagname) eq 'allow') {
3698: &add_filetype($allfiles,$attr->{'src'},'src');
3699: }
1.640 albertel 3700: if (lc($tagname) eq 'img') {
3701: &add_filetype($allfiles,$attr->{'src'},'src');
3702: }
1.886 albertel 3703: if (lc($tagname) eq 'a') {
1.1222 raeburn 3704: unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
1.1221 raeburn 3705: &add_filetype($allfiles,$attr->{'href'},'href');
3706: }
1.886 albertel 3707: }
1.645 raeburn 3708: if (lc($tagname) eq 'script') {
1.1164 raeburn 3709: my $src;
1.645 raeburn 3710: if ($attr->{'archive'} =~ /\.jar$/i) {
3711: &add_filetype($allfiles,$attr->{'archive'},'archive');
3712: } else {
1.1164 raeburn 3713: if ($attr->{'src'} ne '') {
3714: $src = $attr->{'src'};
3715: &add_filetype($allfiles,$src,'src');
3716: }
3717: }
3718: my $text = $p->get_trimmed_text();
3719: if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
3720: my @swfargs = split(/,/,$1);
3721: foreach my $item (@swfargs) {
3722: $item =~ s/["']//g;
3723: $item =~ s/^\s+//;
3724: $item =~ s/\s+$//;
3725: }
3726: if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
3727: if (ref($related{$swfargs[0]}) eq 'ARRAY') {
3728: push(@{$related{$swfargs[0]}},$swfargs[2]);
3729: } else {
3730: $related{$swfargs[0]} = [$swfargs[2]];
3731: }
3732: }
1.645 raeburn 3733: }
3734: }
3735: if (lc($tagname) eq 'link') {
3736: if (lc($attr->{'rel'}) eq 'stylesheet') {
3737: &add_filetype($allfiles,$attr->{'href'},'href');
3738: }
3739: }
1.640 albertel 3740: if (lc($tagname) eq 'object' ||
3741: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
3742: foreach my $item (keys(%javafiles)) {
3743: $javafiles{$item} = '';
3744: }
1.1164 raeburn 3745: if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
3746: $lastids{lc($tagname)} = $attr->{'id'};
3747: }
1.640 albertel 3748: }
3749: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
3750: my $name = lc($attr->{'name'});
3751: foreach my $item (keys(%javafiles)) {
3752: if ($name eq $item) {
3753: $javafiles{$item} = $attr->{'value'};
3754: last;
3755: }
3756: }
1.1164 raeburn 3757: my $pathfrom;
1.640 albertel 3758: foreach my $item (keys(%mediafiles)) {
3759: if ($name eq $item) {
1.1164 raeburn 3760: $pathfrom = $attr->{'value'};
3761: $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
3762: &add_filetype($allfiles,$pathfrom,$name);
1.640 albertel 3763: last;
3764: }
3765: }
1.1164 raeburn 3766: if ($name eq 'flashvars') {
3767: $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
3768: }
3769: if ($pathfrom ne '') {
3770: &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
3771: $pathfrom);
3772: }
1.640 albertel 3773: }
3774: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
3775: foreach my $item (keys(%javafiles)) {
3776: if ($attr->{$item}) {
3777: $javafiles{$item} = $attr->{$item};
3778: last;
3779: }
3780: }
3781: foreach my $item (keys(%mediafiles)) {
3782: if ($attr->{$item}) {
3783: &add_filetype($allfiles,$attr->{$item},$item);
3784: last;
3785: }
3786: }
1.1164 raeburn 3787: if (lc($tagname) eq 'embed') {
3788: if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
3789: &embedded_dependency($allfiles,\%related,$attr->{'name'},
3790: $attr->{'src'});
3791: }
3792: }
1.640 albertel 3793: }
1.1243 raeburn 3794: if (lc($tagname) eq 'iframe') {
3795: my $src = $attr->{'src'} ;
3796: if (($src ne '') && ($src !~ m{^(/|https?://)})) {
3797: &add_filetype($allfiles,$src,'src');
3798: } elsif ($src =~ m{^/}) {
3799: if ($env{'request.course.id'}) {
3800: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
3801: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
3802: my $url = &hreflocation('',$fullpath);
3803: if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
3804: my $relpath = $1;
3805: if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
3806: &add_filetype($allfiles,$1,'src');
3807: }
3808: }
3809: }
3810: }
3811: }
1.1164 raeburn 3812: if ($t->[4] =~ m{/>$}) {
1.1243 raeburn 3813: pop(@state);
1.1164 raeburn 3814: }
1.640 albertel 3815: } elsif ($t->[0] eq 'E') {
3816: my ($tagname) = ($t->[1]);
3817: if ($javafiles{'codebase'} ne '') {
3818: $javafiles{'codebase'} .= '/';
3819: }
3820: if (lc($tagname) eq 'applet' ||
3821: lc($tagname) eq 'object' ||
3822: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
3823: ) {
3824: foreach my $item (keys(%javafiles)) {
3825: if ($item ne 'codebase' && $javafiles{$item} ne '') {
3826: my $file=$javafiles{'codebase'}.$javafiles{$item};
3827: &add_filetype($allfiles,$file,$item);
3828: }
3829: }
3830: }
3831: pop @state;
3832: }
3833: }
1.1164 raeburn 3834: foreach my $id (sort(keys(%flashvars))) {
3835: if ($shockwave{$id} ne '') {
3836: my @pairs = split(/\&/,$flashvars{$id});
3837: foreach my $pair (@pairs) {
3838: my ($key,$value) = split(/\=/,$pair);
3839: if ($key eq 'thumb') {
3840: &add_filetype($allfiles,$value,$key);
3841: } elsif ($key eq 'content') {
3842: my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
3843: my ($ext) = ($value =~ /\.([^.]+)$/);
3844: if ($ext ne '') {
3845: &add_filetype($allfiles,$path.$value,$ext);
3846: }
3847: }
3848: }
3849: }
3850: }
1.637 raeburn 3851: return 'ok';
3852: }
3853:
1.639 albertel 3854: sub add_filetype {
3855: my ($allfiles,$file,$type)=@_;
3856: if (exists($allfiles->{$file})) {
3857: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
3858: push(@{$allfiles->{$file}}, &escape($type));
3859: }
3860: } else {
3861: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 3862: }
3863: }
3864:
1.1164 raeburn 3865: sub embedded_dependency {
3866: my ($allfiles,$related,$identifier,$pathfrom) = @_;
3867: if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
3868: if (($identifier ne '') &&
3869: (ref($related->{$identifier}) eq 'ARRAY') &&
3870: ($pathfrom ne '')) {
3871: my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
3872: foreach my $dep (@{$related->{$identifier}}) {
3873: &add_filetype($allfiles,$path.$dep,'object');
3874: }
3875: }
3876: }
3877: return;
3878: }
3879:
1.493 albertel 3880: sub removeuploadedurl {
1.984 neumanie 3881: my ($url)=@_;
3882: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 3883: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 3884: }
3885:
3886: sub removeuserfile {
3887: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 3888: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3889: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 3890: if ($result eq 'ok') {
1.798 raeburn 3891: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
3892: my $metafile = $fname.'.meta';
3893: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 3894: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 3895: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3896: my $sqlresult =
1.823 albertel 3897: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3898: 'portfolio_metadata',$group,
3899: 'delete');
1.798 raeburn 3900: }
3901: }
3902: return $result;
1.257 www 3903: }
1.15 www 3904:
1.530 albertel 3905: sub mkdiruserfile {
3906: my ($docuname,$docudom,$dir)=@_;
3907: my $home=&homeserver($docuname,$docudom);
3908: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
3909: }
3910:
1.531 albertel 3911: sub renameuserfile {
3912: my ($docuname,$docudom,$old,$new)=@_;
3913: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3914: my $result = &reply("renameuserfile:$docudom:$docuname:".
3915: &escape("$old").':'.&escape("$new"),$home);
3916: if ($result eq 'ok') {
3917: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
3918: my $oldmeta = $old.'.meta';
3919: my $newmeta = $new.'.meta';
3920: my $metaresult =
3921: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 3922: my $url = "/uploaded/$docudom/$docuname/$old";
3923: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3924: my $sqlresult =
1.823 albertel 3925: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3926: 'portfolio_metadata',$group,
3927: 'delete');
1.798 raeburn 3928: }
3929: }
3930: return $result;
1.531 albertel 3931: }
3932:
1.14 www 3933: # ------------------------------------------------------------------------- Log
3934:
3935: sub log {
3936: my ($dom,$nam,$hom,$what)=@_;
1.47 www 3937: return critical("log:$dom:$nam:$what",$hom);
1.157 www 3938: }
3939:
3940: # ------------------------------------------------------------------ Course Log
1.352 www 3941: #
3942: # This routine flushes several buffers of non-mission-critical nature
3943: #
1.157 www 3944:
3945: sub flushcourselogs {
1.352 www 3946: &logthis('Flushing log buffers');
3947: #
3948: # course logs
3949: # This is a log of all transactions in a course, which can be used
3950: # for data mining purposes
3951: #
3952: # It also collects the courseid database, which lists last transaction
3953: # times and course titles for all courseids
3954: #
3955: my %courseidbuffer=();
1.921 raeburn 3956: foreach my $crsid (keys(%courselogs)) {
1.352 www 3957: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 3958: &escape($courselogs{$crsid}),
3959: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 3960: delete $courselogs{$crsid};
3961: } else {
3962: &logthis('Failed to flush log buffer for '.$crsid);
3963: if (length($courselogs{$crsid})>40000) {
1.672 albertel 3964: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 3965: " exceeded maximum size, deleting.</font>");
3966: delete $courselogs{$crsid};
3967: }
1.352 www 3968: }
1.920 raeburn 3969: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 3970: 'description' => $coursedescrbuf{$crsid},
3971: 'inst_code' => $courseinstcodebuf{$crsid},
3972: 'type' => $coursetypebuf{$crsid},
3973: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 3974: };
1.191 harris41 3975: }
1.352 www 3976: #
3977: # Write course id database (reverse lookup) to homeserver of courses
3978: # Is used in pickcourse
3979: #
1.840 albertel 3980: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 3981: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 3982: $courseidbuffer{$crs_home},
3983: $crs_home,'timeonly');
1.352 www 3984: }
3985: #
3986: # File accesses
3987: # Writes to the dynamic metadata of resources to get hit counts, etc.
3988: #
1.449 matthew 3989: foreach my $entry (keys(%accesshash)) {
1.458 matthew 3990: if ($entry =~ /___count$/) {
3991: my ($dom,$name);
1.807 albertel 3992: ($dom,$name,undef)=
1.811 albertel 3993: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 3994: if (! defined($dom) || $dom eq '' ||
3995: ! defined($name) || $name eq '') {
1.620 albertel 3996: my $cid = $env{'request.course.id'};
3997: $dom = $env{'request.'.$cid.'.domain'};
3998: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 3999: }
1.450 matthew 4000: my $value = $accesshash{$entry};
4001: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
4002: my %temphash=($url => $value);
1.449 matthew 4003: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
4004: if ($result eq 'ok') {
4005: delete $accesshash{$entry};
4006: }
4007: } else {
1.811 albertel 4008: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159 www 4009: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450 matthew 4010: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 4011: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
4012: delete $accesshash{$entry};
4013: }
1.185 www 4014: }
1.191 harris41 4015: }
1.352 www 4016: #
4017: # Roles
4018: # Reverse lookup of user roles for course faculty/staff and co-authorship
4019: #
1.800 albertel 4020: foreach my $entry (keys(%userrolehash)) {
1.351 www 4021: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 4022: split(/\:/,$entry);
4023: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 4024: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 4025: $rudom,$runame) eq 'ok') {
4026: delete $userrolehash{$entry};
4027: }
4028: }
1.662 raeburn 4029: #
4030: # Reverse lookup of domain roles (dc, ad, li, sc, au)
4031: #
4032: my %domrolebuffer = ();
1.1000 raeburn 4033: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 4034: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 4035: if ($domrolebuffer{$rudom}) {
4036: $domrolebuffer{$rudom}.='&'.&escape($entry).
4037: '='.&escape($domainrolehash{$entry});
4038: } else {
4039: $domrolebuffer{$rudom}.=&escape($entry).
4040: '='.&escape($domainrolehash{$entry});
4041: }
4042: delete $domainrolehash{$entry};
4043: }
4044: foreach my $dom (keys(%domrolebuffer)) {
1.841 albertel 4045: my %servers = &get_servers($dom,'library');
4046: foreach my $tryserver (keys(%servers)) {
4047: unless (&reply('domroleput:'.$dom.':'.
4048: $domrolebuffer{$dom},$tryserver) eq 'ok') {
4049: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
4050: }
1.662 raeburn 4051: }
4052: }
1.186 www 4053: $dumpcount++;
1.157 www 4054: }
4055:
4056: sub courselog {
4057: my $what=shift;
1.158 www 4058: $what=time.':'.$what;
1.620 albertel 4059: unless ($env{'request.course.id'}) { return ''; }
4060: $coursedombuf{$env{'request.course.id'}}=
4061: $env{'course.'.$env{'request.course.id'}.'.domain'};
4062: $coursenumbuf{$env{'request.course.id'}}=
4063: $env{'course.'.$env{'request.course.id'}.'.num'};
4064: $coursehombuf{$env{'request.course.id'}}=
4065: $env{'course.'.$env{'request.course.id'}.'.home'};
4066: $coursedescrbuf{$env{'request.course.id'}}=
4067: $env{'course.'.$env{'request.course.id'}.'.description'};
4068: $courseinstcodebuf{$env{'request.course.id'}}=
4069: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
4070: $courseownerbuf{$env{'request.course.id'}}=
4071: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 4072: $coursetypebuf{$env{'request.course.id'}}=
4073: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 4074: if (defined $courselogs{$env{'request.course.id'}}) {
4075: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 4076: } else {
1.620 albertel 4077: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 4078: }
1.620 albertel 4079: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 4080: &flushcourselogs();
4081: }
1.158 www 4082: }
4083:
4084: sub courseacclog {
4085: my $fnsymb=shift;
1.620 albertel 4086: unless ($env{'request.course.id'}) { return ''; }
4087: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144 www 4088: if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187 www 4089: $what.=':POST';
1.583 matthew 4090: # FIXME: Probably ought to escape things....
1.800 albertel 4091: foreach my $key (keys(%env)) {
4092: if ($key=~/^form\.(.*)/) {
1.975 raeburn 4093: my $formitem = $1;
4094: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
4095: $what.=':'.$formitem.'='.$env{$key};
4096: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
4097: $what.=':'.$formitem.'='.$env{$key};
4098: }
1.158 www 4099: }
1.191 harris41 4100: }
1.583 matthew 4101: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
4102: # FIXME: We should not be depending on a form parameter that someone
4103: # editing lonsearchcat.pm might change in the future.
1.620 albertel 4104: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 4105: $what.= ':POST';
4106: # FIXME: Probably ought to escape things....
4107: foreach my $element ('courseexp','crsfulltext','crsrelated',
4108: 'crsdiscuss') {
1.620 albertel 4109: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 4110: }
4111: }
1.158 www 4112: }
4113: &courselog($what);
1.149 www 4114: }
4115:
1.185 www 4116: sub countacc {
4117: my $url=&declutter(shift);
1.458 matthew 4118: return if (! defined($url) || $url eq '');
1.620 albertel 4119: unless ($env{'request.course.id'}) { return ''; }
1.1158 www 4120: #
4121: # Mark that this url was used in this course
4122: #
1.620 albertel 4123: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158 www 4124: #
4125: # Increase the access count for this resource in this child process
4126: #
1.281 www 4127: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 4128: $accesshash{$key}++;
1.185 www 4129: }
1.349 www 4130:
1.361 www 4131: sub linklog {
4132: my ($from,$to)=@_;
4133: $from=&declutter($from);
4134: $to=&declutter($to);
4135: $accesshash{$from.'___'.$to.'___comefrom'}=1;
4136: $accesshash{$to.'___'.$from.'___goto'}=1;
4137: }
1.1160 www 4138:
4139: sub statslog {
4140: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
4141: if ($users<2) { return; }
4142: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
4143: 'course' => $env{'request.course.id'},
4144: 'sections' => '"all"',
4145: 'num_students' => $users,
4146: 'part' => $part,
4147: 'symb' => $symb,
4148: 'mean_tries' => $av_attempts,
4149: 'deg_of_diff' => $degdiff});
4150: foreach my $key (keys(%dynstore)) {
4151: $accesshash{$key}=$dynstore{$key};
4152: }
4153: }
1.361 www 4154:
1.349 www 4155: sub userrolelog {
4156: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169 droeschl 4157: if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350 www 4158: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
4159: $userrolehash
4160: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 4161: =$tend.':'.$tstart;
1.662 raeburn 4162: }
1.1169 droeschl 4163: if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898 albertel 4164: $userrolehash
4165: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
4166: =$tend.':'.$tstart;
4167: }
1.1169 droeschl 4168: if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
1.662 raeburn 4169: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
4170: $domainrolehash
4171: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
4172: = $tend.':'.$tstart;
4173: }
1.351 www 4174: }
4175:
1.957 raeburn 4176: sub courserolelog {
4177: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1184 raeburn 4178: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
4179: my $cdom = $1;
4180: my $cnum = $2;
4181: my $sec = $3;
4182: my $namespace = 'rolelog';
4183: my %storehash = (
4184: role => $trole,
4185: start => $tstart,
4186: end => $tend,
4187: selfenroll => $selfenroll,
4188: context => $context,
4189: );
4190: if ($trole eq 'gr') {
4191: $namespace = 'groupslog';
4192: $storehash{'group'} = $sec;
4193: } else {
4194: $storehash{'section'} = $sec;
4195: }
1.1188 raeburn 4196: &write_log('course',$namespace,\%storehash,$delflag,$username,
4197: $domain,$cnum,$cdom);
1.1184 raeburn 4198: if (($trole ne 'st') || ($sec ne '')) {
4199: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957 raeburn 4200: }
4201: }
4202: return;
4203: }
4204:
1.1184 raeburn 4205: sub domainrolelog {
4206: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4207: if ($area =~ m{^/($match_domain)/$}) {
4208: my $cdom = $1;
4209: my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
4210: my $namespace = 'rolelog';
4211: my %storehash = (
4212: role => $trole,
4213: start => $tstart,
4214: end => $tend,
4215: context => $context,
4216: );
1.1188 raeburn 4217: &write_log('domain',$namespace,\%storehash,$delflag,$username,
4218: $domain,$domconfiguser,$cdom);
1.1184 raeburn 4219: }
4220: return;
4221:
4222: }
4223:
4224: sub coauthorrolelog {
4225: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4226: if ($area =~ m{^/($match_domain)/($match_username)$}) {
4227: my $audom = $1;
4228: my $auname = $2;
4229: my $namespace = 'rolelog';
4230: my %storehash = (
4231: role => $trole,
4232: start => $tstart,
4233: end => $tend,
4234: context => $context,
4235: );
1.1188 raeburn 4236: &write_log('author',$namespace,\%storehash,$delflag,$username,
4237: $domain,$auname,$audom);
1.1184 raeburn 4238: }
4239: return;
4240: }
4241:
1.351 www 4242: sub get_course_adv_roles {
1.948 raeburn 4243: my ($cid,$codes) = @_;
1.620 albertel 4244: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 4245: my %coursehash=&coursedescription($cid);
1.988 raeburn 4246: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 4247: my %nothide=();
1.800 albertel 4248: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 4249: if ($user !~ /:/) {
4250: $nothide{join(':',split(/[\@]/,$user))}=1;
4251: } else {
4252: $nothide{$user}=1;
4253: }
1.470 www 4254: }
1.1219 raeburn 4255: my @possdoms = ($coursehash{'domain'});
4256: if ($coursehash{'checkforpriv'}) {
4257: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
4258: }
1.351 www 4259: my %returnhash=();
4260: my %dumphash=
4261: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
4262: my $now=time;
1.997 raeburn 4263: my %privileged;
1.1000 raeburn 4264: foreach my $entry (keys(%dumphash)) {
1.800 albertel 4265: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 4266: if (($tstart) && ($tstart<0)) { next; }
4267: if (($tend) && ($tend<$now)) { next; }
4268: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 4269: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 4270: if ($username eq '' || $domain eq '') { next; }
1.1219 raeburn 4271: if ((&privileged($username,$domain,\@possdoms)) &&
1.997 raeburn 4272: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 4273: if ($role eq 'cr') { next; }
1.948 raeburn 4274: if ($codes) {
4275: if ($section) { $role .= ':'.$section; }
4276: if ($returnhash{$role}) {
4277: $returnhash{$role}.=','.$username.':'.$domain;
4278: } else {
4279: $returnhash{$role}=$username.':'.$domain;
4280: }
1.351 www 4281: } else {
1.988 raeburn 4282: my $key=&plaintext($role,$crstype);
1.973 bisitz 4283: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 4284: if ($returnhash{$key}) {
4285: $returnhash{$key}.=','.$username.':'.$domain;
4286: } else {
4287: $returnhash{$key}=$username.':'.$domain;
4288: }
1.351 www 4289: }
1.948 raeburn 4290: }
1.400 www 4291: return %returnhash;
4292: }
4293:
4294: sub get_my_roles {
1.937 raeburn 4295: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 4296: unless (defined($uname)) { $uname=$env{'user.name'}; }
4297: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 4298: my (%dumphash,%nothide);
1.1086 raeburn 4299: if ($context eq 'userroles') {
1.1166 raeburn 4300: %dumphash = &dump('roles',$udom,$uname);
1.858 raeburn 4301: } else {
1.1219 raeburn 4302: %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 4303: if ($hidepriv) {
4304: my %coursehash=&coursedescription($udom.'_'.$uname);
4305: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
4306: if ($user !~ /:/) {
4307: $nothide{join(':',split(/[\@]/,$user))} = 1;
4308: } else {
4309: $nothide{$user} = 1;
4310: }
4311: }
4312: }
1.858 raeburn 4313: }
1.400 www 4314: my %returnhash=();
4315: my $now=time;
1.999 raeburn 4316: my %privileged;
1.800 albertel 4317: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 4318: my ($role,$tend,$tstart);
4319: if ($context eq 'userroles') {
1.1149 raeburn 4320: next if ($entry =~ /^rolesdef/);
1.867 raeburn 4321: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
4322: } else {
4323: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
4324: }
1.400 www 4325: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 4326: my $status = 'active';
1.939 raeburn 4327: if (($tend) && ($tend<=$now)) {
1.832 raeburn 4328: $status = 'previous';
4329: }
4330: if (($tstart) && ($now<$tstart)) {
4331: $status = 'future';
4332: }
4333: if (ref($types) eq 'ARRAY') {
4334: if (!grep(/^\Q$status\E$/,@{$types})) {
4335: next;
4336: }
4337: } else {
4338: if ($status ne 'active') {
4339: next;
4340: }
4341: }
1.867 raeburn 4342: my ($rolecode,$username,$domain,$section,$area);
4343: if ($context eq 'userroles') {
1.1186 raeburn 4344: ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867 raeburn 4345: (undef,$domain,$username,$section) = split(/\//,$area);
4346: } else {
4347: ($role,$username,$domain,$section) = split(/\:/,$entry);
4348: }
1.832 raeburn 4349: if (ref($roledoms) eq 'ARRAY') {
4350: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
4351: next;
4352: }
4353: }
4354: if (ref($roles) eq 'ARRAY') {
4355: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 4356: if ($role =~ /^cr\//) {
4357: if (!grep(/^cr$/,@{$roles})) {
4358: next;
4359: }
1.1104 raeburn 4360: } elsif ($role =~ /^gr\//) {
4361: if (!grep(/^gr$/,@{$roles})) {
4362: next;
4363: }
1.922 raeburn 4364: } else {
4365: next;
4366: }
1.832 raeburn 4367: }
1.867 raeburn 4368: }
1.937 raeburn 4369: if ($hidepriv) {
1.1219 raeburn 4370: my @privroles = ('dc','su');
1.999 raeburn 4371: if ($context eq 'userroles') {
1.1219 raeburn 4372: next if (grep(/^\Q$role\E$/,@privroles));
1.999 raeburn 4373: } else {
1.1219 raeburn 4374: my $possdoms = [$domain];
4375: if (ref($roledoms) eq 'ARRAY') {
4376: push(@{$possdoms},@{$roledoms});
1.999 raeburn 4377: }
1.1219 raeburn 4378: if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999 raeburn 4379: if (!$nothide{$username.':'.$domain}) {
4380: next;
4381: }
4382: }
1.937 raeburn 4383: }
4384: }
1.933 raeburn 4385: if ($withsec) {
4386: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
4387: $tstart.':'.$tend;
4388: } else {
4389: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
4390: }
1.832 raeburn 4391: }
1.373 www 4392: return %returnhash;
1.399 www 4393: }
4394:
4395: # ----------------------------------------------------- Frontpage Announcements
4396: #
4397: #
4398:
4399: sub postannounce {
4400: my ($server,$text)=@_;
1.844 albertel 4401: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 4402: unless ($text=~/\w/) { $text=''; }
4403: return &reply('setannounce:'.&escape($text),$server);
4404: }
4405:
4406: sub getannounce {
1.448 albertel 4407:
4408: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 4409: my $announcement='';
1.800 albertel 4410: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 4411: close($fh);
1.399 www 4412: if ($announcement=~/\w/) {
4413: return
4414: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 4415: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 4416: } else {
4417: return '';
4418: }
4419: } else {
4420: return '';
4421: }
1.351 www 4422: }
1.353 www 4423:
4424: # ---------------------------------------------------------- Course ID routines
4425: # Deal with domain's nohist_courseid.db files
4426: #
4427:
4428: sub courseidput {
1.921 raeburn 4429: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 4430: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 4431: my $outcome;
4432: if ($caller eq 'timeonly') {
4433: my $cids = '';
4434: foreach my $item (keys(%$storehash)) {
4435: $cids.=&escape($item).'&';
4436: }
4437: $cids=~s/\&$//;
4438: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
4439: $coursehome);
4440: } else {
4441: my $items = '';
4442: foreach my $item (keys(%$storehash)) {
4443: $items.= &escape($item).'='.
4444: &freeze_escape($$storehash{$item}).'&';
4445: }
4446: $items=~s/\&$//;
4447: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
4448: $coursehome);
1.918 raeburn 4449: }
4450: if ($outcome eq 'unknown_cmd') {
4451: my $what;
4452: foreach my $cid (keys(%$storehash)) {
4453: $what .= &escape($cid).'=';
1.921 raeburn 4454: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 4455: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 4456: }
4457: $what =~ s/\:$/&/;
4458: }
4459: $what =~ s/\&$//;
4460: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
4461: } else {
4462: return $outcome;
4463: }
1.353 www 4464: }
4465:
4466: sub courseiddump {
1.921 raeburn 4467: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 4468: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 4469: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1247 raeburn 4470: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1287 raeburn 4471: $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918 raeburn 4472: my $as_hash = 1;
4473: my %returnhash;
4474: if (!$domfilter) { $domfilter=''; }
1.845 albertel 4475: my %libserv = &all_library();
4476: foreach my $tryserver (keys(%libserv)) {
4477: if ( ( $hostidflag == 1
4478: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
4479: || (!defined($hostidflag)) ) {
4480:
1.918 raeburn 4481: if (($domfilter eq '') ||
4482: (&host_domain($tryserver) eq $domfilter)) {
1.1180 droeschl 4483: my $rep;
4484: if (grep { $_ eq $tryserver } current_machine_ids()) {
4485: $rep = LONCAPA::Lond::dump_course_id_handler(
4486: join(":", (&host_domain($tryserver), $sincefilter,
4487: &escape($descfilter), &escape($instcodefilter),
4488: &escape($ownerfilter), &escape($coursefilter),
4489: &escape($typefilter), &escape($regexp_ok),
4490: $as_hash, &escape($selfenrollonly),
4491: &escape($catfilter), $showhidden, $caller,
4492: &escape($cloner), &escape($cc_clone), $cloneonly,
4493: &escape($createdbefore), &escape($createdafter),
1.1287 raeburn 4494: &escape($creationcontext),$domcloner,$hasuniquecode,
4495: $reqcrsdom,&escape($reqinstcode))));
1.1180 droeschl 4496: } else {
4497: $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
4498: $sincefilter.':'.&escape($descfilter).':'.
4499: &escape($instcodefilter).':'.&escape($ownerfilter).
4500: ':'.&escape($coursefilter).':'.&escape($typefilter).
4501: ':'.&escape($regexp_ok).':'.$as_hash.':'.
4502: &escape($selfenrollonly).':'.&escape($catfilter).':'.
4503: $showhidden.':'.$caller.':'.&escape($cloner).':'.
4504: &escape($cc_clone).':'.$cloneonly.':'.
4505: &escape($createdbefore).':'.&escape($createdafter).':'.
1.1287 raeburn 4506: &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
4507: ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1180 droeschl 4508: }
4509:
1.918 raeburn 4510: my @pairs=split(/\&/,$rep);
4511: foreach my $item (@pairs) {
4512: my ($key,$value)=split(/\=/,$item,2);
4513: $key = &unescape($key);
4514: next if ($key =~ /^error: 2 /);
4515: my $result = &thaw_unescape($value);
4516: if (ref($result) eq 'HASH') {
4517: $returnhash{$key}=$result;
4518: } else {
1.921 raeburn 4519: my @responses = split(/:/,$value);
4520: my @items = ('description','inst_code','owner','type');
1.918 raeburn 4521: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 4522: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 4523: }
1.1008 raeburn 4524: }
1.353 www 4525: }
4526: }
4527: }
4528: }
4529: return %returnhash;
4530: }
4531:
1.1055 raeburn 4532: sub courselastaccess {
4533: my ($cdom,$cnum,$hostidref) = @_;
4534: my %returnhash;
4535: if ($cdom && $cnum) {
4536: my $chome = &homeserver($cnum,$cdom);
4537: if ($chome ne 'no_host') {
4538: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
4539: &extract_lastaccess(\%returnhash,$rep);
4540: }
4541: } else {
4542: if (!$cdom) { $cdom=''; }
4543: my %libserv = &all_library();
4544: foreach my $tryserver (keys(%libserv)) {
4545: if (ref($hostidref) eq 'ARRAY') {
4546: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
4547: }
4548: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
4549: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
4550: &extract_lastaccess(\%returnhash,$rep);
4551: }
4552: }
4553: }
4554: return %returnhash;
4555: }
4556:
4557: sub extract_lastaccess {
4558: my ($returnhash,$rep) = @_;
4559: if (ref($returnhash) eq 'HASH') {
4560: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
4561: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
4562: $rep eq '') {
4563: my @pairs=split(/\&/,$rep);
4564: foreach my $item (@pairs) {
4565: my ($key,$value)=split(/\=/,$item,2);
4566: $key = &unescape($key);
4567: next if ($key =~ /^error: 2 /);
4568: $returnhash->{$key} = &thaw_unescape($value);
4569: }
4570: }
4571: }
4572: return;
4573: }
4574:
1.658 raeburn 4575: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 4576:
4577: sub dcmailput {
1.685 raeburn 4578: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 4579: my $status = &Apache::lonnet::critical(
1.740 www 4580: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
4581: &escape($message),$server);
1.662 raeburn 4582: return $status;
4583: }
4584:
1.658 raeburn 4585: sub dcmaildump {
4586: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 4587: my %returnhash=();
1.846 albertel 4588:
4589: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 4590: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
4591: &escape($enddate).':';
4592: my @esc_senders=map { &escape($_)} @$senders;
4593: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 4594: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 4595: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 4596: if (($key) && ($value)) {
4597: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 4598: }
4599: }
4600: }
4601: return %returnhash;
4602: }
1.662 raeburn 4603: # ---------------------------------------------------------- Domain roles
4604:
4605: sub get_domain_roles {
4606: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 4607: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 4608: $startdate = '.';
4609: }
1.1018 raeburn 4610: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 4611: $enddate = '.';
4612: }
1.922 raeburn 4613: my $rolelist;
4614: if (ref($roles) eq 'ARRAY') {
1.1219 raeburn 4615: $rolelist = join('&',@{$roles});
1.922 raeburn 4616: }
1.662 raeburn 4617: my %personnel = ();
1.841 albertel 4618:
4619: my %servers = &get_servers($dom,'library');
4620: foreach my $tryserver (keys(%servers)) {
4621: %{$personnel{$tryserver}}=();
4622: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
4623: &escape($startdate).':'.
4624: &escape($enddate).':'.
4625: &escape($rolelist), $tryserver))) {
4626: my ($key,$value) = split(/\=/,$line,2);
4627: if (($key) && ($value)) {
4628: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
4629: }
4630: }
1.662 raeburn 4631: }
4632: return %personnel;
4633: }
1.658 raeburn 4634:
1.1057 www 4635: # ----------------------------------------------------------- Interval timing
1.149 www 4636:
1.1153 www 4637: {
4638: # Caches needed for speedup of navmaps
4639: # We don't want to cache this for very long at all (5 seconds at most)
4640: #
4641: # The user for whom we cache
4642: my $cachedkey='';
4643: # The cached times for this user
4644: my %cachedtimes=();
4645: # When this was last done
1.1282 raeburn 4646: my $cachedtime='';
1.1153 www 4647:
4648: sub load_all_first_access {
1.1308 ! raeburn 4649: my ($uname,$udom,$ignorecache)=@_;
1.1156 www 4650: if (($cachedkey eq $uname.':'.$udom) &&
1.1308 ! raeburn 4651: (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
! 4652: (!$ignorecache)) {
1.1154 raeburn 4653: return;
4654: }
4655: $cachedtime=time;
4656: $cachedkey=$uname.':'.$udom;
4657: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153 www 4658: }
4659:
1.504 albertel 4660: sub get_first_access {
1.1308 ! raeburn 4661: my ($type,$argsymb,$argmap,$ignorecache)=@_;
1.790 albertel 4662: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4663: if ($argsymb) { $symb=$argsymb; }
4664: my ($map,$id,$res)=&decode_symb($symb);
1.1162 raeburn 4665: if ($argmap) { $map = $argmap; }
1.926 albertel 4666: if ($type eq 'course') {
4667: $res='course';
4668: } elsif ($type eq 'map') {
1.588 albertel 4669: $res=&symbread($map);
4670: } else {
4671: $res=$symb;
4672: }
1.1308 ! raeburn 4673: &load_all_first_access($uname,$udom,$ignorecache);
1.1153 www 4674: return $cachedtimes{"$courseid\0$res"};
1.504 albertel 4675: }
4676:
4677: sub set_first_access {
1.1162 raeburn 4678: my ($type,$interval)=@_;
1.790 albertel 4679: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4680: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 4681: if ($type eq 'course') {
4682: $res='course';
4683: } elsif ($type eq 'map') {
1.588 albertel 4684: $res=&symbread($map);
4685: } else {
4686: $res=$symb;
4687: }
1.1153 www 4688: $cachedkey='';
1.1162 raeburn 4689: my $firstaccess=&get_first_access($type,$symb,$map);
1.505 albertel 4690: if (!$firstaccess) {
1.1162 raeburn 4691: my $start = time;
4692: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
4693: $udom,$uname);
4694: if ($putres eq 'ok') {
4695: &put('timerinterval',{"$courseid\0$res"=>$interval},
4696: $udom,$uname);
4697: &appenv(
4698: {
4699: 'course.'.$courseid.'.firstaccess.'.$res => $start,
4700: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
4701: }
4702: );
4703: }
4704: return $putres;
1.505 albertel 4705: }
4706: return 'already_set';
1.504 albertel 4707: }
1.1153 www 4708: }
1.1282 raeburn 4709:
1.110 www 4710: # --------------------------------------------- Set Expire Date for Spreadsheet
4711:
4712: sub expirespread {
4713: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 4714: my $cid=$env{'request.course.id'};
1.110 www 4715: if ($cid) {
4716: my $now=time;
4717: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 4718: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
4719: $env{'course.'.$cid.'.num'}.
1.110 www 4720: ':nohist_expirationdates:'.
4721: &escape($key).'='.$now,
1.620 albertel 4722: $env{'course.'.$cid.'.home'})
1.110 www 4723: }
4724: return 'ok';
1.14 www 4725: }
4726:
1.109 www 4727: # ----------------------------------------------------- Devalidate Spreadsheets
4728:
4729: sub devalidate {
1.325 www 4730: my ($symb,$uname,$udom)=@_;
1.620 albertel 4731: my $cid=$env{'request.course.id'};
1.109 www 4732: if ($cid) {
1.391 matthew 4733: # delete the stored spreadsheets for
4734: # - the student level sheet of this user in course's homespace
4735: # - the assessment level sheet for this resource
4736: # for this user in user's homespace
1.553 albertel 4737: # - current conditional state info
1.325 www 4738: my $key=$uname.':'.$udom.':';
1.109 www 4739: my $status=
1.299 matthew 4740: &del('nohist_calculatedsheets',
1.391 matthew 4741: [$key.'studentcalc:'],
1.620 albertel 4742: $env{'course.'.$cid.'.domain'},
4743: $env{'course.'.$cid.'.num'})
1.133 albertel 4744: .' '.
4745: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 4746: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 4747: unless ($status eq 'ok ok') {
4748: &logthis('Could not devalidate spreadsheet '.
1.325 www 4749: $uname.' at '.$udom.' for '.
1.109 www 4750: $symb.': '.$status);
1.133 albertel 4751: }
1.553 albertel 4752: &delenv('user.state.'.$cid);
1.109 www 4753: }
4754: }
4755:
1.265 albertel 4756: sub get_scalar {
4757: my ($string,$end) = @_;
4758: my $value;
4759: if ($$string =~ s/^([^&]*?)($end)/$2/) {
4760: $value = $1;
4761: } elsif ($$string =~ s/^([^&]*?)&//) {
4762: $value = $1;
4763: }
4764: return &unescape($value);
4765: }
4766:
4767: sub array2str {
4768: my (@array) = @_;
4769: my $result=&arrayref2str(\@array);
4770: $result=~s/^__ARRAY_REF__//;
4771: $result=~s/__END_ARRAY_REF__$//;
4772: return $result;
4773: }
4774:
1.204 albertel 4775: sub arrayref2str {
4776: my ($arrayref) = @_;
1.265 albertel 4777: my $result='__ARRAY_REF__';
1.204 albertel 4778: foreach my $elem (@$arrayref) {
1.265 albertel 4779: if(ref($elem) eq 'ARRAY') {
4780: $result.=&arrayref2str($elem).'&';
4781: } elsif(ref($elem) eq 'HASH') {
4782: $result.=&hashref2str($elem).'&';
4783: } elsif(ref($elem)) {
4784: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 4785: } else {
4786: $result.=&escape($elem).'&';
4787: }
4788: }
4789: $result=~s/\&$//;
1.265 albertel 4790: $result .= '__END_ARRAY_REF__';
1.204 albertel 4791: return $result;
4792: }
4793:
1.168 albertel 4794: sub hash2str {
1.204 albertel 4795: my (%hash) = @_;
4796: my $result=&hashref2str(\%hash);
1.265 albertel 4797: $result=~s/^__HASH_REF__//;
4798: $result=~s/__END_HASH_REF__$//;
1.204 albertel 4799: return $result;
4800: }
4801:
4802: sub hashref2str {
4803: my ($hashref)=@_;
1.265 albertel 4804: my $result='__HASH_REF__';
1.800 albertel 4805: foreach my $key (sort(keys(%$hashref))) {
4806: if (ref($key) eq 'ARRAY') {
4807: $result.=&arrayref2str($key).'=';
4808: } elsif (ref($key) eq 'HASH') {
4809: $result.=&hashref2str($key).'=';
4810: } elsif (ref($key)) {
1.265 albertel 4811: $result.='=';
1.800 albertel 4812: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 4813: } else {
1.1132 raeburn 4814: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 4815: }
4816:
1.800 albertel 4817: if(ref($hashref->{$key}) eq 'ARRAY') {
4818: $result.=&arrayref2str($hashref->{$key}).'&';
4819: } elsif(ref($hashref->{$key}) eq 'HASH') {
4820: $result.=&hashref2str($hashref->{$key}).'&';
4821: } elsif(ref($hashref->{$key})) {
1.265 albertel 4822: $result.='&';
1.800 albertel 4823: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 4824: } else {
1.800 albertel 4825: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 4826: }
4827: }
1.168 albertel 4828: $result=~s/\&$//;
1.265 albertel 4829: $result .= '__END_HASH_REF__';
1.168 albertel 4830: return $result;
4831: }
4832:
4833: sub str2hash {
1.265 albertel 4834: my ($string)=@_;
4835: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
4836: return %$hash;
4837: }
4838:
4839: sub str2hashref {
1.168 albertel 4840: my ($string) = @_;
1.265 albertel 4841:
4842: my %hash;
4843:
4844: if($string !~ /^__HASH_REF__/) {
4845: if (! ($string eq '' || !defined($string))) {
4846: $hash{'error'}='Not hash reference';
4847: }
4848: return (\%hash, $string);
4849: }
4850:
4851: $string =~ s/^__HASH_REF__//;
4852:
4853: while($string !~ /^__END_HASH_REF__/) {
4854: #key
4855: my $key='';
4856: if($string =~ /^__HASH_REF__/) {
4857: ($key, $string)=&str2hashref($string);
4858: if(defined($key->{'error'})) {
4859: $hash{'error'}='Bad data';
4860: return (\%hash, $string);
4861: }
4862: } elsif($string =~ /^__ARRAY_REF__/) {
4863: ($key, $string)=&str2arrayref($string);
4864: if($key->[0] eq 'Array reference error') {
4865: $hash{'error'}='Bad data';
4866: return (\%hash, $string);
4867: }
4868: } else {
4869: $string =~ s/^(.*?)=//;
1.267 albertel 4870: $key=&unescape($1);
1.265 albertel 4871: }
4872: $string =~ s/^=//;
4873:
4874: #value
4875: my $value='';
4876: if($string =~ /^__HASH_REF__/) {
4877: ($value, $string)=&str2hashref($string);
4878: if(defined($value->{'error'})) {
4879: $hash{'error'}='Bad data';
4880: return (\%hash, $string);
4881: }
4882: } elsif($string =~ /^__ARRAY_REF__/) {
4883: ($value, $string)=&str2arrayref($string);
4884: if($value->[0] eq 'Array reference error') {
4885: $hash{'error'}='Bad data';
4886: return (\%hash, $string);
4887: }
4888: } else {
4889: $value=&get_scalar(\$string,'__END_HASH_REF__');
4890: }
4891: $string =~ s/^&//;
4892:
4893: $hash{$key}=$value;
1.204 albertel 4894: }
1.265 albertel 4895:
4896: $string =~ s/^__END_HASH_REF__//;
4897:
4898: return (\%hash, $string);
1.204 albertel 4899: }
4900:
4901: sub str2array {
1.265 albertel 4902: my ($string)=@_;
4903: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
4904: return @$array;
4905: }
4906:
4907: sub str2arrayref {
1.204 albertel 4908: my ($string) = @_;
1.265 albertel 4909: my @array;
4910:
4911: if($string !~ /^__ARRAY_REF__/) {
4912: if (! ($string eq '' || !defined($string))) {
4913: $array[0]='Array reference error';
4914: }
4915: return (\@array, $string);
4916: }
4917:
4918: $string =~ s/^__ARRAY_REF__//;
4919:
4920: while($string !~ /^__END_ARRAY_REF__/) {
4921: my $value='';
4922: if($string =~ /^__HASH_REF__/) {
4923: ($value, $string)=&str2hashref($string);
4924: if(defined($value->{'error'})) {
4925: $array[0] ='Array reference error';
4926: return (\@array, $string);
4927: }
4928: } elsif($string =~ /^__ARRAY_REF__/) {
4929: ($value, $string)=&str2arrayref($string);
4930: if($value->[0] eq 'Array reference error') {
4931: $array[0] ='Array reference error';
4932: return (\@array, $string);
4933: }
4934: } else {
4935: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
4936: }
4937: $string =~ s/^&//;
4938:
4939: push(@array, $value);
1.191 harris41 4940: }
1.265 albertel 4941:
4942: $string =~ s/^__END_ARRAY_REF__//;
4943:
4944: return (\@array, $string);
1.168 albertel 4945: }
4946:
1.167 albertel 4947: # -------------------------------------------------------------------Temp Store
4948:
1.168 albertel 4949: sub tmpreset {
4950: my ($symb,$namespace,$domain,$stuname) = @_;
4951: if (!$symb) {
4952: $symb=&symbread();
1.620 albertel 4953: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4954: }
4955: $symb=escape($symb);
4956:
1.620 albertel 4957: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 4958: $namespace=~s/\//\_/g;
4959: $namespace=~s/\W//g;
4960:
1.620 albertel 4961: if (!$domain) { $domain=$env{'user.domain'}; }
4962: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4963: if ($domain eq 'public' && $stuname eq 'public') {
4964: $stuname=$ENV{'REMOTE_ADDR'};
4965: }
1.1117 foxr 4966: my $path=LONCAPA::tempdir();
1.168 albertel 4967: my %hash;
4968: if (tie(%hash,'GDBM_File',
4969: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4970: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 4971: foreach my $key (keys(%hash)) {
1.180 albertel 4972: if ($key=~ /:$symb/) {
1.168 albertel 4973: delete($hash{$key});
4974: }
4975: }
4976: }
4977: }
4978:
1.167 albertel 4979: sub tmpstore {
1.168 albertel 4980: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4981:
4982: if (!$symb) {
4983: $symb=&symbread();
1.620 albertel 4984: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4985: }
4986: $symb=escape($symb);
4987:
4988: if (!$namespace) {
4989: # I don't think we would ever want to store this for a course.
4990: # it seems this will only be used if we don't have a course.
1.620 albertel 4991: #$namespace=$env{'request.course.id'};
1.168 albertel 4992: #if (!$namespace) {
1.620 albertel 4993: $namespace=$env{'request.state'};
1.168 albertel 4994: #}
4995: }
4996: $namespace=~s/\//\_/g;
4997: $namespace=~s/\W//g;
1.620 albertel 4998: if (!$domain) { $domain=$env{'user.domain'}; }
4999: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 5000: if ($domain eq 'public' && $stuname eq 'public') {
5001: $stuname=$ENV{'REMOTE_ADDR'};
5002: }
1.168 albertel 5003: my $now=time;
5004: my %hash;
1.1117 foxr 5005: my $path=LONCAPA::tempdir();
1.168 albertel 5006: if (tie(%hash,'GDBM_File',
5007: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 5008: &GDBM_WRCREAT(),0640)) {
1.168 albertel 5009: $hash{"version:$symb"}++;
5010: my $version=$hash{"version:$symb"};
5011: my $allkeys='';
5012: foreach my $key (keys(%$storehash)) {
5013: $allkeys.=$key.':';
1.591 albertel 5014: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 5015: }
5016: $hash{"$version:$symb:timestamp"}=$now;
5017: $allkeys.='timestamp';
5018: $hash{"$version:keys:$symb"}=$allkeys;
5019: if (untie(%hash)) {
5020: return 'ok';
5021: } else {
5022: return "error:$!";
5023: }
5024: } else {
5025: return "error:$!";
5026: }
5027: }
1.167 albertel 5028:
1.168 albertel 5029: # -----------------------------------------------------------------Temp Restore
1.167 albertel 5030:
1.168 albertel 5031: sub tmprestore {
5032: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 5033:
1.168 albertel 5034: if (!$symb) {
5035: $symb=&symbread();
1.620 albertel 5036: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 5037: }
5038: $symb=escape($symb);
5039:
1.620 albertel 5040: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 5041:
1.620 albertel 5042: if (!$domain) { $domain=$env{'user.domain'}; }
5043: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 5044: if ($domain eq 'public' && $stuname eq 'public') {
5045: $stuname=$ENV{'REMOTE_ADDR'};
5046: }
1.168 albertel 5047: my %returnhash;
5048: $namespace=~s/\//\_/g;
5049: $namespace=~s/\W//g;
5050: my %hash;
1.1117 foxr 5051: my $path=LONCAPA::tempdir();
1.168 albertel 5052: if (tie(%hash,'GDBM_File',
5053: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 5054: &GDBM_READER(),0640)) {
1.168 albertel 5055: my $version=$hash{"version:$symb"};
5056: $returnhash{'version'}=$version;
5057: my $scope;
5058: for ($scope=1;$scope<=$version;$scope++) {
5059: my $vkeys=$hash{"$scope:keys:$symb"};
5060: my @keys=split(/:/,$vkeys);
5061: my $key;
5062: $returnhash{"$scope:keys"}=$vkeys;
5063: foreach $key (@keys) {
1.591 albertel 5064: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
5065: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 5066: }
5067: }
1.168 albertel 5068: if (!(untie(%hash))) {
5069: return "error:$!";
5070: }
5071: } else {
5072: return "error:$!";
5073: }
5074: return %returnhash;
1.167 albertel 5075: }
5076:
1.9 www 5077: # ----------------------------------------------------------------------- Store
5078:
5079: sub store {
1.1269 raeburn 5080: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 5081: my $home='';
5082:
1.168 albertel 5083: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 5084:
1.213 www 5085: $symb=&symbclean($symb);
1.122 albertel 5086: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 5087:
1.620 albertel 5088: if (!$domain) { $domain=$env{'user.domain'}; }
5089: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 5090:
5091: &devalidate($symb,$stuname,$domain);
1.109 www 5092:
5093: $symb=escape($symb);
1.187 www 5094: if (!$namespace) {
1.620 albertel 5095: unless ($namespace=$env{'request.course.id'}) {
1.187 www 5096: return '';
5097: }
5098: }
1.620 albertel 5099: if (!$home) { $home=$env{'user.home'}; }
1.447 www 5100:
5101: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
5102: $$storehash{'host'}=$perlvar{'lonHostID'};
5103:
1.12 www 5104: my $namevalue='';
1.800 albertel 5105: foreach my $key (keys(%$storehash)) {
5106: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 5107: }
1.12 www 5108: $namevalue=~s/\&$//;
1.187 www 5109: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1269 raeburn 5110: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9 www 5111: }
5112:
1.47 www 5113: # -------------------------------------------------------------- Critical Store
5114:
5115: sub cstore {
1.1269 raeburn 5116: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 5117: my $home='';
5118:
1.168 albertel 5119: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 5120:
1.213 www 5121: $symb=&symbclean($symb);
1.122 albertel 5122: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 5123:
1.620 albertel 5124: if (!$domain) { $domain=$env{'user.domain'}; }
5125: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 5126:
5127: &devalidate($symb,$stuname,$domain);
1.109 www 5128:
5129: $symb=escape($symb);
1.187 www 5130: if (!$namespace) {
1.620 albertel 5131: unless ($namespace=$env{'request.course.id'}) {
1.187 www 5132: return '';
5133: }
5134: }
1.620 albertel 5135: if (!$home) { $home=$env{'user.home'}; }
1.447 www 5136:
5137: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
5138: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 5139:
1.47 www 5140: my $namevalue='';
1.800 albertel 5141: foreach my $key (keys(%$storehash)) {
5142: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 5143: }
1.47 www 5144: $namevalue=~s/\&$//;
1.187 www 5145: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 5146: return critical
1.1269 raeburn 5147: ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47 www 5148: }
5149:
1.9 www 5150: # --------------------------------------------------------------------- Restore
5151:
5152: sub restore {
1.124 www 5153: my ($symb,$namespace,$domain,$stuname) = @_;
5154: my $home='';
5155:
1.168 albertel 5156: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 5157:
1.122 albertel 5158: if (!$symb) {
1.1224 raeburn 5159: return if ($namespace eq 'courserequests');
5160: unless ($symb=escape(&symbread())) { return ''; }
1.122 albertel 5161: } else {
1.1224 raeburn 5162: unless ($namespace eq 'courserequests') {
5163: $symb=&escape(&symbclean($symb));
5164: }
1.122 albertel 5165: }
1.188 www 5166: if (!$namespace) {
1.620 albertel 5167: unless ($namespace=$env{'request.course.id'}) {
1.188 www 5168: return '';
5169: }
5170: }
1.620 albertel 5171: if (!$domain) { $domain=$env{'user.domain'}; }
5172: if (!$stuname) { $stuname=$env{'user.name'}; }
5173: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 5174: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
5175:
1.12 www 5176: my %returnhash=();
1.800 albertel 5177: foreach my $line (split(/\&/,$answer)) {
5178: my ($name,$value)=split(/\=/,$line);
1.591 albertel 5179: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 5180: }
1.75 www 5181: my $version;
5182: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 5183: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
5184: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 5185: }
1.75 www 5186: }
1.13 www 5187: return %returnhash;
1.34 www 5188: }
5189:
5190: # ---------------------------------------------------------- Course Description
1.1118 foxr 5191: #
5192: #
1.34 www 5193:
5194: sub coursedescription {
1.731 albertel 5195: my ($courseid,$args)=@_;
1.34 www 5196: $courseid=~s/^\///;
1.49 www 5197: $courseid=~s/\_/\//g;
1.34 www 5198: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 5199: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 5200: my $normalid=$cdomain.'_'.$cnum;
5201: # need to always cache even if we get errors otherwise we keep
5202: # trying and trying and trying to get the course description.
5203: my %envhash=();
5204: my %returnhash=();
1.731 albertel 5205:
5206: my $expiretime=600;
5207: if ($env{'request.course.id'} eq $normalid) {
5208: $expiretime=120;
5209: }
5210:
5211: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
5212: if (!$args->{'freshen_cache'}
5213: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
5214: foreach my $key (keys(%env)) {
5215: next if ($key !~ /^\Q$prefix\E(.*)/);
5216: my ($setting) = $1;
5217: $returnhash{$setting} = $env{$key};
5218: }
5219: return %returnhash;
5220: }
5221:
1.1118 foxr 5222: # get the data again
5223:
1.731 albertel 5224: if (!$args->{'one_time'}) {
5225: $envhash{'course.'.$normalid.'.last_cache'}=time;
5226: }
1.811 albertel 5227:
1.34 www 5228: if ($chome ne 'no_host') {
1.302 albertel 5229: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 5230: if (!exists($returnhash{'con_lost'})) {
1.1118 foxr 5231: my $username = $env{'user.name'}; # Defult username
5232: if(defined $args->{'user'}) {
5233: $username = $args->{'user'};
5234: }
1.129 albertel 5235: $returnhash{'home'}= $chome;
5236: $returnhash{'domain'} = $cdomain;
5237: $returnhash{'num'} = $cnum;
1.741 raeburn 5238: if (!defined($returnhash{'type'})) {
5239: $returnhash{'type'} = 'Course';
5240: }
1.130 albertel 5241: while (my ($name,$value) = each %returnhash) {
1.53 www 5242: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 5243: }
1.270 www 5244: $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117 foxr 5245: $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118 foxr 5246: $username.'_'.$cdomain.'_'.$cnum;
1.60 www 5247: $envhash{'course.'.$normalid.'.home'}=$chome;
5248: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
5249: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 5250: }
5251: }
1.731 albertel 5252: if (!$args->{'one_time'}) {
1.949 raeburn 5253: &appenv(\%envhash);
1.731 albertel 5254: }
1.302 albertel 5255: return %returnhash;
1.461 www 5256: }
5257:
1.1080 raeburn 5258: sub update_released_required {
5259: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
5260: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
5261: $cid = $env{'request.course.id'};
5262: $cdom = $env{'course.'.$cid.'.domain'};
5263: $cnum = $env{'course.'.$cid.'.num'};
5264: $chome = $env{'course.'.$cid.'.home'};
5265: }
5266: if ($needsrelease) {
5267: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
5268: my $needsupdate;
5269: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
5270: $needsupdate = 1;
5271: } else {
5272: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
5273: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
5274: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
5275: $needsupdate = 1;
5276: }
5277: }
5278: if ($needsupdate) {
5279: my %needshash = (
5280: 'internal.releaserequired' => $needsrelease,
5281: );
5282: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
5283: if ($putresult eq 'ok') {
5284: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
5285: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
5286: if (ref($crsinfo{$cid}) eq 'HASH') {
5287: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
5288: &courseidput($cdom,\%crsinfo,$chome,'notime');
5289: }
5290: }
5291: }
5292: }
5293: return;
5294: }
5295:
1.461 www 5296: # -------------------------------------------------See if a user is privileged
5297:
5298: sub privileged {
1.1219 raeburn 5299: my ($username,$domain,$possdomains,$possroles)=@_;
1.1170 droeschl 5300: my $now = time;
1.1219 raeburn 5301: my $roles;
5302: if (ref($possroles) eq 'ARRAY') {
5303: $roles = $possroles;
5304: } else {
5305: $roles = ['dc','su'];
5306: }
5307: if (ref($possdomains) eq 'ARRAY') {
5308: my %privileged = &privileged_by_domain($possdomains,$roles);
5309: foreach my $dom (@{$possdomains}) {
5310: if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
5311: (ref($privileged{$dom}) eq 'HASH')) {
5312: foreach my $role (@{$roles}) {
5313: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5314: if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
5315: my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
5316: return 1 unless (($end && $end < $now) ||
5317: ($start && $start > $now));
5318: }
5319: }
5320: }
5321: }
5322: }
5323: } else {
5324: my %rolesdump = &dump("roles", $domain, $username) or return 0;
5325: my $now = time;
1.1170 droeschl 5326:
1.1275 musolffc 5327: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170 droeschl 5328: my ($trole, $tend, $tstart) = split(/_/, $role);
1.1219 raeburn 5329: if (grep(/^\Q$trole\E$/,@{$roles})) {
1.1170 droeschl 5330: return 1 unless ($tend && $tend < $now)
1.1219 raeburn 5331: or ($tstart && $tstart > $now);
1.1170 droeschl 5332: }
1.1219 raeburn 5333: }
5334: }
5335: return 0;
5336: }
1.1170 droeschl 5337:
1.1219 raeburn 5338: sub privileged_by_domain {
5339: my ($domains,$roles) = @_;
5340: my %privileged = ();
5341: my $cachetime = 60*60*24;
5342: my $now = time;
5343: unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
5344: return %privileged;
5345: }
5346: foreach my $dom (@{$domains}) {
5347: next if (ref($privileged{$dom}) eq 'HASH');
5348: my $needroles;
5349: foreach my $role (@{$roles}) {
5350: my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
5351: if (defined($cached)) {
5352: if (ref($result) eq 'HASH') {
5353: $privileged{$dom}{$role} = $result;
5354: }
5355: } else {
5356: $needroles = 1;
5357: }
5358: }
5359: if ($needroles) {
5360: my %dompersonnel = &get_domain_roles($dom,$roles);
5361: $privileged{$dom} = {};
5362: foreach my $server (keys(%dompersonnel)) {
5363: if (ref($dompersonnel{$server}) eq 'HASH') {
5364: foreach my $item (keys(%{$dompersonnel{$server}})) {
5365: my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
5366: my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
5367: next if ($end && $end < $now);
5368: $privileged{$dom}{$trole}{$uname.':'.$udom} =
5369: $dompersonnel{$server}{$item};
5370: }
5371: }
5372: }
5373: if (ref($privileged{$dom}) eq 'HASH') {
5374: foreach my $role (@{$roles}) {
5375: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5376: &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
5377: } else {
5378: my %hash = ();
5379: &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
5380: }
5381: }
5382: }
5383: }
5384: }
5385: return %privileged;
1.9 www 5386: }
1.1 albertel 5387:
1.103 harris41 5388: # -------------------------------------------------------- Get user privileges
1.11 www 5389:
5390: sub rolesinit {
1.1169 droeschl 5391: my ($domain, $username) = @_;
5392: my %userroles = ('user.login.time' => time);
5393: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
5394:
5395: # firstaccess and timerinterval are related to timed maps/resources.
5396: # also, blocking can be triggered by an activating timer
5397: # it's saved in the user's %env.
5398: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
5399: my %timerinterval = &dump('timerinterval', $domain, $username);
5400: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
5401: %timerintchk, %timerintenv);
5402:
1.1162 raeburn 5403: foreach my $key (keys(%firstaccess)) {
1.1169 droeschl 5404: my ($cid, $rest) = split(/\0/, $key);
1.1162 raeburn 5405: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
5406: }
1.1169 droeschl 5407:
1.1162 raeburn 5408: foreach my $key (keys(%timerinterval)) {
5409: my ($cid,$rest) = split(/\0/,$key);
5410: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
5411: }
1.1169 droeschl 5412:
1.11 www 5413: my %allroles=();
1.1162 raeburn 5414: my %allgroups=();
1.11 www 5415:
1.1274 raeburn 5416: for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169 droeschl 5417: my $role = $rolesdump{$area};
5418: $area =~ s/\_\w\w$//;
5419:
5420: my ($trole, $tend, $tstart, $group_privs);
5421:
5422: if ($role =~ /^cr/) {
5423: # Custom role, defined by a user
5424: # e.g., user.role.cr/msu/smith/mynewrole
5425: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
5426: $trole = $1;
5427: ($tend, $tstart) = split('_', $2);
5428: } else {
5429: $trole = $role;
5430: }
5431: } elsif ($role =~ m|^gr/|) {
5432: # Role of member in a group, defined within a course/community
5433: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
5434: ($trole, $tend, $tstart) = split(/_/, $role);
5435: next if $tstart eq '-1';
5436: ($trole, $group_privs) = split(/\//, $trole);
5437: $group_privs = &unescape($group_privs);
5438: } else {
5439: # Just a normal role, defined in roles.tab
5440: ($trole, $tend, $tstart) = split(/_/,$role);
5441: }
5442:
5443: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
5444: $username);
5445: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
5446:
5447: # role expired or not available yet?
5448: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
5449: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
5450:
5451: next if $area eq '' or $trole eq '';
5452:
5453: my $spec = "$trole.$area";
5454: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
5455:
5456: if ($trole =~ /^cr\//) {
5457: # Custom role, defined by a user
5458: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5459: } elsif ($trole eq 'gr') {
5460: # Role of a member in a group, defined within a course/community
5461: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
5462: next;
5463: } else {
5464: # Normal role, defined in roles.tab
5465: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5466: }
5467:
5468: my $cid = $tdomain.'_'.$trest;
5469: unless ($firstaccchk{$cid}) {
5470: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
5471: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
5472: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
5473: $coursetimerstarts{$cid}{$item};
5474: }
5475: }
5476: $firstaccchk{$cid} = 1;
5477: }
5478: unless ($timerintchk{$cid}) {
5479: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
5480: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
5481: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
5482: $coursetimerintervals{$cid}{$item};
1.1162 raeburn 5483: }
1.12 www 5484: }
1.1169 droeschl 5485: $timerintchk{$cid} = 1;
1.191 harris41 5486: }
1.11 www 5487: }
1.1169 droeschl 5488:
5489: @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
5490: \%allroles, \%allgroups);
5491: $env{'user.adv'} = $userroles{'user.adv'};
5492:
1.1162 raeburn 5493: return (\%userroles,\%firstaccenv,\%timerintenv);
1.11 www 5494: }
5495:
1.567 raeburn 5496: sub set_arearole {
1.1215 raeburn 5497: my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
5498: unless ($nolog) {
1.567 raeburn 5499: # log the associated role with the area
1.1215 raeburn 5500: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
5501: }
1.743 albertel 5502: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 5503: }
5504:
5505: sub custom_roleprivs {
5506: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
5507: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1250 raeburn 5508: my $homsvr = &homeserver($rauthor,$rdomain);
1.838 albertel 5509: if (&hostname($homsvr) ne '') {
1.567 raeburn 5510: my ($rdummy,$roledef)=
5511: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
5512: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
5513: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
5514: if (defined($syspriv)) {
1.1043 raeburn 5515: if ($trest =~ /^$match_community$/) {
5516: $syspriv =~ s/bre\&S//;
5517: }
1.567 raeburn 5518: $$allroles{'cm./'}.=':'.$syspriv;
5519: $$allroles{$spec.'./'}.=':'.$syspriv;
5520: }
5521: if ($tdomain ne '') {
5522: if (defined($dompriv)) {
5523: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
5524: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
5525: }
5526: if (($trest ne '') && (defined($coursepriv))) {
5527: $$allroles{'cm.'.$area}.=':'.$coursepriv;
5528: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
5529: }
5530: }
5531: }
5532: }
5533: }
5534:
1.678 raeburn 5535: sub group_roleprivs {
5536: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
5537: my $access = 1;
5538: my $now = time;
5539: if (($tend!=0) && ($tend<$now)) { $access = 0; }
5540: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
5541: if ($access) {
1.811 albertel 5542: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 5543: $$allgroups{$course}{$group} .=':'.$group_privs;
5544: }
5545: }
1.567 raeburn 5546:
5547: sub standard_roleprivs {
5548: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
5549: if (defined($pr{$trole.':s'})) {
5550: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
5551: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
5552: }
5553: if ($tdomain ne '') {
5554: if (defined($pr{$trole.':d'})) {
5555: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5556: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5557: }
5558: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
5559: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
5560: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
5561: }
5562: }
5563: }
5564:
5565: sub set_userprivs {
1.1064 raeburn 5566: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 5567: my $author=0;
5568: my $adv=0;
1.678 raeburn 5569: my %grouproles = ();
5570: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 5571: my @groupkeys;
1.1000 raeburn 5572: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 5573: push(@groupkeys,$role);
5574: }
5575: if (ref($groups_roles) eq 'HASH') {
5576: foreach my $key (keys(%{$groups_roles})) {
5577: unless (grep(/^\Q$key\E$/,@groupkeys)) {
5578: push(@groupkeys,$key);
5579: }
5580: }
5581: }
5582: if (@groupkeys > 0) {
5583: foreach my $role (@groupkeys) {
5584: my ($trole,$area,$sec,$extendedarea);
5585: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
5586: $trole = $1;
5587: $area = $2;
5588: $sec = $3;
5589: $extendedarea = $area.$sec;
5590: if (exists($$allgroups{$area})) {
5591: foreach my $group (keys(%{$$allgroups{$area}})) {
5592: my $spec = $trole.'.'.$extendedarea;
5593: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 5594: $$allgroups{$area}{$group};
1.1064 raeburn 5595: }
1.678 raeburn 5596: }
5597: }
5598: }
5599: }
5600: }
1.800 albertel 5601: foreach my $group (keys(%grouproles)) {
5602: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 5603: }
1.800 albertel 5604: foreach my $role (keys(%{$allroles})) {
5605: my %thesepriv;
1.941 raeburn 5606: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 5607: foreach my $item (split(/:/,$$allroles{$role})) {
5608: if ($item ne '') {
5609: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 5610: if ($restrictions eq '') {
5611: $thesepriv{$privilege}='F';
5612: } elsif ($thesepriv{$privilege} ne 'F') {
5613: $thesepriv{$privilege}.=$restrictions;
5614: }
5615: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
5616: }
5617: }
5618: my $thesestr='';
1.1104 raeburn 5619: foreach my $priv (sort(keys(%thesepriv))) {
1.800 albertel 5620: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
5621: }
5622: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 5623: }
5624: return ($author,$adv);
5625: }
5626:
1.994 raeburn 5627: sub role_status {
1.1104 raeburn 5628: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 5629: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1250 raeburn 5630: my ($one,$two) = split(m{\./},$rolekey,2);
5631: (undef,undef,$$role) = split(/\./,$one,3);
1.994 raeburn 5632: unless (!defined($$role) || $$role eq '') {
1.1251 raeburn 5633: $$where = '/'.$two;
1.994 raeburn 5634: $$trolecode=$$role.'.'.$$where;
5635: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
5636: $$tstatus='is';
1.1104 raeburn 5637: if ($$tstart && $$tstart>$update) {
1.994 raeburn 5638: $$tstatus='future';
1.1034 raeburn 5639: if ($$tstart<$now) {
5640: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 5641: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 5642: my (%allroles,%allgroups,$group_privs,
5643: %groups_roles,@rolecodes);
1.1002 raeburn 5644: my %userroles = (
5645: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
5646: );
1.1064 raeburn 5647: @rolecodes = ('cm');
1.1002 raeburn 5648: my $spec=$$role.'.'.$$where;
5649: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
5650: if ($$role =~ /^cr\//) {
5651: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 5652: push(@rolecodes,'cr');
1.1002 raeburn 5653: } elsif ($$role eq 'gr') {
1.1064 raeburn 5654: push(@rolecodes,$$role);
1.1002 raeburn 5655: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
5656: $env{'user.name'});
1.1064 raeburn 5657: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 5658: (undef,my $group_privs) = split(/\//,$trole);
5659: $group_privs = &unescape($group_privs);
5660: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 5661: 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 5662: &get_groups_roles($tdomain,$trest,
5663: \%course_roles,\@rolecodes,
5664: \%groups_roles);
1.1002 raeburn 5665: } else {
1.1064 raeburn 5666: push(@rolecodes,$$role);
1.1002 raeburn 5667: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
5668: }
1.1064 raeburn 5669: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
5670: &appenv(\%userroles,\@rolecodes);
1.1002 raeburn 5671: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
5672: }
5673: }
1.1034 raeburn 5674: $$tstatus = 'is';
1.1002 raeburn 5675: }
1.994 raeburn 5676: }
5677: if ($$tend) {
1.1104 raeburn 5678: if ($$tend<$update) {
1.994 raeburn 5679: $$tstatus='expired';
5680: } elsif ($$tend<$now) {
5681: $$tstatus='will_not';
5682: }
5683: }
5684: }
5685: }
5686: }
5687:
1.1104 raeburn 5688: sub get_groups_roles {
5689: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
5690: return unless((ref($cdom_courseroles) eq 'HASH') &&
5691: (ref($rolecodes) eq 'ARRAY') &&
5692: (ref($groups_roles) eq 'HASH'));
5693: if (keys(%{$cdom_courseroles}) > 0) {
5694: my ($cnum) = ($rest =~ /^($match_courseid)/);
5695: if ($cdom ne '' && $cnum ne '') {
5696: foreach my $key (keys(%{$cdom_courseroles})) {
5697: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
5698: my $crsrole = $1;
5699: my $crssec = $2;
5700: if ($crsrole =~ /^cr/) {
5701: unless (grep(/^cr$/,@{$rolecodes})) {
5702: push(@{$rolecodes},'cr');
5703: }
5704: } else {
5705: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
5706: push(@{$rolecodes},$crsrole);
5707: }
5708: }
5709: my $rolekey = "$crsrole./$cdom/$cnum";
5710: if ($crssec ne '') {
5711: $rolekey .= "/$crssec";
5712: }
5713: $rolekey .= './';
5714: $groups_roles->{$rolekey} = $rolecodes;
5715: }
5716: }
5717: }
5718: }
5719: return;
5720: }
5721:
5722: sub delete_env_groupprivs {
5723: my ($where,$courseroles,$possroles) = @_;
5724: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
5725: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
5726: unless (ref($courseroles->{$udom}) eq 'HASH') {
5727: %{$courseroles->{$udom}} =
5728: &get_my_roles('','','userroles',['active'],
5729: $possroles,[$udom],1);
5730: }
5731: if (ref($courseroles->{$udom}) eq 'HASH') {
5732: foreach my $item (keys(%{$courseroles->{$udom}})) {
5733: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
5734: my $area = '/'.$cdom.'/'.$cnum;
5735: my $privkey = "user.priv.$crsrole.$area";
5736: if ($crssec ne '') {
5737: $privkey .= '/'.$crssec;
5738: }
5739: $privkey .= ".$area/$group";
5740: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
5741: }
5742: }
5743: return;
5744: }
5745:
1.994 raeburn 5746: sub check_adhoc_privs {
1.1104 raeburn 5747: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994 raeburn 5748: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1185 raeburn 5749: my $setprivs;
1.994 raeburn 5750: if ($env{$cckey}) {
5751: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104 raeburn 5752: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 5753: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088 raeburn 5754: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185 raeburn 5755: $setprivs = 1;
1.994 raeburn 5756: }
5757: } else {
1.1088 raeburn 5758: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185 raeburn 5759: $setprivs = 1;
1.994 raeburn 5760: }
1.1185 raeburn 5761: return $setprivs;
1.994 raeburn 5762: }
5763:
5764: sub set_adhoc_privileges {
5765: # role can be cc or ca
1.1088 raeburn 5766: my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994 raeburn 5767: my $area = '/'.$dcdom.'/'.$pickedcourse;
5768: my $spec = $role.'.'.$area;
5769: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1215 raeburn 5770: $env{'user.name'},1);
1.994 raeburn 5771: my %ccrole = ();
5772: &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
5773: my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
5774: &appenv(\%userroles,[$role,'cm']);
5775: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088 raeburn 5776: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
5777: &appenv( {'request.role' => $spec,
5778: 'request.role.domain' => $dcdom,
5779: 'request.course.sec' => ''
5780: }
5781: );
5782: my $tadv=0;
5783: if (&allowed('adv') eq 'F') { $tadv=1; }
5784: &appenv({'request.role.adv' => $tadv});
5785: }
1.994 raeburn 5786: }
5787:
1.12 www 5788: # --------------------------------------------------------------- get interface
5789:
5790: sub get {
1.131 albertel 5791: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 5792: my $items='';
1.800 albertel 5793: foreach my $item (@$storearr) {
5794: $items.=&escape($item).'&';
1.191 harris41 5795: }
1.12 www 5796: $items=~s/\&$//;
1.620 albertel 5797: if (!$udomain) { $udomain=$env{'user.domain'}; }
5798: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 5799: my $uhome=&homeserver($uname,$udomain);
5800:
1.133 albertel 5801: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 5802: my @pairs=split(/\&/,$rep);
1.273 albertel 5803: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
5804: return @pairs;
5805: }
1.15 www 5806: my %returnhash=();
1.42 www 5807: my $i=0;
1.800 albertel 5808: foreach my $item (@$storearr) {
5809: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 5810: $i++;
1.191 harris41 5811: }
1.15 www 5812: return %returnhash;
1.27 www 5813: }
5814:
5815: # --------------------------------------------------------------- del interface
5816:
5817: sub del {
1.133 albertel 5818: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 5819: my $items='';
1.800 albertel 5820: foreach my $item (@$storearr) {
5821: $items.=&escape($item).'&';
1.191 harris41 5822: }
1.984 neumanie 5823:
1.27 www 5824: $items=~s/\&$//;
1.620 albertel 5825: if (!$udomain) { $udomain=$env{'user.domain'}; }
5826: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 5827: my $uhome=&homeserver($uname,$udomain);
5828: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 5829: }
5830:
5831: # -------------------------------------------------------------- dump interface
5832:
1.1180 droeschl 5833: sub unserialize {
5834: my ($rep, $escapedkeys) = @_;
5835:
5836: return {} if $rep =~ /^error/;
5837:
5838: my %returnhash=();
1.1252 raeburn 5839: foreach my $item (split(/\&/,$rep)) {
1.1180 droeschl 5840: my ($key, $value) = split(/=/, $item, 2);
5841: $key = unescape($key) unless $escapedkeys;
5842: next if $key =~ /^error: 2 /;
1.1252 raeburn 5843: $returnhash{$key} = &thaw_unescape($value);
1.1180 droeschl 5844: }
5845: #return %returnhash;
5846: return \%returnhash;
5847: }
5848:
5849: # see Lond::dump_with_regexp
5850: # if $escapedkeys hash keys won't get unescaped.
1.15 www 5851: sub dump {
1.1180 droeschl 5852: my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755 albertel 5853: if (!$udomain) { $udomain=$env{'user.domain'}; }
5854: if (!$uname) { $uname=$env{'user.name'}; }
5855: my $uhome=&homeserver($uname,$udomain);
1.1167 droeschl 5856:
1.1266 raeburn 5857: if ($regexp) {
5858: $regexp=&escape($regexp);
5859: } else {
5860: $regexp='.';
5861: }
1.1180 droeschl 5862: if (grep { $_ eq $uhome } current_machine_ids()) {
5863: # user is hosted on this machine
1.1266 raeburn 5864: my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
1.1226 raeburn 5865: $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1180 droeschl 5866: return %{unserialize($reply, $escapedkeys)};
5867: }
1.1166 raeburn 5868: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755 albertel 5869: my @pairs=split(/\&/,$rep);
5870: my %returnhash=();
1.1098 foxr 5871: if (!($rep =~ /^error/ )) {
5872: foreach my $item (@pairs) {
5873: my ($key,$value)=split(/=/,$item,2);
1.1180 droeschl 5874: $key = unescape($key) unless $escapedkeys;
5875: #$key = &unescape($key);
1.1098 foxr 5876: next if ($key =~ /^error: 2 /);
5877: $returnhash{$key}=&thaw_unescape($value);
5878: }
1.755 albertel 5879: }
5880: return %returnhash;
1.407 www 5881: }
5882:
1.1098 foxr 5883:
1.717 albertel 5884: # --------------------------------------------------------- dumpstore interface
5885:
5886: sub dumpstore {
5887: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180 droeschl 5888: # same as dump but keys must be escaped. They may contain colon separated
5889: # lists of values that may themself contain colons (e.g. symbs).
5890: return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717 albertel 5891: }
5892:
1.407 www 5893: # -------------------------------------------------------------- keys interface
5894:
5895: sub getkeys {
5896: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 5897: if (!$udomain) { $udomain=$env{'user.domain'}; }
5898: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 5899: my $uhome=&homeserver($uname,$udomain);
5900: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
5901: my @keyarray=();
1.800 albertel 5902: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 5903: next if ($key =~ /^error: 2 /);
1.800 albertel 5904: push(@keyarray,&unescape($key));
1.407 www 5905: }
5906: return @keyarray;
1.318 matthew 5907: }
5908:
1.319 matthew 5909: # --------------------------------------------------------------- currentdump
5910: sub currentdump {
1.328 matthew 5911: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 5912: $courseid = $env{'request.course.id'} if (! defined($courseid));
5913: $sdom = $env{'user.domain'} if (! defined($sdom));
5914: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 5915: my $uhome = &homeserver($sname,$sdom);
1.1180 droeschl 5916: my $rep;
5917:
5918: if (grep { $_ eq $uhome } current_machine_ids()) {
5919: $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
5920: $courseid)));
5921: } else {
5922: $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
5923: }
5924:
1.318 matthew 5925: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 5926: #
1.318 matthew 5927: my %returnhash=();
1.319 matthew 5928: #
5929: if ($rep eq "unknown_cmd") {
5930: # an old lond will not know currentdump
5931: # Do a dump and make it look like a currentdump
1.822 albertel 5932: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 5933: return if ($tmp[0] =~ /^(error:|no_such_host)/);
5934: my %hash = @tmp;
5935: @tmp=();
1.424 matthew 5936: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 5937: } else {
5938: my @pairs=split(/\&/,$rep);
1.800 albertel 5939: foreach my $pair (@pairs) {
5940: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 5941: my ($symb,$param) = split(/:/,$key);
5942: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 5943: &thaw_unescape($value);
1.319 matthew 5944: }
1.191 harris41 5945: }
1.12 www 5946: return %returnhash;
1.424 matthew 5947: }
5948:
5949: sub convert_dump_to_currentdump{
5950: my %hash = %{shift()};
5951: my %returnhash;
5952: # Code ripped from lond, essentially. The only difference
5953: # here is the unescaping done by lonnet::dump(). Conceivably
5954: # we might run in to problems with parameter names =~ /^v\./
5955: while (my ($key,$value) = each(%hash)) {
5956: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 5957: $symb = &unescape($symb);
5958: $param = &unescape($param);
1.424 matthew 5959: next if ($v eq 'version' || $symb eq 'keys');
5960: next if (exists($returnhash{$symb}) &&
5961: exists($returnhash{$symb}->{$param}) &&
5962: $returnhash{$symb}->{'v.'.$param} > $v);
5963: $returnhash{$symb}->{$param}=$value;
5964: $returnhash{$symb}->{'v.'.$param}=$v;
5965: }
5966: #
5967: # Remove all of the keys in the hashes which keep track of
5968: # the version of the parameter.
5969: while (my ($symb,$param_hash) = each(%returnhash)) {
5970: # use a foreach because we are going to delete from the hash.
5971: foreach my $key (keys(%$param_hash)) {
5972: delete($param_hash->{$key}) if ($key =~ /^v\./);
5973: }
5974: }
5975: return \%returnhash;
1.12 www 5976: }
5977:
1.627 albertel 5978: # ------------------------------------------------------ critical inc interface
5979:
5980: sub cinc {
5981: return &inc(@_,'critical');
5982: }
5983:
1.449 matthew 5984: # --------------------------------------------------------------- inc interface
5985:
5986: sub inc {
1.627 albertel 5987: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 5988: if (!$udomain) { $udomain=$env{'user.domain'}; }
5989: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 5990: my $uhome=&homeserver($uname,$udomain);
5991: my $items='';
5992: if (! ref($store)) {
5993: # got a single value, so use that instead
5994: $items = &escape($store).'=&';
5995: } elsif (ref($store) eq 'SCALAR') {
5996: $items = &escape($$store).'=&';
5997: } elsif (ref($store) eq 'ARRAY') {
5998: $items = join('=&',map {&escape($_);} @{$store});
5999: } elsif (ref($store) eq 'HASH') {
6000: while (my($key,$value) = each(%{$store})) {
6001: $items.= &escape($key).'='.&escape($value).'&';
6002: }
6003: }
6004: $items=~s/\&$//;
1.627 albertel 6005: if ($critical) {
6006: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
6007: } else {
6008: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
6009: }
1.449 matthew 6010: }
6011:
1.12 www 6012: # --------------------------------------------------------------- put interface
6013:
6014: sub put {
1.134 albertel 6015: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 6016: if (!$udomain) { $udomain=$env{'user.domain'}; }
6017: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 6018: my $uhome=&homeserver($uname,$udomain);
1.12 www 6019: my $items='';
1.800 albertel 6020: foreach my $item (keys(%$storehash)) {
6021: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 6022: }
1.12 www 6023: $items=~s/\&$//;
1.134 albertel 6024: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 6025: }
6026:
1.631 albertel 6027: # ------------------------------------------------------------ newput interface
6028:
6029: sub newput {
6030: my ($namespace,$storehash,$udomain,$uname)=@_;
6031: if (!$udomain) { $udomain=$env{'user.domain'}; }
6032: if (!$uname) { $uname=$env{'user.name'}; }
6033: my $uhome=&homeserver($uname,$udomain);
6034: my $items='';
6035: foreach my $key (keys(%$storehash)) {
6036: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
6037: }
6038: $items=~s/\&$//;
6039: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
6040: }
6041:
6042: # --------------------------------------------------------- putstore interface
6043:
1.524 raeburn 6044: sub putstore {
1.1269 raeburn 6045: my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620 albertel 6046: if (!$udomain) { $udomain=$env{'user.domain'}; }
6047: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 6048: my $uhome=&homeserver($uname,$udomain);
6049: my $items='';
1.715 albertel 6050: foreach my $key (keys(%$storehash)) {
6051: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 6052: }
1.715 albertel 6053: $items=~s/\&$//;
1.716 albertel 6054: my $esc_symb=&escape($symb);
6055: my $esc_v=&escape($version);
1.715 albertel 6056: my $reply =
1.716 albertel 6057: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 6058: $uhome);
1.1269 raeburn 6059: if (($tolog) && ($reply eq 'ok')) {
6060: my $namevalue='';
6061: foreach my $key (keys(%{$storehash})) {
6062: $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
6063: }
6064: $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
6065: '&host='.&escape($perlvar{'lonHostID'}).
6066: '&version='.$esc_v.
6067: '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
6068: &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
6069: }
1.715 albertel 6070: if ($reply eq 'unknown_cmd') {
1.716 albertel 6071: # gfall back to way things use to be done
1.715 albertel 6072: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
6073: $uname);
1.524 raeburn 6074: }
1.715 albertel 6075: return $reply;
6076: }
6077:
6078: sub old_putstore {
1.716 albertel 6079: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
6080: if (!$udomain) { $udomain=$env{'user.domain'}; }
6081: if (!$uname) { $uname=$env{'user.name'}; }
6082: my $uhome=&homeserver($uname,$udomain);
6083: my %newstorehash;
1.800 albertel 6084: foreach my $item (keys(%$storehash)) {
6085: my $key = $version.':'.&escape($symb).':'.$item;
6086: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 6087: }
6088: my $items='';
6089: my %allitems = ();
1.800 albertel 6090: foreach my $item (keys(%newstorehash)) {
6091: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 6092: my $key = $1.':keys:'.$2;
6093: $allitems{$key} .= $3.':';
6094: }
1.800 albertel 6095: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 6096: }
1.800 albertel 6097: foreach my $item (keys(%allitems)) {
6098: $allitems{$item} =~ s/\:$//;
6099: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 6100: }
6101: $items=~s/\&$//;
6102: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 6103: }
6104:
1.47 www 6105: # ------------------------------------------------------ critical put interface
6106:
6107: sub cput {
1.134 albertel 6108: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 6109: if (!$udomain) { $udomain=$env{'user.domain'}; }
6110: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 6111: my $uhome=&homeserver($uname,$udomain);
1.47 www 6112: my $items='';
1.800 albertel 6113: foreach my $item (keys(%$storehash)) {
6114: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 6115: }
1.47 www 6116: $items=~s/\&$//;
1.134 albertel 6117: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 6118: }
6119:
6120: # -------------------------------------------------------------- eget interface
6121:
6122: sub eget {
1.133 albertel 6123: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 6124: my $items='';
1.800 albertel 6125: foreach my $item (@$storearr) {
6126: $items.=&escape($item).'&';
1.191 harris41 6127: }
1.12 www 6128: $items=~s/\&$//;
1.620 albertel 6129: if (!$udomain) { $udomain=$env{'user.domain'}; }
6130: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 6131: my $uhome=&homeserver($uname,$udomain);
6132: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 6133: my @pairs=split(/\&/,$rep);
6134: my %returnhash=();
1.42 www 6135: my $i=0;
1.800 albertel 6136: foreach my $item (@$storearr) {
6137: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 6138: $i++;
1.191 harris41 6139: }
1.12 www 6140: return %returnhash;
6141: }
6142:
1.667 albertel 6143: # ------------------------------------------------------------ tmpput interface
6144: sub tmpput {
1.802 raeburn 6145: my ($storehash,$server,$context)=@_;
1.667 albertel 6146: my $items='';
1.800 albertel 6147: foreach my $item (keys(%$storehash)) {
6148: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 6149: }
6150: $items=~s/\&$//;
1.802 raeburn 6151: if (defined($context)) {
6152: $items .= ':'.&escape($context);
6153: }
1.667 albertel 6154: return &reply("tmpput:$items",$server);
6155: }
6156:
6157: # ------------------------------------------------------------ tmpget interface
6158: sub tmpget {
1.688 albertel 6159: my ($token,$server)=@_;
6160: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
6161: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 6162: my %returnhash;
6163: foreach my $item (split(/\&/,$rep)) {
6164: my ($key,$value)=split(/=/,$item);
1.951 raeburn 6165: next if ($key =~ /^error: 2 /);
1.667 albertel 6166: $returnhash{&unescape($key)}=&thaw_unescape($value);
6167: }
6168: return %returnhash;
6169: }
6170:
1.1113 raeburn 6171: # ------------------------------------------------------------ tmpdel interface
1.688 albertel 6172: sub tmpdel {
6173: my ($token,$server)=@_;
6174: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
6175: return &reply("tmpdel:$token",$server);
6176: }
6177:
1.1198 raeburn 6178: # ------------------------------------------------------------ get_timebased_id
6179:
6180: sub get_timebased_id {
6181: my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
6182: $maxtries) = @_;
6183: my ($newid,$error,$dellock);
6184: unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
6185: return ('','ok','invalid call to get suffix');
6186: }
6187:
6188: # set defaults for any optional args for which values were not supplied
6189: if ($who eq '') {
6190: $who = $env{'user.name'}.':'.$env{'user.domain'};
6191: }
6192: if (!$locktries) {
6193: $locktries = 3;
6194: }
6195: if (!$maxtries) {
6196: $maxtries = 10;
6197: }
6198:
6199: if (($cdom eq '') || ($cnum eq '')) {
6200: if ($env{'request.course.id'}) {
6201: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6202: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6203: }
6204: if (($cdom eq '') || ($cnum eq '')) {
6205: return ('','ok','call to get suffix not in course context');
6206: }
6207: }
6208:
6209: # construct locking item
6210: my $lockhash = {
6211: $prefix."\0".'locked_'.$keyid => $who,
6212: };
6213: my $tries = 0;
6214:
6215: # attempt to get lock on nohist_$namespace file
6216: my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
6217: while (($gotlock ne 'ok') && $tries <$locktries) {
6218: $tries ++;
6219: sleep 1;
6220: $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
6221: }
6222:
6223: # attempt to get unique identifier, based on current timestamp
6224: if ($gotlock eq 'ok') {
6225: my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
6226: my $id = time;
6227: $newid = $id;
1.1268 raeburn 6228: if ($idtype eq 'addcode') {
6229: $newid .= &sixnum_code();
6230: }
1.1198 raeburn 6231: my $idtries = 0;
6232: while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
6233: if ($idtype eq 'concat') {
6234: $newid = $id.$idtries;
1.1268 raeburn 6235: } elsif ($idtype eq 'addcode') {
6236: $newid = $newid.&sixnum_code();
1.1198 raeburn 6237: } else {
6238: $newid ++;
6239: }
6240: $idtries ++;
6241: }
6242: if (!exists($inuse{$prefix."\0".$newid})) {
6243: my %new_item = (
6244: $prefix."\0".$newid => $who,
6245: );
6246: my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
6247: $cdom,$cnum);
6248: if ($putresult ne 'ok') {
6249: undef($newid);
6250: $error = 'error saving new item: '.$putresult;
6251: }
6252: } else {
1.1268 raeburn 6253: undef($newid);
1.1198 raeburn 6254: $error = ('error: no unique suffix available for the new item ');
6255: }
6256: # remove lock
6257: my @del_lock = ($prefix."\0".'locked_'.$keyid);
6258: $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
6259: } else {
6260: $error = "error: could not obtain lockfile\n";
6261: $dellock = 'ok';
1.1276 raeburn 6262: if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
6263: $dellock = 'nolock';
6264: }
1.1198 raeburn 6265: }
6266: return ($newid,$dellock,$error);
6267: }
6268:
1.1268 raeburn 6269: sub sixnum_code {
6270: my $code;
6271: for (0..6) {
6272: $code .= int( rand(9) );
6273: }
6274: return $code;
6275: }
6276:
1.765 albertel 6277: # -------------------------------------------------- portfolio access checking
6278:
6279: sub portfolio_access {
1.1270 raeburn 6280: my ($requrl,$clientip) = @_;
1.765 albertel 6281: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1270 raeburn 6282: my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814 raeburn 6283: if ($result) {
6284: my %setters;
6285: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6286: my ($startblock,$endblock) =
6287: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
6288: if ($startblock && $endblock) {
6289: return 'B';
6290: }
6291: } else {
6292: my ($startblock,$endblock) =
6293: &Apache::loncommon::blockcheck(\%setters,'port');
6294: if ($startblock && $endblock) {
6295: return 'B';
6296: }
6297: }
6298: }
1.765 albertel 6299: if ($result eq 'ok') {
1.766 albertel 6300: return 'F';
1.765 albertel 6301: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 6302: return 'A';
1.765 albertel 6303: }
1.766 albertel 6304: return '';
1.765 albertel 6305: }
6306:
6307: sub get_portfolio_access {
1.1270 raeburn 6308: my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767 albertel 6309:
6310: if (!ref($access_hash)) {
6311: my $current_perms = &get_portfile_permissions($udom,$unum);
6312: my %access_controls = &get_access_controls($current_perms,$group,
6313: $file_name);
6314: $access_hash = $access_controls{$file_name};
6315: }
6316:
1.1270 raeburn 6317: my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765 albertel 6318: my $now = time;
6319: if (ref($access_hash) eq 'HASH') {
6320: foreach my $key (keys(%{$access_hash})) {
6321: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
6322: if ($start > $now) {
6323: next;
6324: }
6325: if ($end && $end<$now) {
6326: next;
6327: }
6328: if ($scope eq 'public') {
6329: $public = $key;
6330: last;
6331: } elsif ($scope eq 'guest') {
6332: $guest = $key;
6333: } elsif ($scope eq 'domains') {
6334: push(@domains,$key);
6335: } elsif ($scope eq 'users') {
6336: push(@users,$key);
6337: } elsif ($scope eq 'course') {
6338: push(@courses,$key);
6339: } elsif ($scope eq 'group') {
6340: push(@groups,$key);
1.1270 raeburn 6341: } elsif ($scope eq 'ip') {
6342: push(@ips,$key);
1.765 albertel 6343: }
6344: }
6345: if ($public) {
6346: return 'ok';
1.1270 raeburn 6347: } elsif (@ips > 0) {
6348: my $allowed;
6349: foreach my $ipkey (@ips) {
6350: if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
6351: if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
6352: $allowed = 1;
6353: last;
6354: }
6355: }
6356: }
6357: if ($allowed) {
6358: return 'ok';
6359: }
1.765 albertel 6360: }
6361: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6362: if ($guest) {
6363: return $guest;
6364: }
6365: } else {
6366: if (@domains > 0) {
6367: foreach my $domkey (@domains) {
6368: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
6369: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
6370: return 'ok';
6371: }
6372: }
6373: }
6374: }
6375: if (@users > 0) {
6376: foreach my $userkey (@users) {
1.865 raeburn 6377: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
6378: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
6379: if (ref($item) eq 'HASH') {
6380: if (($item->{'uname'} eq $env{'user.name'}) &&
6381: ($item->{'udom'} eq $env{'user.domain'})) {
6382: return 'ok';
6383: }
6384: }
6385: }
6386: }
1.765 albertel 6387: }
6388: }
6389: my %roleshash;
6390: my @courses_and_groups = @courses;
6391: push(@courses_and_groups,@groups);
6392: if (@courses_and_groups > 0) {
6393: my (%allgroups,%allroles);
6394: my ($start,$end,$role,$sec,$group);
6395: foreach my $envkey (%env) {
1.1060 raeburn 6396: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6397: my $cid = $2.'_'.$3;
6398: if ($1 eq 'gr') {
6399: $group = $4;
6400: $allgroups{$cid}{$group} = $env{$envkey};
6401: } else {
6402: if ($4 eq '') {
6403: $sec = 'none';
6404: } else {
6405: $sec = $4;
6406: }
6407: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6408: }
1.811 albertel 6409: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6410: my $cid = $2.'_'.$3;
6411: if ($4 eq '') {
6412: $sec = 'none';
6413: } else {
6414: $sec = $4;
6415: }
6416: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6417: }
6418: }
6419: if (keys(%allroles) == 0) {
6420: return;
6421: }
6422: foreach my $key (@courses_and_groups) {
6423: my %content = %{$$access_hash{$key}};
6424: my $cnum = $content{'number'};
6425: my $cdom = $content{'domain'};
6426: my $cid = $cdom.'_'.$cnum;
6427: if (!exists($allroles{$cid})) {
6428: next;
6429: }
6430: foreach my $role_id (keys(%{$content{'roles'}})) {
6431: my @sections = @{$content{'roles'}{$role_id}{'section'}};
6432: my @groups = @{$content{'roles'}{$role_id}{'group'}};
6433: my @status = @{$content{'roles'}{$role_id}{'access'}};
6434: my @roles = @{$content{'roles'}{$role_id}{'role'}};
6435: foreach my $role (keys(%{$allroles{$cid}})) {
6436: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
6437: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
6438: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
6439: if (grep/^all$/,@sections) {
6440: return 'ok';
6441: } else {
6442: if (grep/^$sec$/,@sections) {
6443: return 'ok';
6444: }
6445: }
6446: }
6447: }
6448: if (keys(%{$allgroups{$cid}}) == 0) {
6449: if (grep/^none$/,@groups) {
6450: return 'ok';
6451: }
6452: } else {
6453: if (grep/^all$/,@groups) {
6454: return 'ok';
6455: }
6456: foreach my $group (keys(%{$allgroups{$cid}})) {
6457: if (grep/^$group$/,@groups) {
6458: return 'ok';
6459: }
6460: }
6461: }
6462: }
6463: }
6464: }
6465: }
6466: }
6467: if ($guest) {
6468: return $guest;
6469: }
6470: }
6471: }
6472: return;
6473: }
6474:
6475: sub course_group_datechecker {
6476: my ($dates,$now,$status) = @_;
6477: my ($start,$end) = split(/\./,$dates);
6478: if (!$start && !$end) {
6479: return 'ok';
6480: }
6481: if (grep/^active$/,@{$status}) {
6482: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
6483: return 'ok';
6484: }
6485: }
6486: if (grep/^previous$/,@{$status}) {
6487: if ($end > $now ) {
6488: return 'ok';
6489: }
6490: }
6491: if (grep/^future$/,@{$status}) {
6492: if ($start > $now) {
6493: return 'ok';
6494: }
6495: }
6496: return;
6497: }
6498:
6499: sub parse_portfolio_url {
6500: my ($url) = @_;
6501:
6502: my ($type,$udom,$unum,$group,$file_name);
6503:
1.823 albertel 6504: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 6505: $type = 1;
6506: $udom = $1;
6507: $unum = $2;
6508: $file_name = $3;
1.823 albertel 6509: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 6510: $type = 2;
6511: $udom = $1;
6512: $unum = $2;
6513: $group = $3;
6514: $file_name = $3.'/'.$4;
6515: }
6516: if (wantarray) {
6517: return ($type,$udom,$unum,$file_name,$group);
6518: }
6519: return $type;
6520: }
6521:
6522: sub is_portfolio_url {
6523: my ($url) = @_;
6524: return scalar(&parse_portfolio_url($url));
6525: }
6526:
1.798 raeburn 6527: sub is_portfolio_file {
6528: my ($file) = @_;
1.820 raeburn 6529: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 6530: return 1;
6531: }
6532: return;
6533: }
6534:
1.976 raeburn 6535: sub usertools_access {
1.1084 raeburn 6536: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 6537: my ($access,%tools);
6538: if ($context eq '') {
6539: $context = 'tools';
6540: }
6541: if ($context eq 'requestcourses') {
6542: %tools = (
6543: official => 1,
6544: unofficial => 1,
1.1006 raeburn 6545: community => 1,
1.1246 raeburn 6546: textbook => 1,
1.1305 raeburn 6547: placement => 1,
1.985 raeburn 6548: );
1.1183 raeburn 6549: } elsif ($context eq 'requestauthor') {
6550: %tools = (
6551: requestauthor => 1,
6552: );
1.985 raeburn 6553: } else {
6554: %tools = (
6555: aboutme => 1,
6556: blog => 1,
1.1177 raeburn 6557: webdav => 1,
1.985 raeburn 6558: portfolio => 1,
6559: );
6560: }
1.976 raeburn 6561: return if (!defined($tools{$tool}));
6562:
1.1242 raeburn 6563: if (($udom eq '') || ($uname eq '')) {
1.976 raeburn 6564: $udom = $env{'user.domain'};
6565: $uname = $env{'user.name'};
6566: }
6567:
1.978 raeburn 6568: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
6569: if ($action ne 'reload') {
1.985 raeburn 6570: if ($context eq 'requestcourses') {
6571: return $env{'environment.canrequest.'.$tool};
1.1183 raeburn 6572: } elsif ($context eq 'requestauthor') {
6573: return $env{'environment.canrequest.author'};
1.985 raeburn 6574: } else {
6575: return $env{'environment.availabletools.'.$tool};
6576: }
6577: }
1.976 raeburn 6578: }
6579:
1.1183 raeburn 6580: my ($toolstatus,$inststatus,$envkey);
6581: if ($context eq 'requestauthor') {
6582: $envkey = $context;
6583: } else {
6584: $envkey = $context.'.'.$tool;
6585: }
1.976 raeburn 6586:
1.985 raeburn 6587: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
6588: ($action ne 'reload')) {
1.1183 raeburn 6589: $toolstatus = $env{'environment.'.$envkey};
1.976 raeburn 6590: $inststatus = $env{'environment.inststatus'};
6591: } else {
1.1084 raeburn 6592: if (ref($userenvref) eq 'HASH') {
1.1183 raeburn 6593: $toolstatus = $userenvref->{$envkey};
1.1084 raeburn 6594: $inststatus = $userenvref->{'inststatus'};
6595: } else {
1.1183 raeburn 6596: my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
6597: $toolstatus = $userenv{$envkey};
1.1084 raeburn 6598: $inststatus = $userenv{'inststatus'};
6599: }
1.976 raeburn 6600: }
6601:
6602: if ($toolstatus ne '') {
6603: if ($toolstatus) {
6604: $access = 1;
6605: } else {
6606: $access = 0;
6607: }
6608: return $access;
6609: }
6610:
1.1084 raeburn 6611: my ($is_adv,%domdef);
6612: if (ref($is_advref) eq 'HASH') {
6613: $is_adv = $is_advref->{'is_adv'};
6614: } else {
6615: $is_adv = &is_advanced_user($udom,$uname);
6616: }
6617: if (ref($domdefref) eq 'HASH') {
6618: %domdef = %{$domdefref};
6619: } else {
6620: %domdef = &get_domain_defaults($udom);
6621: }
1.976 raeburn 6622: if (ref($domdef{$tool}) eq 'HASH') {
6623: if ($is_adv) {
6624: if ($domdef{$tool}{'_LC_adv'} ne '') {
6625: if ($domdef{$tool}{'_LC_adv'}) {
6626: $access = 1;
6627: } else {
6628: $access = 0;
6629: }
6630: return $access;
6631: }
6632: }
6633: if ($inststatus ne '') {
6634: my ($hasaccess,$hasnoaccess);
6635: foreach my $affiliation (split(/:/,$inststatus)) {
6636: if ($domdef{$tool}{$affiliation} ne '') {
6637: if ($domdef{$tool}{$affiliation}) {
6638: $hasaccess = 1;
6639: } else {
6640: $hasnoaccess = 1;
6641: }
6642: }
6643: }
6644: if ($hasaccess || $hasnoaccess) {
6645: if ($hasaccess) {
6646: $access = 1;
6647: } elsif ($hasnoaccess) {
6648: $access = 0;
6649: }
6650: return $access;
6651: }
6652: } else {
6653: if ($domdef{$tool}{'default'} ne '') {
6654: if ($domdef{$tool}{'default'}) {
6655: $access = 1;
6656: } elsif ($domdef{$tool}{'default'} == 0) {
6657: $access = 0;
6658: }
6659: return $access;
6660: }
6661: }
6662: } else {
1.1177 raeburn 6663: if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985 raeburn 6664: $access = 1;
6665: } else {
6666: $access = 0;
6667: }
1.976 raeburn 6668: return $access;
6669: }
6670: }
6671:
1.1050 raeburn 6672: sub is_course_owner {
6673: my ($cdom,$cnum,$udom,$uname) = @_;
6674: if (($udom eq '') || ($uname eq '')) {
6675: $udom = $env{'user.domain'};
6676: $uname = $env{'user.name'};
6677: }
6678: unless (($udom eq '') || ($uname eq '')) {
6679: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
6680: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
6681: return 1;
6682: } else {
6683: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
6684: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
6685: return 1;
6686: }
6687: }
6688: }
6689: }
6690: return;
6691: }
6692:
1.976 raeburn 6693: sub is_advanced_user {
6694: my ($udom,$uname) = @_;
1.1085 raeburn 6695: if ($udom ne '' && $uname ne '') {
6696: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128 raeburn 6697: if (wantarray) {
6698: return ($env{'user.adv'},$env{'user.author'});
6699: } else {
6700: return $env{'user.adv'};
6701: }
1.1085 raeburn 6702: }
6703: }
1.976 raeburn 6704: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
6705: my %allroles;
1.1128 raeburn 6706: my ($is_adv,$is_author);
1.976 raeburn 6707: foreach my $role (keys(%roleshash)) {
6708: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
6709: my $area = '/'.$tdomain.'/'.$trest;
6710: if ($sec ne '') {
6711: $area .= '/'.$sec;
6712: }
6713: if (($area ne '') && ($trole ne '')) {
6714: my $spec=$trole.'.'.$area;
6715: if ($trole =~ /^cr\//) {
6716: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
6717: } elsif ($trole ne 'gr') {
6718: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
6719: }
1.1128 raeburn 6720: if ($trole eq 'au') {
6721: $is_author = 1;
6722: }
1.976 raeburn 6723: }
6724: }
6725: foreach my $role (keys(%allroles)) {
6726: last if ($is_adv);
6727: foreach my $item (split(/:/,$allroles{$role})) {
6728: if ($item ne '') {
6729: my ($privilege,$restrictions)=split(/&/,$item);
6730: if ($privilege eq 'adv') {
6731: $is_adv = 1;
6732: last;
6733: }
6734: }
6735: }
6736: }
1.1128 raeburn 6737: if (wantarray) {
6738: return ($is_adv,$is_author);
6739: }
1.976 raeburn 6740: return $is_adv;
6741: }
1.798 raeburn 6742:
1.1035 raeburn 6743: sub check_can_request {
1.1036 raeburn 6744: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 6745: my $canreq = 0;
6746: my ($types,$typename) = &Apache::loncommon::course_types();
6747: my @options = ('approval','validate','autolimit');
6748: my $optregex = join('|',@options);
6749: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
6750: foreach my $type (@{$types}) {
6751: if (&usertools_access($env{'user.name'},
6752: $env{'user.domain'},
6753: $type,undef,'requestcourses')) {
6754: $canreq ++;
1.1036 raeburn 6755: if (ref($request_domains) eq 'HASH') {
6756: push(@{$request_domains->{$type}},$env{'user.domain'});
6757: }
1.1035 raeburn 6758: if ($dom eq $env{'user.domain'}) {
6759: $can_request->{$type} = 1;
6760: }
6761: }
6762: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
6763: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
6764: if (@curr > 0) {
1.1036 raeburn 6765: foreach my $item (@curr) {
6766: if (ref($request_domains) eq 'HASH') {
6767: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
6768: if ($otherdom ne '') {
6769: if (ref($request_domains->{$type}) eq 'ARRAY') {
6770: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
6771: push(@{$request_domains->{$type}},$otherdom);
6772: }
6773: } else {
6774: push(@{$request_domains->{$type}},$otherdom);
6775: }
6776: }
6777: }
6778: }
6779: unless($dom eq $env{'user.domain'}) {
6780: $canreq ++;
1.1035 raeburn 6781: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
6782: $can_request->{$type} = 1;
6783: }
6784: }
6785: }
6786: }
6787: }
6788: }
6789: return $canreq;
6790: }
6791:
1.341 www 6792: # ---------------------------------------------- Custom access rule evaluation
6793:
6794: sub customaccess {
6795: my ($priv,$uri)=@_;
1.807 albertel 6796: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 6797: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 6798: $udom = &LONCAPA::clean_domain($udom);
6799: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 6800: my $access=0;
1.800 albertel 6801: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 6802: my ($effect,$realm,$role,$type)=split(/\:/,$right);
6803: if ($type eq 'user') {
6804: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 6805: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 6806: if ($tdom) {
6807: if ($tdom ne $env{'user.domain'}) { next; }
6808: }
1.896 albertel 6809: if ($tuname) {
6810: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 6811: }
6812: $access=($effect eq 'allow');
6813: last;
6814: }
6815: } else {
6816: if ($role) {
6817: if ($role ne $urole) { next; }
6818: }
6819: foreach my $scope (split(/\s*\,\s*/,$realm)) {
6820: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
6821: if ($tdom) {
6822: if ($tdom ne $udom) { next; }
6823: }
6824: if ($tcrs) {
6825: if ($tcrs ne $ucrs) { next; }
6826: }
6827: if ($tsec) {
6828: if ($tsec ne $usec) { next; }
6829: }
6830: $access=($effect eq 'allow');
6831: last;
6832: }
6833: if ($realm eq '' && $role eq '') {
6834: $access=($effect eq 'allow');
6835: }
1.402 bowersj2 6836: }
1.341 www 6837: }
6838: return $access;
6839: }
6840:
1.103 harris41 6841: # ------------------------------------------------- Check for a user privilege
1.12 www 6842:
6843: sub allowed {
1.1281 raeburn 6844: my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
1.705 albertel 6845: my $ver_orguri=$uri;
1.439 www 6846: $uri=&deversion($uri);
1.152 www 6847: my $orguri=$uri;
1.52 www 6848: $uri=&declutter($uri);
1.809 raeburn 6849:
1.810 raeburn 6850: if ($priv eq 'evb') {
6851: # Evade communication block restrictions for specified role in a course
6852: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
6853: return $1;
6854: } else {
6855: return;
6856: }
6857: }
6858:
1.620 albertel 6859: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 6860: # Free bre access to adm and meta resources
1.775 albertel 6861: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 6862: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
6863: && ($priv eq 'bre')) {
1.14 www 6864: return 'F';
1.159 www 6865: }
6866:
1.545 banghart 6867: # Free bre access to user's own portfolio contents
1.714 raeburn 6868: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 6869: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 6870: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 6871: my %setters;
6872: my ($startblock,$endblock) =
6873: &Apache::loncommon::blockcheck(\%setters,'port');
6874: if ($startblock && $endblock) {
6875: return 'B';
6876: } else {
6877: return 'F';
6878: }
1.545 banghart 6879: }
6880:
1.762 raeburn 6881: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 6882: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
6883: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
6884: if (exists($env{'request.course.id'})) {
6885: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6886: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6887: if (($domain eq $cdom) && ($name eq $cnum)) {
6888: my $courseprivid=$env{'request.course.id'};
6889: $courseprivid=~s/\_/\//;
6890: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
6891: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
6892: return $1;
1.762 raeburn 6893: } else {
6894: if ($env{'request.course.sec'}) {
6895: $courseprivid.='/'.$env{'request.course.sec'};
6896: }
6897: if ($env{'user.priv.'.$env{'request.role'}.'./'.
6898: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
6899: return $2;
6900: }
1.714 raeburn 6901: }
6902: }
6903: }
6904: }
6905:
1.159 www 6906: # Free bre to public access
6907:
6908: if ($priv eq 'bre') {
1.238 www 6909: my $copyright=&metadata($uri,'copyright');
1.620 albertel 6910: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 6911: return 'F';
6912: }
1.238 www 6913: if ($copyright eq 'priv') {
6914: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 6915: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 6916: return '';
6917: }
6918: }
6919: if ($copyright eq 'domain') {
6920: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 6921: unless (($env{'user.domain'} eq $1) ||
6922: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 6923: return '';
6924: }
1.262 matthew 6925: }
1.620 albertel 6926: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 6927: # Library role, so allow browsing of resources in this domain.
6928: return 'F';
1.238 www 6929: }
1.341 www 6930: if ($copyright eq 'custom') {
6931: unless (&customaccess($priv,$uri)) { return ''; }
6932: }
1.14 www 6933: }
1.264 matthew 6934: # Domain coordinator is trying to create a course
1.620 albertel 6935: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 6936: # uri is the requested domain in this case.
6937: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 6938: # a role of dc for the domain in question.
1.620 albertel 6939: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 6940: }
1.29 www 6941:
1.52 www 6942: my $thisallowed='';
6943: my $statecond=0;
6944: my $courseprivid='';
6945:
1.1039 raeburn 6946: my $ownaccess;
1.1043 raeburn 6947: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 6948: if (($priv eq 'bro') && ($env{'user.author'})) {
6949: if ($uri eq '') {
6950: $ownaccess = 1;
6951: } else {
6952: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
6953: my $udom = $env{'user.domain'};
6954: my $uname = $env{'user.name'};
6955: if ($uri =~ m{^\Q$udom\E/?$}) {
6956: $ownaccess = 1;
1.1040 raeburn 6957: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 6958: unless ($uri =~ m{\.\./}) {
6959: $ownaccess = 1;
6960: }
6961: } elsif (($udom ne 'public') && ($uname ne 'public')) {
6962: my $now = time;
6963: if ($uri =~ m{^([^/]+)/?$}) {
6964: my $adom = $1;
6965: foreach my $key (keys(%env)) {
1.1042 raeburn 6966: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 6967: my ($start,$end) = split('.',$env{$key});
6968: if (($now >= $start) && (!$end || $end < $now)) {
6969: $ownaccess = 1;
6970: last;
6971: }
6972: }
6973: }
6974: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
6975: my $adom = $1;
6976: my $aname = $2;
1.1042 raeburn 6977: foreach my $role ('ca','aa') {
6978: if ($env{"user.role.$role./$adom/$aname"}) {
6979: my ($start,$end) =
6980: split('.',$env{"user.role.$role./$adom/$aname"});
6981: if (($now >= $start) && (!$end || $end < $now)) {
6982: $ownaccess = 1;
6983: last;
6984: }
1.1039 raeburn 6985: }
6986: }
6987: }
6988: }
6989: }
6990: }
6991: }
6992:
1.52 www 6993: # Course
6994:
1.620 albertel 6995: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6996: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6997: $thisallowed.=$1;
6998: }
1.52 www 6999: }
1.29 www 7000:
1.52 www 7001: # Domain
7002:
1.620 albertel 7003: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 7004: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 7005: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 7006: $thisallowed.=$1;
7007: }
1.12 www 7008: }
1.52 www 7009:
1.1141 raeburn 7010: # User who is not author or co-author might still be able to edit
7011: # resource of an author in the domain (e.g., if Domain Coordinator).
7012: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
7013: (&allowed('mdc',$env{'request.course.id'}))) {
7014: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
7015: $thisallowed.=$1;
7016: }
7017: }
7018:
1.52 www 7019: # Course: uri itself is a course
1.66 www 7020: my $courseuri=$uri;
7021: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 7022: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 7023:
1.620 albertel 7024: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 7025: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 7026: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 7027: $thisallowed.=$1;
7028: }
1.12 www 7029: }
1.29 www 7030:
1.665 albertel 7031: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 7032: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 7033: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 7034: $thisallowed='';
1.671 raeburn 7035: my ($match)=&is_on_map($uri);
7036: if ($match) {
7037: if ($env{'user.priv.'.$env{'request.role'}.'./'}
7038: =~/\Q$priv\E\&([^\:]*)/) {
1.1281 raeburn 7039: my $value = $1;
7040: if ($noblockcheck) {
7041: $thisallowed.=$value;
1.1162 raeburn 7042: } else {
1.1281 raeburn 7043: my @blockers = &has_comm_blocking($priv,$symb,$uri);
7044: if (@blockers > 0) {
7045: $thisallowed = 'B';
7046: } else {
7047: $thisallowed.=$value;
7048: }
1.1162 raeburn 7049: }
1.671 raeburn 7050: }
7051: } else {
1.705 albertel 7052: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 7053: if ($refuri) {
7054: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 7055: $thisallowed='F';
1.671 raeburn 7056: } else {
7057: $refuri=&declutter($refuri);
7058: my ($match) = &is_on_map($refuri);
7059: if ($match) {
1.1281 raeburn 7060: if ($noblockcheck) {
7061: $thisallowed='F';
1.1162 raeburn 7062: } else {
1.1281 raeburn 7063: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
7064: if (@blockers > 0) {
7065: $thisallowed = 'B';
7066: } else {
7067: $thisallowed='F';
7068: }
1.1162 raeburn 7069: }
1.671 raeburn 7070: }
1.669 raeburn 7071: }
1.671 raeburn 7072: }
7073: }
1.314 www 7074: }
1.492 albertel 7075:
1.766 albertel 7076: if ($priv eq 'bre'
7077: && $thisallowed ne 'F'
7078: && $thisallowed ne '2'
7079: && &is_portfolio_url($uri)) {
1.1270 raeburn 7080: $thisallowed = &portfolio_access($uri,$clientip);
1.766 albertel 7081: }
1.1250 raeburn 7082:
1.52 www 7083: # Full access at system, domain or course-wide level? Exit.
1.29 www 7084: if ($thisallowed=~/F/) {
7085: return 'F';
7086: }
7087:
1.52 www 7088: # If this is generating or modifying users, exit with special codes
1.29 www 7089:
1.643 www 7090: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
7091: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 7092: my ($audom,$auname)=split('/',$uri);
1.643 www 7093: # no author name given, so this just checks on the general right to make a co-author in this domain
7094: unless ($auname) { return $thisallowed; }
7095: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 7096: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
7097: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
7098: ($audom ne $env{'request.role.domain'}))) { return ''; }
7099: }
1.52 www 7100: return $thisallowed;
7101: }
7102: #
1.103 harris41 7103: # Gathered so far: system, domain and course wide privileges
1.52 www 7104: #
7105: # Course: See if uri or referer is an individual resource that is part of
7106: # the course
7107:
1.620 albertel 7108: if ($env{'request.course.id'}) {
1.232 www 7109:
1.620 albertel 7110: $courseprivid=$env{'request.course.id'};
7111: if ($env{'request.course.sec'}) {
7112: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 7113: }
7114: $courseprivid=~s/\_/\//;
7115: my $checkreferer=1;
1.232 www 7116: my ($match,$cond)=&is_on_map($uri);
7117: if ($match) {
7118: $statecond=$cond;
1.620 albertel 7119: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 7120: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 7121: my $value = $1;
7122: if ($priv eq 'bre') {
1.1281 raeburn 7123: if ($noblockcheck) {
7124: $thisallowed.=$value;
1.1162 raeburn 7125: } else {
1.1281 raeburn 7126: my @blockers = &has_comm_blocking($priv,$symb,$uri);
7127: if (@blockers > 0) {
7128: $thisallowed = 'B';
7129: } else {
7130: $thisallowed.=$value;
7131: }
1.1162 raeburn 7132: }
7133: } else {
7134: $thisallowed.=$value;
7135: }
1.52 www 7136: $checkreferer=0;
7137: }
1.29 www 7138: }
1.83 www 7139:
1.148 www 7140: if ($checkreferer) {
1.620 albertel 7141: my $refuri=$env{'httpref.'.$orguri};
1.148 www 7142: unless ($refuri) {
1.800 albertel 7143: foreach my $key (keys(%env)) {
7144: if ($key=~/^httpref\..*\*/) {
7145: my $pattern=$key;
1.156 www 7146: $pattern=~s/^httpref\.\/res\///;
1.148 www 7147: $pattern=~s/\*/\[\^\/\]\+/g;
7148: $pattern=~s/\//\\\//g;
1.152 www 7149: if ($orguri=~/$pattern/) {
1.800 albertel 7150: $refuri=$env{$key};
1.148 www 7151: }
7152: }
1.191 harris41 7153: }
1.148 www 7154: }
1.232 www 7155:
1.148 www 7156: if ($refuri) {
1.152 www 7157: $refuri=&declutter($refuri);
1.232 www 7158: my ($match,$cond)=&is_on_map($refuri);
7159: if ($match) {
7160: my $refstatecond=$cond;
1.620 albertel 7161: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 7162: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 7163: my $value = $1;
7164: if ($priv eq 'bre') {
1.1281 raeburn 7165: if ($noblockcheck) {
7166: $thisallowed.=$value;
1.1162 raeburn 7167: } else {
1.1281 raeburn 7168: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
7169: if (@blockers > 0) {
7170: $thisallowed = 'B';
7171: } else {
7172: $thisallowed.=$value;
7173: }
1.1162 raeburn 7174: }
7175: } else {
7176: $thisallowed.=$value;
7177: }
1.53 www 7178: $uri=$refuri;
7179: $statecond=$refstatecond;
1.52 www 7180: }
7181: }
1.148 www 7182: }
1.29 www 7183: }
1.52 www 7184: }
1.29 www 7185:
1.52 www 7186: #
1.103 harris41 7187: # Gathered now: all privileges that could apply, and condition number
1.52 www 7188: #
7189: #
7190: # Full or no access?
7191: #
1.29 www 7192:
1.52 www 7193: if ($thisallowed=~/F/) {
7194: return 'F';
7195: }
1.29 www 7196:
1.52 www 7197: unless ($thisallowed) {
7198: return '';
7199: }
1.29 www 7200:
1.52 www 7201: # Restrictions exist, deal with them
7202: #
7203: # C:according to course preferences
7204: # R:according to resource settings
7205: # L:unless locked
7206: # X:according to user session state
7207: #
7208:
7209: # Possibly locked functionality, check all courses
1.54 www 7210: # Locks might take effect only after 10 minutes cache expiration for other
7211: # courses, and 2 minutes for current course
1.52 www 7212:
7213: my $envkey;
7214: if ($thisallowed=~/L/) {
1.1000 raeburn 7215: foreach $envkey (keys(%env)) {
1.54 www 7216: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
7217: my $courseid=$2;
7218: my $roleid=$1.'.'.$2;
1.92 www 7219: $courseid=~s/^\///;
1.54 www 7220: my $expiretime=600;
1.620 albertel 7221: if ($env{'request.role'} eq $roleid) {
1.54 www 7222: $expiretime=120;
7223: }
7224: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
7225: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 7226: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 7227: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 7228: }
1.620 albertel 7229: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
7230: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
7231: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
7232: &log($env{'user.domain'},$env{'user.name'},
7233: $env{'user.home'},
1.57 www 7234: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 7235: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 7236: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 7237: return '';
7238: }
7239: }
1.620 albertel 7240: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
7241: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
7242: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
7243: &log($env{'user.domain'},$env{'user.name'},
7244: $env{'user.home'},
1.57 www 7245: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 7246: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 7247: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 7248: return '';
7249: }
7250: }
7251: }
1.29 www 7252: }
1.52 www 7253: }
7254:
7255: #
7256: # Rest of the restrictions depend on selected course
7257: #
7258:
1.620 albertel 7259: unless ($env{'request.course.id'}) {
1.766 albertel 7260: if ($thisallowed eq 'A') {
7261: return 'A';
1.814 raeburn 7262: } elsif ($thisallowed eq 'B') {
7263: return 'B';
1.766 albertel 7264: } else {
7265: return '1';
7266: }
1.52 www 7267: }
1.29 www 7268:
1.52 www 7269: #
7270: # Now user is definitely in a course
7271: #
1.53 www 7272:
7273:
7274: # Course preferences
7275:
7276: if ($thisallowed=~/C/) {
1.620 albertel 7277: my $rolecode=(split(/\./,$env{'request.role'}))[0];
7278: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
7279: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 7280: =~/\Q$rolecode\E/) {
1.1304 raeburn 7281: if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689 albertel 7282: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
7283: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
7284: $env{'request.course.id'});
7285: }
1.237 www 7286: return '';
7287: }
7288:
1.620 albertel 7289: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 7290: =~/\Q$unamedom\E/) {
1.1304 raeburn 7291: if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689 albertel 7292: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
7293: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
7294: $env{'request.course.id'});
7295: }
1.54 www 7296: return '';
7297: }
1.53 www 7298: }
7299:
7300: # Resource preferences
7301:
7302: if ($thisallowed=~/R/) {
1.620 albertel 7303: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 7304: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103 raeburn 7305: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7306: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
7307: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
7308: }
7309: return '';
1.54 www 7310: }
1.53 www 7311: }
1.30 www 7312:
1.246 www 7313: # Restricted by state or randomout?
1.30 www 7314:
1.52 www 7315: if ($thisallowed=~/X/) {
1.620 albertel 7316: if ($env{'acc.randomout'}) {
1.579 albertel 7317: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 7318: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 7319: return '';
7320: }
1.247 www 7321: }
7322: if (&condval($statecond)) {
1.52 www 7323: return '2';
7324: } else {
7325: return '';
7326: }
7327: }
1.30 www 7328:
1.766 albertel 7329: if ($thisallowed eq 'A') {
7330: return 'A';
1.814 raeburn 7331: } elsif ($thisallowed eq 'B') {
7332: return 'B';
1.766 albertel 7333: }
1.52 www 7334: return 'F';
1.232 www 7335: }
1.1162 raeburn 7336:
1.1192 raeburn 7337: # ------------------------------------------- Check construction space access
7338:
7339: sub constructaccess {
7340: my ($url,$setpriv)=@_;
7341:
7342: # We do not allow editing of previous versions of files
7343: if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
7344:
7345: # Get username and domain from URL
7346: my ($ownername,$ownerdomain,$ownerhome);
7347:
7348: ($ownerdomain,$ownername) =
1.1297 damieng 7349: ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)/});
1.1192 raeburn 7350:
7351: # The URL does not really point to any authorspace, forget it
7352: unless (($ownername) && ($ownerdomain)) { return ''; }
7353:
7354: # Now we need to see if the user has access to the authorspace of
7355: # $ownername at $ownerdomain
7356:
7357: if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
7358: # Real author for this?
7359: $ownerhome = $env{'user.home'};
7360: if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
7361: return ($ownername,$ownerdomain,$ownerhome);
7362: }
7363: } else {
7364: # Co-author for this?
7365: if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
7366: exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
7367: $ownerhome = &homeserver($ownername,$ownerdomain);
7368: return ($ownername,$ownerdomain,$ownerhome);
7369: }
7370: }
7371:
7372: # We don't have any access right now. If we are not possibly going to do anything about this,
7373: # we might as well leave
7374: unless ($setpriv) { return ''; }
7375:
7376: # Backdoor access?
7377: my $allowed=&allowed('eco',$ownerdomain);
7378: # Nope
7379: unless ($allowed) { return ''; }
7380: # Looks like we may have access, but could be locked by the owner of the construction space
7381: if ($allowed eq 'U') {
7382: my %blocked=&get('environment',['domcoord.author'],
7383: $ownerdomain,$ownername);
7384: # Is blocked by owner
7385: if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
7386: }
7387: if (($allowed eq 'F') || ($allowed eq 'U')) {
7388: # Grant temporary access
7389: my $then=$env{'user.login.time'};
1.1209 raeburn 7390: my $update=$env{'user.update.time'};
1.1192 raeburn 7391: if (!$update) { $update = $then; }
7392: my $refresh=$env{'user.refresh.time'};
7393: if (!$refresh) { $refresh = $update; }
7394: my $now = time;
7395: &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
7396: $now,'ca','constructaccess');
7397: $ownerhome = &homeserver($ownername,$ownerdomain);
7398: return($ownername,$ownerdomain,$ownerhome);
7399: }
7400: # No business here
7401: return '';
7402: }
7403:
1.1282 raeburn 7404: # ----------------------------------------------------------- Content Blocking
7405:
7406: {
7407: # Caches for faster Course Contents display where content blocking
7408: # is in operation (i.e., interval param set) for timed quiz.
7409: #
7410: # User for whom data are being temporarily cached.
7411: my $cacheduser='';
7412: # Cached blockers for this user (a hash of blocking items).
7413: my %cachedblockers=();
7414: # When the data were last cached.
7415: my $cachedlast='';
7416:
7417: sub load_all_blockers {
7418: my ($uname,$udom,$blocks)=@_;
7419: if (($uname ne '') && ($udom ne '')) {
7420: if (($cacheduser eq $uname.':'.$udom) &&
7421: (abs($cachedlast-time)<5)) {
7422: return;
7423: }
7424: }
7425: $cachedlast=time;
7426: $cacheduser=$uname.':'.$udom;
7427: %cachedblockers = &get_commblock_resources($blocks);
7428: }
7429:
1.1162 raeburn 7430: sub get_comm_blocks {
7431: my ($cdom,$cnum) = @_;
7432: if ($cdom eq '' || $cnum eq '') {
7433: return unless ($env{'request.course.id'});
7434: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7435: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7436: }
7437: my %commblocks;
7438: my $hashid=$cdom.'_'.$cnum;
7439: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
7440: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
7441: %commblocks = %{$blocksref};
7442: } else {
7443: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
7444: my $cachetime = 600;
7445: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
7446: }
7447: return %commblocks;
7448: }
7449:
1.1282 raeburn 7450: sub get_commblock_resources {
7451: my ($blocks) = @_;
7452: my %blockers = ();
7453: return %blockers unless ($env{'request.course.id'});
7454: return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162 raeburn 7455: my %commblocks;
7456: if (ref($blocks) eq 'HASH') {
7457: %commblocks = %{$blocks};
7458: } else {
7459: %commblocks = &get_comm_blocks();
7460: }
1.1282 raeburn 7461: return %blockers unless (keys(%commblocks) > 0);
7462: my $navmap = Apache::lonnavmaps::navmap->new();
7463: return %blockers unless (ref($navmap));
1.1162 raeburn 7464: my $now = time;
7465: foreach my $block (keys(%commblocks)) {
7466: if ($block =~ /^(\d+)____(\d+)$/) {
7467: my ($start,$end) = ($1,$2);
7468: if ($start <= $now && $end >= $now) {
7469: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7470: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
7471: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1282 raeburn 7472: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
7473: $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162 raeburn 7474: }
7475: }
7476: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1282 raeburn 7477: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
7478: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162 raeburn 7479: }
7480: }
7481: }
7482: }
7483: }
7484: } elsif ($block =~ /^firstaccess____(.+)$/) {
7485: my $item = $1;
1.1163 raeburn 7486: my @to_test;
1.1162 raeburn 7487: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7488: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1282 raeburn 7489: my @interval;
7490: my $type = 'map';
7491: if ($item eq 'course') {
7492: $type = 'course';
7493: @interval=&EXT("resource.0.interval");
7494: } else {
7495: if ($item =~ /___\d+___/) {
7496: $type = 'resource';
7497: @interval=&EXT("resource.0.interval",$item);
7498: if (ref($navmap)) {
7499: my $res = $navmap->getBySymb($item);
7500: push(@to_test,$res);
7501: }
1.1162 raeburn 7502: } else {
1.1282 raeburn 7503: my $mapsymb = &symbread($item,1);
7504: if ($mapsymb) {
7505: if (ref($navmap)) {
7506: my $mapres = $navmap->getBySymb($mapsymb);
7507: @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
7508: foreach my $res (@to_test) {
7509: my $symb = $res->symb();
7510: next if ($symb eq $mapsymb);
7511: if ($symb ne '') {
7512: @interval=&EXT("resource.0.interval",$symb);
7513: if ($interval[1] eq 'map') {
7514: last;
1.1162 raeburn 7515: }
7516: }
7517: }
7518: }
7519: }
7520: }
1.1282 raeburn 7521: }
1.1308 ! raeburn 7522: if ($interval[0] =~ /^(\d+/)) {
! 7523: my $timelimit = $1;
1.1282 raeburn 7524: my $first_access;
7525: if ($type eq 'resource') {
7526: $first_access=&get_first_access($interval[1],$item);
7527: } elsif ($type eq 'map') {
7528: $first_access=&get_first_access($interval[1],undef,$item);
7529: } else {
7530: $first_access=&get_first_access($interval[1]);
7531: }
7532: if ($first_access) {
1.1292 raeburn 7533: my $timesup = $first_access+$timelimit;
1.1282 raeburn 7534: if ($timesup > $now) {
7535: my $activeblock;
7536: foreach my $res (@to_test) {
1.1283 raeburn 7537: if ($res->answerable()) {
1.1282 raeburn 7538: $activeblock = 1;
7539: last;
7540: }
7541: }
7542: if ($activeblock) {
7543: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
7544: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
7545: $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
7546: }
7547: }
7548: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
7549: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
7550: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163 raeburn 7551: }
1.1162 raeburn 7552: }
7553: }
7554: }
7555: }
7556: }
7557: }
7558: }
7559: }
7560: }
1.1282 raeburn 7561: return %blockers;
1.1162 raeburn 7562: }
7563:
1.1282 raeburn 7564: sub has_comm_blocking {
7565: my ($priv,$symb,$uri,$blocks) = @_;
7566: my @blockers;
7567: return unless ($env{'request.course.id'});
7568: return unless ($priv eq 'bre');
7569: return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
7570: return if ($env{'request.state'} eq 'construct');
7571: &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
7572: return unless (keys(%cachedblockers) > 0);
7573: my (%possibles,@symbs);
7574: if (!$symb) {
7575: $symb = &symbread($uri,1,1,1,\%possibles);
1.1162 raeburn 7576: }
1.1282 raeburn 7577: if ($symb) {
7578: @symbs = ($symb);
7579: } elsif (keys(%possibles)) {
7580: @symbs = keys(%possibles);
7581: }
7582: my $noblock;
7583: foreach my $symb (@symbs) {
7584: last if ($noblock);
7585: my ($map,$resid,$resurl)=&decode_symb($symb);
7586: foreach my $block (keys(%cachedblockers)) {
7587: if ($block =~ /^firstaccess____(.+)$/) {
7588: my $item = $1;
7589: if (($item eq $map) || ($item eq $symb)) {
7590: $noblock = 1;
7591: last;
7592: }
7593: }
7594: if (ref($cachedblockers{$block}) eq 'HASH') {
7595: if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
7596: if ($cachedblockers{$block}{'resources'}{$symb}) {
7597: unless (grep(/^\Q$block\E$/,@blockers)) {
7598: push(@blockers,$block);
7599: }
7600: }
7601: }
1.1162 raeburn 7602: }
1.1282 raeburn 7603: if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
7604: if ($cachedblockers{$block}{'maps'}{$map}) {
7605: unless (grep(/^\Q$block\E$/,@blockers)) {
7606: push(@blockers,$block);
7607: }
7608: }
1.1162 raeburn 7609: }
7610: }
7611: }
1.1282 raeburn 7612: return if ($noblock);
7613: return @blockers;
7614: }
1.1162 raeburn 7615: }
7616:
1.1282 raeburn 7617: # -------------------------------- Deversion and split uri into path an filename
7618:
1.1133 foxr 7619: #
1.1282 raeburn 7620: # Removes the version from a URI and
1.1133 foxr 7621: # splits it in to its filename and path to the filename.
7622: # Seems like File::Basename could have done this more clearly.
7623: # Parameters:
7624: # $uri - input URI
7625: # Returns:
7626: # Two element list consisting of
7627: # $pathname - the URI up to and excluding the trailing /
7628: # $filename - The part of the URI following the last /
7629: # NOTE:
7630: # Another realization of this is simply:
7631: # use File::Basename;
7632: # ...
7633: # $uri = shift;
7634: # $filename = basename($uri);
7635: # $path = dirname($uri);
7636: # return ($filename, $path);
7637: #
7638: # The implementation below is probably faster however.
7639: #
1.710 albertel 7640: sub split_uri_for_cond {
7641: my $uri=&deversion(&declutter(shift));
7642: my @uriparts=split(/\//,$uri);
7643: my $filename=pop(@uriparts);
7644: my $pathname=join('/',@uriparts);
7645: return ($pathname,$filename);
7646: }
1.232 www 7647: # --------------------------------------------------- Is a resource on the map?
7648:
7649: sub is_on_map {
1.710 albertel 7650: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 7651: #Trying to find the conditional for the file
1.620 albertel 7652: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 7653: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 7654: if ($match) {
1.289 bowersj2 7655: return (1,$1);
7656: } else {
1.434 www 7657: return (0,0);
1.289 bowersj2 7658: }
1.12 www 7659: }
7660:
1.427 www 7661: # --------------------------------------------------------- Get symb from alias
7662:
7663: sub get_symb_from_alias {
7664: my $symb=shift;
7665: my ($map,$resid,$url)=&decode_symb($symb);
7666: # Already is a symb
7667: if ($url) { return $symb; }
7668: # Must be an alias
7669: my $aliassymb='';
7670: my %bighash;
1.620 albertel 7671: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 7672: &GDBM_READER(),0640)) {
7673: my $rid=$bighash{'mapalias_'.$symb};
7674: if ($rid) {
7675: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 7676: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
7677: $resid,$bighash{'src_'.$rid});
1.427 www 7678: }
7679: untie %bighash;
7680: }
7681: return $aliassymb;
7682: }
7683:
1.12 www 7684: # ----------------------------------------------------------------- Define Role
7685:
7686: sub definerole {
7687: if (allowed('mcr','/')) {
7688: my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800 albertel 7689: foreach my $role (split(':',$sysrole)) {
7690: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7691: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
7692: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
7693: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 7694: return "refused:s:$crole&$cqual";
7695: }
7696: }
1.191 harris41 7697: }
1.800 albertel 7698: foreach my $role (split(':',$domrole)) {
7699: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7700: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
7701: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
7702: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 7703: return "refused:d:$crole&$cqual";
7704: }
7705: }
1.191 harris41 7706: }
1.800 albertel 7707: foreach my $role (split(':',$courole)) {
7708: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7709: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
7710: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
7711: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 7712: return "refused:c:$crole&$cqual";
7713: }
7714: }
1.191 harris41 7715: }
1.620 albertel 7716: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
7717: "$env{'user.domain'}:$env{'user.name'}:".
1.21 www 7718: "rolesdef_$rolename=".
7719: escape($sysrole.'_'.$domrole.'_'.$courole);
1.620 albertel 7720: return reply($command,$env{'user.home'});
1.12 www 7721: } else {
7722: return 'refused';
7723: }
1.105 harris41 7724: }
7725:
7726: # ---------------- Make a metadata query against the network of library servers
7727:
7728: sub metadata_query {
1.1237 raeburn 7729: my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120 harris41 7730: my %rhash;
1.845 albertel 7731: my %libserv = &all_library();
1.244 matthew 7732: my @server_list = (defined($server_array) ? @$server_array
7733: : keys(%libserv) );
7734: for my $server (@server_list) {
1.1237 raeburn 7735: my $domains = '';
7736: if (ref($domains_hash) eq 'HASH') {
7737: $domains = $domains_hash->{$server};
7738: }
1.118 harris41 7739: unless ($custom or $customshow) {
1.1237 raeburn 7740: my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118 harris41 7741: $rhash{$server}=$reply;
7742: }
7743: else {
7744: my $reply=&reply("querysend:".&escape($query).':'.
1.1237 raeburn 7745: &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118 harris41 7746: $server);
7747: $rhash{$server}=$reply;
7748: }
1.112 harris41 7749: }
1.118 harris41 7750: return \%rhash;
1.240 www 7751: }
7752:
7753: # ----------------------------------------- Send log queries and wait for reply
7754:
7755: sub log_query {
7756: my ($uname,$udom,$query,%filters)=@_;
7757: my $uhome=&homeserver($uname,$udom);
7758: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 7759: my $uhost=&hostname($uhome);
1.800 albertel 7760: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 7761: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
7762: $uhome);
1.479 albertel 7763: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 7764: return get_query_reply($queryid);
7765: }
7766:
1.818 raeburn 7767: # -------------------------- Update MySQL table for portfolio file
7768:
7769: sub update_portfolio_table {
1.821 raeburn 7770: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 7771: if ($group ne '') {
7772: $file_name =~s /^\Q$group\E//;
7773: }
1.818 raeburn 7774: my $homeserver = &homeserver($uname,$udom);
7775: my $queryid=
1.821 raeburn 7776: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
7777: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 7778: my $reply = &get_query_reply($queryid);
7779: return $reply;
7780: }
7781:
1.899 raeburn 7782: # -------------------------- Update MySQL allusers table
7783:
7784: sub update_allusers_table {
7785: my ($uname,$udom,$names) = @_;
7786: my $homeserver = &homeserver($uname,$udom);
7787: my $queryid=
7788: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
7789: 'lastname='.&escape($names->{'lastname'}).'%%'.
7790: 'firstname='.&escape($names->{'firstname'}).'%%'.
7791: 'middlename='.&escape($names->{'middlename'}).'%%'.
7792: 'generation='.&escape($names->{'generation'}).'%%'.
7793: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
7794: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 7795: return;
1.899 raeburn 7796: }
7797:
1.508 raeburn 7798: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 7799:
7800: sub fetch_enrollment_query {
1.511 raeburn 7801: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508 raeburn 7802: my $homeserver;
1.547 raeburn 7803: my $maxtries = 1;
1.508 raeburn 7804: if ($context eq 'automated') {
7805: $homeserver = $perlvar{'lonHostID'};
1.547 raeburn 7806: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 7807: } else {
7808: $homeserver = &homeserver($cnum,$dom);
7809: }
1.838 albertel 7810: my $host=&hostname($homeserver);
1.506 raeburn 7811: my $cmd = '';
1.1000 raeburn 7812: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 7813: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 7814: }
7815: $cmd =~ s/%%$//;
7816: $cmd = &escape($cmd);
7817: my $query = 'fetchenrollment';
1.620 albertel 7818: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 7819: unless ($queryid=~/^\Q$host\E\_/) {
7820: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
7821: return 'error: '.$queryid;
7822: }
1.506 raeburn 7823: my $reply = &get_query_reply($queryid);
1.547 raeburn 7824: my $tries = 1;
7825: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
7826: $reply = &get_query_reply($queryid);
7827: $tries ++;
7828: }
1.526 raeburn 7829: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 7830: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 7831: } else {
1.901 albertel 7832: my @responses = split(/:/,$reply);
1.515 raeburn 7833: if ($homeserver eq $perlvar{'lonHostID'}) {
1.800 albertel 7834: foreach my $line (@responses) {
7835: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 7836: $$replyref{$key} = $value;
7837: }
7838: } else {
1.1117 foxr 7839: my $pathname = LONCAPA::tempdir();
1.800 albertel 7840: foreach my $line (@responses) {
7841: my ($key,$value) = split(/=/,$line);
1.506 raeburn 7842: $$replyref{$key} = $value;
7843: if ($value > 0) {
1.800 albertel 7844: foreach my $item (@{$$affiliatesref{$key}}) {
7845: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 7846: my $destname = $pathname.'/'.$filename;
7847: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 7848: if ($xml_classlist =~ /^error/) {
7849: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
7850: } else {
1.506 raeburn 7851: if ( open(FILE,">$destname") ) {
7852: print FILE &unescape($xml_classlist);
7853: close(FILE);
1.526 raeburn 7854: } else {
7855: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 7856: }
7857: }
7858: }
7859: }
7860: }
7861: }
7862: return 'ok';
7863: }
7864: return 'error';
7865: }
7866:
1.242 www 7867: sub get_query_reply {
7868: my $queryid=shift;
1.1117 foxr 7869: my $replyfile=LONCAPA::tempdir().$queryid;
1.240 www 7870: my $reply='';
7871: for (1..100) {
1.1289 damieng 7872: sleep(0.2);
1.240 www 7873: if (-e $replyfile.'.end') {
1.448 albertel 7874: if (open(my $fh,$replyfile)) {
1.904 albertel 7875: $reply = join('',<$fh>);
7876: close($fh);
1.240 www 7877: } else { return 'error: reply_file_error'; }
1.242 www 7878: return &unescape($reply);
7879: }
1.240 www 7880: }
1.242 www 7881: return 'timeout:'.$queryid;
1.240 www 7882: }
7883:
7884: sub courselog_query {
1.241 www 7885: #
7886: # possible filters:
7887: # url: url or symb
7888: # username
7889: # domain
7890: # action: view, submit, grade
7891: # start: timestamp
7892: # end: timestamp
7893: #
1.240 www 7894: my (%filters)=@_;
1.620 albertel 7895: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 7896: if ($filters{'url'}) {
7897: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
7898: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
7899: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
7900: }
1.620 albertel 7901: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
7902: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 7903: return &log_query($cname,$cdom,'courselog',%filters);
7904: }
7905:
7906: sub userlog_query {
1.858 raeburn 7907: #
7908: # possible filters:
7909: # action: log check role
7910: # start: timestamp
7911: # end: timestamp
7912: #
1.240 www 7913: my ($uname,$udom,%filters)=@_;
7914: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 7915: }
7916:
1.506 raeburn 7917: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
7918:
7919: sub auto_run {
1.508 raeburn 7920: my ($cnum,$cdom) = @_;
1.876 raeburn 7921: my $response = 0;
7922: my $settings;
7923: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
7924: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
7925: $settings = $domconfig{'autoenroll'};
7926: if ($settings->{'run'} eq '1') {
7927: $response = 1;
7928: }
7929: } else {
1.934 raeburn 7930: my $homeserver;
7931: if (&is_course($cdom,$cnum)) {
7932: $homeserver = &homeserver($cnum,$cdom);
7933: } else {
7934: $homeserver = &domain($cdom,'primary');
7935: }
7936: if ($homeserver ne 'no_host') {
7937: $response = &reply('autorun:'.$cdom,$homeserver);
7938: }
1.876 raeburn 7939: }
1.506 raeburn 7940: return $response;
7941: }
1.776 albertel 7942:
1.506 raeburn 7943: sub auto_get_sections {
1.508 raeburn 7944: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 7945: my $homeserver;
7946: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7947: $homeserver = &homeserver($cnum,$cdom);
7948: }
7949: if (!defined($homeserver)) {
7950: if ($cdom =~ /^$match_domain$/) {
7951: $homeserver = &domain($cdom,'primary');
7952: }
7953: }
7954: my @secs;
7955: if (defined($homeserver)) {
7956: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
7957: unless ($response eq 'refused') {
7958: @secs = split(/:/,$response);
7959: }
1.506 raeburn 7960: }
7961: return @secs;
7962: }
1.776 albertel 7963:
1.506 raeburn 7964: sub auto_new_course {
1.1099 raeburn 7965: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 7966: my $homeserver = &homeserver($cnum,$cdom);
1.1099 raeburn 7967: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 7968: return $response;
7969: }
1.776 albertel 7970:
1.506 raeburn 7971: sub auto_validate_courseID {
1.508 raeburn 7972: my ($cnum,$cdom,$inst_course_id) = @_;
7973: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 7974: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 7975: return $response;
7976: }
1.776 albertel 7977:
1.1007 raeburn 7978: sub auto_validate_instcode {
1.1020 raeburn 7979: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 7980: my ($homeserver,$response);
7981: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7982: $homeserver = &homeserver($cnum,$cdom);
7983: }
7984: if (!defined($homeserver)) {
7985: if ($cdom =~ /^$match_domain$/) {
7986: $homeserver = &domain($cdom,'primary');
7987: }
7988: }
1.1065 raeburn 7989: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
7990: &escape($instcode).':'.&escape($owner),$homeserver));
1.1216 raeburn 7991: my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
7992: return ($outcome,$description,$defaultcredits);
1.1007 raeburn 7993: }
7994:
1.506 raeburn 7995: sub auto_create_password {
1.873 raeburn 7996: my ($cnum,$cdom,$authparam,$udom) = @_;
7997: my ($homeserver,$response);
1.506 raeburn 7998: my $create_passwd = 0;
7999: my $authchk = '';
1.873 raeburn 8000: if ($udom =~ /^$match_domain$/) {
8001: $homeserver = &domain($udom,'primary');
8002: }
8003: if ($homeserver eq '') {
8004: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
8005: $homeserver = &homeserver($cnum,$cdom);
8006: }
8007: }
8008: if ($homeserver eq '') {
8009: $authchk = 'nodomain';
1.506 raeburn 8010: } else {
1.873 raeburn 8011: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
8012: if ($response eq 'refused') {
8013: $authchk = 'refused';
8014: } else {
1.901 albertel 8015: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 8016: }
1.506 raeburn 8017: }
8018: return ($authparam,$create_passwd,$authchk);
8019: }
8020:
1.706 raeburn 8021: sub auto_photo_permission {
8022: my ($cnum,$cdom,$students) = @_;
8023: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 8024: my ($outcome,$perm_reqd,$conditions) =
8025: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 8026: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
8027: return (undef,undef);
8028: }
1.706 raeburn 8029: return ($outcome,$perm_reqd,$conditions);
8030: }
8031:
8032: sub auto_checkphotos {
8033: my ($uname,$udom,$pid) = @_;
8034: my $homeserver = &homeserver($uname,$udom);
8035: my ($result,$resulttype);
8036: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 8037: &escape($uname).':'.&escape($pid),
8038: $homeserver));
1.709 albertel 8039: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
8040: return (undef,undef);
8041: }
1.706 raeburn 8042: if ($outcome) {
8043: ($result,$resulttype) = split(/:/,$outcome);
8044: }
8045: return ($result,$resulttype);
8046: }
8047:
8048: sub auto_photochoice {
8049: my ($cnum,$cdom) = @_;
8050: my $homeserver = &homeserver($cnum,$cdom);
8051: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 8052: &escape($cdom),
8053: $homeserver)));
1.709 albertel 8054: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
8055: return (undef,undef);
8056: }
1.706 raeburn 8057: return ($update,$comment);
8058: }
8059:
8060: sub auto_photoupdate {
8061: my ($affiliatesref,$dom,$cnum,$photo) = @_;
8062: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 8063: my $host=&hostname($homeserver);
1.706 raeburn 8064: my $cmd = '';
8065: my $maxtries = 1;
1.800 albertel 8066: foreach my $affiliate (keys(%{$affiliatesref})) {
8067: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 8068: }
8069: $cmd =~ s/%%$//;
8070: $cmd = &escape($cmd);
8071: my $query = 'institutionalphotos';
8072: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
8073: unless ($queryid=~/^\Q$host\E\_/) {
8074: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
8075: return 'error: '.$queryid;
8076: }
8077: my $reply = &get_query_reply($queryid);
8078: my $tries = 1;
8079: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
8080: $reply = &get_query_reply($queryid);
8081: $tries ++;
8082: }
8083: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
8084: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
8085: } else {
8086: my @responses = split(/:/,$reply);
8087: my $outcome = shift(@responses);
8088: foreach my $item (@responses) {
8089: my ($key,$value) = split(/=/,$item);
8090: $$photo{$key} = $value;
8091: }
8092: return $outcome;
8093: }
8094: return 'error';
8095: }
8096:
1.521 raeburn 8097: sub auto_instcode_format {
1.793 albertel 8098: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
8099: $cat_order) = @_;
1.521 raeburn 8100: my $courses = '';
1.772 raeburn 8101: my @homeservers;
1.521 raeburn 8102: if ($caller eq 'global') {
1.841 albertel 8103: my %servers = &get_servers($codedom,'library');
8104: foreach my $tryserver (keys(%servers)) {
8105: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
8106: push(@homeservers,$tryserver);
8107: }
1.584 raeburn 8108: }
1.1022 raeburn 8109: } elsif ($caller eq 'requests') {
8110: if ($codedom =~ /^$match_domain$/) {
8111: my $chome = &domain($codedom,'primary');
8112: unless ($chome eq 'no_host') {
8113: push(@homeservers,$chome);
8114: }
8115: }
1.521 raeburn 8116: } else {
1.772 raeburn 8117: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 8118: }
1.793 albertel 8119: foreach my $code (keys(%{$instcodes})) {
8120: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 8121: }
8122: chop($courses);
1.772 raeburn 8123: my $ok_response = 0;
8124: my $response;
8125: while (@homeservers > 0 && $ok_response == 0) {
8126: my $server = shift(@homeservers);
8127: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
8128: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
8129: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 8130: split(/:/,$response);
1.772 raeburn 8131: %{$codes} = (%{$codes},&str2hash($codes_str));
8132: push(@{$codetitles},&str2array($codetitles_str));
8133: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
8134: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
8135: $ok_response = 1;
8136: }
8137: }
8138: if ($ok_response) {
1.521 raeburn 8139: return 'ok';
1.772 raeburn 8140: } else {
8141: return $response;
1.521 raeburn 8142: }
8143: }
8144:
1.792 raeburn 8145: sub auto_instcode_defaults {
8146: my ($domain,$returnhash,$code_order) = @_;
8147: my @homeservers;
1.841 albertel 8148:
8149: my %servers = &get_servers($domain,'library');
8150: foreach my $tryserver (keys(%servers)) {
8151: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
8152: push(@homeservers,$tryserver);
8153: }
1.792 raeburn 8154: }
1.841 albertel 8155:
1.792 raeburn 8156: my $response;
1.841 albertel 8157: foreach my $server (@homeservers) {
1.792 raeburn 8158: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 8159: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
8160:
8161: foreach my $pair (split(/\&/,$response)) {
8162: my ($name,$value)=split(/\=/,$pair);
8163: if ($name eq 'code_order') {
8164: @{$code_order} = split(/\&/,&unescape($value));
8165: } else {
8166: $returnhash->{&unescape($name)}=&unescape($value);
8167: }
8168: }
8169: return 'ok';
1.792 raeburn 8170: }
1.841 albertel 8171:
8172: return $response;
1.1003 raeburn 8173: }
8174:
8175: sub auto_possible_instcodes {
1.1007 raeburn 8176: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
8177: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
8178: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
8179: return;
8180: }
1.1003 raeburn 8181: my (@homeservers,$uhome);
8182: if (defined(&domain($domain,'primary'))) {
8183: $uhome=&domain($domain,'primary');
8184: push(@homeservers,&domain($domain,'primary'));
8185: } else {
8186: my %servers = &get_servers($domain,'library');
8187: foreach my $tryserver (keys(%servers)) {
8188: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
8189: push(@homeservers,$tryserver);
8190: }
8191: }
8192: }
8193: my $response;
8194: foreach my $server (@homeservers) {
8195: $response=&reply('autopossibleinstcodes:'.$domain,$server);
8196: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 8197: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
8198: split(':',$response);
8199: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
8200: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 8201: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 8202: my ($name,$value)=split('=',$item);
8203: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 8204: }
8205: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 8206: my ($name,$value)=split('=',$item);
8207: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 8208: }
8209: return 'ok';
8210: }
8211: return $response;
8212: }
1.792 raeburn 8213:
1.1010 raeburn 8214: sub auto_courserequest_checks {
8215: my ($dom) = @_;
1.1020 raeburn 8216: my ($homeserver,%validations);
8217: if ($dom =~ /^$match_domain$/) {
8218: $homeserver = &domain($dom,'primary');
8219: }
8220: unless ($homeserver eq 'no_host') {
8221: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
8222: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
8223: my @items = split(/&/,$response);
8224: foreach my $item (@items) {
8225: my ($key,$value) = split('=',$item);
8226: $validations{&unescape($key)} = &thaw_unescape($value);
8227: }
8228: }
8229: }
1.1010 raeburn 8230: return %validations;
8231: }
8232:
1.1020 raeburn 8233: sub auto_courserequest_validation {
1.1255 raeburn 8234: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020 raeburn 8235: my ($homeserver,$response);
8236: if ($dom =~ /^$match_domain$/) {
8237: $homeserver = &domain($dom,'primary');
8238: }
1.1255 raeburn 8239: unless ($homeserver eq 'no_host') {
8240: my $customdata;
8241: if (ref($custominfo) eq 'HASH') {
8242: $customdata = &freeze_escape($custominfo);
8243: }
1.1020 raeburn 8244: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 8245: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1255 raeburn 8246: ':'.&escape($instcode).':'.&escape($instseclist).':'.
8247: $customdata,$homeserver));
1.1020 raeburn 8248: }
8249: return $response;
8250: }
8251:
1.777 albertel 8252: sub auto_validate_class_sec {
1.918 raeburn 8253: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 8254: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 8255: my $ownerlist;
8256: if (ref($owners) eq 'ARRAY') {
8257: $ownerlist = join(',',@{$owners});
8258: } else {
8259: $ownerlist = $owners;
8260: }
1.773 raeburn 8261: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 8262: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 8263: return $response;
8264: }
8265:
1.1248 raeburn 8266: sub auto_crsreq_update {
8267: my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1257 raeburn 8268: $code,$accessstart,$accessend,$inbound) = @_;
1.1248 raeburn 8269: my ($homeserver,%crsreqresponse);
8270: if ($cdom =~ /^$match_domain$/) {
8271: $homeserver = &domain($cdom,'primary');
8272: }
8273: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
8274: my $info;
8275: if (ref($inbound) eq 'HASH') {
8276: $info = &freeze_escape($inbound);
8277: }
8278: my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
8279: ':'.&escape($action).':'.&escape($ownername).':'.
8280: &escape($ownerdomain).':'.&escape($fullname).':'.
1.1257 raeburn 8281: &escape($title).':'.&escape($code).':'.
8282: &escape($accessstart).':'.&escape($accessend).':'.$info,
8283: $homeserver);
1.1248 raeburn 8284: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
8285: my @items = split(/&/,$response);
8286: foreach my $item (@items) {
8287: my ($key,$value) = split('=',$item);
8288: $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
8289: }
8290: }
8291: }
8292: return \%crsreqresponse;
8293: }
8294:
1.1305 raeburn 8295: sub auto_export_grades {
8296: my ($cnum,$cdom,$gradesref) = @_;
8297: return;
8298: }
8299:
1.1287 raeburn 8300: sub check_instcode_cloning {
8301: my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
8302: unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
8303: return;
8304: }
8305: my $canclone;
8306: if (@{$code_order} > 0) {
8307: my $instcoderegexp ='^';
8308: my @clonecodes = split(/\&/,$cloner);
8309: foreach my $item (@{$code_order}) {
8310: if (grep(/^\Q$item\E=/,@clonecodes)) {
8311: foreach my $pair (@clonecodes) {
8312: my ($key,$val) = split(/\=/,$pair,2);
8313: $val = &unescape($val);
8314: if ($key eq $item) {
8315: $instcoderegexp .= '('.$val.')';
8316: last;
8317: }
8318: }
8319: } else {
8320: $instcoderegexp .= $codedefaults->{$item};
8321: }
8322: }
8323: $instcoderegexp .= '$';
8324: my (@from,@to);
8325: eval {
8326: (@from) = ($clonefromcode =~ /$instcoderegexp/);
8327: (@to) = ($clonetocode =~ /$instcoderegexp/);
8328: };
8329: if ((@from > 0) && (@to > 0)) {
8330: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
8331: if (!@diffs) {
8332: $canclone = 1;
8333: }
8334: }
8335: }
8336: return $canclone;
8337: }
8338:
8339: sub default_instcode_cloning {
8340: my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
8341: my (%codedefaults,@code_order,$canclone);
8342: if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
8343: %codedefaults = %{$codedefaultsref};
8344: @code_order = @{$codeorderref};
8345: } elsif ($clonedom) {
8346: &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
8347: }
8348: if (($domdefclone) && (@code_order)) {
8349: my @clonecodes = split(/\+/,$domdefclone);
8350: my $instcoderegexp ='^';
8351: foreach my $item (@code_order) {
8352: if (grep(/^\Q$item\E$/,@clonecodes)) {
8353: $instcoderegexp .= '('.$codedefaults{$item}.')';
8354: } else {
8355: $instcoderegexp .= $codedefaults{$item};
8356: }
8357: }
8358: $instcoderegexp .= '$';
8359: my (@from,@to);
8360: eval {
8361: (@from) = ($clonefromcode =~ /$instcoderegexp/);
8362: (@to) = ($clonetocode =~ /$instcoderegexp/);
8363: };
8364: if ((@from > 0) && (@to > 0)) {
8365: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
8366: if (!@diffs) {
8367: $canclone = 1;
8368: }
8369: }
8370: }
8371: return $canclone;
8372: }
8373:
1.679 raeburn 8374: # ------------------------------------------------------- Course Group routines
8375:
8376: sub get_coursegroups {
1.809 raeburn 8377: my ($cdom,$cnum,$group,$namespace) = @_;
8378: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 8379: }
8380:
1.679 raeburn 8381: sub modify_coursegroup {
8382: my ($cdom,$cnum,$groupsettings) = @_;
8383: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
8384: }
8385:
1.809 raeburn 8386: sub toggle_coursegroup_status {
8387: my ($cdom,$cnum,$group,$action) = @_;
8388: my ($from_namespace,$to_namespace);
8389: if ($action eq 'delete') {
8390: $from_namespace = 'coursegroups';
8391: $to_namespace = 'deleted_groups';
8392: } else {
8393: $from_namespace = 'deleted_groups';
8394: $to_namespace = 'coursegroups';
8395: }
8396: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 8397: if (my $tmp = &error(%curr_group)) {
8398: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
8399: return ('read error',$tmp);
8400: } else {
8401: my %savedsettings = %curr_group;
1.809 raeburn 8402: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 8403: my $deloutcome;
8404: if ($result eq 'ok') {
1.809 raeburn 8405: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 8406: } else {
8407: return ('write error',$result);
8408: }
8409: if ($deloutcome eq 'ok') {
8410: return 'ok';
8411: } else {
8412: return ('delete error',$deloutcome);
8413: }
8414: }
8415: }
8416:
1.679 raeburn 8417: sub modify_group_roles {
1.957 raeburn 8418: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 8419: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
8420: my $role = 'gr/'.&escape($userprivs);
8421: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 8422: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 8423: if ($result eq 'ok') {
8424: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
8425: }
1.679 raeburn 8426: return $result;
8427: }
8428:
8429: sub modify_coursegroup_membership {
8430: my ($cdom,$cnum,$membership) = @_;
8431: my $result = &put('groupmembership',$membership,$cdom,$cnum);
8432: return $result;
8433: }
8434:
1.682 raeburn 8435: sub get_active_groups {
8436: my ($udom,$uname,$cdom,$cnum) = @_;
8437: my $now = time;
8438: my %groups = ();
8439: foreach my $key (keys(%env)) {
1.811 albertel 8440: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 8441: my ($start,$end) = split(/\./,$env{$key});
8442: if (($end!=0) && ($end<$now)) { next; }
8443: if (($start!=0) && ($start>$now)) { next; }
8444: if ($1 eq $cdom && $2 eq $cnum) {
8445: $groups{$3} = $env{$key} ;
8446: }
8447: }
8448: }
8449: return %groups;
8450: }
8451:
1.683 raeburn 8452: sub get_group_membership {
8453: my ($cdom,$cnum,$group) = @_;
8454: return(&dump('groupmembership',$cdom,$cnum,$group));
8455: }
8456:
8457: sub get_users_groups {
8458: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 8459: my @usersgroups;
1.683 raeburn 8460: my $cachetime=1800;
8461:
8462: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 8463: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
8464: if (defined($cached)) {
1.734 albertel 8465: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 8466: } else {
8467: $grouplist = '';
1.816 raeburn 8468: my $courseurl = &courseid_to_courseurl($courseid);
1.1166 raeburn 8469: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 8470: my $access_end = $env{'course.'.$courseid.
8471: '.default_enrollment_end_date'};
8472: my $now = time;
8473: foreach my $key (keys(%roleshash)) {
8474: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
8475: my $group = $1;
8476: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
8477: my $start = $2;
8478: my $end = $1;
8479: if ($start == -1) { next; } # deleted from group
8480: if (($start!=0) && ($start>$now)) { next; }
8481: if (($end!=0) && ($end<$now)) {
8482: if ($access_end && $access_end < $now) {
8483: if ($access_end - $end < 86400) {
8484: push(@usersgroups,$group);
1.733 raeburn 8485: }
8486: }
1.817 raeburn 8487: next;
1.733 raeburn 8488: }
1.817 raeburn 8489: push(@usersgroups,$group);
1.683 raeburn 8490: }
8491: }
8492: }
1.817 raeburn 8493: @usersgroups = &sort_course_groups($courseid,@usersgroups);
8494: $grouplist = join(':',@usersgroups);
8495: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 8496: }
1.733 raeburn 8497: return @usersgroups;
1.683 raeburn 8498: }
8499:
8500: sub devalidate_getgroups_cache {
8501: my ($udom,$uname,$cdom,$cnum)=@_;
8502: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 8503:
1.683 raeburn 8504: my $hashid="$udom:$uname:$courseid";
8505: &devalidate_cache_new('getgroups',$hashid);
8506: }
8507:
1.12 www 8508: # ------------------------------------------------------------------ Plain Text
8509:
8510: sub plaintext {
1.988 raeburn 8511: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 8512: if ($short =~ m{^cr/}) {
1.758 albertel 8513: return (split('/',$short))[-1];
8514: }
1.742 raeburn 8515: if (!defined($cid)) {
8516: $cid = $env{'request.course.id'};
8517: }
8518: my %rolenames = (
1.1008 raeburn 8519: Course => 'std',
8520: Community => 'alt1',
1.1305 raeburn 8521: Placement => 'std',
1.742 raeburn 8522: );
1.1037 raeburn 8523: if ($cid ne '') {
8524: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
8525: unless ($forcedefault) {
8526: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
8527: &Apache::lonlocal::mt_escape(\$roletext);
8528: return &Apache::lonlocal::mt($roletext);
8529: }
8530: }
8531: }
8532: if ((defined($type)) && (defined($rolenames{$type})) &&
8533: (defined($rolenames{$type})) &&
8534: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 8535: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 8536: } elsif ($cid ne '') {
8537: my $crstype = $env{'course.'.$cid.'.type'};
8538: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
8539: (defined($prp{$short}{$rolenames{$crstype}}))) {
8540: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
8541: }
1.742 raeburn 8542: }
1.1037 raeburn 8543: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 8544: }
8545:
8546: # ----------------------------------------------------------------- Assign Role
8547:
8548: sub assignrole {
1.957 raeburn 8549: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
8550: $context)=@_;
1.21 www 8551: my $mrole;
8552: if ($role =~ /^cr\//) {
1.393 www 8553: my $cwosec=$url;
1.811 albertel 8554: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 8555: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 8556: my $refused = 1;
8557: if ($context eq 'requestcourses') {
8558: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
8559: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
8560: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
8561: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8562: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8563: if ($crsenv{'internal.courseowner'} eq
8564: $env{'user.name'}.':'.$env{'user.domain'}) {
8565: $refused = '';
8566: }
8567: }
8568: }
8569: }
8570: }
8571: if ($refused) {
8572: &logthis('Refused custom assignrole: '.
8573: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
8574: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
8575: return 'refused';
8576: }
1.104 www 8577: }
1.21 www 8578: $mrole='cr';
1.678 raeburn 8579: } elsif ($role =~ /^gr\//) {
8580: my $cwogrp=$url;
1.811 albertel 8581: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 8582: unless (&allowed('mdg',$cwogrp)) {
8583: &logthis('Refused group assignrole: '.
8584: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
8585: $env{'user.name'}.' at '.$env{'user.domain'});
8586: return 'refused';
8587: }
8588: $mrole='gr';
1.21 www 8589: } else {
1.82 www 8590: my $cwosec=$url;
1.811 albertel 8591: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 8592: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
8593: my $refused;
8594: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
8595: if (!(&allowed('c'.$role,$url))) {
8596: $refused = 1;
8597: }
8598: } else {
8599: $refused = 1;
8600: }
1.947 raeburn 8601: if ($refused) {
1.1045 raeburn 8602: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8603: if (!$selfenroll && $context eq 'course') {
8604: my %crsenv;
8605: if ($role eq 'cc' || $role eq 'co') {
8606: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8607: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
8608: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
8609: if ($crsenv{'internal.courseowner'} eq
8610: $env{'user.name'}.':'.$env{'user.domain'}) {
8611: $refused = '';
8612: }
8613: }
8614: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
8615: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
8616: if ($crsenv{'internal.courseowner'} eq
8617: $env{'user.name'}.':'.$env{'user.domain'}) {
8618: $refused = '';
8619: }
8620: }
8621: }
8622: }
8623: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 8624: $refused = '';
1.1017 raeburn 8625: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 8626: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 8627: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 8628: my $wrongcc;
8629: if ($cnum =~ /^$match_community$/) {
8630: $wrongcc = 1 if ($role eq 'cc');
8631: } else {
8632: $wrongcc = 1 if ($role eq 'co');
8633: }
8634: unless ($wrongcc) {
8635: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8636: if ($crsenv{'internal.courseowner'} eq
8637: $env{'user.name'}.':'.$env{'user.domain'}) {
8638: $refused = '';
8639: }
1.1017 raeburn 8640: }
8641: }
1.1183 raeburn 8642: } elsif ($context eq 'requestauthor') {
8643: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
8644: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
8645: if ($env{'environment.requestauthor'} eq 'automatic') {
8646: $refused = '';
8647: } else {
8648: my %domdefaults = &get_domain_defaults($udom);
8649: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
8650: my $checkbystatus;
8651: if ($env{'user.adv'}) {
8652: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
8653: if ($disposition eq 'automatic') {
8654: $refused = '';
8655: } elsif ($disposition eq '') {
8656: $checkbystatus = 1;
8657: }
8658: } else {
8659: $checkbystatus = 1;
8660: }
8661: if ($checkbystatus) {
8662: if ($env{'environment.inststatus'}) {
8663: my @inststatuses = split(/,/,$env{'environment.inststatus'});
8664: foreach my $type (@inststatuses) {
8665: if (($type ne '') &&
8666: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
8667: $refused = '';
8668: }
8669: }
8670: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
8671: $refused = '';
8672: }
8673: }
8674: }
8675: }
8676: }
1.1017 raeburn 8677: }
8678: if ($refused) {
1.947 raeburn 8679: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
8680: ' '.$role.' '.$end.' '.$start.' by '.
8681: $env{'user.name'}.' at '.$env{'user.domain'});
8682: return 'refused';
8683: }
1.932 raeburn 8684: }
1.1131 raeburn 8685: } elsif ($role eq 'au') {
8686: if ($url ne '/'.$udom.'/') {
8687: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
8688: ' to assign author role for '.$uname.':'.$udom.
8689: ' in domain: '.$url.' refused (wrong domain).');
8690: return 'refused';
8691: }
1.104 www 8692: }
1.21 www 8693: $mrole=$role;
8694: }
1.620 albertel 8695: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 8696: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 8697: if ($end) { $command.='_'.$end; }
1.21 www 8698: if ($start) {
8699: if ($end) {
1.81 www 8700: $command.='_'.$start;
1.21 www 8701: } else {
1.81 www 8702: $command.='_0_'.$start;
1.21 www 8703: }
8704: }
1.739 raeburn 8705: my $origstart = $start;
8706: my $origend = $end;
1.957 raeburn 8707: my $delflag;
1.357 www 8708: # actually delete
8709: if ($deleteflag) {
1.373 www 8710: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 8711: # modify command to delete the role
1.620 albertel 8712: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 8713: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 8714: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 8715: # set start and finish to negative values for userrolelog
8716: $start=-1;
8717: $end=-1;
1.957 raeburn 8718: $delflag = 1;
1.357 www 8719: }
8720: }
8721: # send command
1.349 www 8722: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 8723: # log new user role if status is ok
1.349 www 8724: if ($answer eq 'ok') {
1.663 raeburn 8725: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.1184 raeburn 8726: if (($role eq 'cc') || ($role eq 'in') ||
8727: ($role eq 'ep') || ($role eq 'ad') ||
8728: ($role eq 'ta') || ($role eq 'st') ||
8729: ($role=~/^cr/) || ($role eq 'gr') ||
8730: ($role eq 'co')) {
1.1200 raeburn 8731: # for course roles, perform group memberships changes triggered by role change.
8732: unless ($role =~ /^gr/) {
8733: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
8734: $origstart,$selfenroll,$context);
8735: }
1.1184 raeburn 8736: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8737: $selfenroll,$context);
8738: } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
8739: ($role eq 'au') || ($role eq 'dc')) {
8740: &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8741: $context);
8742: } elsif (($role eq 'ca') || ($role eq 'aa')) {
8743: &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8744: $context);
8745: }
1.1053 raeburn 8746: if ($role eq 'cc') {
8747: &autoupdate_coowners($url,$end,$start,$uname,$udom);
8748: }
1.349 www 8749: }
8750: return $answer;
1.169 harris41 8751: }
8752:
1.1053 raeburn 8753: sub autoupdate_coowners {
8754: my ($url,$end,$start,$uname,$udom) = @_;
8755: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
8756: if (($cdom ne '') && ($cnum ne '')) {
8757: my $now = time;
8758: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
8759: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
8760: my %coursehash = &coursedescription($cdom.'_'.$cnum);
8761: my $instcode = $coursehash{'internal.coursecode'};
8762: if ($instcode ne '') {
1.1056 raeburn 8763: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
8764: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 8765: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 8766: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
8767: if ($result eq 'valid') {
8768: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 8769: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
8770: push(@newcoowners,$coowner);
8771: }
8772: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
8773: push(@newcoowners,$uname.':'.$udom);
8774: }
8775: @newcoowners = sort(@newcoowners);
8776: } else {
8777: push(@newcoowners,$uname.':'.$udom);
8778: }
8779: } else {
8780: if ($coursehash{'internal.co-owners'}) {
8781: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
8782: unless ($coowner eq $uname.':'.$udom) {
8783: push(@newcoowners,$coowner);
8784: }
8785: }
8786: unless (@newcoowners > 0) {
8787: $delcoowners = 1;
8788: $coowners = '';
8789: }
8790: }
8791: }
8792: if (@newcoowners || $delcoowners) {
8793: &store_coowners($cdom,$cnum,$coursehash{'home'},
8794: $delcoowners,@newcoowners);
8795: }
8796: }
8797: }
8798: }
8799: }
8800: }
8801: }
8802:
8803: sub store_coowners {
8804: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
8805: my $cid = $cdom.'_'.$cnum;
8806: my ($coowners,$delresult,$putresult);
8807: if (@newcoowners) {
8808: $coowners = join(',',@newcoowners);
8809: my %coownershash = (
8810: 'internal.co-owners' => $coowners,
8811: );
8812: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
8813: if ($putresult eq 'ok') {
8814: if ($env{'course.'.$cid.'.num'} eq $cnum) {
8815: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
8816: }
8817: }
8818: }
8819: if ($delcoowners) {
8820: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
8821: if ($delresult eq 'ok') {
8822: if ($env{'course.'.$cid.'.internal.co-owners'}) {
8823: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
8824: }
8825: }
8826: }
8827: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
8828: my %crsinfo =
8829: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
8830: if (ref($crsinfo{$cid}) eq 'HASH') {
8831: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
8832: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
8833: }
8834: }
8835: }
8836:
1.169 harris41 8837: # -------------------------------------------------- Modify user authentication
1.197 www 8838: # Overrides without validation
8839:
1.169 harris41 8840: sub modifyuserauth {
8841: my ($udom,$uname,$umode,$upass)=@_;
8842: my $uhome=&homeserver($uname,$udom);
1.197 www 8843: unless (&allowed('mau',$udom)) { return 'refused'; }
8844: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 8845: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
8846: ' in domain '.$env{'request.role.domain'});
1.169 harris41 8847: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
8848: &escape($upass),$uhome);
1.620 albertel 8849: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 8850: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
8851: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
8852: &log($udom,,$uname,$uhome,
1.620 albertel 8853: 'Authentication changed by '.$env{'user.domain'}.', '.
8854: $env{'user.name'}.', '.$umode.
1.197 www 8855: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 8856: unless ($reply eq 'ok') {
1.197 www 8857: &logthis('Authentication mode error: '.$reply);
1.169 harris41 8858: return 'error: '.$reply;
8859: }
1.170 harris41 8860: return 'ok';
1.80 www 8861: }
8862:
1.81 www 8863: # --------------------------------------------------------------- Modify a user
1.80 www 8864:
1.81 www 8865: sub modifyuser {
1.206 matthew 8866: my ($udom, $uname, $uid,
8867: $umode, $upass, $first,
8868: $middle, $last, $gene,
1.1058 raeburn 8869: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 8870: $udom= &LONCAPA::clean_domain($udom);
8871: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 8872: my $showcandelete = 'none';
8873: if (ref($candelete) eq 'ARRAY') {
8874: if (@{$candelete} > 0) {
8875: $showcandelete = join(', ',@{$candelete});
8876: }
8877: }
1.81 www 8878: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 8879: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 8880: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 8881: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
8882: ' desiredhome not specified').
1.620 albertel 8883: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
8884: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 8885: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 8886: my $newuser;
8887: if ($uhome eq 'no_host') {
8888: $newuser = 1;
8889: }
1.80 www 8890: # ----------------------------------------------------------------- Create User
1.406 albertel 8891: if (($uhome eq 'no_host') &&
8892: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 8893: my $unhome='';
1.844 albertel 8894: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 8895: $unhome = $desiredhome;
1.620 albertel 8896: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
8897: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 8898: } else { # load balancing routine for determining $unhome
1.81 www 8899: my $loadm=10000000;
1.841 albertel 8900: my %servers = &get_servers($udom,'library');
8901: foreach my $tryserver (keys(%servers)) {
8902: my $answer=reply('load',$tryserver);
8903: if (($answer=~/\d+/) && ($answer<$loadm)) {
8904: $loadm=$answer;
8905: $unhome=$tryserver;
8906: }
1.80 www 8907: }
8908: }
8909: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 8910: return 'error: unable to find a home server for '.$uname.
8911: ' in domain '.$udom;
1.80 www 8912: }
8913: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
8914: &escape($upass),$unhome);
8915: unless ($reply eq 'ok') {
8916: return 'error: '.$reply;
8917: }
1.230 stredwic 8918: $uhome=&homeserver($uname,$udom,'true');
1.80 www 8919: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 8920: return 'error: unable verify users home machine.';
1.80 www 8921: }
1.209 matthew 8922: } # End of creation of new user
1.80 www 8923: # ---------------------------------------------------------------------- Add ID
8924: if ($uid) {
8925: $uid=~tr/A-Z/a-z/;
8926: my %uidhash=&idrget($udom,$uname);
1.196 www 8927: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
8928: && (!$forceid)) {
1.80 www 8929: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 8930: return 'error: user id "'.$uid.'" does not match '.
8931: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 8932: }
8933: } else {
1.1300 raeburn 8934: &idput($udom,{$uname => $uid},$uhome,'ids');
1.80 www 8935: }
8936: }
8937: # -------------------------------------------------------------- Add names, etc
1.313 matthew 8938: my @tmp=&get('environment',
1.899 raeburn 8939: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 8940: 'permanentemail','inststatus'],
1.134 albertel 8941: $udom,$uname);
1.1075 raeburn 8942: my (%names,%oldnames);
1.313 matthew 8943: if ($tmp[0] =~ m/^error:.*/) {
8944: %names=();
8945: } else {
8946: %names = @tmp;
1.1075 raeburn 8947: %oldnames = %names;
1.313 matthew 8948: }
1.388 www 8949: #
1.1058 raeburn 8950: # If name, email and/or uid are blank (e.g., because an uploaded file
8951: # of users did not contain them), do not overwrite existing values
8952: # unless field is in $candelete array ref.
8953: #
8954:
8955: my @fields = ('firstname','middlename','lastname','generation',
8956: 'permanentemail','id');
8957: my %newvalues;
8958: if (ref($candelete) eq 'ARRAY') {
8959: foreach my $field (@fields) {
8960: if (grep(/^\Q$field\E$/,@{$candelete})) {
8961: if ($field eq 'firstname') {
8962: $names{$field} = $first;
8963: } elsif ($field eq 'middlename') {
8964: $names{$field} = $middle;
8965: } elsif ($field eq 'lastname') {
8966: $names{$field} = $last;
8967: } elsif ($field eq 'generation') {
8968: $names{$field} = $gene;
8969: } elsif ($field eq 'permanentemail') {
8970: $names{$field} = $email;
8971: } elsif ($field eq 'id') {
8972: $names{$field} = $uid;
8973: }
8974: }
8975: }
8976: }
1.388 www 8977: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 8978: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 8979: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 8980: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 8981: if ($email) {
8982: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 8983: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 8984: }
1.899 raeburn 8985: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 8986: if (defined($inststatus)) {
8987: $names{'inststatus'} = '';
8988: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
8989: if (ref($usertypes) eq 'HASH') {
8990: my @okstatuses;
8991: foreach my $item (split(/:/,$inststatus)) {
8992: if (defined($usertypes->{$item})) {
8993: push(@okstatuses,$item);
8994: }
8995: }
8996: if (@okstatuses) {
8997: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
8998: }
8999: }
9000: }
1.1075 raeburn 9001: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 9002: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 9003: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 9004: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
9005: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
9006: } else {
9007: $logmsg .= ' during self creation';
9008: }
1.1075 raeburn 9009: my $changed;
9010: if ($newuser) {
9011: $changed = 1;
9012: } else {
9013: foreach my $field (@fields) {
9014: if ($names{$field} ne $oldnames{$field}) {
9015: $changed = 1;
9016: last;
9017: }
9018: }
9019: }
9020: unless ($changed) {
9021: $logmsg = 'No changes in user information needed for: '.$logmsg;
9022: &logthis($logmsg);
9023: return 'ok';
9024: }
9025: my $reply = &put('environment', \%names, $udom,$uname);
9026: if ($reply ne 'ok') {
9027: return 'error: '.$reply;
9028: }
1.1087 raeburn 9029: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
9030: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
9031: }
1.1075 raeburn 9032: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
9033: &devalidate_cache_new('namescache',$uname.':'.$udom);
9034: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 9035: &logthis($logmsg);
1.134 albertel 9036: return 'ok';
1.80 www 9037: }
9038:
1.81 www 9039: # -------------------------------------------------------------- Modify student
1.80 www 9040:
1.81 www 9041: sub modifystudent {
9042: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 9043: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1216 raeburn 9044: $selfenroll,$context,$inststatus,$credits)=@_;
1.455 albertel 9045: if (!$cid) {
1.620 albertel 9046: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 9047: return 'not_in_class';
9048: }
1.80 www 9049: }
9050: # --------------------------------------------------------------- Make the user
1.81 www 9051: my $reply=&modifyuser
1.209 matthew 9052: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 9053: $desiredhome,$email,$inststatus);
1.80 www 9054: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 9055: # This will cause &modify_student_enrollment to get the uid from the
1.1235 raeburn 9056: # student's environment
1.297 matthew 9057: $uid = undef if (!$forceid);
1.455 albertel 9058: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1216 raeburn 9059: $gene,$usec,$end,$start,$type,$locktype,
9060: $cid,$selfenroll,$context,$credits);
1.297 matthew 9061: return $reply;
9062: }
9063:
9064: sub modify_student_enrollment {
1.1216 raeburn 9065: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
9066: $locktype,$cid,$selfenroll,$context,$credits) = @_;
1.455 albertel 9067: my ($cdom,$cnum,$chome);
9068: if (!$cid) {
1.620 albertel 9069: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 9070: return 'not_in_class';
9071: }
1.620 albertel 9072: $cdom=$env{'course.'.$cid.'.domain'};
9073: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 9074: } else {
9075: ($cdom,$cnum)=split(/_/,$cid);
9076: }
1.620 albertel 9077: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 9078: if (!$chome) {
1.457 raeburn 9079: $chome=&homeserver($cnum,$cdom);
1.297 matthew 9080: }
1.455 albertel 9081: if (!$chome) { return 'unknown_course'; }
1.297 matthew 9082: # Make sure the user exists
1.81 www 9083: my $uhome=&homeserver($uname,$udom);
9084: if (($uhome eq '') || ($uhome eq 'no_host')) {
9085: return 'error: no such user';
9086: }
1.297 matthew 9087: # Get student data if we were not given enough information
9088: if (!defined($first) || $first eq '' ||
9089: !defined($last) || $last eq '' ||
9090: !defined($uid) || $uid eq '' ||
9091: !defined($middle) || $middle eq '' ||
9092: !defined($gene) || $gene eq '') {
1.294 matthew 9093: # They did not supply us with enough data to enroll the student, so
9094: # we need to pick up more information.
1.297 matthew 9095: my %tmp = &get('environment',
1.294 matthew 9096: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 9097: ,$udom,$uname);
9098:
1.800 albertel 9099: #foreach my $key (keys(%tmp)) {
9100: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 9101: #}
1.294 matthew 9102: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
9103: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
9104: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 9105: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 9106: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
9107: }
1.556 albertel 9108: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148 raeburn 9109: my $user = "$uname:$udom";
9110: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487 albertel 9111: my $reply=cput('classlist',
1.1148 raeburn 9112: {$user =>
1.1216 raeburn 9113: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits) },
1.487 albertel 9114: $cdom,$cnum);
1.1148 raeburn 9115: if (($reply eq 'ok') || ($reply eq 'delayed')) {
9116: &devalidate_getsection_cache($udom,$uname,$cid);
9117: } else {
1.81 www 9118: return 'error: '.$reply;
9119: }
1.297 matthew 9120: # Add student role to user
1.83 www 9121: my $uurl='/'.$cid;
1.81 www 9122: $uurl=~s/\_/\//g;
9123: if ($usec) {
9124: $uurl.='/'.$usec;
9125: }
1.1148 raeburn 9126: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
9127: $selfenroll,$context);
9128: if ($result ne 'ok') {
9129: if ($old_entry{$user} ne '') {
9130: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
9131: } else {
9132: $reply = &del('classlist',[$user],$cdom,$cnum);
9133: }
9134: }
9135: return $result;
1.21 www 9136: }
9137:
1.556 albertel 9138: sub format_name {
9139: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
9140: my $name;
9141: if ($first ne 'lastname') {
9142: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
9143: } else {
9144: if ($lastname=~/\S/) {
9145: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
9146: $name=~s/\s+,/,/;
9147: } else {
9148: $name.= $firstname.' '.$middlename.' '.$generation;
9149: }
9150: }
9151: $name=~s/^\s+//;
9152: $name=~s/\s+$//;
9153: $name=~s/\s+/ /g;
9154: return $name;
9155: }
9156:
1.84 www 9157: # ------------------------------------------------- Write to course preferences
9158:
9159: sub writecoursepref {
9160: my ($courseid,%prefs)=@_;
9161: $courseid=~s/^\///;
9162: $courseid=~s/\_/\//g;
9163: my ($cdomain,$cnum)=split(/\//,$courseid);
9164: my $chome=homeserver($cnum,$cdomain);
9165: if (($chome eq '') || ($chome eq 'no_host')) {
9166: return 'error: no such course';
9167: }
9168: my $cstring='';
1.800 albertel 9169: foreach my $pref (keys(%prefs)) {
9170: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 9171: }
1.84 www 9172: $cstring=~s/\&$//;
9173: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
9174: }
9175:
9176: # ---------------------------------------------------------- Make/modify course
9177:
9178: sub createcourse {
1.741 raeburn 9179: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 9180: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 9181: $url=&declutter($url);
9182: my $cid='';
1.1028 raeburn 9183: if ($context eq 'requestcourses') {
9184: my $can_create = 0;
9185: my ($ownername,$ownerdom) = split(':',$course_owner);
9186: if ($udom eq $ownerdom) {
9187: if (&usertools_access($ownername,$ownerdom,$category,undef,
9188: $context)) {
9189: $can_create = 1;
9190: }
9191: } else {
9192: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
9193: $category);
9194: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
9195: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
9196: if (@curr > 0) {
9197: my @options = qw(approval validate autolimit);
9198: my $optregex = join('|',@options);
9199: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
9200: $can_create = 1;
9201: }
9202: }
9203: }
9204: }
9205: if ($can_create) {
9206: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
9207: unless (&allowed('ccc',$udom)) {
9208: return 'refused';
9209: }
1.1017 raeburn 9210: }
9211: } else {
9212: return 'refused';
9213: }
1.1028 raeburn 9214: } elsif (!&allowed('ccc',$udom)) {
9215: return 'refused';
1.84 www 9216: }
1.1011 raeburn 9217: # --------------------------------------------------------------- Get Unique ID
9218: my $uname;
9219: if ($cnum =~ /^$match_courseid$/) {
9220: my $chome=&homeserver($cnum,$udom,'true');
9221: if (($chome eq '') || ($chome eq 'no_host')) {
9222: $uname = $cnum;
9223: } else {
1.1038 raeburn 9224: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 9225: }
9226: } else {
1.1038 raeburn 9227: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 9228: }
9229: return $uname if ($uname =~ /^error/);
9230: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 9231: if (!defined($course_server)) {
9232: if (defined(&domain($udom,'primary'))) {
9233: $course_server = &domain($udom,'primary');
9234: } else {
9235: $course_server = $env{'user.home'};
9236: }
9237: }
9238: my %host_servers =
9239: &Apache::lonnet::get_servers($udom,'library');
9240: unless ($host_servers{$course_server}) {
9241: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 9242: }
1.84 www 9243: # ------------------------------------------------------------- Make the course
9244: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 9245: $course_server);
1.84 www 9246: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 9247: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 9248: if (($uhome eq '') || ($uhome eq 'no_host')) {
9249: return 'error: no such course';
9250: }
1.271 www 9251: # ----------------------------------------------------------------- Course made
1.516 raeburn 9252: # log existence
1.1029 raeburn 9253: my $now = time;
1.918 raeburn 9254: my $newcourse = {
9255: $udom.'_'.$uname => {
1.921 raeburn 9256: description => $description,
9257: inst_code => $inst_code,
9258: owner => $course_owner,
9259: type => $crstype,
1.1029 raeburn 9260: creator => $env{'user.name'}.':'.
9261: $env{'user.domain'},
9262: created => $now,
9263: context => $context,
1.918 raeburn 9264: },
9265: };
1.921 raeburn 9266: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 9267: # set toplevel url
1.271 www 9268: my $topurl=$url;
9269: unless ($nonstandard) {
9270: # ------------------------------------------ For standard courses, make top url
9271: my $mapurl=&clutter($url);
1.278 www 9272: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 9273: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 9274: <map>
9275: <resource id="1" type="start"></resource>
9276: <resource id="2" src="$mapurl"></resource>
9277: <resource id="3" type="finish"></resource>
9278: <link index="1" from="1" to="2"></link>
9279: <link index="2" from="2" to="3"></link>
9280: </map>
9281: ENDINITMAP
9282: $topurl=&declutter(
1.638 albertel 9283: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 9284: );
9285: }
9286: # ----------------------------------------------------------- Write preferences
1.84 www 9287: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 9288: ('description' => $description,
9289: 'url' => $topurl,
9290: 'internal.creator' => $env{'user.name'}.':'.
9291: $env{'user.domain'},
9292: 'internal.created' => $now,
9293: 'internal.creationcontext' => $context)
9294: );
1.84 www 9295: return '/'.$udom.'/'.$uname;
9296: }
9297:
1.1011 raeburn 9298: # ------------------------------------------------------------------- Create ID
9299: sub generate_coursenum {
1.1038 raeburn 9300: my ($udom,$crstype) = @_;
1.1011 raeburn 9301: my $domdesc = &domain($udom);
9302: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 9303: my $first;
9304: if ($crstype eq 'Community') {
9305: $first = '0';
9306: } else {
9307: $first = int(1+rand(9));
9308: }
9309: my $uname=$first.
1.1011 raeburn 9310: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
9311: substr($$.time,0,5).unpack("H8",pack("I32",time)).
9312: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
9313: # ----------------------------------------------- Make sure that does not exist
9314: my $uhome=&homeserver($uname,$udom,'true');
9315: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 9316: if ($crstype eq 'Community') {
9317: $first = '0';
9318: } else {
9319: $first = int(1+rand(9));
9320: }
9321: $uname=$first.
1.1011 raeburn 9322: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
9323: substr($$.time,0,5).unpack("H8",pack("I32",time)).
9324: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
9325: $uhome=&homeserver($uname,$udom,'true');
9326: unless (($uhome eq '') || ($uhome eq 'no_host')) {
9327: return 'error: unable to generate unique course-ID';
9328: }
9329: }
9330: return $uname;
9331: }
9332:
1.813 albertel 9333: sub is_course {
1.1167 droeschl 9334: my ($cdom, $cnum) = scalar(@_) == 1 ?
9335: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
9336:
9337: return unless $cdom and $cnum;
9338:
9339: my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
9340: '.');
9341:
1.1219 raeburn 9342: return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167 droeschl 9343: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813 albertel 9344: }
9345:
1.1015 raeburn 9346: sub store_userdata {
9347: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 9348: my $result;
1.1016 raeburn 9349: if ($datakey ne '') {
1.1013 raeburn 9350: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 9351: if ($udom eq '' || $uname eq '') {
9352: $udom = $env{'user.domain'};
9353: $uname = $env{'user.name'};
9354: }
9355: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 9356: if (($uhome eq '') || ($uhome eq 'no_host')) {
9357: $result = 'error: no_host';
9358: } else {
9359: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
9360: $storehash->{'host'} = $perlvar{'lonHostID'};
9361:
9362: my $namevalue='';
9363: foreach my $key (keys(%{$storehash})) {
9364: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
9365: }
9366: $namevalue=~s/\&$//;
1.1224 raeburn 9367: unless ($namespace eq 'courserequests') {
9368: $datakey = &escape($datakey);
9369: }
1.1105 raeburn 9370: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
9371: $namevalue,$uhome);
1.1013 raeburn 9372: }
9373: } else {
9374: $result = 'error: data to store was not a hash reference';
9375: }
9376: } else {
9377: $result= 'error: invalid requestkey';
9378: }
9379: return $result;
9380: }
9381:
1.21 www 9382: # ---------------------------------------------------------- Assign Custom Role
9383:
9384: sub assigncustomrole {
1.957 raeburn 9385: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9386: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 9387: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 9388: }
9389:
9390: # ----------------------------------------------------------------- Revoke Role
9391:
9392: sub revokerole {
1.957 raeburn 9393: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9394: my $now=time;
1.965 raeburn 9395: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 9396: }
9397:
9398: # ---------------------------------------------------------- Revoke Custom Role
9399:
9400: sub revokecustomrole {
1.957 raeburn 9401: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9402: my $now=time;
1.357 www 9403: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 9404: $deleteflag,$selfenroll,$context);
1.17 www 9405: }
9406:
1.533 banghart 9407: # ------------------------------------------------------------ Disk usage
1.535 albertel 9408: sub diskusage {
1.955 raeburn 9409: my ($udom,$uname,$directorypath,$getpropath)=@_;
9410: $directorypath =~ s/\/$//;
9411: my $listing=&reply('du2:'.&escape($directorypath).':'
9412: .&escape($getpropath).':'.&escape($uname).':'
9413: .&escape($udom),homeserver($uname,$udom));
9414: if ($listing eq 'unknown_cmd') {
9415: if ($getpropath) {
9416: $directorypath = &propath($udom,$uname).'/'.$directorypath;
9417: }
9418: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
9419: }
1.514 albertel 9420: return $listing;
1.512 banghart 9421: }
9422:
1.566 banghart 9423: sub is_locked {
1.1096 raeburn 9424: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 9425: my @check;
9426: my $is_locked;
1.1093 raeburn 9427: push (@check,$file_name);
1.613 albertel 9428: my %locked = &get('file_permissions',\@check,
1.620 albertel 9429: $env{'user.domain'},$env{'user.name'});
1.615 albertel 9430: my ($tmp)=keys(%locked);
9431: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 9432:
1.566 banghart 9433: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 9434: $is_locked = 'false';
9435: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 9436: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 9437: $is_locked = 'true';
1.1096 raeburn 9438: if (ref($which) eq 'ARRAY') {
9439: push(@{$which},$entry);
9440: } else {
9441: last;
9442: }
1.745 raeburn 9443: }
9444: }
1.566 banghart 9445: } else {
9446: $is_locked = 'false';
9447: }
1.1093 raeburn 9448: return $is_locked;
1.566 banghart 9449: }
9450:
1.759 albertel 9451: sub declutter_portfile {
9452: my ($file) = @_;
1.833 albertel 9453: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 9454: return $file;
9455: }
9456:
1.559 banghart 9457: # ------------------------------------------------------------- Mark as Read Only
9458:
9459: sub mark_as_readonly {
9460: my ($domain,$user,$files,$what) = @_;
1.613 albertel 9461: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 9462: my ($tmp)=keys(%current_permissions);
9463: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 9464: foreach my $file (@{$files}) {
1.759 albertel 9465: $file = &declutter_portfile($file);
1.561 banghart 9466: push(@{$current_permissions{$file}},$what);
1.559 banghart 9467: }
1.613 albertel 9468: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 9469: return;
9470: }
9471:
1.572 banghart 9472: # ------------------------------------------------------------Save Selected Files
9473:
9474: sub save_selected_files {
9475: my ($user, $path, @files) = @_;
9476: my $filename = $user."savedfiles";
1.573 banghart 9477: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 9478: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 9479: foreach my $file (@files) {
1.620 albertel 9480: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 9481: }
9482: foreach my $file (@other_files) {
1.574 banghart 9483: print (OUT $file."\n");
1.572 banghart 9484: }
1.574 banghart 9485: close (OUT);
1.572 banghart 9486: return 'ok';
9487: }
9488:
1.574 banghart 9489: sub clear_selected_files {
9490: my ($user) = @_;
9491: my $filename = $user."savedfiles";
1.1117 foxr 9492: open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574 banghart 9493: print (OUT undef);
9494: close (OUT);
9495: return ("ok");
9496: }
9497:
1.572 banghart 9498: sub files_in_path {
9499: my ($user, $path) = @_;
9500: my $filename = $user."savedfiles";
9501: my %return_files;
1.1117 foxr 9502: open (IN, '<'.LONCAPA::tempdir().$filename);
1.573 banghart 9503: while (my $line_in = <IN>) {
1.574 banghart 9504: chomp ($line_in);
9505: my @paths_and_file = split (m!/!, $line_in);
9506: my $file_part = pop (@paths_and_file);
9507: my $path_part = join ('/', @paths_and_file);
1.573 banghart 9508: $path_part.='/';
9509: my $path_and_file = $path_part.$file_part;
9510: if ($path_part eq $path) {
9511: $return_files{$file_part}= 'selected';
9512: }
9513: }
1.574 banghart 9514: close (IN);
9515: return (\%return_files);
1.572 banghart 9516: }
9517:
9518: # called in portfolio select mode, to show files selected NOT in current directory
9519: sub files_not_in_path {
9520: my ($user, $path) = @_;
9521: my $filename = $user."savedfiles";
9522: my @return_files;
9523: my $path_part;
1.1117 foxr 9524: open(IN, '<'.LONCAPA::.$filename);
1.800 albertel 9525: while (my $line = <IN>) {
1.572 banghart 9526: #ok, I know it's clunky, but I want it to work
1.800 albertel 9527: my @paths_and_file = split(m|/|, $line);
9528: my $file_part = pop(@paths_and_file);
9529: chomp($file_part);
9530: my $path_part = join('/', @paths_and_file);
1.572 banghart 9531: $path_part .= '/';
9532: my $path_and_file = $path_part.$file_part;
9533: if ($path_part ne $path) {
1.800 albertel 9534: push(@return_files, ($path_and_file));
1.572 banghart 9535: }
9536: }
1.800 albertel 9537: close(OUT);
1.574 banghart 9538: return (@return_files);
1.572 banghart 9539: }
9540:
1.1273 raeburn 9541: #------------------------------Submitted/Handedback Portfolio Files Versioning
9542:
9543: sub portfiles_versioning {
9544: my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
9545: my $portfolio_root = '/userfiles/portfolio';
9546: return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
9547: foreach my $file (@{$portfiles}) {
9548: &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
9549: my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
9550: my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
9551: my $getpropath = 1;
9552: my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
9553: $stu_name,$getpropath);
9554: my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
9555: my $new_answer =
9556: &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
9557: if ($new_answer ne 'problem getting file') {
9558: push(@{$versioned_portfiles}, $directory.$new_answer);
9559: &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
9560: [$symb,$env{'request.course.id'},'graded']);
9561: }
9562: }
9563: }
9564:
9565: sub get_next_version {
9566: my ($answer_name, $answer_ext, $dir_list) = @_;
9567: my $version;
9568: if (ref($dir_list) eq 'ARRAY') {
9569: foreach my $row (@{$dir_list}) {
9570: my ($file) = split(/\&/,$row,2);
9571: my ($file_name,$file_version,$file_ext) =
9572: &file_name_version_ext($file);
9573: if (($file_name eq $answer_name) &&
9574: ($file_ext eq $answer_ext)) {
9575: # gets here if filename and extension match,
9576: # regardless of version
9577: if ($file_version ne '') {
9578: # a versioned file is found so save it for later
9579: if ($file_version > $version) {
9580: $version = $file_version;
9581: }
9582: }
9583: }
9584: }
9585: }
9586: $version ++;
9587: return($version);
9588: }
9589:
9590: sub version_selected_portfile {
9591: my ($domain,$stu_name,$directory,$file_name,$version) = @_;
9592: my ($answer_name,$answer_ver,$answer_ext) =
9593: &file_name_version_ext($file_name);
9594: my $new_answer;
9595: $env{'form.copy'} =
9596: &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
9597: if($env{'form.copy'} eq '-1') {
9598: $new_answer = 'problem getting file';
9599: } else {
9600: $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
9601: my $copy_result =
9602: &finishuserfileupload($stu_name,$domain,'copy',
9603: '/portfolio'.$directory.$new_answer);
9604: }
9605: undef($env{'form.copy'});
9606: return ($new_answer);
9607: }
9608:
9609: sub file_name_version_ext {
9610: my ($file)=@_;
9611: my @file_parts = split(/\./, $file);
9612: my ($name,$version,$ext);
9613: if (@file_parts > 1) {
9614: $ext=pop(@file_parts);
9615: if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
9616: $version=pop(@file_parts);
9617: }
9618: $name=join('.',@file_parts);
9619: } else {
9620: $name=join('.',@file_parts);
9621: }
9622: return($name,$version,$ext);
9623: }
9624:
1.745 raeburn 9625: #----------------------------------------------Get portfolio file permissions
1.629 banghart 9626:
1.745 raeburn 9627: sub get_portfile_permissions {
9628: my ($domain,$user) = @_;
1.613 albertel 9629: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 9630: my ($tmp)=keys(%current_permissions);
9631: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 9632: return \%current_permissions;
9633: }
9634:
9635: #---------------------------------------------Get portfolio file access controls
9636:
1.749 raeburn 9637: sub get_access_controls {
1.745 raeburn 9638: my ($current_permissions,$group,$file) = @_;
1.769 albertel 9639: my %access;
9640: my $real_file = $file;
9641: $file =~ s/\.meta$//;
1.745 raeburn 9642: if (defined($file)) {
1.749 raeburn 9643: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
9644: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 9645: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 9646: }
9647: }
1.745 raeburn 9648: } else {
1.749 raeburn 9649: foreach my $key (keys(%{$current_permissions})) {
9650: if ($key =~ /\0accesscontrol$/) {
9651: if (defined($group)) {
9652: if ($key !~ m-^\Q$group\E/-) {
9653: next;
9654: }
9655: }
9656: my ($fullpath) = split(/\0/,$key);
9657: if (ref($$current_permissions{$key}) eq 'HASH') {
9658: foreach my $control (keys(%{$$current_permissions{$key}})) {
9659: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
9660: }
9661: }
9662: }
9663: }
9664: }
9665: return %access;
9666: }
9667:
9668: sub modify_access_controls {
9669: my ($file_name,$changes,$domain,$user)=@_;
9670: my ($outcome,$deloutcome);
9671: my %store_permissions;
9672: my %new_values;
9673: my %new_control;
9674: my %translation;
9675: my @deletions = ();
9676: my $now = time;
9677: if (exists($$changes{'activate'})) {
9678: if (ref($$changes{'activate'}) eq 'HASH') {
9679: my @newitems = sort(keys(%{$$changes{'activate'}}));
9680: my $numnew = scalar(@newitems);
9681: for (my $i=0; $i<$numnew; $i++) {
9682: my $newkey = $newitems[$i];
9683: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 9684: if ($newkey =~ /^\d+:/) {
9685: $newkey =~ s/^(\d+)/$newid/;
9686: $translation{$1} = $newid;
9687: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
9688: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
9689: $translation{$1} = $newid;
9690: }
1.749 raeburn 9691: $new_values{$file_name."\0".$newkey} =
9692: $$changes{'activate'}{$newitems[$i]};
9693: $new_control{$newkey} = $now;
9694: }
9695: }
9696: }
9697: my %todelete;
9698: my %changed_items;
9699: foreach my $action ('delete','update') {
9700: if (exists($$changes{$action})) {
9701: if (ref($$changes{$action}) eq 'HASH') {
9702: foreach my $key (keys(%{$$changes{$action}})) {
9703: my ($itemnum) = ($key =~ /^([^:]+):/);
9704: if ($action eq 'delete') {
9705: $todelete{$itemnum} = 1;
9706: } else {
9707: $changed_items{$itemnum} = $key;
9708: }
9709: }
1.745 raeburn 9710: }
9711: }
1.749 raeburn 9712: }
9713: # get lock on access controls for file.
9714: my $lockhash = {
9715: $file_name."\0".'locked_access_records' => $env{'user.name'}.
9716: ':'.$env{'user.domain'},
9717: };
9718: my $tries = 0;
9719: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9720:
1.1288 damieng 9721: while (($gotlock ne 'ok') && $tries < 10) {
1.749 raeburn 9722: $tries ++;
1.1289 damieng 9723: sleep(0.1);
1.749 raeburn 9724: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9725: }
9726: if ($gotlock eq 'ok') {
9727: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
9728: my ($tmp)=keys(%curr_permissions);
9729: if ($tmp=~/^error:/) { undef(%curr_permissions); }
9730: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
9731: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
9732: if (ref($curr_controls) eq 'HASH') {
9733: foreach my $control_item (keys(%{$curr_controls})) {
9734: my ($itemnum) = ($control_item =~ /^([^:]+):/);
9735: if (defined($todelete{$itemnum})) {
9736: push(@deletions,$file_name."\0".$control_item);
9737: } else {
9738: if (defined($changed_items{$itemnum})) {
9739: $new_control{$changed_items{$itemnum}} = $now;
9740: push(@deletions,$file_name."\0".$control_item);
9741: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
9742: } else {
9743: $new_control{$control_item} = $$curr_controls{$control_item};
9744: }
9745: }
1.745 raeburn 9746: }
9747: }
9748: }
1.970 raeburn 9749: my ($group);
9750: if (&is_course($domain,$user)) {
9751: ($group,my $file) = split(/\//,$file_name,2);
9752: }
1.749 raeburn 9753: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
9754: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
9755: $outcome = &put('file_permissions',\%new_values,$domain,$user);
9756: # remove lock
9757: my @del_lock = ($file_name."\0".'locked_access_records');
9758: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 9759: my $sqlresult =
1.970 raeburn 9760: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 9761: $group);
1.749 raeburn 9762: } else {
9763: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 9764: }
1.749 raeburn 9765: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 9766: }
9767:
1.827 raeburn 9768: sub make_public_indefinitely {
1.1271 raeburn 9769: my (@requrl) = @_;
9770: return &automated_portfile_access('public',\@requrl);
9771: }
9772:
9773: sub automated_portfile_access {
9774: my ($accesstype,$addsref,$delsref,$info) = @_;
1.1273 raeburn 9775: unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
9776: return 'invalid';
9777: }
1.1271 raeburn 9778: my %urls;
9779: if (ref($addsref) eq 'ARRAY') {
9780: foreach my $requrl (@{$addsref}) {
9781: if (&is_portfolio_url($requrl)) {
9782: unless (exists($urls{$requrl})) {
9783: $urls{$requrl} = 'add';
9784: }
9785: }
9786: }
9787: }
9788: if (ref($delsref) eq 'ARRAY') {
9789: foreach my $requrl (@{$delsref}) {
9790: if (&is_portfolio_url($requrl)) {
9791: unless (exists($urls{$requrl})) {
9792: $urls{$requrl} = 'delete';
9793: }
9794: }
9795: }
9796: }
9797: unless (keys(%urls)) {
9798: return 'invalid';
9799: }
9800: my $ip;
9801: if ($accesstype eq 'ip') {
9802: if (ref($info) eq 'HASH') {
9803: if ($info->{'ip'} ne '') {
9804: $ip = $info->{'ip'};
9805: }
9806: }
9807: if ($ip eq '') {
9808: return 'invalid';
9809: }
9810: }
9811: my $errors;
1.827 raeburn 9812: my $now = time;
1.1271 raeburn 9813: my %current_perms;
9814: foreach my $requrl (sort(keys(%urls))) {
9815: my $action;
9816: if ($urls{$requrl} eq 'add') {
9817: $action = 'activate';
9818: } else {
9819: $action = 'none';
9820: }
9821: my $aclnum = 0;
1.827 raeburn 9822: my (undef,$udom,$unum,$file_name,$group) =
9823: &parse_portfolio_url($requrl);
1.1271 raeburn 9824: unless (exists($current_perms{$unum.':'.$udom})) {
9825: $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
9826: }
9827: my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
1.827 raeburn 9828: $group,$file_name);
9829: foreach my $key (keys(%{$access_controls{$file_name}})) {
9830: my ($num,$scope,$end,$start) =
9831: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
1.1271 raeburn 9832: if ($scope eq $accesstype) {
9833: if (($start <= $now) && ($end == 0)) {
9834: if ($accesstype eq 'ip') {
9835: if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
9836: if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
9837: if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
9838: if ($urls{$requrl} eq 'add') {
9839: $action = 'none';
9840: last;
9841: } else {
9842: $action = 'delete';
9843: $aclnum = $num;
9844: last;
9845: }
9846: }
9847: }
9848: }
9849: } elsif ($accesstype eq 'public') {
9850: if ($urls{$requrl} eq 'add') {
9851: $action = 'none';
9852: last;
9853: } else {
9854: $action = 'delete';
9855: $aclnum = $num;
9856: last;
9857: }
9858: }
9859: } elsif ($accesstype eq 'public') {
1.827 raeburn 9860: $action = 'update';
9861: $aclnum = $num;
1.1271 raeburn 9862: last;
1.827 raeburn 9863: }
9864: }
9865: }
9866: if ($action eq 'none') {
1.1271 raeburn 9867: next;
1.827 raeburn 9868: } else {
9869: my %changes;
9870: my $newend = 0;
9871: my $newstart = $now;
1.1271 raeburn 9872: my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
1.827 raeburn 9873: $changes{$action}{$newkey} = {
1.1271 raeburn 9874: type => $accesstype,
1.827 raeburn 9875: time => {
9876: start => $newstart,
9877: end => $newend,
9878: },
9879: };
1.1271 raeburn 9880: if ($accesstype eq 'ip') {
9881: $changes{$action}{$newkey}{'ip'} = [$ip];
9882: }
1.827 raeburn 9883: my ($outcome,$deloutcome,$new_values,$translation) =
9884: &modify_access_controls($file_name,\%changes,$udom,$unum);
1.1271 raeburn 9885: unless ($outcome eq 'ok') {
9886: $errors .= $outcome.' ';
9887: }
1.827 raeburn 9888: }
1.1271 raeburn 9889: }
9890: if ($errors) {
9891: $errors =~ s/\s$//;
9892: return $errors;
1.827 raeburn 9893: } else {
1.1271 raeburn 9894: return 'ok';
1.827 raeburn 9895: }
9896: }
9897:
1.745 raeburn 9898: #------------------------------------------------------Get Marked as Read Only
9899:
9900: sub get_marked_as_readonly {
9901: my ($domain,$user,$what,$group) = @_;
9902: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 9903: my @readonly_files;
1.629 banghart 9904: my $cmp1=$what;
9905: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 9906: while (my ($file_name,$value) = each(%{$current_permissions})) {
9907: if (defined($group)) {
9908: if ($file_name !~ m-^\Q$group\E/-) {
9909: next;
9910: }
9911: }
1.561 banghart 9912: if (ref($value) eq "ARRAY"){
9913: foreach my $stored_what (@{$value}) {
1.629 banghart 9914: my $cmp2=$stored_what;
1.759 albertel 9915: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 9916: $cmp2=join('',@{$stored_what});
1.745 raeburn 9917: }
1.629 banghart 9918: if ($cmp1 eq $cmp2) {
1.561 banghart 9919: push(@readonly_files, $file_name);
1.745 raeburn 9920: last;
1.563 banghart 9921: } elsif (!defined($what)) {
9922: push(@readonly_files, $file_name);
1.745 raeburn 9923: last;
1.561 banghart 9924: }
9925: }
1.745 raeburn 9926: }
1.561 banghart 9927: }
9928: return @readonly_files;
9929: }
1.577 banghart 9930: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 9931:
1.577 banghart 9932: sub get_marked_as_readonly_hash {
1.745 raeburn 9933: my ($current_permissions,$group,$what) = @_;
1.577 banghart 9934: my %readonly_files;
1.745 raeburn 9935: while (my ($file_name,$value) = each(%{$current_permissions})) {
9936: if (defined($group)) {
9937: if ($file_name !~ m-^\Q$group\E/-) {
9938: next;
9939: }
9940: }
1.577 banghart 9941: if (ref($value) eq "ARRAY"){
9942: foreach my $stored_what (@{$value}) {
1.745 raeburn 9943: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 9944: foreach my $lock_descriptor(@{$stored_what}) {
9945: if ($lock_descriptor eq 'graded') {
9946: $readonly_files{$file_name} = 'graded';
9947: } elsif ($lock_descriptor eq 'handback') {
9948: $readonly_files{$file_name} = 'handback';
9949: } else {
9950: if (!exists($readonly_files{$file_name})) {
9951: $readonly_files{$file_name} = 'locked';
9952: }
9953: }
1.745 raeburn 9954: }
1.750 banghart 9955: }
1.577 banghart 9956: }
9957: }
9958: }
9959: return %readonly_files;
9960: }
1.559 banghart 9961: # ------------------------------------------------------------ Unmark as Read Only
9962:
9963: sub unmark_as_readonly {
1.629 banghart 9964: # unmarks $file_name (if $file_name is defined), or all files locked by $what
9965: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 9966: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 9967: $file_name = &declutter_portfile($file_name);
1.634 albertel 9968: my $symb_crs = $what;
9969: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 9970: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 9971: my ($tmp)=keys(%current_permissions);
9972: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 9973: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 9974: foreach my $file (@readonly_files) {
1.759 albertel 9975: my $clean_file = &declutter_portfile($file);
9976: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 9977: my $current_locks = $current_permissions{$file};
1.563 banghart 9978: my @new_locks;
9979: my @del_keys;
9980: if (ref($current_locks) eq "ARRAY"){
9981: foreach my $locker (@{$current_locks}) {
1.632 albertel 9982: my $compare=$locker;
1.749 raeburn 9983: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 9984: $compare=join('',@{$locker});
1.746 raeburn 9985: if ($compare ne $symb_crs) {
9986: push(@new_locks, $locker);
9987: }
1.563 banghart 9988: }
9989: }
1.650 albertel 9990: if (scalar(@new_locks) > 0) {
1.563 banghart 9991: $current_permissions{$file} = \@new_locks;
9992: } else {
9993: push(@del_keys, $file);
1.613 albertel 9994: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 9995: delete($current_permissions{$file});
1.563 banghart 9996: }
9997: }
1.561 banghart 9998: }
1.613 albertel 9999: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 10000: return;
10001: }
1.512 banghart 10002:
1.17 www 10003: # ------------------------------------------------------------ Directory lister
10004:
10005: sub dirlist {
1.955 raeburn 10006: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 10007: $uri=~s/^\///;
10008: $uri=~s/\/$//;
1.253 stredwic 10009: my ($udom, $uname);
1.955 raeburn 10010: if ($getuserdir) {
1.253 stredwic 10011: $udom = $userdomain;
10012: $uname = $username;
1.955 raeburn 10013: } else {
10014: (undef,$udom,$uname)=split(/\//,$uri);
10015: if(defined($userdomain)) {
10016: $udom = $userdomain;
10017: }
10018: if(defined($username)) {
10019: $uname = $username;
10020: }
1.253 stredwic 10021: }
1.955 raeburn 10022: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 10023:
1.955 raeburn 10024: $dirRoot = $perlvar{'lonDocRoot'};
10025: if (defined($getpropath)) {
10026: $dirRoot = &propath($udom,$uname);
1.253 stredwic 10027: $dirRoot =~ s/\/$//;
1.955 raeburn 10028: } elsif (defined($getuserdir)) {
10029: my $subdir=$uname.'__';
10030: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
10031: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
10032: ."/$udom/$subdir/$uname";
10033: } elsif (defined($alternateRoot)) {
10034: $dirRoot = $alternateRoot;
1.751 banghart 10035: }
1.253 stredwic 10036:
10037: if($udom) {
10038: if($uname) {
1.1135 raeburn 10039: my $uhome = &homeserver($uname,$udom);
1.1136 raeburn 10040: if ($uhome eq 'no_host') {
10041: return ([],'no_host');
10042: }
1.955 raeburn 10043: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 10044: .$getuserdir.':'.&escape($dirRoot)
1.1135 raeburn 10045: .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955 raeburn 10046: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 10047: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955 raeburn 10048: } else {
10049: @listing_results = map { &unescape($_); } split(/:/,$listing);
10050: }
1.605 matthew 10051: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 10052: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605 matthew 10053: @listing_results = split(/:/,$listing);
10054: } else {
10055: @listing_results = map { &unescape($_); } split(/:/,$listing);
10056: }
1.1135 raeburn 10057: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
1.1136 raeburn 10058: ($listing eq 'rejected') || ($listing eq 'refused') ||
10059: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
10060: return ([],$listing);
10061: } else {
10062: return (\@listing_results);
1.1135 raeburn 10063: }
1.955 raeburn 10064: } elsif(!$alternateRoot) {
1.1136 raeburn 10065: my (%allusers,%listerror);
1.841 albertel 10066: my %servers = &get_servers($udom,'library');
1.955 raeburn 10067: foreach my $tryserver (keys(%servers)) {
10068: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
10069: &escape($udom),$tryserver);
10070: if ($listing eq 'unknown_cmd') {
10071: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
10072: $udom, $tryserver);
10073: } else {
10074: @listing_results = map { &unescape($_); } split(/:/,$listing);
10075: }
1.841 albertel 10076: if ($listing eq 'unknown_cmd') {
10077: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
10078: $udom, $tryserver);
10079: @listing_results = split(/:/,$listing);
10080: } else {
10081: @listing_results =
10082: map { &unescape($_); } split(/:/,$listing);
10083: }
1.1136 raeburn 10084: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
10085: ($listing eq 'rejected') || ($listing eq 'refused') ||
10086: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
10087: $listerror{$tryserver} = $listing;
10088: } else {
1.841 albertel 10089: foreach my $line (@listing_results) {
10090: my ($entry) = split(/&/,$line,2);
10091: $allusers{$entry} = 1;
10092: }
10093: }
1.253 stredwic 10094: }
1.1136 raeburn 10095: my @alluserslist=();
1.800 albertel 10096: foreach my $user (sort(keys(%allusers))) {
1.1136 raeburn 10097: push(@alluserslist,$user.'&user');
1.253 stredwic 10098: }
1.1136 raeburn 10099: return (\@alluserslist);
1.253 stredwic 10100: } else {
1.1136 raeburn 10101: return ([],'missing username');
1.253 stredwic 10102: }
1.955 raeburn 10103: } elsif(!defined($getpropath)) {
1.1136 raeburn 10104: my $path = $perlvar{'lonDocRoot'}.'/res/';
10105: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
10106: return (\@all_domains);
1.955 raeburn 10107: } else {
1.1136 raeburn 10108: return ([],'missing domain');
1.275 stredwic 10109: }
10110: }
10111:
10112: # --------------------------------------------- GetFileTimestamp
10113: # This function utilizes dirlist and returns the date stamp for
10114: # when it was last modified. It will also return an error of -1
10115: # if an error occurs
10116:
10117: sub GetFileTimestamp {
1.955 raeburn 10118: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 10119: $studentDomain = &LONCAPA::clean_domain($studentDomain);
10120: $studentName = &LONCAPA::clean_username($studentName);
1.1136 raeburn 10121: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
10122: undef,$getuserdir);
10123: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
10124: return -1;
10125: }
10126: if (ref($fileref) eq 'ARRAY') {
10127: my @stats = split('&',$fileref->[0]);
1.375 matthew 10128: # @stats contains first the filename, then the stat output
10129: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 10130: } else {
10131: return -1;
1.253 stredwic 10132: }
1.26 www 10133: }
10134:
1.712 albertel 10135: sub stat_file {
10136: my ($uri) = @_;
1.787 albertel 10137: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 10138:
1.955 raeburn 10139: my ($udom,$uname,$file);
1.712 albertel 10140: if ($uri =~ m-^/(uploaded|editupload)/-) {
10141: ($udom,$uname,$file) =
1.811 albertel 10142: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 10143: $file = 'userfiles/'.$file;
10144: }
10145: if ($uri =~ m-^/res/-) {
10146: ($udom,$uname) =
1.807 albertel 10147: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 10148: $file = $uri;
10149: }
10150:
10151: if (!$udom || !$uname || !$file) {
10152: # unable to handle the uri
10153: return ();
10154: }
1.956 raeburn 10155: my $getpropath;
10156: if ($file =~ /^userfiles\//) {
10157: $getpropath = 1;
10158: }
1.1136 raeburn 10159: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
10160: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
10161: return ();
10162: } else {
10163: if (ref($listref) eq 'ARRAY') {
10164: my @stats = split('&',$listref->[0]);
10165: shift(@stats); #filename is first
10166: return @stats;
10167: }
1.712 albertel 10168: }
10169: return ();
10170: }
10171:
1.26 www 10172: # -------------------------------------------------------- Value of a Condition
10173:
1.713 albertel 10174: # gets the value of a specific preevaluated condition
10175: # stored in the string $env{user.state.<cid>}
10176: # or looks up a condition reference in the bighash and if if hasn't
10177: # already been evaluated recurses into docondval to get the value of
10178: # the condition, then memoizing it to
10179: # $env{user.state.<cid>.<condition>}
1.40 www 10180: sub directcondval {
10181: my $number=shift;
1.620 albertel 10182: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 10183: &Apache::lonuserstate::evalstate();
10184: }
1.713 albertel 10185: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
10186: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
10187: } elsif ($number =~ /^_/) {
10188: my $sub_condition;
10189: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10190: &GDBM_READER(),0640)) {
10191: $sub_condition=$bighash{'conditions'.$number};
10192: untie(%bighash);
10193: }
10194: my $value = &docondval($sub_condition);
1.949 raeburn 10195: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 10196: return $value;
10197: }
1.620 albertel 10198: if ($env{'user.state.'.$env{'request.course.id'}}) {
10199: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 10200: } else {
10201: return 2;
10202: }
10203: }
10204:
1.713 albertel 10205: # get the collection of conditions for this resource
1.26 www 10206: sub condval {
10207: my $condidx=shift;
1.54 www 10208: my $allpathcond='';
1.713 albertel 10209: foreach my $cond (split(/\|/,$condidx)) {
10210: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
10211: $allpathcond.=
10212: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
10213: }
1.191 harris41 10214: }
1.54 www 10215: $allpathcond=~s/\|$//;
1.713 albertel 10216: return &docondval($allpathcond);
10217: }
10218:
10219: #evaluates an expression of conditions
10220: sub docondval {
10221: my ($allpathcond) = @_;
10222: my $result=0;
10223: if ($env{'request.course.id'}
10224: && defined($allpathcond)) {
10225: my $operand='|';
10226: my @stack;
10227: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
10228: if ($chunk eq '(') {
10229: push @stack,($operand,$result);
10230: } elsif ($chunk eq ')') {
10231: my $before=pop @stack;
10232: if (pop @stack eq '&') {
10233: $result=$result>$before?$before:$result;
10234: } else {
10235: $result=$result>$before?$result:$before;
10236: }
10237: } elsif (($chunk eq '&') || ($chunk eq '|')) {
10238: $operand=$chunk;
10239: } else {
10240: my $new=directcondval($chunk);
10241: if ($operand eq '&') {
10242: $result=$result>$new?$new:$result;
10243: } else {
10244: $result=$result>$new?$result:$new;
10245: }
10246: }
10247: }
1.26 www 10248: }
10249: return $result;
1.421 albertel 10250: }
10251:
10252: # ---------------------------------------------------- Devalidate courseresdata
10253:
10254: sub devalidatecourseresdata {
10255: my ($coursenum,$coursedomain)=@_;
10256: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 10257: &devalidate_cache_new('courseres',$hashid);
1.28 www 10258: }
10259:
1.763 www 10260:
1.200 www 10261: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 10262: #
10263: # Parameters:
10264: # $coursenum - Number of the course.
10265: # $coursedomain - Domain at which the course was created.
10266: # Returns:
10267: # A hash of the course parameters along (I think) with timestamps
10268: # and version info.
1.877 foxr 10269:
1.624 albertel 10270: sub get_courseresdata {
10271: my ($coursenum,$coursedomain)=@_;
1.200 www 10272: my $coursehom=&homeserver($coursenum,$coursedomain);
10273: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 10274: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 10275: my %dumpreply;
1.417 albertel 10276: unless (defined($cached)) {
1.624 albertel 10277: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 10278: $result=\%dumpreply;
1.251 albertel 10279: my ($tmp) = keys(%dumpreply);
10280: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 10281: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 10282: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
10283: return $tmp;
1.416 albertel 10284: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 10285: $result=undef;
1.599 albertel 10286: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 10287: }
10288: }
1.624 albertel 10289: return $result;
10290: }
10291:
1.633 albertel 10292: sub devalidateuserresdata {
10293: my ($uname,$udom)=@_;
10294: my $hashid="$udom:$uname";
10295: &devalidate_cache_new('userres',$hashid);
10296: }
10297:
1.624 albertel 10298: sub get_userresdata {
10299: my ($uname,$udom)=@_;
10300: #most student don\'t have any data set, check if there is some data
10301: if (&EXT_cache_status($udom,$uname)) { return undef; }
10302:
10303: my $hashid="$udom:$uname";
10304: my ($result,$cached)=&is_cached_new('userres',$hashid);
10305: if (!defined($cached)) {
10306: my %resourcedata=&dump('resourcedata',$udom,$uname);
10307: $result=\%resourcedata;
10308: &do_cache_new('userres',$hashid,$result,600);
10309: }
10310: my ($tmp)=keys(%$result);
10311: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
10312: return $result;
10313: }
10314: #error 2 occurs when the .db doesn't exist
10315: if ($tmp!~/error: 2 /) {
1.1294 raeburn 10316: if ((!defined($cached)) || ($tmp ne 'con_lost')) {
10317: &logthis("<font color=\"blue\">WARNING:".
10318: " Trying to get resource data for ".
10319: $uname." at ".$udom.": ".
10320: $tmp."</font>");
10321: }
1.624 albertel 10322: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 10323: #&EXT_cache_set($udom,$uname);
10324: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 10325: undef($tmp); # not really an error so don't send it back
1.624 albertel 10326: }
10327: return $tmp;
10328: }
1.879 foxr 10329: #----------------------------------------------- resdata - return resource data
10330: # Purpose:
10331: # Return resource data for either users or for a course.
10332: # Parameters:
10333: # $name - Course/user name.
10334: # $domain - Name of the domain the user/course is registered on.
10335: # $type - Type of thing $name is (must be 'course' or 'user'
1.1301 raeburn 10336: # $mapp - decluttered URL of enclosing map
10337: # $recursed - Ref to scalar -- set to 1, if nested maps have been recursed.
10338: # $recurseup - Ref to array of map URLs, starting with map containing
10339: # $mapp up through hierarchy of nested maps to top level map.
10340: # $courseid - CourseID (first part of param identifier).
10341: # $modifier - Middle part of param identifier.
10342: # $what - Last part of param identifier.
1.879 foxr 10343: # @which - Array of names of resources desired.
10344: # Returns:
10345: # The value of the first reasource in @which that is found in the
10346: # resource hash.
10347: # Exceptional Conditions:
10348: # If the $type passed in is not valid (not the string 'course' or
10349: # 'user', an undefined reference is returned.
10350: # If none of the resources are found, an undef is returned
1.624 albertel 10351: sub resdata {
1.1301 raeburn 10352: my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
10353: $modifier,$what,@which)=@_;
1.624 albertel 10354: my $result;
10355: if ($type eq 'course') {
10356: $result=&get_courseresdata($name,$domain);
10357: } elsif ($type eq 'user') {
10358: $result=&get_userresdata($name,$domain);
10359: }
10360: if (!ref($result)) { return $result; }
1.251 albertel 10361: foreach my $item (@which) {
1.1301 raeburn 10362: if ($item->[1] eq 'course') {
10363: if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
10364: unless ($$recursed) {
1.1302 raeburn 10365: @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
1.1301 raeburn 10366: $$recursed = 1;
10367: }
10368: foreach my $item (@${recurseup}) {
10369: my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
10370: last if (defined($result->{$norecursechk}));
10371: my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
10372: if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
10373: }
10374: }
10375: }
10376: if (defined($result->{$item->[0]})) {
1.927 albertel 10377: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 10378: }
1.250 albertel 10379: }
1.291 albertel 10380: return undef;
1.200 www 10381: }
10382:
1.1298 raeburn 10383: sub get_domain_ltitools {
10384: my ($cdom) = @_;
10385: my %ltitools;
10386: my ($result,$cached)=&is_cached_new('ltitools',$cdom);
10387: if (defined($cached)) {
10388: if (ref($result) eq 'HASH') {
10389: %ltitools = %{$result};
10390: }
10391: } else {
10392: my %domconfig = &get_dom('configuration',['ltitools'],$cdom);
10393: if (ref($domconfig{'ltitools'}) eq 'HASH') {
10394: %ltitools = %{$domconfig{'ltitools'}};
10395: }
10396: my $cachetime = 24*60*60;
10397: &do_cache_new('ltitools',$cdom,\%ltitools,$cachetime);
10398: }
10399: return %ltitools;
10400: }
10401:
1.1236 raeburn 10402: sub get_numsuppfiles {
10403: my ($cnum,$cdom,$ignorecache)=@_;
10404: my $hashid=$cnum.':'.$cdom;
10405: my ($suppcount,$cached);
10406: unless ($ignorecache) {
10407: ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
10408: }
10409: unless (defined($cached)) {
10410: my $chome=&homeserver($cnum,$cdom);
10411: unless ($chome eq 'no_host') {
10412: ($suppcount,my $errors) = (0,0);
10413: my $suppmap = 'supplemental.sequence';
10414: ($suppcount,$errors) =
10415: &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
10416: }
10417: &do_cache_new('suppcount',$hashid,$suppcount,600);
10418: }
10419: return $suppcount;
10420: }
10421:
1.379 matthew 10422: #
10423: # EXT resource caching routines
10424: #
10425:
1.1302 raeburn 10426: {
10427: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
10428: #
10429: # The course for which we cache
10430: my $cachedmapkey='';
10431: # The cached recursive maps for this course
10432: my %cachedmaps=();
10433: # When this was last done
10434: my $cachedmaptime='';
10435:
1.379 matthew 10436: sub clear_EXT_cache_status {
1.383 albertel 10437: &delenv('cache.EXT.');
1.379 matthew 10438: }
10439:
10440: sub EXT_cache_status {
10441: my ($target_domain,$target_user) = @_;
1.383 albertel 10442: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 10443: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 10444: # We know already the user has no data
10445: return 1;
10446: } else {
10447: return 0;
10448: }
10449: }
10450:
10451: sub EXT_cache_set {
10452: my ($target_domain,$target_user) = @_;
1.383 albertel 10453: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 10454: #&appenv({$cachename => time});
1.379 matthew 10455: }
10456:
1.28 www 10457: # --------------------------------------------------------- Value of a Variable
1.58 www 10458: sub EXT {
1.715 albertel 10459:
1.1228 raeburn 10460: my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68 www 10461: unless ($varname) { return ''; }
1.218 albertel 10462: #get real user name/domain, courseid and symb
10463: my $courseid;
1.359 albertel 10464: my $publicuser;
1.427 www 10465: if ($symbparm) {
10466: $symbparm=&get_symb_from_alias($symbparm);
10467: }
1.218 albertel 10468: if (!($uname && $udom)) {
1.790 albertel 10469: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 10470: if (!$symbparm) { $symbparm=$cursymb; }
10471: } else {
1.620 albertel 10472: $courseid=$env{'request.course.id'};
1.218 albertel 10473: }
1.48 www 10474: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
10475: my $rest;
1.320 albertel 10476: if (defined($therest[0])) {
1.48 www 10477: $rest=join('.',@therest);
10478: } else {
10479: $rest='';
10480: }
1.320 albertel 10481:
1.57 www 10482: my $qualifierrest=$qualifier;
10483: if ($rest) { $qualifierrest.='.'.$rest; }
10484: my $spacequalifierrest=$space;
10485: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 10486: if ($realm eq 'user') {
1.48 www 10487: # --------------------------------------------------------------- user.resource
10488: if ($space eq 'resource') {
1.651 albertel 10489: if ( (defined($Apache::lonhomework::parsing_a_problem)
10490: || defined($Apache::lonhomework::parsing_a_task))
10491: &&
1.744 albertel 10492: ($symbparm eq &symbread()) ) {
10493: # if we are in the middle of processing the resource the
10494: # get the value we are planning on committing
10495: if (defined($Apache::lonhomework::results{$qualifierrest})) {
10496: return $Apache::lonhomework::results{$qualifierrest};
10497: } else {
10498: return $Apache::lonhomework::history{$qualifierrest};
10499: }
1.335 albertel 10500: } else {
1.359 albertel 10501: my %restored;
1.620 albertel 10502: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 10503: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
10504: } else {
10505: %restored=&restore($symbparm,$courseid,$udom,$uname);
10506: }
1.335 albertel 10507: return $restored{$qualifierrest};
10508: }
1.48 www 10509: # ----------------------------------------------------------------- user.access
10510: } elsif ($space eq 'access') {
1.218 albertel 10511: # FIXME - not supporting calls for a specific user
1.48 www 10512: return &allowed($qualifier,$rest);
10513: # ------------------------------------------ user.preferences, user.environment
10514: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 10515: if (($uname eq $env{'user.name'}) &&
10516: ($udom eq $env{'user.domain'})) {
10517: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 10518: } else {
1.359 albertel 10519: my %returnhash;
10520: if (!$publicuser) {
10521: %returnhash=&userenvironment($udom,$uname,
10522: $qualifierrest);
10523: }
1.218 albertel 10524: return $returnhash{$qualifierrest};
10525: }
1.48 www 10526: # ----------------------------------------------------------------- user.course
10527: } elsif ($space eq 'course') {
1.218 albertel 10528: # FIXME - not supporting calls for a specific user
1.620 albertel 10529: return $env{join('.',('request.course',$qualifier))};
1.48 www 10530: # ------------------------------------------------------------------- user.role
10531: } elsif ($space eq 'role') {
1.218 albertel 10532: # FIXME - not supporting calls for a specific user
1.620 albertel 10533: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 10534: if ($qualifier eq 'value') {
10535: return $role;
10536: } elsif ($qualifier eq 'extent') {
10537: return $where;
10538: }
10539: # ----------------------------------------------------------------- user.domain
10540: } elsif ($space eq 'domain') {
1.218 albertel 10541: return $udom;
1.48 www 10542: # ------------------------------------------------------------------- user.name
10543: } elsif ($space eq 'name') {
1.218 albertel 10544: return $uname;
1.48 www 10545: # ---------------------------------------------------- Any other user namespace
1.29 www 10546: } else {
1.359 albertel 10547: my %reply;
10548: if (!$publicuser) {
10549: %reply=&get($space,[$qualifierrest],$udom,$uname);
10550: }
10551: return $reply{$qualifierrest};
1.48 www 10552: }
1.236 www 10553: } elsif ($realm eq 'query') {
10554: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 10555: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
10556: [$spacequalifierrest]);
1.620 albertel 10557: return $env{'form.'.$spacequalifierrest};
1.236 www 10558: } elsif ($realm eq 'request') {
1.48 www 10559: # ------------------------------------------------------------- request.browser
10560: if ($space eq 'browser') {
1.1145 bisitz 10561: return $env{'browser.'.$qualifier};
1.57 www 10562: # ------------------------------------------------------------ request.filename
10563: } else {
1.620 albertel 10564: return $env{'request.'.$spacequalifierrest};
1.29 www 10565: }
1.28 www 10566: } elsif ($realm eq 'course') {
1.48 www 10567: # ---------------------------------------------------------- course.description
1.620 albertel 10568: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 10569: } elsif ($realm eq 'resource') {
1.165 www 10570:
1.620 albertel 10571: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 10572: if (!$symbparm) { $symbparm=&symbread(); }
10573: }
1.693 albertel 10574:
1.1232 raeburn 10575: if ($qualifier eq '') {
10576: if ($space eq 'title') {
10577: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
10578: return &gettitle($symbparm);
10579: }
1.693 albertel 10580:
1.1232 raeburn 10581: if ($space eq 'map') {
10582: my ($map) = &decode_symb($symbparm);
10583: return &symbread($map);
10584: }
10585: if ($space eq 'maptitle') {
10586: my ($map) = &decode_symb($symbparm);
10587: return &gettitle($map);
10588: }
10589: if ($space eq 'filename') {
10590: if ($symbparm) {
10591: return &clutter((&decode_symb($symbparm))[2]);
10592: }
10593: return &hreflocation('',$env{'request.filename'});
1.905 albertel 10594: }
1.1232 raeburn 10595:
1.1233 raeburn 10596: if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
10597: if ($space eq 'visibleparts') {
10598: my $navmap = Apache::lonnavmaps::navmap->new();
10599: my $item;
10600: if (ref($navmap)) {
10601: my $res = $navmap->getBySymb($symbparm);
10602: my $parts = $res->parts();
10603: if (ref($parts) eq 'ARRAY') {
10604: $item = join(',',@{$parts});
10605: }
10606: undef($navmap);
1.1232 raeburn 10607: }
1.1233 raeburn 10608: return $item;
1.1232 raeburn 10609: }
10610: }
10611: }
1.693 albertel 10612:
1.1301 raeburn 10613: my ($section, $group, @groups, @recurseup, $recursed);
10614: my ($courselevelm,$courseleveli,$courselevel,$mapp);
1.1228 raeburn 10615: if (($courseid eq '') && ($cid)) {
10616: $courseid = $cid;
10617: }
10618: if (($symbparm && $courseid) &&
10619: (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165 www 10620:
1.218 albertel 10621: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 10622:
1.60 www 10623: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 10624: my $symbp=$symbparm;
1.1301 raeburn 10625: $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 10626: my $symbparm=$symbp.'.'.$spacequalifierrest;
1.1301 raeburn 10627: my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
1.218 albertel 10628: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
1.620 albertel 10629: if (($env{'user.name'} eq $uname) &&
10630: ($env{'user.domain'} eq $udom)) {
10631: $section=$env{'request.course.sec'};
1.733 raeburn 10632: @groups = split(/:/,$env{'request.course.groups'});
10633: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 10634: } else {
1.539 albertel 10635: if (! defined($usection)) {
1.551 albertel 10636: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 10637: } else {
10638: $section = $usection;
10639: }
1.733 raeburn 10640: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 10641: }
10642:
10643: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
10644: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
1.1301 raeburn 10645: my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
1.218 albertel 10646: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
10647:
1.593 albertel 10648: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 10649: my $courselevelr=$courseid.'.'.$symbparm;
1.1301 raeburn 10650: $courseleveli=$courseid.'.'.$recurseparm;
1.593 albertel 10651: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 10652:
1.60 www 10653: # ----------------------------------------------------------- first, check user
1.624 albertel 10654:
1.1301 raeburn 10655: my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
10656: \@recurseup,$courseid,'.',$spacequalifierrest,
1.927 albertel 10657: ([$courselevelr,'resource'],
10658: [$courselevelm,'map' ],
1.1301 raeburn 10659: [$courseleveli,'map' ],
1.927 albertel 10660: [$courselevel, 'course' ]));
1.931 albertel 10661: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 10662:
1.594 albertel 10663: # ------------------------------------------------ second, check some of course
1.684 raeburn 10664: my $coursereply;
1.691 raeburn 10665: if (@groups > 0) {
10666: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
1.1301 raeburn 10667: $recurseparm,$mapparm,$spacequalifierrest,
10668: $mapp,\$recursed,\@recurseup);
10669: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 10670: }
1.96 www 10671:
1.684 raeburn 10672: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 10673: $env{'course.'.$courseid.'.domain'},
1.1301 raeburn 10674: 'course',$mapp,\$recursed,\@recurseup,
10675: $courseid,'.['.$section.'].',$spacequalifierrest,
1.927 albertel 10676: ([$seclevelr, 'resource'],
10677: [$seclevelm, 'map' ],
1.1301 raeburn 10678: [$secleveli, 'map' ],
1.927 albertel 10679: [$seclevel, 'course' ],
10680: [$courselevelr,'resource']));
10681: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 10682:
1.60 www 10683: # ------------------------------------------------------ third, check map parms
1.218 albertel 10684: my %parmhash=();
10685: my $thisparm='';
10686: if (tie(%parmhash,'GDBM_File',
1.620 albertel 10687: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 10688: &GDBM_READER(),0640)) {
1.218 albertel 10689: $thisparm=$parmhash{$symbparm};
10690: untie(%parmhash);
10691: }
1.927 albertel 10692: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 10693: }
1.594 albertel 10694: # ------------------------------------------ fourth, look in resource metadata
1.1301 raeburn 10695:
10696: my $what = $spacequalifierrest;
10697: $what=~s/\./\_/;
1.282 albertel 10698: my $filename;
10699: if (!$symbparm) { $symbparm=&symbread(); }
10700: if ($symbparm) {
1.409 www 10701: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 10702: } else {
1.620 albertel 10703: $filename=$env{'request.filename'};
1.282 albertel 10704: }
1.1301 raeburn 10705: my $metadata=&metadata($filename,$what);
1.927 albertel 10706: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.1301 raeburn 10707: $metadata=&metadata($filename,'parameter_'.$what);
1.927 albertel 10708: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 10709:
1.1301 raeburn 10710: # ----------------------------------------------- fifth, look in rest of course
1.593 albertel 10711: if ($symbparm && defined($courseid) &&
1.620 albertel 10712: $courseid eq $env{'request.course.id'}) {
1.624 albertel 10713: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
10714: $env{'course.'.$courseid.'.domain'},
1.1301 raeburn 10715: 'course',$mapp,\$recursed,\@recurseup,
10716: $courseid,'.',$spacequalifierrest,
1.927 albertel 10717: ([$courselevelm,'map' ],
1.1301 raeburn 10718: [$courseleveli,'map' ],
1.927 albertel 10719: [$courselevel, 'course']));
10720: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 10721: }
1.145 www 10722: # ------------------------------------------------------------------ Cascade up
1.218 albertel 10723: unless ($space eq '0') {
1.336 albertel 10724: my @parts=split(/_/,$space);
10725: my $id=pop(@parts);
10726: my $part=join('_',@parts);
10727: if ($part eq '') { $part='0'; }
1.927 albertel 10728: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 10729: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 10730: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 10731: }
1.395 albertel 10732: if ($recurse) { return undef; }
10733: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 10734: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 10735: # ---------------------------------------------------- Any other user namespace
10736: } elsif ($realm eq 'environment') {
10737: # ----------------------------------------------------------------- environment
1.620 albertel 10738: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
10739: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 10740: } else {
1.770 albertel 10741: if ($uname eq 'anonymous' && $udom eq '') {
10742: return '';
10743: }
1.219 albertel 10744: my %returnhash=&userenvironment($udom,$uname,
10745: $spacequalifierrest);
10746: return $returnhash{$spacequalifierrest};
10747: }
1.28 www 10748: } elsif ($realm eq 'system') {
1.48 www 10749: # ----------------------------------------------------------------- system.time
10750: if ($space eq 'time') {
10751: return time;
10752: }
1.696 albertel 10753: } elsif ($realm eq 'server') {
10754: # ----------------------------------------------------------------- system.time
10755: if ($space eq 'name') {
10756: return $ENV{'SERVER_NAME'};
10757: }
1.28 www 10758: }
1.48 www 10759: return '';
1.61 www 10760: }
10761:
1.927 albertel 10762: sub get_reply {
10763: my ($reply_value) = @_;
1.940 raeburn 10764: if (ref($reply_value) eq 'ARRAY') {
10765: if (wantarray) {
10766: return @$reply_value;
10767: }
10768: return $reply_value->[0];
10769: } else {
10770: return $reply_value;
1.927 albertel 10771: }
10772: }
10773:
1.691 raeburn 10774: sub check_group_parms {
1.1301 raeburn 10775: my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
10776: $recursed,$recurseupref) = @_;
10777: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
10778: [$what,'course']);
10779: my $coursereply;
1.691 raeburn 10780: foreach my $group (@{$groups}) {
1.1301 raeburn 10781: my @groupitems = ();
1.691 raeburn 10782: foreach my $level (@levels) {
1.927 albertel 10783: my $item = $courseid.'.['.$group.'].'.$level->[0];
10784: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 10785: }
1.1301 raeburn 10786: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
10787: $env{'course.'.$courseid.'.domain'},
10788: 'course',$mapp,$recursed,$recurseupref,
10789: $courseid,'.['.$group.'].',$what,
10790: @groupitems);
10791: last if (defined($coursereply));
1.691 raeburn 10792: }
10793: return $coursereply;
10794: }
10795:
1.1301 raeburn 10796: sub get_map_hierarchy {
1.1302 raeburn 10797: my ($mapname,$courseid) = @_;
10798: my @recurseup = ();
1.1301 raeburn 10799: if ($mapname) {
1.1302 raeburn 10800: if (($cachedmapkey eq $courseid) &&
10801: (abs($cachedmaptime-time)<5)) {
10802: if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
10803: return @{$cachedmaps{$mapname}};
10804: }
10805: }
1.1301 raeburn 10806: my $navmap = Apache::lonnavmaps::navmap->new();
10807: if (ref($navmap)) {
10808: @recurseup = $navmap->recurseup_maps($mapname);
10809: undef($navmap);
1.1302 raeburn 10810: $cachedmaps{$mapname} = \@recurseup;
10811: $cachedmaptime=time;
10812: $cachedmapkey=$courseid;
1.1301 raeburn 10813: }
10814: }
10815: return @recurseup;
10816: }
10817:
1.1302 raeburn 10818: }
10819:
1.691 raeburn 10820: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 10821: my ($courseid,@groups) = @_;
10822: @groups = sort(@groups);
1.691 raeburn 10823: return @groups;
10824: }
10825:
1.395 albertel 10826: sub packages_tab_default {
10827: my ($uri,$varname)=@_;
10828: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 10829:
10830: my (@extension,@specifics,$do_default);
10831: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 10832: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 10833: if ($pack_type eq 'default') {
10834: $do_default=1;
10835: } elsif ($pack_type eq 'extension') {
10836: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 10837: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 10838: # only look at packages defaults for packages that this id is
1.738 albertel 10839: push(@specifics,[$package,$pack_type,$pack_part]);
10840: }
10841: }
10842: # first look for a package that matches the requested part id
10843: foreach my $package (@specifics) {
10844: my (undef,$pack_type,$pack_part)=@{$package};
10845: next if ($pack_part ne $part);
10846: if (defined($packagetab{"$pack_type&$name&default"})) {
10847: return $packagetab{"$pack_type&$name&default"};
10848: }
10849: }
10850: # look for any possible matching non extension_ package
10851: foreach my $package (@specifics) {
10852: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 10853: if (defined($packagetab{"$pack_type&$name&default"})) {
10854: return $packagetab{"$pack_type&$name&default"};
10855: }
1.585 albertel 10856: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 10857: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
10858: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 10859: }
10860: }
1.738 albertel 10861: # look for any posible extension_ match
10862: foreach my $package (@extension) {
10863: my ($package,$pack_type)=@{$package};
10864: if (defined($packagetab{"$pack_type&$name&default"})) {
10865: return $packagetab{"$pack_type&$name&default"};
10866: }
10867: if (defined($packagetab{$package."&$name&default"})) {
10868: return $packagetab{$package."&$name&default"};
10869: }
10870: }
10871: # look for a global default setting
10872: if ($do_default && defined($packagetab{"default&$name&default"})) {
10873: return $packagetab{"default&$name&default"};
10874: }
1.395 albertel 10875: return undef;
10876: }
10877:
1.334 albertel 10878: sub add_prefix_and_part {
10879: my ($prefix,$part)=@_;
10880: my $keyroot;
10881: if (defined($prefix) && $prefix !~ /^__/) {
10882: # prefix that has a part already
10883: $keyroot=$prefix;
10884: } elsif (defined($prefix)) {
10885: # prefix that is missing a part
10886: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
10887: } else {
10888: # no prefix at all
10889: if (defined($part)) { $keyroot='_'.$part; }
10890: }
10891: return $keyroot;
10892: }
10893:
1.71 www 10894: # ---------------------------------------------------------------- Get metadata
10895:
1.599 albertel 10896: my %metaentry;
1.1070 www 10897: my %importedpartids;
1.71 www 10898: sub metadata {
1.176 www 10899: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 10900: $uri=&declutter($uri);
1.288 albertel 10901: # if it is a non metadata possible uri return quickly
1.529 albertel 10902: if (($uri eq '') ||
10903: (($uri =~ m|^/*adm/|) &&
1.1298 raeburn 10904: ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|exttools?)$})) ||
1.1108 raeburn 10905: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 10906: return undef;
10907: }
1.1261 raeburn 10908: if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv})
1.924 albertel 10909: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 10910: return undef;
1.288 albertel 10911: }
1.73 www 10912: my $filename=$uri;
10913: $uri=~s/\.meta$//;
1.172 www 10914: #
10915: # Is the metadata already cached?
1.177 www 10916: # Look at timestamp of caching
1.172 www 10917: # Everything is cached by the main uri, libraries are never directly cached
10918: #
1.428 albertel 10919: if (!defined($liburi)) {
1.599 albertel 10920: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 10921: if (defined($cached)) { return $result->{':'.$what}; }
10922: }
10923: {
1.1069 www 10924: # Imported parts would go here
1.1070 www 10925: my %importedids=();
10926: my @origfileimportpartids=();
1.1069 www 10927: my $importedparts=0;
1.172 www 10928: #
10929: # Is this a recursive call for a library?
10930: #
1.599 albertel 10931: # if (! exists($metacache{$uri})) {
10932: # $metacache{$uri}={};
10933: # }
1.924 albertel 10934: my $cachetime = 60*60;
1.171 www 10935: if ($liburi) {
10936: $liburi=&declutter($liburi);
10937: $filename=$liburi;
1.401 bowersj2 10938: } else {
1.599 albertel 10939: &devalidate_cache_new('meta',$uri);
10940: undef(%metaentry);
1.401 bowersj2 10941: }
1.140 www 10942: my %metathesekeys=();
1.73 www 10943: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 10944: my $metastring;
1.1140 www 10945: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929 albertel 10946: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 10947: $metastring =
1.929 albertel 10948: &Apache::lonnet::ssi_body($which,
1.924 albertel 10949: ('grade_target' => 'meta'));
10950: $cachetime = 1; # only want this cached in the child not long term
1.1108 raeburn 10951: } elsif (($uri !~ m -^(editupload)/-) &&
10952: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 10953: my $file=&filelocation('',&clutter($filename));
1.599 albertel 10954: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 10955: $metastring=&getfile($file);
1.489 albertel 10956: }
1.208 albertel 10957: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 10958: my $token;
1.140 www 10959: undef %metathesekeys;
1.71 www 10960: while ($token=$parser->get_token) {
1.339 albertel 10961: if ($token->[0] eq 'S') {
10962: if (defined($token->[2]->{'package'})) {
1.172 www 10963: #
10964: # This is a package - get package info
10965: #
1.339 albertel 10966: my $package=$token->[2]->{'package'};
10967: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10968: if (defined($token->[2]->{'id'})) {
10969: $keyroot.='_'.$token->[2]->{'id'};
10970: }
1.599 albertel 10971: if ($metaentry{':packages'}) {
10972: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 10973: } else {
1.599 albertel 10974: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 10975: }
1.736 albertel 10976: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 10977: my $part=$keyroot;
10978: $part=~s/^\_//;
1.736 albertel 10979: if ($pack_entry=~/^\Q$package\E\&/ ||
10980: $pack_entry=~/^\Q$package\E_0\&/) {
10981: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 10982: # ignore package.tab specified default values
10983: # here &package_tab_default() will fetch those
10984: if ($subp eq 'default') { next; }
1.736 albertel 10985: my $value=$packagetab{$pack_entry};
1.432 albertel 10986: my $unikey;
10987: if ($pack =~ /_0$/) {
10988: $unikey='parameter_0_'.$name;
10989: $part=0;
10990: } else {
10991: $unikey='parameter'.$keyroot.'_'.$name;
10992: }
1.339 albertel 10993: if ($subp eq 'display') {
10994: $value.=' [Part: '.$part.']';
10995: }
1.599 albertel 10996: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 10997: $metathesekeys{$unikey}=1;
1.599 albertel 10998: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10999: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 11000: }
1.599 albertel 11001: if (defined($metaentry{':'.$unikey.'.default'})) {
11002: $metaentry{':'.$unikey}=
11003: $metaentry{':'.$unikey.'.default'};
1.356 albertel 11004: }
1.339 albertel 11005: }
11006: }
11007: } else {
1.172 www 11008: #
11009: # This is not a package - some other kind of start tag
1.339 albertel 11010: #
11011: my $entry=$token->[1];
1.1068 www 11012: my $unikey='';
1.175 www 11013:
1.339 albertel 11014: if ($entry eq 'import') {
1.175 www 11015: #
11016: # Importing a library here
1.339 albertel 11017: #
1.1067 www 11018: my $location=$parser->get_text('/import');
11019: my $dir=$filename;
11020: $dir=~s|[^/]*$||;
11021: $location=&filelocation($dir,$location);
1.1069 www 11022:
1.1068 www 11023: my $importmode=$token->[2]->{'importmode'};
11024: if ($importmode eq 'problem') {
1.1069 www 11025: # Import as problem/response
1.1068 www 11026: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11027: } elsif ($importmode eq 'part') {
11028: # Import as part(s)
1.1069 www 11029: $importedparts=1;
11030: # We need to get the original file and the imported file to get the part order correct
11031: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
11032: # Load and inspect original file
1.1070 www 11033: if ($#origfileimportpartids<0) {
11034: undef(%importedpartids);
11035: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
11036: my $origfile=&getfile($origfilelocation);
11037: @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
11038: }
11039:
1.1069 www 11040: # Load and inspect imported file
11041: my $impfile=&getfile($location);
11042: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
11043: if ($#impfilepartids>=0) {
11044: # This problem had parts
1.1070 www 11045: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 11046: } else {
11047: # Importing by turning a single problem into a problem part
11048: # It gets the import-tags ID as part-ID
11049: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 11050: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 11051: }
1.1068 www 11052: } else {
11053: # Normal import
11054: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11055: if (defined($token->[2]->{'id'})) {
11056: $unikey.='_'.$token->[2]->{'id'};
11057: }
1.1067 www 11058: }
11059:
1.339 albertel 11060: if ($depthcount<20) {
1.736 albertel 11061: my $metadata =
11062: &metadata($uri,'keys', $location,$unikey,
11063: $depthcount+1);
11064: foreach my $meta (split(',',$metadata)) {
11065: $metaentry{':'.$meta}=$metaentry{':'.$meta};
11066: $metathesekeys{$meta}=1;
1.339 albertel 11067: }
1.1068 www 11068:
11069: }
1.1067 www 11070: } else {
11071: #
11072: # Not importing, some other kind of non-package, non-library start tag
11073: #
11074: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
11075: if (defined($token->[2]->{'id'})) {
11076: $unikey.='_'.$token->[2]->{'id'};
11077: }
1.339 albertel 11078: if (defined($token->[2]->{'name'})) {
11079: $unikey.='_'.$token->[2]->{'name'};
11080: }
11081: $metathesekeys{$unikey}=1;
1.736 albertel 11082: foreach my $param (@{$token->[3]}) {
11083: $metaentry{':'.$unikey.'.'.$param} =
11084: $token->[2]->{$param};
1.339 albertel 11085: }
11086: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 11087: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 11088: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
11089: # only ws inside the tag, and not in default, so use default
11090: # as value
1.599 albertel 11091: $metaentry{':'.$unikey}=$default;
1.908 albertel 11092: } elsif ( $internaltext =~ /\S/ ) {
11093: # something interesting inside the tag
11094: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 11095: } else {
1.908 albertel 11096: # no interesting values, don't set a default
1.339 albertel 11097: }
1.172 www 11098: # end of not-a-package not-a-library import
1.339 albertel 11099: }
1.172 www 11100: # end of not-a-package start tag
1.339 albertel 11101: }
1.172 www 11102: # the next is the end of "start tag"
1.339 albertel 11103: }
11104: }
1.483 albertel 11105: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 11106: $extension = lc($extension);
11107: if ($extension eq 'htm') { $extension='html'; }
11108:
1.737 albertel 11109: foreach my $key (keys(%packagetab)) {
1.483 albertel 11110: #no specific packages #how's our extension
11111: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 11112: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 11113: \%metathesekeys);
11114: }
1.883 albertel 11115:
11116: if (!exists($metaentry{':packages'})
11117: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 11118: foreach my $key (keys(%packagetab)) {
1.483 albertel 11119: #no specific packages well let's get default then
11120: if ($key!~/^default&/) { next; }
1.488 albertel 11121: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 11122: \%metathesekeys);
11123: }
11124: }
1.338 www 11125: # are there custom rights to evaluate
1.599 albertel 11126: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 11127:
1.338 www 11128: #
11129: # Importing a rights file here
1.339 albertel 11130: #
11131: unless ($depthcount) {
1.599 albertel 11132: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 11133: my $dir=$filename;
11134: $dir=~s|[^/]*$||;
11135: $location=&filelocation($dir,$location);
1.736 albertel 11136: my $rights_metadata =
11137: &metadata($uri,'keys',$location,'_rights',
11138: $depthcount+1);
11139: foreach my $rights (split(',',$rights_metadata)) {
11140: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
11141: $metathesekeys{$rights}=1;
1.339 albertel 11142: }
11143: }
11144: }
1.737 albertel 11145: # uniqifiy package listing
11146: my %seen;
11147: my @uniq_packages =
11148: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
11149: $metaentry{':packages'} = join(',',@uniq_packages);
11150:
1.1070 www 11151: if ($importedparts) {
11152: # We had imported parts and need to rebuild partorder
11153: $metaentry{':partorder'}='';
11154: $metathesekeys{'partorder'}=1;
11155: for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
11156: if ($origfileimportpartids[$index] eq 'part') {
11157: # original part, part of the problem
11158: $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
11159: } else {
11160: # we have imported parts at this position
11161: $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
11162: }
11163: }
11164: $metaentry{':partorder'}=~s/^\,//;
11165: }
11166:
1.737 albertel 11167: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 11168: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1274 raeburn 11169: $metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924 albertel 11170: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 11171: # this is the end of "was not already recently cached
1.71 www 11172: }
1.599 albertel 11173: return $metaentry{':'.$what};
1.261 albertel 11174: }
11175:
1.488 albertel 11176: sub metadata_create_package_def {
1.483 albertel 11177: my ($uri,$key,$package,$metathesekeys)=@_;
11178: my ($pack,$name,$subp)=split(/\&/,$key);
11179: if ($subp eq 'default') { next; }
11180:
1.599 albertel 11181: if (defined($metaentry{':packages'})) {
11182: $metaentry{':packages'}.=','.$package;
1.483 albertel 11183: } else {
1.599 albertel 11184: $metaentry{':packages'}=$package;
1.483 albertel 11185: }
11186: my $value=$packagetab{$key};
11187: my $unikey;
11188: $unikey='parameter_0_'.$name;
1.599 albertel 11189: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 11190: $$metathesekeys{$unikey}=1;
1.599 albertel 11191: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
11192: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 11193: }
1.599 albertel 11194: if (defined($metaentry{':'.$unikey.'.default'})) {
11195: $metaentry{':'.$unikey}=
11196: $metaentry{':'.$unikey.'.default'};
1.483 albertel 11197: }
11198: }
11199:
1.261 albertel 11200: sub metadata_generate_part0 {
11201: my ($metadata,$metacache,$uri) = @_;
11202: my %allnames;
1.737 albertel 11203: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 11204: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 11205: my $part=$$metacache{':'.$metakey.'.part'};
11206: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 11207: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 11208: $allnames{$name}=$part;
11209: }
11210: }
11211: }
11212: foreach my $name (keys(%allnames)) {
11213: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 11214: my $key=":parameter_0_$name";
1.261 albertel 11215: $$metacache{"$key.part"}='0';
11216: $$metacache{"$key.name"}=$name;
1.428 albertel 11217: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 11218: $allnames{$name}.'_'.$name.
11219: '.type'};
1.428 albertel 11220: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 11221: '.display'};
1.644 www 11222: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 11223: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 11224: $$metacache{"$key.display"}=$olddis;
11225: }
1.71 www 11226: }
11227:
1.764 albertel 11228: # ------------------------------------------------------ Devalidate title cache
11229:
11230: sub devalidate_title_cache {
11231: my ($url)=@_;
11232: if (!$env{'request.course.id'}) { return; }
11233: my $symb=&symbread($url);
11234: if (!$symb) { return; }
11235: my $key=$env{'request.course.id'}."\0".$symb;
11236: &devalidate_cache_new('title',$key);
11237: }
11238:
1.1014 droeschl 11239: # ------------------------------------------------- Get the title of a course
11240:
11241: sub current_course_title {
11242: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
11243: }
1.301 www 11244: # ------------------------------------------------- Get the title of a resource
11245:
11246: sub gettitle {
11247: my $urlsymb=shift;
11248: my $symb=&symbread($urlsymb);
1.534 albertel 11249: if ($symb) {
1.620 albertel 11250: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 11251: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 11252: if (defined($cached)) {
11253: return $result;
11254: }
1.534 albertel 11255: my ($map,$resid,$url)=&decode_symb($symb);
11256: my $title='';
1.907 albertel 11257: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
11258: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
11259: } else {
11260: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11261: &GDBM_READER(),0640)) {
11262: my $mapid=$bighash{'map_pc_'.&clutter($map)};
11263: $title=$bighash{'title_'.$mapid.'.'.$resid};
11264: untie(%bighash);
11265: }
1.534 albertel 11266: }
11267: $title=~s/\&colon\;/\:/gs;
11268: if ($title) {
1.1159 www 11269: # Remember both $symb and $title for dynamic metadata
11270: $accesshash{$symb.'___crstitle'}=$title;
1.1161 www 11271: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159 www 11272: # Cache this title and then return it
1.599 albertel 11273: return &do_cache_new('title',$key,$title,600);
1.534 albertel 11274: }
11275: $urlsymb=$url;
11276: }
11277: my $title=&metadata($urlsymb,'title');
11278: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
11279: return $title;
1.301 www 11280: }
1.613 albertel 11281:
1.614 albertel 11282: sub get_slot {
11283: my ($which,$cnum,$cdom)=@_;
11284: if (!$cnum || !$cdom) {
1.790 albertel 11285: (undef,my $courseid)=&whichuser();
1.620 albertel 11286: $cdom=$env{'course.'.$courseid.'.domain'};
11287: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 11288: }
1.703 albertel 11289: my $key=join("\0",'slots',$cdom,$cnum,$which);
11290: my %slotinfo;
11291: if (exists($remembered{$key})) {
11292: $slotinfo{$which} = $remembered{$key};
11293: } else {
11294: %slotinfo=&get('slots',[$which],$cdom,$cnum);
11295: &Apache::lonhomework::showhash(%slotinfo);
11296: my ($tmp)=keys(%slotinfo);
11297: if ($tmp=~/^error:/) { return (); }
11298: $remembered{$key} = $slotinfo{$which};
11299: }
1.616 albertel 11300: if (ref($slotinfo{$which}) eq 'HASH') {
11301: return %{$slotinfo{$which}};
11302: }
11303: return $slotinfo{$which};
1.614 albertel 11304: }
1.1150 raeburn 11305:
11306: sub get_reservable_slots {
11307: my ($cnum,$cdom,$uname,$udom) = @_;
11308: my $now = time;
11309: my $reservable_info;
11310: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
11311: if (exists($remembered{$key})) {
11312: $reservable_info = $remembered{$key};
11313: } else {
11314: my %resv;
11315: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
11316: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
11317: $reservable_info = \%resv;
11318: $remembered{$key} = $reservable_info;
11319: }
11320: return $reservable_info;
11321: }
11322:
11323: sub get_course_slots {
11324: my ($cnum,$cdom) = @_;
11325: my $hashid=$cnum.':'.$cdom;
11326: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
11327: if (defined($cached)) {
11328: if (ref($result) eq 'HASH') {
11329: return %{$result};
11330: }
11331: } else {
11332: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
11333: my ($tmp) = keys(%slots);
11334: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1219 raeburn 11335: &do_cache_new('allslots',$hashid,\%slots,600);
1.1150 raeburn 11336: return %slots;
11337: }
11338: }
11339: return;
11340: }
11341:
11342: sub devalidate_slots_cache {
11343: my ($cnum,$cdom)=@_;
11344: my $hashid=$cnum.':'.$cdom;
11345: &devalidate_cache_new('allslots',$hashid);
11346: }
11347:
1.1181 raeburn 11348: sub get_coursechange {
11349: my ($cdom,$cnum) = @_;
11350: if ($cdom eq '' || $cnum eq '') {
11351: return unless ($env{'request.course.id'});
11352: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
11353: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
11354: }
11355: my $hashid=$cdom.'_'.$cnum;
11356: my ($change,$cached)=&is_cached_new('crschange',$hashid);
11357: if ((defined($cached)) && ($change ne '')) {
11358: return $change;
11359: } else {
11360: my %crshash;
11361: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
11362: if ($crshash{'internal.contentchange'} eq '') {
11363: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
11364: if ($change eq '') {
11365: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
11366: $change = $crshash{'internal.created'};
11367: }
11368: } else {
11369: $change = $crshash{'internal.contentchange'};
11370: }
11371: my $cachetime = 600;
11372: &do_cache_new('crschange',$hashid,$change,$cachetime);
11373: }
11374: return $change;
11375: }
11376:
11377: sub devalidate_coursechange_cache {
11378: my ($cnum,$cdom)=@_;
11379: my $hashid=$cnum.':'.$cdom;
11380: &devalidate_cache_new('crschange',$hashid);
11381: }
11382:
1.31 www 11383: # ------------------------------------------------- Update symbolic store links
11384:
11385: sub symblist {
11386: my ($mapname,%newhash)=@_;
1.438 www 11387: $mapname=&deversion(&declutter($mapname));
1.31 www 11388: my %hash;
1.620 albertel 11389: if (($env{'request.course.fn'}) && (%newhash)) {
11390: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 11391: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 11392: foreach my $url (keys(%newhash)) {
1.711 albertel 11393: next if ($url eq 'last_known'
11394: && $env{'form.no_update_last_known'});
11395: $hash{declutter($url)}=&encode_symb($mapname,
11396: $newhash{$url}->[1],
11397: $newhash{$url}->[0]);
1.191 harris41 11398: }
1.31 www 11399: if (untie(%hash)) {
11400: return 'ok';
11401: }
11402: }
11403: }
11404: return 'error';
1.212 www 11405: }
11406:
11407: # --------------------------------------------------------------- Verify a symb
11408:
11409: sub symbverify {
1.1190 raeburn 11410: my ($symb,$thisurl,$encstate)=@_;
1.510 www 11411: my $thisfn=$thisurl;
1.439 www 11412: $thisfn=&declutter($thisfn);
1.215 www 11413: # direct jump to resource in page or to a sequence - will construct own symbs
11414: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
11415: # check URL part
1.409 www 11416: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 11417:
1.431 www 11418: unless ($url eq $thisfn) { return 0; }
1.213 www 11419:
1.216 www 11420: $symb=&symbclean($symb);
1.510 www 11421: $thisurl=&deversion($thisurl);
1.439 www 11422: $thisfn=&deversion($thisfn);
1.213 www 11423:
11424: my %bighash;
11425: my $okay=0;
1.431 www 11426:
1.620 albertel 11427: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 11428: &GDBM_READER(),0640)) {
1.1204 raeburn 11429: my $noclutter;
1.1032 raeburn 11430: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
11431: $thisurl =~ s/\?.+$//;
1.1204 raeburn 11432: if ($map =~ m{^uploaded/.+\.page$}) {
11433: $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
11434: $thisurl =~ s{^\Qhttp://https://\E}{https://};
11435: $noclutter = 1;
11436: }
11437: }
11438: my $ids;
11439: if ($noclutter) {
11440: $ids=$bighash{'ids_'.$thisurl};
11441: } else {
11442: $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032 raeburn 11443: }
1.1102 raeburn 11444: unless ($ids) {
11445: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
11446: $ids=$bighash{$idkey};
1.216 www 11447: }
11448: if ($ids) {
11449: # ------------------------------------------------------------------- Has ID(s)
1.1202 raeburn 11450: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
1.1203 raeburn 11451: $symb =~ s/\?.+$//;
1.1202 raeburn 11452: }
1.800 albertel 11453: foreach my $id (split(/\,/,$ids)) {
11454: my ($mapid,$resid)=split(/\./,$id);
1.216 www 11455: if (
11456: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190 raeburn 11457: eq $symb) {
11458: if (ref($encstate)) {
11459: $$encstate = $bighash{'encrypted_'.$id};
11460: }
1.620 albertel 11461: if (($env{'request.role.adv'}) ||
1.1101 raeburn 11462: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
11463: ($thisurl eq '/adm/navmaps')) {
1.1190 raeburn 11464: $okay=1;
1.1202 raeburn 11465: last;
1.582 albertel 11466: }
11467: }
1.216 www 11468: }
11469: }
1.213 www 11470: untie(%bighash);
11471: }
11472: return $okay;
1.31 www 11473: }
11474:
1.210 www 11475: # --------------------------------------------------------------- Clean-up symb
11476:
11477: sub symbclean {
11478: my $symb=shift;
1.568 albertel 11479: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 11480: # remove version from map
11481: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 11482:
1.210 www 11483: # remove version from URL
11484: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 11485:
1.507 www 11486: # remove wrapper
11487:
1.510 www 11488: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 11489: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 11490: return $symb;
1.409 www 11491: }
11492:
11493: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 11494:
11495: sub encode_symb {
11496: my ($map,$resid,$url)=@_;
11497: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
11498: }
1.409 www 11499:
11500: sub decode_symb {
1.568 albertel 11501: my $symb=shift;
11502: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
11503: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 11504: return (&fixversion($map),$resid,&fixversion($url));
11505: }
11506:
11507: sub fixversion {
11508: my $fn=shift;
1.609 banghart 11509: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 11510: my %bighash;
11511: my $uri=&clutter($fn);
1.620 albertel 11512: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 11513: # is this cached?
1.599 albertel 11514: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 11515: if (defined($cached)) { return $result; }
11516: # unfortunately not cached, or expired
1.620 albertel 11517: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 11518: &GDBM_READER(),0640)) {
11519: if ($bighash{'version_'.$uri}) {
11520: my $version=$bighash{'version_'.$uri};
1.444 www 11521: unless (($version eq 'mostrecent') ||
11522: ($version==&getversion($uri))) {
1.440 www 11523: $uri=~s/\.(\w+)$/\.$version\.$1/;
11524: }
11525: }
11526: untie %bighash;
1.413 www 11527: }
1.599 albertel 11528: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 11529: }
11530:
11531: sub deversion {
11532: my $url=shift;
11533: $url=~s/\.\d+\.(\w+)$/\.$1/;
11534: return $url;
1.210 www 11535: }
11536:
1.31 www 11537: # ------------------------------------------------------ Return symb list entry
11538:
11539: sub symbread {
1.1282 raeburn 11540: my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
1.1265 raeburn 11541: my $cache_str='request.symbread.cached.'.$thisfn;
1.1282 raeburn 11542: if (defined($env{$cache_str})) {
11543: if ($ignorecachednull) {
11544: return $env{$cache_str} unless ($env{$cache_str} eq '');
11545: } else {
11546: return $env{$cache_str};
11547: }
11548: }
1.242 www 11549: # no filename provided? try from environment
1.1265 raeburn 11550: unless ($thisfn) {
1.620 albertel 11551: if ($env{'request.symb'}) {
11552: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 11553: }
1.620 albertel 11554: $thisfn=$env{'request.filename'};
1.44 www 11555: }
1.569 albertel 11556: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 11557: # is that filename actually a symb? Verify, clean, and return
11558: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 11559: if (&symbverify($thisfn,$1)) {
1.620 albertel 11560: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 11561: }
1.242 www 11562: }
1.44 www 11563: $thisfn=declutter($thisfn);
1.31 www 11564: my %hash;
1.37 www 11565: my %bighash;
11566: my $syval='';
1.620 albertel 11567: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 11568: my $targetfn = $thisfn;
1.609 banghart 11569: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 11570: $targetfn = 'adm/wrapper/'.$thisfn;
11571: }
1.687 albertel 11572: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
11573: $targetfn=$1;
11574: }
1.620 albertel 11575: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 11576: &GDBM_READER(),0640)) {
1.481 raeburn 11577: $syval=$hash{$targetfn};
1.37 www 11578: untie(%hash);
11579: }
11580: # ---------------------------------------------------------- There was an entry
11581: if ($syval) {
1.601 albertel 11582: #unless ($syval=~/\_\d+$/) {
1.620 albertel 11583: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 11584: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 11585: #return $env{$cache_str}='';
1.601 albertel 11586: #}
11587: #$syval.=$1;
11588: #}
1.37 www 11589: } else {
11590: # ------------------------------------------------------- Was not in symb table
1.620 albertel 11591: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 11592: &GDBM_READER(),0640)) {
1.37 www 11593: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 11594: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 11595: unless ($ids) {
11596: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 11597: }
11598: unless ($ids) {
11599: # alias?
11600: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 11601: }
1.37 www 11602: if ($ids) {
11603: # ------------------------------------------------------------------- Has ID(s)
11604: my @possibilities=split(/\,/,$ids);
1.39 www 11605: if ($#possibilities==0) {
11606: # ----------------------------------------------- There is only one possibility
1.37 www 11607: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 11608: $syval=&encode_symb($bighash{'map_id_'.$mapid},
11609: $resid,$thisfn);
1.1282 raeburn 11610: if (ref($possibles) eq 'HASH') {
11611: $possibles->{$syval} = 1;
11612: }
11613: if ($checkforblock) {
11614: my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
11615: if (@blockers) {
11616: $syval = '';
11617: return;
11618: }
11619: }
11620: } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39 www 11621: # ------------------------------------------ There is more than one possibility
11622: my $realpossible=0;
1.800 albertel 11623: foreach my $id (@possibilities) {
11624: my $file=$bighash{'src_'.$id};
1.1282 raeburn 11625: my $canaccess;
11626: if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
11627: $canaccess = 1;
11628: } else {
11629: $canaccess = &allowed('bre',$file);
11630: }
11631: if ($canaccess) {
11632: my ($mapid,$resid)=split(/\./,$id);
11633: if ($bighash{'map_type_'.$mapid} ne 'page') {
11634: my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
11635: $resid,$thisfn);
11636: if (ref($possibles) eq 'HASH') {
11637: $possibles->{$syval} = 1;
11638: }
11639: if ($checkforblock) {
11640: my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
11641: unless (@blockers > 0) {
11642: $syval = $poss_syval;
11643: $realpossible++;
11644: }
11645: } else {
11646: $syval = $poss_syval;
11647: $realpossible++;
11648: }
11649: }
1.39 www 11650: }
1.191 harris41 11651: }
1.39 www 11652: if ($realpossible!=1) { $syval=''; }
1.249 www 11653: } else {
11654: $syval='';
1.37 www 11655: }
11656: }
1.1282 raeburn 11657: untie(%bighash);
1.481 raeburn 11658: }
1.31 www 11659: }
1.62 www 11660: if ($syval) {
1.620 albertel 11661: return $env{$cache_str}=$syval;
1.62 www 11662: }
1.31 www 11663: }
1.949 raeburn 11664: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 11665: return $env{$cache_str}='';
1.31 www 11666: }
11667:
11668: # ---------------------------------------------------------- Return random seed
11669:
1.32 www 11670: sub numval {
11671: my $txt=shift;
11672: $txt=~tr/A-J/0-9/;
11673: $txt=~tr/a-j/0-9/;
11674: $txt=~tr/K-T/0-9/;
11675: $txt=~tr/k-t/0-9/;
11676: $txt=~tr/U-Z/0-5/;
11677: $txt=~tr/u-z/0-5/;
11678: $txt=~s/\D//g;
1.564 albertel 11679: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 11680: return int($txt);
1.368 albertel 11681: }
11682:
1.484 albertel 11683: sub numval2 {
11684: my $txt=shift;
11685: $txt=~tr/A-J/0-9/;
11686: $txt=~tr/a-j/0-9/;
11687: $txt=~tr/K-T/0-9/;
11688: $txt=~tr/k-t/0-9/;
11689: $txt=~tr/U-Z/0-5/;
11690: $txt=~tr/u-z/0-5/;
11691: $txt=~s/\D//g;
11692: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
11693: my $total;
11694: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 11695: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 11696: return int($total);
11697: }
11698:
1.575 albertel 11699: sub numval3 {
11700: use integer;
11701: my $txt=shift;
11702: $txt=~tr/A-J/0-9/;
11703: $txt=~tr/a-j/0-9/;
11704: $txt=~tr/K-T/0-9/;
11705: $txt=~tr/k-t/0-9/;
11706: $txt=~tr/U-Z/0-5/;
11707: $txt=~tr/u-z/0-5/;
11708: $txt=~s/\D//g;
11709: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
11710: my $total;
11711: foreach my $val (@txts) { $total+=$val; }
11712: if ($_64bit) { $total=(($total<<32)>>32); }
11713: return $total;
11714: }
11715:
1.675 albertel 11716: sub digest {
11717: my ($data)=@_;
11718: my $digest=&Digest::MD5::md5($data);
11719: my ($a,$b,$c,$d)=unpack("iiii",$digest);
11720: my ($e,$f);
11721: {
11722: use integer;
11723: $e=($a+$b);
11724: $f=($c+$d);
11725: if ($_64bit) {
11726: $e=(($e<<32)>>32);
11727: $f=(($f<<32)>>32);
11728: }
11729: }
11730: if (wantarray) {
11731: return ($e,$f);
11732: } else {
11733: my $g;
11734: {
11735: use integer;
11736: $g=($e+$f);
11737: if ($_64bit) {
11738: $g=(($g<<32)>>32);
11739: }
11740: }
11741: return $g;
11742: }
11743: }
11744:
1.368 albertel 11745: sub latest_rnd_algorithm_id {
1.675 albertel 11746: return '64bit5';
1.366 albertel 11747: }
1.32 www 11748:
1.503 albertel 11749: sub get_rand_alg {
11750: my ($courseid)=@_;
1.790 albertel 11751: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 11752: if ($courseid) {
1.620 albertel 11753: return $env{"course.$courseid.rndseed"};
1.503 albertel 11754: }
11755: return &latest_rnd_algorithm_id();
11756: }
11757:
1.562 albertel 11758: sub validCODE {
11759: my ($CODE)=@_;
11760: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
11761: return 0;
11762: }
11763:
1.491 albertel 11764: sub getCODE {
1.620 albertel 11765: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 11766: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
11767: defined($Apache::lonhomework::parsing_a_task) ) &&
11768: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 11769: return $Apache::lonhomework::history{'resource.CODE'};
11770: }
11771: return undef;
11772: }
1.1133 foxr 11773: #
11774: # Determines the random seed for a specific context:
11775: #
11776: # parameters:
11777: # symb - in course context the symb for the seed.
11778: # course_id - The course id of the form domain_coursenum.
11779: # domain - Domain for the user.
11780: # course - Course for the user.
11781: # cenv - environment of the course.
11782: #
11783: # NOTE:
11784: # All parameters are picked out of the environment if missing
11785: # or not defined.
11786: # If a symb cannot be determined the current time is used instead.
11787: #
11788: # For a given well defined symb, courside, domain, username,
11789: # and course environment, the seed is reproducible.
11790: #
1.31 www 11791: sub rndseed {
1.1133 foxr 11792: my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790 albertel 11793: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 11794: if (!defined($symb)) {
1.366 albertel 11795: unless ($symb=$wsymb) { return time; }
11796: }
1.1146 foxr 11797: if (!defined $courseid) {
11798: $courseid=$wcourseid;
11799: }
11800: if (!defined $domain) { $domain=$wdomain; }
11801: if (!defined $username) { $username=$wusername }
1.1133 foxr 11802:
11803: my $which;
11804: if (defined($cenv->{'rndseed'})) {
11805: $which = $cenv->{'rndseed'};
11806: } else {
11807: $which =&get_rand_alg($courseid);
11808: }
1.491 albertel 11809: if (defined(&getCODE())) {
1.1133 foxr 11810:
1.675 albertel 11811: if ($which eq '64bit5') {
11812: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
11813: } elsif ($which eq '64bit4') {
1.575 albertel 11814: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
11815: } else {
11816: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
11817: }
1.675 albertel 11818: } elsif ($which eq '64bit5') {
11819: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 11820: } elsif ($which eq '64bit4') {
11821: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 11822: } elsif ($which eq '64bit3') {
11823: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 11824: } elsif ($which eq '64bit2') {
11825: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 11826: } elsif ($which eq '64bit') {
11827: return &rndseed_64bit($symb,$courseid,$domain,$username);
11828: }
11829: return &rndseed_32bit($symb,$courseid,$domain,$username);
11830: }
11831:
11832: sub rndseed_32bit {
11833: my ($symb,$courseid,$domain,$username)=@_;
11834: {
11835: use integer;
11836: my $symbchck=unpack("%32C*",$symb) << 27;
11837: my $symbseed=numval($symb) << 22;
11838: my $namechck=unpack("%32C*",$username) << 17;
11839: my $nameseed=numval($username) << 12;
11840: my $domainseed=unpack("%32C*",$domain) << 7;
11841: my $courseseed=unpack("%32C*",$courseid);
11842: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 11843: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11844: #&logthis("rndseed :$num:$symb");
1.564 albertel 11845: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 11846: return $num;
11847: }
11848: }
11849:
11850: sub rndseed_64bit {
11851: my ($symb,$courseid,$domain,$username)=@_;
11852: {
11853: use integer;
11854: my $symbchck=unpack("%32S*",$symb) << 21;
11855: my $symbseed=numval($symb) << 10;
11856: my $namechck=unpack("%32S*",$username);
11857:
11858: my $nameseed=numval($username) << 21;
11859: my $domainseed=unpack("%32S*",$domain) << 10;
11860: my $courseseed=unpack("%32S*",$courseid);
11861:
11862: my $num1=$symbchck+$symbseed+$namechck;
11863: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11864: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11865: #&logthis("rndseed :$num:$symb");
1.564 albertel 11866: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 11867: return "$num1,$num2";
1.155 albertel 11868: }
1.366 albertel 11869: }
11870:
1.443 albertel 11871: sub rndseed_64bit2 {
11872: my ($symb,$courseid,$domain,$username)=@_;
11873: {
11874: use integer;
11875: # strings need to be an even # of cahracters long, it it is odd the
11876: # last characters gets thrown away
11877: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11878: my $symbseed=numval($symb) << 10;
11879: my $namechck=unpack("%32S*",$username.' ');
11880:
11881: my $nameseed=numval($username) << 21;
1.501 albertel 11882: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11883: my $courseseed=unpack("%32S*",$courseid.' ');
11884:
11885: my $num1=$symbchck+$symbseed+$namechck;
11886: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11887: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11888: #&logthis("rndseed :$num:$symb");
1.803 albertel 11889: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 11890: return "$num1,$num2";
11891: }
11892: }
11893:
11894: sub rndseed_64bit3 {
11895: my ($symb,$courseid,$domain,$username)=@_;
11896: {
11897: use integer;
11898: # strings need to be an even # of cahracters long, it it is odd the
11899: # last characters gets thrown away
11900: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11901: my $symbseed=numval2($symb) << 10;
11902: my $namechck=unpack("%32S*",$username.' ');
11903:
11904: my $nameseed=numval2($username) << 21;
1.443 albertel 11905: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11906: my $courseseed=unpack("%32S*",$courseid.' ');
11907:
11908: my $num1=$symbchck+$symbseed+$namechck;
11909: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11910: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11911: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 11912: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 11913:
1.503 albertel 11914: return "$num1:$num2";
1.443 albertel 11915: }
11916: }
11917:
1.575 albertel 11918: sub rndseed_64bit4 {
11919: my ($symb,$courseid,$domain,$username)=@_;
11920: {
11921: use integer;
11922: # strings need to be an even # of cahracters long, it it is odd the
11923: # last characters gets thrown away
11924: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11925: my $symbseed=numval3($symb) << 10;
11926: my $namechck=unpack("%32S*",$username.' ');
11927:
11928: my $nameseed=numval3($username) << 21;
11929: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11930: my $courseseed=unpack("%32S*",$courseid.' ');
11931:
11932: my $num1=$symbchck+$symbseed+$namechck;
11933: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11934: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11935: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 11936: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 11937:
1.575 albertel 11938: return "$num1:$num2";
11939: }
11940: }
11941:
1.675 albertel 11942: sub rndseed_64bit5 {
11943: my ($symb,$courseid,$domain,$username)=@_;
11944: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
11945: return "$num1:$num2";
11946: }
11947:
1.366 albertel 11948: sub rndseed_CODE_64bit {
11949: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 11950: {
1.366 albertel 11951: use integer;
1.443 albertel 11952: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 11953: my $symbseed=numval2($symb);
1.491 albertel 11954: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11955: my $CODEseed=numval(&getCODE());
1.443 albertel 11956: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 11957: my $num1=$symbseed+$CODEchck;
11958: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 11959: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11960: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 11961: if ($_64bit) { $num1=(($num1<<32)>>32); }
11962: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 11963: return "$num1:$num2";
1.366 albertel 11964: }
11965: }
11966:
1.575 albertel 11967: sub rndseed_CODE_64bit4 {
11968: my ($symb,$courseid,$domain,$username)=@_;
11969: {
11970: use integer;
11971: my $symbchck=unpack("%32S*",$symb.' ') << 16;
11972: my $symbseed=numval3($symb);
11973: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11974: my $CODEseed=numval3(&getCODE());
11975: my $courseseed=unpack("%32S*",$courseid.' ');
11976: my $num1=$symbseed+$CODEchck;
11977: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 11978: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11979: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 11980: if ($_64bit) { $num1=(($num1<<32)>>32); }
11981: if ($_64bit) { $num2=(($num2<<32)>>32); }
11982: return "$num1:$num2";
11983: }
11984: }
11985:
1.675 albertel 11986: sub rndseed_CODE_64bit5 {
11987: my ($symb,$courseid,$domain,$username)=@_;
11988: my $code = &getCODE();
11989: my ($num1,$num2)=&digest("$symb,$courseid,$code");
11990: return "$num1:$num2";
11991: }
11992:
1.366 albertel 11993: sub setup_random_from_rndseed {
11994: my ($rndseed)=@_;
1.503 albertel 11995: if ($rndseed =~/([,:])/) {
1.1262 raeburn 11996: my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
11997: if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
11998: &Math::Random::random_set_seed_from_phrase($rndseed);
11999: } else {
12000: &Math::Random::random_set_seed($num1,$num2);
12001: }
1.366 albertel 12002: } else {
12003: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 12004: }
1.36 albertel 12005: }
12006:
1.474 albertel 12007: sub latest_receipt_algorithm_id {
1.835 albertel 12008: return 'receipt3';
1.474 albertel 12009: }
12010:
1.480 www 12011: sub recunique {
12012: my $fucourseid=shift;
12013: my $unique;
1.835 albertel 12014: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
12015: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 12016: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 12017: } else {
12018: $unique=$perlvar{'lonReceipt'};
12019: }
12020: return unpack("%32C*",$unique);
12021: }
12022:
12023: sub recprefix {
12024: my $fucourseid=shift;
12025: my $prefix;
1.835 albertel 12026: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
12027: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 12028: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 12029: } else {
12030: $prefix=$perlvar{'lonHostID'};
12031: }
12032: return unpack("%32C*",$prefix);
12033: }
12034:
1.76 www 12035: sub ireceipt {
1.474 albertel 12036: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 12037:
12038: my $return =&recprefix($fucourseid).'-';
12039:
12040: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
12041: $env{'request.state'} eq 'construct') {
12042: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
12043: return $return;
12044: }
12045:
1.76 www 12046: my $cuname=unpack("%32C*",$funame);
12047: my $cudom=unpack("%32C*",$fudom);
12048: my $cucourseid=unpack("%32C*",$fucourseid);
12049: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 12050: my $cunique=&recunique($fucourseid);
1.474 albertel 12051: my $cpart=unpack("%32S*",$part);
1.835 albertel 12052: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
12053:
1.790 albertel 12054: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 12055:
12056: $return.= ($cunique%$cuname+
12057: $cunique%$cudom+
12058: $cusymb%$cuname+
12059: $cusymb%$cudom+
12060: $cucourseid%$cuname+
12061: $cucourseid%$cudom+
12062: $cpart%$cuname+
12063: $cpart%$cudom);
12064: } else {
12065: $return.= ($cunique%$cuname+
12066: $cunique%$cudom+
12067: $cusymb%$cuname+
12068: $cusymb%$cudom+
12069: $cucourseid%$cuname+
12070: $cucourseid%$cudom);
12071: }
12072: return $return;
1.76 www 12073: }
12074:
12075: sub receipt {
1.474 albertel 12076: my ($part)=@_;
1.790 albertel 12077: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 12078: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 12079: }
1.260 ng 12080:
1.790 albertel 12081: sub whichuser {
12082: my ($passedsymb)=@_;
12083: my ($symb,$courseid,$domain,$name,$publicuser);
12084: if (defined($env{'form.grade_symb'})) {
12085: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
12086: my $allowed=&allowed('vgr',$tmp_courseid);
12087: if (!$allowed &&
12088: exists($env{'request.course.sec'}) &&
12089: $env{'request.course.sec'} !~ /^\s*$/) {
12090: $allowed=&allowed('vgr',$tmp_courseid.
12091: '/'.$env{'request.course.sec'});
12092: }
12093: if ($allowed) {
12094: ($symb)=&get_env_multiple('form.grade_symb');
12095: $courseid=$tmp_courseid;
12096: ($domain)=&get_env_multiple('form.grade_domain');
12097: ($name)=&get_env_multiple('form.grade_username');
12098: return ($symb,$courseid,$domain,$name,$publicuser);
12099: }
12100: }
12101: if (!$passedsymb) {
12102: $symb=&symbread();
12103: } else {
12104: $symb=$passedsymb;
12105: }
12106: $courseid=$env{'request.course.id'};
12107: $domain=$env{'user.domain'};
12108: $name=$env{'user.name'};
12109: if ($name eq 'public' && $domain eq 'public') {
12110: if (!defined($env{'form.username'})) {
12111: $env{'form.username'}.=time.rand(10000000);
12112: }
12113: $name.=$env{'form.username'};
12114: }
12115: return ($symb,$courseid,$domain,$name,$publicuser);
12116:
12117: }
12118:
1.36 albertel 12119: # ------------------------------------------------------------ Serves up a file
1.472 albertel 12120: # returns either the contents of the file or
12121: # -1 if the file doesn't exist
1.481 raeburn 12122: #
12123: # if the target is a file that was uploaded via DOCS,
12124: # a check will be made to see if a current copy exists on the local server,
12125: # if it does this will be served, otherwise a copy will be retrieved from
12126: # the home server for the course and stored in /home/httpd/html/userfiles on
12127: # the local server.
1.472 albertel 12128:
1.36 albertel 12129: sub getfile {
1.538 albertel 12130: my ($file) = @_;
1.609 banghart 12131: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 12132: &repcopy($file);
12133: return &readfile($file);
12134: }
12135:
12136: sub repcopy_userfile {
12137: my ($file)=@_;
1.1142 raeburn 12138: my $londocroot = $perlvar{'lonDocRoot'};
12139: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164 raeburn 12140: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538 albertel 12141: my ($cdom,$cnum,$filename) =
1.811 albertel 12142: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 12143: my $uri="/uploaded/$cdom/$cnum/$filename";
12144: if (-e "$file") {
1.828 www 12145: # we already have a local copy, check it out
1.538 albertel 12146: my @fileinfo = stat($file);
1.828 www 12147: my $rtncode;
12148: my $info;
1.538 albertel 12149: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 12150: if ($lwpresp ne 'ok') {
1.828 www 12151: # there is no such file anymore, even though we had a local copy
1.482 albertel 12152: if ($rtncode eq '404') {
1.538 albertel 12153: unlink($file);
1.482 albertel 12154: }
12155: return -1;
12156: }
12157: if ($info < $fileinfo[9]) {
1.828 www 12158: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 12159: return 'ok';
1.828 www 12160: } else {
12161: # the file is outdated, get rid of it
12162: unlink($file);
1.482 albertel 12163: }
1.828 www 12164: }
12165: # one way or the other, at this point, we don't have the file
12166: # construct the correct path for the file
12167: my @parts = ($cdom,$cnum);
12168: if ($filename =~ m|^(.+)/[^/]+$|) {
12169: push @parts, split(/\//,$1);
12170: }
12171: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
12172: foreach my $part (@parts) {
12173: $path .= '/'.$part;
12174: if (!-e $path) {
12175: mkdir($path,0770);
1.482 albertel 12176: }
12177: }
1.828 www 12178: # now the path exists for sure
12179: # get a user agent
12180: my $ua=new LWP::UserAgent;
12181: my $transferfile=$file.'.in.transfer';
12182: # FIXME: this should flock
12183: if (-e $transferfile) { return 'ok'; }
12184: my $request;
12185: $uri=~s/^\///;
1.980 raeburn 12186: my $homeserver = &homeserver($cnum,$cdom);
12187: my $protocol = $protocol{$homeserver};
12188: $protocol = 'http' if ($protocol ne 'https');
12189: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 12190: my $response=$ua->request($request,$transferfile);
12191: # did it work?
12192: if ($response->is_error()) {
12193: unlink($transferfile);
12194: &logthis("Userfile repcopy failed for $uri");
12195: return -1;
12196: }
12197: # worked, rename the transfer file
12198: rename($transferfile,$file);
1.607 raeburn 12199: return 'ok';
1.481 raeburn 12200: }
12201:
1.517 albertel 12202: sub tokenwrapper {
12203: my $uri=shift;
1.980 raeburn 12204: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 12205: $uri=~s|^/||;
1.620 albertel 12206: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 12207: my $token=$1;
1.552 albertel 12208: my (undef,$udom,$uname,$file)=split('/',$uri,4);
12209: if ($udom && $uname && $file) {
12210: $file=~s|(\?\.*)*$||;
1.949 raeburn 12211: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 12212: my $homeserver = &homeserver($uname,$udom);
12213: my $protocol = $protocol{$homeserver};
12214: $protocol = 'http' if ($protocol ne 'https');
12215: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 12216: (($uri=~/\?/)?'&':'?').'token='.$token.
12217: '&tokenissued='.$perlvar{'lonHostID'};
12218: } else {
12219: return '/adm/notfound.html';
12220: }
12221: }
12222:
1.828 www 12223: # call with reqtype HEAD: get last modification time
12224: # call with reqtype GET: get the file contents
12225: # Do not call this with reqtype GET for large files! It loads everything into memory
12226: #
1.481 raeburn 12227: sub getuploaded {
12228: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
12229: $uri=~s/^\///;
1.980 raeburn 12230: my $homeserver = &homeserver($cnum,$cdom);
12231: my $protocol = $protocol{$homeserver};
12232: $protocol = 'http' if ($protocol ne 'https');
12233: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 12234: my $ua=new LWP::UserAgent;
12235: my $request=new HTTP::Request($reqtype,$uri);
12236: my $response=$ua->request($request);
12237: $$rtncode = $response->code;
1.482 albertel 12238: if (! $response->is_success()) {
12239: return 'failed';
12240: }
12241: if ($reqtype eq 'HEAD') {
1.486 www 12242: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 12243: } elsif ($reqtype eq 'GET') {
12244: $$info = $response->content;
1.472 albertel 12245: }
1.482 albertel 12246: return 'ok';
1.36 albertel 12247: }
12248:
1.481 raeburn 12249: sub readfile {
12250: my $file = shift;
12251: if ( (! -e $file ) || ($file eq '') ) { return -1; };
12252: my $fh;
12253: open($fh,"<$file");
12254: my $a='';
1.800 albertel 12255: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 12256: return $a;
12257: }
12258:
1.36 albertel 12259: sub filelocation {
1.590 banghart 12260: my ($dir,$file) = @_;
12261: my $location;
12262: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 12263:
12264: if ($file =~ m-^/adm/-) {
12265: $file=~s-^/adm/wrapper/-/-;
12266: $file=~s-^/adm/coursedocs/showdoc/-/-;
12267: }
1.882 albertel 12268:
1.1139 www 12269: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956 raeburn 12270: $location = $file;
1.609 banghart 12271: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 12272: my ($udom,$uname,$filename)=
1.811 albertel 12273: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 12274: my $home=&homeserver($uname,$udom);
12275: my $is_me=0;
12276: my @ids=¤t_machine_ids();
12277: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
12278: if ($is_me) {
1.1117 foxr 12279: $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 12280: } else {
12281: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
12282: $udom.'/'.$uname.'/'.$filename;
12283: }
1.882 albertel 12284: } elsif ($file =~ m-^/adm/-) {
12285: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 12286: } else {
12287: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139 www 12288: $file=~s:^/(res|priv)/:/:;
12289: my $space=$1;
1.590 banghart 12290: if ( !( $file =~ m:^/:) ) {
12291: $location = $dir. '/'.$file;
12292: } else {
1.1142 raeburn 12293: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590 banghart 12294: }
1.59 albertel 12295: }
1.590 banghart 12296: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 12297: while ($location=~m{/\.\./}) {
12298: if ($location =~ m{/[^/]+/\.\./}) {
12299: $location=~ s{/[^/]+/\.\./}{/}g;
12300: } else {
12301: $location=~ s{/\.\./}{/}g;
12302: }
12303: } #remove dir/..
1.590 banghart 12304: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
12305: return $location;
1.46 www 12306: }
1.36 albertel 12307:
1.46 www 12308: sub hreflocation {
12309: my ($dir,$file)=@_;
1.980 raeburn 12310: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 12311: $file=filelocation($dir,$file);
1.700 albertel 12312: } elsif ($file=~m-^/adm/-) {
12313: $file=~s-^/adm/wrapper/-/-;
12314: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 12315: }
12316: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
12317: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
12318: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143 raeburn 12319: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
12320: {/uploaded/$1/$2/}x;
1.46 www 12321: }
1.913 albertel 12322: if ($file=~ m{^/userfiles/}) {
12323: $file =~ s{^/userfiles/}{/uploaded/};
12324: }
1.462 albertel 12325: return $file;
1.465 albertel 12326: }
12327:
1.1139 www 12328:
12329:
12330:
12331:
1.465 albertel 12332: sub current_machine_domains {
1.853 albertel 12333: return &machine_domains(&hostname($perlvar{'lonHostID'}));
12334: }
12335:
12336: sub machine_domains {
12337: my ($hostname) = @_;
1.465 albertel 12338: my @domains;
1.838 albertel 12339: my %hostname = &all_hostnames();
1.465 albertel 12340: while( my($id, $name) = each(%hostname)) {
1.467 matthew 12341: # &logthis("-$id-$name-$hostname-");
1.465 albertel 12342: if ($hostname eq $name) {
1.844 albertel 12343: push(@domains,&host_domain($id));
1.465 albertel 12344: }
12345: }
12346: return @domains;
12347: }
12348:
12349: sub current_machine_ids {
1.853 albertel 12350: return &machine_ids(&hostname($perlvar{'lonHostID'}));
12351: }
12352:
12353: sub machine_ids {
12354: my ($hostname) = @_;
12355: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 12356: my @ids;
1.888 albertel 12357: my %name_to_host = &all_names();
1.889 albertel 12358: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
12359: return @{ $name_to_host{$hostname} };
12360: }
12361: return;
1.31 www 12362: }
12363:
1.824 raeburn 12364: sub additional_machine_domains {
12365: my @domains;
12366: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
12367: while( my $line = <$fh>) {
12368: $line =~ s/\s//g;
12369: push(@domains,$line);
12370: }
12371: return @domains;
12372: }
12373:
12374: sub default_login_domain {
12375: my $domain = $perlvar{'lonDefDomain'};
12376: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
12377: foreach my $posdom (¤t_machine_domains(),
12378: &additional_machine_domains()) {
12379: if (lc($posdom) eq lc($testdomain)) {
12380: $domain=$posdom;
12381: last;
12382: }
12383: }
12384: return $domain;
12385: }
12386:
1.31 www 12387: # ------------------------------------------------------------- Declutters URLs
12388:
12389: sub declutter {
12390: my $thisfn=shift;
1.569 albertel 12391: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1261 raeburn 12392: unless ($thisfn=~m{^/home/httpd/html/priv/}) {
12393: $thisfn=~s{^/home/httpd/html}{};
12394: }
1.31 www 12395: $thisfn=~s/^\///;
1.697 albertel 12396: $thisfn=~s|^adm/wrapper/||;
12397: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 12398: $thisfn=~s/^res\///;
1.1172 bisitz 12399: $thisfn=~s/^priv\///;
1.1032 raeburn 12400: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
12401: $thisfn=~s/\?.+$//;
12402: }
1.268 www 12403: return $thisfn;
12404: }
12405:
12406: # ------------------------------------------------------------- Clutter up URLs
12407:
12408: sub clutter {
12409: my $thisfn='/'.&declutter(shift);
1.887 albertel 12410: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 12411: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 12412: $thisfn='/res'.$thisfn;
12413: }
1.1031 raeburn 12414: if ($thisfn !~m|^/adm|) {
12415: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 12416: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 12417: } else {
12418: my ($ext) = ($thisfn =~ /\.(\w+)$/);
12419: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 12420: if ($embstyle eq 'ssi'
12421: || ($embstyle eq 'hdn')
12422: || ($embstyle eq 'rat')
12423: || ($embstyle eq 'prv')
12424: || ($embstyle eq 'ign')) {
12425: #do nothing with these
12426: } elsif (($embstyle eq 'img')
1.695 albertel 12427: || ($embstyle eq 'emb')
12428: || ($embstyle eq 'wrp')) {
12429: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 12430: } elsif ($embstyle eq 'unk'
12431: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 12432: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 12433: } else {
1.718 www 12434: # &logthis("Got a blank emb style");
1.695 albertel 12435: }
1.694 albertel 12436: }
1.1298 raeburn 12437: } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/exttools?$}) {
12438: $thisfn='/adm/wrapper'.$thisfn;
1.694 albertel 12439: }
1.31 www 12440: return $thisfn;
1.12 www 12441: }
12442:
1.787 albertel 12443: sub clutter_with_no_wrapper {
12444: my $uri = &clutter(shift);
12445: if ($uri =~ m-^/adm/-) {
12446: $uri =~ s-^/adm/wrapper/-/-;
12447: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
12448: }
12449: return $uri;
12450: }
12451:
1.557 albertel 12452: sub freeze_escape {
12453: my ($value)=@_;
12454: if (ref($value)) {
12455: $value=&nfreeze($value);
12456: return '__FROZEN__'.&escape($value);
12457: }
12458: return &escape($value);
12459: }
12460:
1.11 www 12461:
1.557 albertel 12462: sub thaw_unescape {
12463: my ($value)=@_;
12464: if ($value =~ /^__FROZEN__/) {
12465: substr($value,0,10,undef);
12466: $value=&unescape($value);
12467: return &thaw($value);
12468: }
12469: return &unescape($value);
12470: }
12471:
1.436 albertel 12472: sub correct_line_ends {
12473: my ($result)=@_;
12474: $$result =~s/\r\n/\n/mg;
12475: $$result =~s/\r/\n/mg;
1.415 albertel 12476: }
1.1 albertel 12477: # ================================================================ Main Program
12478:
1.184 www 12479: sub goodbye {
1.204 albertel 12480: &logthis("Starting Shut down");
1.443 albertel 12481: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 12482: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 12483: #converted
1.599 albertel 12484: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 12485: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
12486: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
12487: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 12488: #1.1 only
1.870 albertel 12489: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
12490: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
12491: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
12492: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
12493: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 12494: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
12495: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 12496: &flushcourselogs();
12497: &logthis("Shutting down");
12498: }
12499:
1.852 albertel 12500: sub get_dns {
1.1210 raeburn 12501: my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869 albertel 12502: if (!$ignore_cache) {
12503: my ($content,$cached)=
12504: &Apache::lonnet::is_cached_new('dns',$url);
12505: if ($cached) {
1.1210 raeburn 12506: &$func($content,$hashref);
1.869 albertel 12507: return;
12508: }
12509: }
12510:
12511: my %alldns;
1.852 albertel 12512: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
12513: foreach my $dns (<$config>) {
12514: next if ($dns !~ /^\^(\S*)/x);
1.979 raeburn 12515: my $line = $1;
12516: my ($host,$protocol) = split(/:/,$line);
12517: if ($protocol ne 'https') {
12518: $protocol = 'http';
12519: }
12520: $alldns{$host} = $protocol;
1.869 albertel 12521: }
12522: while (%alldns) {
1.1263 raeburn 12523: my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852 albertel 12524: my $ua=new LWP::UserAgent;
1.1134 raeburn 12525: $ua->timeout(30);
1.979 raeburn 12526: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 12527: my $response=$ua->request($request);
1.979 raeburn 12528: delete($alldns{$dns});
1.852 albertel 12529: next if ($response->is_error());
12530: my @content = split("\n",$response->content);
1.1210 raeburn 12531: unless ($nocache) {
1.1219 raeburn 12532: &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1210 raeburn 12533: }
12534: &$func(\@content,$hashref);
1.869 albertel 12535: return;
1.852 albertel 12536: }
12537: close($config);
1.871 albertel 12538: my $which = (split('/',$url))[3];
12539: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
12540: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 12541: my @content = <$config>;
1.1210 raeburn 12542: &$func(\@content,$hashref);
12543: return;
12544: }
12545:
12546: # ------------------------------------------------------Get DNS checksums file
1.1211 raeburn 12547: sub parse_dns_checksums_tab {
1.1210 raeburn 12548: my ($lines,$hashref) = @_;
1.1264 raeburn 12549: my $lonhost = $perlvar{'lonHostID'};
12550: my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1210 raeburn 12551: my $loncaparev = &get_server_loncaparev($machine_dom);
1.1264 raeburn 12552: my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
12553: my $webconfdir = '/etc/httpd/conf';
12554: if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
12555: $webconfdir = '/etc/apache2';
12556: } elsif ($distro =~ /^sles(\d+)$/) {
12557: if ($1 >= 10) {
12558: $webconfdir = '/etc/apache2';
12559: }
12560: } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
12561: if ($1 >= 10.0) {
12562: $webconfdir = '/etc/apache2';
12563: }
12564: }
1.1210 raeburn 12565: my ($release,$timestamp) = split(/\-/,$loncaparev);
12566: my (%chksum,%revnum);
12567: if (ref($lines) eq 'ARRAY') {
12568: chomp(@{$lines});
1.1238 raeburn 12569: my $version = shift(@{$lines});
12570: if ($version eq $release) {
1.1210 raeburn 12571: foreach my $line (@{$lines}) {
1.1238 raeburn 12572: my ($file,$version,$shasum) = split(/,/,$line);
1.1264 raeburn 12573: if ($file =~ m{^/etc/httpd/conf}) {
12574: if ($webconfdir eq '/etc/apache2') {
12575: $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
12576: }
12577: }
1.1238 raeburn 12578: $chksum{$file} = $shasum;
12579: $revnum{$file} = $version;
1.1210 raeburn 12580: }
12581: if (ref($hashref) eq 'HASH') {
12582: %{$hashref} = (
12583: sums => \%chksum,
12584: versions => \%revnum,
12585: );
12586: }
12587: }
12588: }
1.869 albertel 12589: return;
1.852 albertel 12590: }
1.1210 raeburn 12591:
12592: sub fetch_dns_checksums {
1.1238 raeburn 12593: my %checksums;
12594: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1260 raeburn 12595: my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1238 raeburn 12596: my ($release,$timestamp) = split(/\-/,$loncaparev);
12597: &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1211 raeburn 12598: \%checksums);
1.1210 raeburn 12599: return \%checksums;
12600: }
12601:
1.327 albertel 12602: # ------------------------------------------------------------ Read domain file
12603: {
1.852 albertel 12604: my $loaded;
1.846 albertel 12605: my %domain;
12606:
1.852 albertel 12607: sub parse_domain_tab {
12608: my ($lines) = @_;
12609: foreach my $line (@$lines) {
12610: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 12611:
1.846 albertel 12612: chomp($line);
1.852 albertel 12613: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 12614: my %this_domain;
12615: foreach my $field ('description', 'auth_def', 'auth_arg_def',
12616: 'lang_def', 'city', 'longi', 'lati',
12617: 'primary') {
12618: $this_domain{$field} = shift(@elements);
12619: }
12620: $domain{$name} = \%this_domain;
1.852 albertel 12621: }
12622: }
1.864 albertel 12623:
12624: sub reset_domain_info {
12625: undef($loaded);
12626: undef(%domain);
12627: }
12628:
1.852 albertel 12629: sub load_domain_tab {
1.1293 raeburn 12630: my ($ignore_cache,$nocache) = @_;
12631: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852 albertel 12632: my $fh;
12633: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
12634: my @lines = <$fh>;
12635: &parse_domain_tab(\@lines);
1.448 albertel 12636: }
1.852 albertel 12637: close($fh);
12638: $loaded = 1;
1.327 albertel 12639: }
1.846 albertel 12640:
12641: sub domain {
1.852 albertel 12642: &load_domain_tab() if (!$loaded);
12643:
1.846 albertel 12644: my ($name,$what) = @_;
12645: return if ( !exists($domain{$name}) );
12646:
12647: if (!$what) {
12648: return $domain{$name}{'description'};
12649: }
12650: return $domain{$name}{$what};
12651: }
1.974 raeburn 12652:
12653: sub domain_info {
12654: &load_domain_tab() if (!$loaded);
12655: return %domain;
12656: }
12657:
1.327 albertel 12658: }
12659:
12660:
1.1 albertel 12661: # ------------------------------------------------------------- Read hosts file
12662: {
1.838 albertel 12663: my %hostname;
1.844 albertel 12664: my %hostdom;
1.845 albertel 12665: my %libserv;
1.852 albertel 12666: my $loaded;
1.888 albertel 12667: my %name_to_host;
1.1074 raeburn 12668: my %internetdom;
1.1107 raeburn 12669: my %LC_dns_serv;
1.852 albertel 12670:
12671: sub parse_hosts_tab {
12672: my ($file) = @_;
12673: foreach my $configline (@$file) {
12674: next if ($configline =~ /^(\#|\s*$ )/x);
1.1107 raeburn 12675: chomp($configline);
12676: if ($configline =~ /^\^/) {
12677: if ($configline =~ /^\^([\w.\-]+)/) {
12678: $LC_dns_serv{$1} = 1;
12679: }
12680: next;
12681: }
1.1074 raeburn 12682: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 12683: $name=~s/\s//g;
12684: if ($id && $domain && $role && $name) {
12685: $hostname{$id}=$name;
1.888 albertel 12686: push(@{$name_to_host{$name}}, $id);
1.852 albertel 12687: $hostdom{$id}=$domain;
12688: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 12689: if (defined($protocol)) {
12690: if ($protocol eq 'https') {
12691: $protocol{$id} = $protocol;
12692: } else {
12693: $protocol{$id} = 'http';
12694: }
1.968 raeburn 12695: } else {
1.969 raeburn 12696: $protocol{$id} = 'http';
1.968 raeburn 12697: }
1.1074 raeburn 12698: if (defined($intdom)) {
12699: $internetdom{$id} = $intdom;
12700: }
1.852 albertel 12701: }
12702: }
12703: }
1.864 albertel 12704:
12705: sub reset_hosts_info {
1.897 albertel 12706: &purge_remembered();
1.864 albertel 12707: &reset_domain_info();
12708: &reset_hosts_ip_info();
1.892 albertel 12709: undef(%name_to_host);
1.864 albertel 12710: undef(%hostname);
12711: undef(%hostdom);
12712: undef(%libserv);
12713: undef($loaded);
12714: }
1.1 albertel 12715:
1.852 albertel 12716: sub load_hosts_tab {
1.1293 raeburn 12717: my ($ignore_cache,$nocache) = @_;
12718: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.852 albertel 12719: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
12720: my @config = <$config>;
12721: &parse_hosts_tab(\@config);
12722: close($config);
12723: $loaded=1;
1.1 albertel 12724: }
1.852 albertel 12725:
1.838 albertel 12726: sub hostname {
1.852 albertel 12727: &load_hosts_tab() if (!$loaded);
12728:
1.838 albertel 12729: my ($lonid) = @_;
12730: return $hostname{$lonid};
12731: }
1.845 albertel 12732:
1.838 albertel 12733: sub all_hostnames {
1.852 albertel 12734: &load_hosts_tab() if (!$loaded);
12735:
1.838 albertel 12736: return %hostname;
12737: }
1.845 albertel 12738:
1.888 albertel 12739: sub all_names {
1.1293 raeburn 12740: my ($ignore_cache,$nocache) = @_;
12741: &load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888 albertel 12742:
12743: return %name_to_host;
12744: }
12745:
1.974 raeburn 12746: sub all_host_domain {
12747: &load_hosts_tab() if (!$loaded);
12748: return %hostdom;
12749: }
12750:
1.845 albertel 12751: sub is_library {
1.852 albertel 12752: &load_hosts_tab() if (!$loaded);
12753:
1.845 albertel 12754: return exists($libserv{$_[0]});
12755: }
12756:
12757: sub all_library {
1.852 albertel 12758: &load_hosts_tab() if (!$loaded);
12759:
1.845 albertel 12760: return %libserv;
12761: }
12762:
1.1062 droeschl 12763: sub unique_library {
12764: #2x reverse removes all hostnames that appear more than once
12765: my %unique = reverse &all_library();
12766: return reverse %unique;
12767: }
12768:
1.841 albertel 12769: sub get_servers {
1.852 albertel 12770: &load_hosts_tab() if (!$loaded);
12771:
1.841 albertel 12772: my ($domain,$type) = @_;
12773: my %possible_hosts = ($type eq 'library') ? %libserv
12774: : %hostname;
12775: my %result;
1.842 albertel 12776: if (ref($domain) eq 'ARRAY') {
12777: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 12778: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 12779: $result{$host} = $hostname;
12780: }
12781: }
12782: } else {
12783: while ( my ($host,$hostname) = each(%possible_hosts)) {
12784: if ($hostdom{$host} eq $domain) {
12785: $result{$host} = $hostname;
12786: }
1.841 albertel 12787: }
12788: }
12789: return %result;
12790: }
1.845 albertel 12791:
1.1062 droeschl 12792: sub get_unique_servers {
12793: my %unique = reverse &get_servers(@_);
12794: return reverse %unique;
12795: }
12796:
1.844 albertel 12797: sub host_domain {
1.852 albertel 12798: &load_hosts_tab() if (!$loaded);
12799:
1.844 albertel 12800: my ($lonid) = @_;
12801: return $hostdom{$lonid};
12802: }
12803:
1.841 albertel 12804: sub all_domains {
1.852 albertel 12805: &load_hosts_tab() if (!$loaded);
12806:
1.841 albertel 12807: my %seen;
12808: my @uniq = grep(!$seen{$_}++, values(%hostdom));
12809: return @uniq;
12810: }
1.1074 raeburn 12811:
12812: sub internet_dom {
12813: &load_hosts_tab() if (!$loaded);
12814:
12815: my ($lonid) = @_;
12816: return $internetdom{$lonid};
12817: }
1.1107 raeburn 12818:
12819: sub is_LC_dns {
12820: &load_hosts_tab() if (!$loaded);
12821:
12822: my ($hostname) = @_;
12823: return exists($LC_dns_serv{$hostname});
12824: }
12825:
1.1 albertel 12826: }
12827:
1.847 albertel 12828: {
12829: my %iphost;
1.856 albertel 12830: my %name_to_ip;
12831: my %lonid_to_ip;
1.869 albertel 12832:
1.847 albertel 12833: sub get_hosts_from_ip {
12834: my ($ip) = @_;
12835: my %iphosts = &get_iphost();
12836: if (ref($iphosts{$ip})) {
12837: return @{$iphosts{$ip}};
12838: }
12839: return;
1.839 albertel 12840: }
1.864 albertel 12841:
12842: sub reset_hosts_ip_info {
12843: undef(%iphost);
12844: undef(%name_to_ip);
12845: undef(%lonid_to_ip);
12846: }
1.856 albertel 12847:
12848: sub get_host_ip {
12849: my ($lonid) = @_;
12850: if (exists($lonid_to_ip{$lonid})) {
12851: return $lonid_to_ip{$lonid};
12852: }
12853: my $name=&hostname($lonid);
12854: my $ip = gethostbyname($name);
12855: return if (!$ip || length($ip) ne 4);
12856: $ip=inet_ntoa($ip);
12857: $name_to_ip{$name} = $ip;
12858: $lonid_to_ip{$lonid} = $ip;
12859: return $ip;
12860: }
1.847 albertel 12861:
12862: sub get_iphost {
1.1293 raeburn 12863: my ($ignore_cache,$nocache) = @_;
1.894 albertel 12864:
1.869 albertel 12865: if (!$ignore_cache) {
12866: if (%iphost) {
12867: return %iphost;
12868: }
12869: my ($ip_info,$cached)=
12870: &Apache::lonnet::is_cached_new('iphost','iphost');
12871: if ($cached) {
12872: %iphost = %{$ip_info->[0]};
12873: %name_to_ip = %{$ip_info->[1]};
12874: %lonid_to_ip = %{$ip_info->[2]};
12875: return %iphost;
12876: }
12877: }
1.894 albertel 12878:
12879: # get yesterday's info for fallback
12880: my %old_name_to_ip;
12881: my ($ip_info,$cached)=
12882: &Apache::lonnet::is_cached_new('iphost','iphost');
12883: if ($cached) {
12884: %old_name_to_ip = %{$ip_info->[1]};
12885: }
12886:
1.1293 raeburn 12887: my %name_to_host = &all_names($ignore_cache,$nocache);
1.888 albertel 12888: foreach my $name (keys(%name_to_host)) {
1.847 albertel 12889: my $ip;
12890: if (!exists($name_to_ip{$name})) {
12891: $ip = gethostbyname($name);
12892: if (!$ip || length($ip) ne 4) {
1.894 albertel 12893: if (defined($old_name_to_ip{$name})) {
12894: $ip = $old_name_to_ip{$name};
12895: &logthis("Can't find $name defaulting to old $ip");
12896: } else {
12897: &logthis("Name $name no IP found");
12898: next;
12899: }
12900: } else {
12901: $ip=inet_ntoa($ip);
1.847 albertel 12902: }
12903: $name_to_ip{$name} = $ip;
12904: } else {
12905: $ip = $name_to_ip{$name};
1.653 albertel 12906: }
1.888 albertel 12907: foreach my $id (@{ $name_to_host{$name} }) {
12908: $lonid_to_ip{$id} = $ip;
12909: }
12910: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 12911: }
1.1293 raeburn 12912: unless ($nocache) {
12913: &do_cache_new('iphost','iphost',
12914: [\%iphost,\%name_to_ip,\%lonid_to_ip],
12915: 48*60*60);
12916: }
1.869 albertel 12917:
1.847 albertel 12918: return %iphost;
1.598 albertel 12919: }
12920:
1.992 raeburn 12921: #
12922: # Given a DNS returns the loncapa host name for that DNS
12923: #
12924: sub host_from_dns {
12925: my ($dns) = @_;
12926: my @hosts;
12927: my $ip;
12928:
1.993 raeburn 12929: if (exists($name_to_ip{$dns})) {
1.992 raeburn 12930: $ip = $name_to_ip{$dns};
12931: }
12932: if (!$ip) {
12933: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
12934: if (length($ip) == 4) {
12935: $ip = &IO::Socket::inet_ntoa($ip);
12936: }
12937: }
12938: if ($ip) {
12939: @hosts = get_hosts_from_ip($ip);
12940: return $hosts[0];
12941: }
12942: return undef;
1.986 foxr 12943: }
1.992 raeburn 12944:
1.1074 raeburn 12945: sub get_internet_names {
12946: my ($lonid) = @_;
12947: return if ($lonid eq '');
12948: my ($idnref,$cached)=
12949: &Apache::lonnet::is_cached_new('internetnames',$lonid);
12950: if ($cached) {
12951: return $idnref;
12952: }
12953: my $ip = &get_host_ip($lonid);
12954: my @hosts = &get_hosts_from_ip($ip);
12955: my %iphost = &get_iphost();
12956: my (@idns,%seen);
12957: foreach my $id (@hosts) {
12958: my $dom = &host_domain($id);
12959: my $prim_id = &domain($dom,'primary');
12960: my $prim_ip = &get_host_ip($prim_id);
12961: next if ($seen{$prim_ip});
12962: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
12963: foreach my $id (@{$iphost{$prim_ip}}) {
12964: my $intdom = &internet_dom($id);
12965: unless (grep(/^\Q$intdom\E$/,@idns)) {
12966: push(@idns,$intdom);
12967: }
12968: }
12969: }
12970: $seen{$prim_ip} = 1;
12971: }
1.1219 raeburn 12972: return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074 raeburn 12973: }
12974:
1.986 foxr 12975: }
12976:
1.1079 raeburn 12977: sub all_loncaparevs {
1.1249 raeburn 12978: 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 12979: }
12980:
1.1227 raeburn 12981: # ---------------------------------------------------------- Read loncaparev table
12982: {
12983: sub load_loncaparevs {
12984: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
12985: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
12986: while (my $configline=<$config>) {
12987: chomp($configline);
12988: my ($hostid,$loncaparev)=split(/:/,$configline);
12989: $loncaparevs{$hostid}=$loncaparev;
12990: }
12991: close($config);
12992: }
12993: }
12994: }
12995: }
12996:
12997: # ---------------------------------------------------------- Read serverhostID table
12998: {
12999: sub load_serverhomeIDs {
13000: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
13001: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
13002: while (my $configline=<$config>) {
13003: chomp($configline);
13004: my ($name,$id)=split(/:/,$configline);
13005: $serverhomeIDs{$name}=$id;
13006: }
13007: close($config);
13008: }
13009: }
13010: }
13011: }
13012:
13013:
1.862 albertel 13014: BEGIN {
13015:
13016: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
13017: unless ($readit) {
13018: {
13019: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
13020: %perlvar = (%perlvar,%{$configvars});
13021: }
13022:
13023:
1.1 albertel 13024: # ------------------------------------------------------ Read spare server file
13025: {
1.448 albertel 13026: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 13027:
13028: while (my $configline=<$config>) {
13029: chomp($configline);
1.284 matthew 13030: if ($configline) {
1.784 albertel 13031: my ($host,$type) = split(':',$configline,2);
1.785 albertel 13032: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 13033: push(@{ $spareid{$type} }, $host);
1.1 albertel 13034: }
13035: }
1.448 albertel 13036: close($config);
1.1 albertel 13037: }
1.11 www 13038: # ------------------------------------------------------------ Read permissions
13039: {
1.448 albertel 13040: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 13041:
13042: while (my $configline=<$config>) {
1.448 albertel 13043: chomp($configline);
13044: if ($configline) {
13045: my ($role,$perm)=split(/ /,$configline);
13046: if ($perm ne '') { $pr{$role}=$perm; }
13047: }
1.11 www 13048: }
1.448 albertel 13049: close($config);
1.11 www 13050: }
13051:
13052: # -------------------------------------------- Read plain texts for permissions
13053: {
1.448 albertel 13054: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 13055:
13056: while (my $configline=<$config>) {
1.448 albertel 13057: chomp($configline);
13058: if ($configline) {
1.742 raeburn 13059: my ($short,@plain)=split(/:/,$configline);
13060: %{$prp{$short}} = ();
13061: if (@plain > 0) {
13062: $prp{$short}{'std'} = $plain[0];
13063: for (my $i=1; $i<@plain; $i++) {
13064: $prp{$short}{'alt'.$i} = $plain[$i];
13065: }
13066: }
1.448 albertel 13067: }
1.135 www 13068: }
1.448 albertel 13069: close($config);
1.135 www 13070: }
13071:
13072: # ---------------------------------------------------------- Read package table
13073: {
1.448 albertel 13074: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 13075:
13076: while (my $configline=<$config>) {
1.483 albertel 13077: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 13078: chomp($configline);
13079: my ($short,$plain)=split(/:/,$configline);
13080: my ($pack,$name)=split(/\&/,$short);
13081: if ($plain ne '') {
13082: $packagetab{$pack.'&'.$name.'&name'}=$name;
13083: $packagetab{$short}=$plain;
13084: }
1.11 www 13085: }
1.448 albertel 13086: close($config);
1.329 matthew 13087: }
13088:
1.1073 raeburn 13089: # ---------------------------------------------------------- Read loncaparev table
1.1227 raeburn 13090:
13091: &load_loncaparevs();
1.1073 raeburn 13092:
1.1074 raeburn 13093: # ---------------------------------------------------------- Read serverhostID table
13094:
1.1227 raeburn 13095: &load_serverhomeIDs();
13096:
13097: # ---------------------------------------------------------- Read releaseslist XML
1.1079 raeburn 13098: {
13099: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
13100: if (-e $file) {
13101: my $parser = HTML::LCParser->new($file);
13102: while (my $token = $parser->get_token()) {
13103: if ($token->[0] eq 'S') {
13104: my $item = $token->[1];
13105: my $name = $token->[2]{'name'};
13106: my $value = $token->[2]{'value'};
1.1285 raeburn 13107: my $valuematch = $token->[2]{'valuematch'};
1.1303 raeburn 13108: my $namematch = $token->[2]{'namematch'};
13109: if ($item eq 'parameter') {
13110: if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
13111: my $release = $parser->get_text();
13112: $release =~ s/(^\s*|\s*$ )//gx;
13113: $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
13114: }
13115: } elsif ($item ne '' && $name ne '') {
1.1079 raeburn 13116: my $release = $parser->get_text();
13117: $release =~ s/(^\s*|\s*$ )//gx;
1.1303 raeburn 13118: $needsrelease{$item.':'.$name.':'.$value} = $release;
1.1079 raeburn 13119: }
13120: }
13121: }
13122: }
1.1073 raeburn 13123: }
13124:
1.1138 raeburn 13125: # ---------------------------------------------------------- Read managers table
13126: {
13127: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
13128: if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
13129: while (my $configline=<$config>) {
13130: chomp($configline);
13131: next if ($configline =~ /^\#/);
13132: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
13133: $managerstab{$configline} = 1;
13134: }
13135: }
13136: close($config);
13137: }
13138: }
13139: }
13140:
1.329 matthew 13141: # ------------- set up temporary directory
13142: {
1.1117 foxr 13143: $tmpdir = LONCAPA::tempdir();
1.329 matthew 13144:
1.11 www 13145: }
13146:
1.794 albertel 13147: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
13148: 'compress_threshold'=> 20_000,
13149: });
1.185 www 13150:
1.281 www 13151: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 13152: $dumpcount=0;
1.958 www 13153: $locknum=0;
1.22 www 13154:
1.163 harris41 13155: &logtouch();
1.672 albertel 13156: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 13157: $readit=1;
1.564 albertel 13158: {
13159: use integer;
13160: my $test=(2**32)+1;
1.568 albertel 13161: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 13162: &logthis(" Detected 64bit platform ($_64bit)");
13163: }
1.195 www 13164: }
1.1 albertel 13165: }
1.179 www 13166:
1.1 albertel 13167: 1;
1.191 harris41 13168: __END__
13169:
1.243 albertel 13170: =pod
13171:
1.191 harris41 13172: =head1 NAME
13173:
1.243 albertel 13174: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 13175:
13176: =head1 SYNOPSIS
13177:
1.243 albertel 13178: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 13179:
13180: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
13181:
1.243 albertel 13182: Common parameters:
13183:
13184: =over 4
13185:
13186: =item *
13187:
13188: $uname : an internal username (if $cname expecting a course Id specifically)
13189:
13190: =item *
13191:
13192: $udom : a domain (if $cdom expecting a course's domain specifically)
13193:
13194: =item *
13195:
13196: $symb : a resource instance identifier
13197:
13198: =item *
13199:
13200: $namespace : the name of a .db file that contains the data needed or
13201: being set.
13202:
13203: =back
13204:
1.394 bowersj2 13205: =head1 OVERVIEW
1.191 harris41 13206:
1.394 bowersj2 13207: lonnet provides subroutines which interact with the
13208: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
13209: about classes, users, and resources.
1.243 albertel 13210:
13211: For many of these objects you can also use this to store data about
13212: them or modify them in various ways.
1.191 harris41 13213:
1.394 bowersj2 13214: =head2 Symbs
1.191 harris41 13215:
1.394 bowersj2 13216: To identify a specific instance of a resource, LON-CAPA uses symbols
13217: or "symbs"X<symb>. These identifiers are built from the URL of the
13218: map, the resource number of the resource in the map, and the URL of
13219: the resource itself. The latter is somewhat redundant, but might help
13220: if maps change.
13221:
13222: An example is
13223:
13224: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
13225:
13226: The respective map entry is
13227:
13228: <resource id="19" src="/res/msu/korte/tests/part12.problem"
13229: title="Problem 2">
13230: </resource>
13231:
13232: Symbs are used by the random number generator, as well as to store and
13233: restore data specific to a certain instance of for example a problem.
13234:
13235: =head2 Storing And Retrieving Data
13236:
13237: X<store()>X<cstore()>X<restore()>Three of the most important functions
13238: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
13239: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
13240: is is the non-critical message twin of cstore. These functions are for
13241: handlers to store a perl hash to a user's permanent data space in an
13242: easy manner, and to retrieve it again on another call. It is expected
13243: that a handler would use this once at the beginning to retrieve data,
13244: and then again once at the end to send only the new data back.
13245:
13246: The data is stored in the user's data directory on the user's
13247: homeserver under the ID of the course.
13248:
13249: The hash that is returned by restore will have all of the previous
13250: value for all of the elements of the hash.
13251:
13252: Example:
13253:
13254: #creating a hash
13255: my %hash;
13256: $hash{'foo'}='bar';
13257:
13258: #storing it
13259: &Apache::lonnet::cstore(\%hash);
13260:
13261: #changing a value
13262: $hash{'foo'}='notbar';
13263:
13264: #adding a new value
13265: $hash{'bar'}='foo';
13266: &Apache::lonnet::cstore(\%hash);
13267:
13268: #retrieving the hash
13269: my %history=&Apache::lonnet::restore();
13270:
13271: #print the hash
13272: foreach my $key (sort(keys(%history))) {
13273: print("\%history{$key} = $history{$key}");
13274: }
13275:
13276: Will print out:
1.191 harris41 13277:
1.394 bowersj2 13278: %history{1:foo} = bar
13279: %history{1:keys} = foo:timestamp
13280: %history{1:timestamp} = 990455579
13281: %history{2:bar} = foo
13282: %history{2:foo} = notbar
13283: %history{2:keys} = foo:bar:timestamp
13284: %history{2:timestamp} = 990455580
13285: %history{bar} = foo
13286: %history{foo} = notbar
13287: %history{timestamp} = 990455580
13288: %history{version} = 2
13289:
13290: Note that the special hash entries C<keys>, C<version> and
13291: C<timestamp> were added to the hash. C<version> will be equal to the
13292: total number of versions of the data that have been stored. The
13293: C<timestamp> attribute will be the UNIX time the hash was
13294: stored. C<keys> is available in every historical section to list which
13295: keys were added or changed at a specific historical revision of a
13296: hash.
13297:
13298: B<Warning>: do not store the hash that restore returns directly. This
13299: will cause a mess since it will restore the historical keys as if the
13300: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 13301:
1.394 bowersj2 13302: Calling convention:
1.191 harris41 13303:
1.1225 raeburn 13304: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1269 raeburn 13305: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191 harris41 13306:
1.394 bowersj2 13307: For more detailed information, see lonnet specific documentation.
1.191 harris41 13308:
1.394 bowersj2 13309: =head1 RETURN MESSAGES
1.191 harris41 13310:
1.394 bowersj2 13311: =over 4
1.191 harris41 13312:
1.394 bowersj2 13313: =item * B<con_lost>: unable to contact remote host
1.191 harris41 13314:
1.394 bowersj2 13315: =item * B<con_delayed>: unable to contact remote host, message will be delivered
13316: when the connection is brought back up
1.191 harris41 13317:
1.394 bowersj2 13318: =item * B<con_failed>: unable to contact remote host and unable to save message
13319: for later delivery
1.191 harris41 13320:
1.967 bisitz 13321: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 13322:
1.394 bowersj2 13323: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 13324: that was requested
1.191 harris41 13325:
1.243 albertel 13326: =back
1.191 harris41 13327:
1.243 albertel 13328: =head1 PUBLIC SUBROUTINES
1.191 harris41 13329:
1.243 albertel 13330: =head2 Session Environment Functions
1.191 harris41 13331:
1.243 albertel 13332: =over 4
1.191 harris41 13333:
1.394 bowersj2 13334: =item *
13335: X<appenv()>
1.949 raeburn 13336: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 13337: the user envirnoment file, and will be restored for each access this
1.620 albertel 13338: user makes during this session, also modifies the %env for the current
1.949 raeburn 13339: process. Optional rolesarrayref - if defined contains a reference to an array
13340: of roles which are exempt from the restriction on modifying user.role entries
13341: in the user's environment.db and in %env.
1.191 harris41 13342:
13343: =item *
1.394 bowersj2 13344: X<delenv()>
1.987 raeburn 13345: B<delenv($delthis,$regexp)>: removes all items from the session
13346: environment file that begin with $delthis. If the
13347: optional second arg - $regexp - is true, $delthis is treated as a
13348: regular expression, otherwise \Q$delthis\E is used.
13349: The values are also deleted from the current processes %env.
1.191 harris41 13350:
1.795 albertel 13351: =item * get_env_multiple($name)
13352:
13353: gets $name from the %env hash, it seemlessly handles the cases where multiple
13354: values may be defined and end up as an array ref.
13355:
13356: returns an array of values
13357:
1.243 albertel 13358: =back
13359:
13360: =head2 User Information
1.191 harris41 13361:
1.243 albertel 13362: =over 4
1.191 harris41 13363:
13364: =item *
1.394 bowersj2 13365: X<queryauthenticate()>
13366: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 13367: authentication scheme
13368:
13369: =item *
1.394 bowersj2 13370: X<authenticate()>
1.1073 raeburn 13371: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 13372: authenticate user from domain's lib servers (first use the current
13373: one). C<$upass> should be the users password.
1.1073 raeburn 13374: $checkdefauth is optional (value is 1 if a check should be made to
13375: authenticate user using default authentication method, and allow
13376: account creation if username does not have account in the domain).
13377: $clientcancheckhost is optional (value is 1 if checking whether the
13378: server can host will occur on the client side in lonauth.pm).
1.191 harris41 13379:
13380: =item *
1.394 bowersj2 13381: X<homeserver()>
13382: B<homeserver($uname,$udom)>: find the server which has
13383: the user's directory and files (there must be only one), this caches
13384: the answer, and also caches if there is a borken connection.
1.191 harris41 13385:
13386: =item *
1.394 bowersj2 13387: X<idget()>
1.1300 raeburn 13388: B<idget($udom,$idsref,$namespace)>: find the usernames behind either
13389: a list of student/employee IDs or clicker IDs
13390: (student/employee IDs are a unique resource in a domain, there must be
13391: only 1 ID per username, and only 1 username per ID in a specific domain).
13392: clickerIDs are not necessarily unique, as students might share clickers.
13393: (returns hash: id=>name,id=>name)
1.191 harris41 13394:
13395: =item *
1.394 bowersj2 13396: X<idrget()>
13397: B<idrget($udom,@unames)>: find the IDs behind a list of
13398: usernames (returns hash: name=>id,name=>id)
1.191 harris41 13399:
13400: =item *
1.394 bowersj2 13401: X<idput()>
1.1300 raeburn 13402: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of
13403: names and associated student/employee IDs or clicker IDs.
13404:
13405: =item *
13406: X<iddel()>
13407: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted
13408: student/employee ID or clicker ID username look-ups from domain.
13409: The homeserver ($uhome) and namespace ($namespace) are optional.
13410: If no $uhome is provided, it will be determined usig &homeserver()
13411: for each user. If no $namespace is provided, the default is ids.
13412:
13413: =item *
13414: X<updateclickers()>
13415: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update
13416: clicker ID-to-username look-ups in clickers.db on library server.
13417: Permitted actions are add or del (i.e., add or delete). The
13418: clickers.db contains clickerID as keys (escaped), and each corresponding
13419: value is an escaped comma-separated list of usernames (for whom the
13420: library server is the homeserver), who registered that particular ID.
13421: If $critical is true, the update will be sent via &critical, otherwise
13422: &reply() will be used.
1.191 harris41 13423:
13424: =item *
1.394 bowersj2 13425: X<rolesinit()>
1.1169 droeschl 13426: B<rolesinit($udom,$username)>: get user privileges.
13427: returns user role, first access and timer interval hashes
1.243 albertel 13428:
13429: =item *
1.1171 droeschl 13430: X<privileged()>
13431: B<privileged($username,$domain)>: returns a true if user has a
13432: privileged and active role (i.e. su or dc), false otherwise.
13433:
13434: =item *
1.551 albertel 13435: X<getsection()>
13436: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 13437: course $cname, return section name/number or '' for "not in course"
13438: and '-1' for "no section"
13439:
13440: =item *
1.394 bowersj2 13441: X<userenvironment()>
13442: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 13443: passed in @what from the requested user's environment, returns a hash
13444:
1.858 raeburn 13445: =item *
13446: X<userlog_query()>
1.859 albertel 13447: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
13448: activity.log file. %filters defines filters applied when parsing the
13449: log file. These can be start or end timestamps, or the type of action
13450: - log to look for Login or Logout events, check for Checkin or
13451: Checkout, role for role selection. The response is in the form
13452: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
13453: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 13454:
1.243 albertel 13455: =back
13456:
13457: =head2 User Roles
13458:
13459: =over 4
13460:
13461: =item *
13462:
1.1284 raeburn 13463: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege;
13464: returns codes for allowed actions.
13465:
13466: The first argument is required, all others are optional.
13467:
13468: $priv is the privilege being checked.
13469: $uri contains additional information about what is being checked for access (e.g.,
13470: URL, course ID etc.).
13471: $symb is the unique resource instance identifier in a course; if needed,
13472: but not provided, it will be retrieved via a call to &symbread().
13473: $role is the role for which a priv is being checked (only used if priv is evb).
13474: $clientip is the user's IP address (only used when checking for access to portfolio
13475: files).
13476: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
13477: prevents recursive calls to &allowed.
13478:
1.243 albertel 13479: F: full access
13480: U,I,K: authentication modes (cxx only)
13481: '': forbidden
13482: 1: user needs to choose course
13483: 2: browse allowed
1.766 albertel 13484: A: passphrase authentication needed
1.1284 raeburn 13485: B: access temporarily blocked because of a blocking event in a course.
1.243 albertel 13486:
13487: =item *
13488:
1.1192 raeburn 13489: constructaccess($url,$setpriv) : check for access to construction space URL
13490:
13491: See if the owner domain and name in the URL match those in the
13492: expected environment. If so, return three element list
13493: ($ownername,$ownerdomain,$ownerhome).
13494:
13495: Otherwise return the null string.
13496:
13497: If second argument 'setpriv' is true, it assigns the privileges,
13498: and returns the same three element list, unless the owner has
13499: blocked "ad hoc" Domain Coordinator access to the Author Space,
13500: in which case the null string is returned.
13501:
13502: =item *
13503:
1.243 albertel 13504: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
13505: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
13506: and course level
13507:
13508: =item *
13509:
1.988 raeburn 13510: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
13511: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 13512: $type is Course (default) or Community.
1.988 raeburn 13513: If $forcedefault evaluates to true, text returned will be default
13514: text for $type. Otherwise, if this is a course, the text returned
13515: will be a custom name for the role (if defined in the course's
13516: environment). If no custom name is defined the default is returned.
13517:
1.832 raeburn 13518: =item *
13519:
1.1219 raeburn 13520: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858 raeburn 13521: All arguments are optional. Returns a hash of a roles, either for
13522: co-author/assistant author roles for a user's Construction Space
1.906 albertel 13523: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 13524: In the hash, keys are set to colon-separated $uname,$udom,$role, and
13525: (optionally) if $withsec is true, a fourth colon-separated item - $section.
13526: For each key, value is set to colon-separated start and end times for
13527: the role. If no username and domain are specified, will default to
1.934 raeburn 13528: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 13529: of role statuses (active, future or previous), roles
13530: (e.g., cc,in, st etc.) and domains of the roles which can be used
13531: to restrict the list of roles reported. If no array ref is
13532: provided for types, will default to return only active roles.
1.834 albertel 13533:
1.1195 raeburn 13534: =item *
13535:
13536: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196 raeburn 13537: user: $uname:$udom has a role in the course: $cdom_$cnum.
13538:
13539: Additional optional arguments are: $type (if role checking is to be restricted
13540: to certain user status types -- previous (expired roles), active (currently
1.1195 raeburn 13541: available roles) or future (roles available in the future), and
13542: $hideprivileged -- if true will not report course roles for users who
1.1219 raeburn 13543: have active Domain Coordinator role in course's domain or in additional
13544: domains (specified in 'Domains to check for privileged users' in course
13545: environment -- set via: Course Settings -> Classlists and staff listing).
13546:
13547: =item *
13548:
13549: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
13550: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
13551: $possdomains and $possroles are optional array refs -- to domains to check and
13552: roles to check. If $possdomains is not specified, a dump will be done of the
13553: users' roles.db to check for a dc or su role in any domain. This can be
13554: time consuming if &privileged is called repeatedly (e.g., when displaying a
13555: classlist), so in such cases, supplying a $possdomains array is preferred, as
13556: this then allows &privileged_by_domain() to be used, which caches the identity
13557: of privileged users, eliminating the need for repeated calls to &dump().
13558:
13559: =item *
13560:
13561: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
13562: where the outer hash keys are domains specified in the $possdomains array ref,
13563: next inner hash keys are privileged roles specified in the $roles array ref,
13564: and the innermost hash contains key = value pairs for username:domain = end:start
13565: for active or future "privileged" users with that role in that domain. To avoid
13566: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
13567: innerhash are cached using priv_$role and $dom as the identifiers.
1.1195 raeburn 13568:
1.243 albertel 13569: =back
13570:
13571: =head2 User Modification
13572:
13573: =over 4
13574:
13575: =item *
13576:
1.957 raeburn 13577: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 13578: user for the level given by URL. Optional start and end dates (leave empty
13579: string or zero for "no date")
1.191 harris41 13580:
13581: =item *
13582:
1.243 albertel 13583: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
13584: change a users, password, possible return values are: ok,
13585: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
13586: refused
1.191 harris41 13587:
13588: =item *
13589:
1.243 albertel 13590: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 13591:
13592: =item *
13593:
1.1058 raeburn 13594: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
13595: $forceid,$desiredhome,$email,$inststatus,$candelete) :
13596:
13597: will update user information (firstname,middlename,lastname,generation,
13598: permanentemail), and if forceid is true, student/employee ID also.
13599: A user's institutional affiliation(s) can also be updated.
13600: User information fields will not be overwritten with empty entries
13601: unless the field is included in the $candelete array reference.
13602: This array is included when a single user is modified via "Manage Users",
13603: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 13604:
13605: =item *
13606:
1.286 matthew 13607: modifystudent
13608:
1.957 raeburn 13609: modify a student's enrollment and identification information.
1.1235 raeburn 13610: The course id is resolved based on the current user's environment.
13611: This means the invoking user must be a course coordinator or otherwise
1.286 matthew 13612: associated with a course.
13613:
1.297 matthew 13614: This call is essentially a wrapper for lonnet::modifyuser and
13615: lonnet::modify_student_enrollment
1.286 matthew 13616:
13617: Inputs:
13618:
13619: =over 4
13620:
1.957 raeburn 13621: =item B<$udom> Student's loncapa domain
1.286 matthew 13622:
1.957 raeburn 13623: =item B<$uname> Student's loncapa login name
1.286 matthew 13624:
1.964 bisitz 13625: =item B<$uid> Student/Employee ID
1.286 matthew 13626:
1.957 raeburn 13627: =item B<$umode> Student's authentication mode
1.286 matthew 13628:
1.957 raeburn 13629: =item B<$upass> Student's password
1.286 matthew 13630:
1.957 raeburn 13631: =item B<$first> Student's first name
1.286 matthew 13632:
1.957 raeburn 13633: =item B<$middle> Student's middle name
1.286 matthew 13634:
1.957 raeburn 13635: =item B<$last> Student's last name
1.286 matthew 13636:
1.957 raeburn 13637: =item B<$gene> Student's generation
1.286 matthew 13638:
1.957 raeburn 13639: =item B<$usec> Student's section in course
1.286 matthew 13640:
13641: =item B<$end> Unix time of the roles expiration
13642:
13643: =item B<$start> Unix time of the roles start date
13644:
13645: =item B<$forceid> If defined, allow $uid to be changed
13646:
13647: =item B<$desiredhome> server to use as home server for student
13648:
1.957 raeburn 13649: =item B<$email> Student's permanent e-mail address
13650:
13651: =item B<$type> Type of enrollment (auto or manual)
13652:
1.963 raeburn 13653: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
13654:
13655: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 13656:
1.963 raeburn 13657: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 13658:
1.963 raeburn 13659: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 13660:
1.1216 raeburn 13661: =item B<$inststatus> institutional status of user - : separated string of escaped status types
13662:
13663: =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 13664:
1.286 matthew 13665: =back
1.297 matthew 13666:
13667: =item *
13668:
13669: modify_student_enrollment
13670:
1.1235 raeburn 13671: Change a student's enrollment status in a class. The environment variable
1.297 matthew 13672: 'role.request.course' must be defined for this function to proceed.
13673:
13674: Inputs:
13675:
13676: =over 4
13677:
1.1235 raeburn 13678: =item $udom, student's domain
1.297 matthew 13679:
1.1235 raeburn 13680: =item $uname, student's name
1.297 matthew 13681:
1.1235 raeburn 13682: =item $uid, student's user id
1.297 matthew 13683:
1.1235 raeburn 13684: =item $first, student's first name
1.297 matthew 13685:
13686: =item $middle
13687:
13688: =item $last
13689:
13690: =item $gene
13691:
13692: =item $usec
13693:
13694: =item $end
13695:
13696: =item $start
13697:
1.957 raeburn 13698: =item $type
13699:
13700: =item $locktype
13701:
13702: =item $cid
13703:
13704: =item $selfenroll
13705:
13706: =item $context
13707:
1.1216 raeburn 13708: =item $credits, number of credits student will earn from this class
13709:
1.297 matthew 13710: =back
13711:
1.191 harris41 13712:
13713: =item *
13714:
1.243 albertel 13715: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
13716: custom role; give a custom role to a user for the level given by URL. Specify
13717: name and domain of role author, and role name
1.191 harris41 13718:
13719: =item *
13720:
1.243 albertel 13721: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 13722:
13723: =item *
13724:
1.243 albertel 13725: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
13726:
13727: =back
13728:
13729: =head2 Course Infomation
13730:
13731: =over 4
1.191 harris41 13732:
13733: =item *
13734:
1.1118 foxr 13735: coursedescription($courseid,$options) : returns a hash of information about the
1.631 albertel 13736: specified course id, including all environment settings for the
13737: course, the description of the course will be in the hash under the
13738: key 'description'
1.191 harris41 13739:
1.1118 foxr 13740: $options is an optional parameter that if supplied is a hash reference that controls
13741: what how this function works. It has the following key/values:
13742:
13743: =over 4
13744:
13745: =item freshen_cache
13746:
13747: If defined, and the environment cache for the course is valid, it is
13748: returned in the returned hash.
13749:
13750: =item one_time
13751:
13752: If defined, the last cache time is set to _now_
13753:
13754: =item user
13755:
13756: If defined, the supplied username is used instead of the current user.
13757:
13758:
13759: =back
13760:
1.191 harris41 13761: =item *
13762:
1.624 albertel 13763: resdata($name,$domain,$type,@which) : request for current parameter
13764: setting for a specific $type, where $type is either 'course' or 'user',
13765: @what should be a list of parameters to ask about. This routine caches
1.1235 raeburn 13766: answers for 10 minutes.
1.243 albertel 13767:
1.877 foxr 13768: =item *
13769:
13770: get_courseresdata($courseid, $domain) : dump the entire course resource
13771: data base, returning a hash that is keyed by the resource name and has
13772: values that are the resource value. I believe that the timestamps and
13773: versions are also returned.
13774:
1.1236 raeburn 13775: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
13776: supplemental content area. This routine caches the number of files for
13777: 10 minutes.
13778:
1.243 albertel 13779: =back
13780:
13781: =head2 Course Modification
13782:
13783: =over 4
1.191 harris41 13784:
13785: =item *
13786:
1.243 albertel 13787: writecoursepref($courseid,%prefs) : write preferences (environment
13788: database) for a course
1.191 harris41 13789:
13790: =item *
13791:
1.1011 raeburn 13792: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
13793:
13794: =item *
13795:
1.1038 raeburn 13796: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 13797:
1.1167 droeschl 13798: =item *
13799:
13800: is_course($courseid), is_course($cdom, $cnum)
13801:
13802: Accepts either a combined $courseid (in the form of domain_courseid) or the
13803: two component version $cdom, $cnum. It checks if the specified course exists.
13804:
13805: Returns:
13806: undef if the course doesn't exist, otherwise
13807: in scalar context the combined courseid.
13808: in list context the two components of the course identifier, domain and
13809: courseid.
13810:
1.243 albertel 13811: =back
13812:
13813: =head2 Resource Subroutines
13814:
13815: =over 4
1.191 harris41 13816:
13817: =item *
13818:
1.243 albertel 13819: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 13820:
13821: =item *
13822:
1.243 albertel 13823: repcopy($filename) : subscribes to the requested file, and attempts to
13824: replicate from the owning library server, Might return
1.607 raeburn 13825: 'unavailable', 'not_found', 'forbidden', 'ok', or
13826: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 13827: resource. Expects the local filesystem pathname
13828: (/home/httpd/html/res/....)
13829:
13830: =back
13831:
13832: =head2 Resource Information
13833:
13834: =over 4
1.191 harris41 13835:
13836: =item *
13837:
1.1228 raeburn 13838: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates
13839: and returns the value of a variety of different possible values,
13840: $varname should be a request string, and the other parameters can be
13841: used to specify who and what one is asking about. Ordinarily, $cid
13842: does not need to be specified, as it is retrived from
13843: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
13844: within lonuserstate::loadmap() when initializing a course, before
13845: $env{'request.course.id'} has been set, so it needs to be provided
13846: in that one case.
1.243 albertel 13847:
13848: Possible values for $varname are environment.lastname (or other item
13849: from the envirnment hash), user.name (or someother aspect about the
13850: user), resource.0.maxtries (or some other part and parameter of a
13851: resource)
1.204 albertel 13852:
13853: =item *
13854:
1.243 albertel 13855: directcondval($number) : get current value of a condition; reads from a state
13856: string
1.204 albertel 13857:
13858: =item *
13859:
1.243 albertel 13860: condval($condidx) : value of condition index based on state
1.204 albertel 13861:
13862: =item *
13863:
1.243 albertel 13864: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
13865: resource's metadata, $what should be either a specific key, or either
13866: 'keys' (to get a list of possible keys) or 'packages' to get a list of
13867: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
13868:
13869: this function automatically caches all requests
1.191 harris41 13870:
13871: =item *
13872:
1.243 albertel 13873: metadata_query($query,$custom,$customshow) : make a metadata query against the
13874: network of library servers; returns file handle of where SQL and regex results
13875: will be stored for query
1.191 harris41 13876:
13877: =item *
13878:
1.1282 raeburn 13879: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
13880: return symbolic list entry (all arguments optional).
13881:
13882: Args: filename is the filename (including path) for the file for which a symb
13883: is required; donotrecurse, if true will prevent calls to allowed() being made
13884: to check access status if more than one resource was found in the bighash
13885: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
13886: a randompick); ignorecachednull, if true will prevent a symb of '' being
13887: returned if $env{$cache_str} is defined as ''; checkforblock if true will
13888: cause possible symbs to be checked to determine if they are subject to content
13889: blocking, if so they will not be included as possible symbs; possibles is a
13890: ref to a hash, which, as a side effect, will be populated with all possible
13891: symbs (content blocking not tested).
13892:
1.243 albertel 13893: returns the data handle
1.191 harris41 13894:
13895: =item *
13896:
1.1190 raeburn 13897: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
13898: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582 albertel 13899: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190 raeburn 13900: on failure, user must be in a course, as it assumes the existence of
13901: the course initial hash, and uses $env('request.course.id'}. The third
13902: arg is an optional reference to a scalar. If this arg is passed in the
13903: call to symbverify, it will be set to 1 if the symb has been set to be
13904: encrypted; otherwise it will be null.
1.191 harris41 13905:
13906: =item *
13907:
1.243 albertel 13908: symbclean($symb) : removes versions numbers from a symb, returns the
13909: cleaned symb
1.191 harris41 13910:
13911: =item *
13912:
1.243 albertel 13913: is_on_map($uri) : checks if the $uri is somewhere on the current
13914: course map, user must be in a course for it to work.
1.191 harris41 13915:
13916: =item *
13917:
1.243 albertel 13918: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 13919:
13920: =item *
13921:
1.243 albertel 13922: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
13923: a random seed, all arguments are optional, if they aren't sent it uses the
13924: environment to derive them. Note: if symb isn't sent and it can't get one
13925: from &symbread it will use the current time as its return value
1.191 harris41 13926:
13927: =item *
13928:
1.243 albertel 13929: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
13930: unfakeable, receipt
1.191 harris41 13931:
13932: =item *
13933:
1.620 albertel 13934: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 13935:
13936: =item *
13937:
1.243 albertel 13938: countacc($url) : count the number of accesses to a given URL
1.191 harris41 13939:
13940: =item *
13941:
1.243 albertel 13942: 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 13943:
13944: =item *
13945:
1.243 albertel 13946: 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 13947:
13948: =item *
13949:
1.243 albertel 13950: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 13951:
13952: =item *
13953:
1.243 albertel 13954: devalidate($symb) : devalidate temporary spreadsheet calculations,
13955: forcing spreadsheet to reevaluate the resource scores next time.
13956:
1.1195 raeburn 13957: =item *
13958:
1.1196 raeburn 13959: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
13960: when viewing in course context.
1.1195 raeburn 13961:
1.1196 raeburn 13962: input: six args -- filename (decluttered), course number, course domain,
13963: url, symb (if registered) and group (if this is a
13964: group item -- e.g., bulletin board, group page etc.).
1.1195 raeburn 13965:
1.1196 raeburn 13966: output: array of five scalars --
1.1195 raeburn 13967: $cfile -- url for file editing if editable on current server
13968: $home -- homeserver of resource (i.e., for author if published,
13969: or course if uploaded.).
13970: $switchserver -- 1 if server switch will be needed.
1.1196 raeburn 13971: $forceedit -- 1 if icon/link should be to go to edit mode
13972: $forceview -- 1 if icon/link should be to go to view mode
1.1195 raeburn 13973:
13974: =item *
13975:
13976: is_course_upload($file,$cnum,$cdom)
13977:
13978: Used in course context to determine if current file was uploaded to
13979: the course (i.e., would be found in /userfiles/docs on the course's
13980: homeserver.
13981:
13982: input: 3 args -- filename (decluttered), course number and course domain.
13983: output: boolean -- 1 if file was uploaded.
13984:
1.243 albertel 13985: =back
13986:
13987: =head2 Storing/Retreiving Data
13988:
13989: =over 4
1.191 harris41 13990:
13991: =item *
13992:
1.1269 raeburn 13993: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
13994: permanently for this url; hashref needs to be given and should be a \%hashname;
13995: the remaining args aren't required and if they aren't passed or are '' they will
13996: be derived from the env (with the exception of $laststore, which is an
13997: optional arg used when a user's submission is stored in grading).
13998: $laststore is $version=$timestamp, where $version is the most recent version
13999: number retrieved for the corresponding $symb in the $namespace db file, and
14000: $timestamp is the timestamp for that transaction (UNIX time).
14001: $laststore is currently only passed when cstore() is called by
14002: structuretags::finalize_storage().
1.191 harris41 14003:
14004: =item *
14005:
1.1269 raeburn 14006: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
14007: but uses critical subroutine
1.191 harris41 14008:
14009: =item *
14010:
1.243 albertel 14011: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
14012: all args are optional
1.191 harris41 14013:
14014: =item *
14015:
1.717 albertel 14016: dumpstore($namespace,$udom,$uname,$regexp,$range) :
14017: dumps the complete (or key matching regexp) namespace into a hash
14018: ($udom, $uname, $regexp, $range are optional) for a namespace that is
14019: normally &store()ed into
14020:
14021: $range should be either an integer '100' (give me the first 100
14022: matching records)
14023: or be two integers sperated by a - with no spaces
14024: '30-50' (give me the 30th through the 50th matching
14025: records)
14026:
14027:
14028: =item *
14029:
1.1269 raeburn 14030: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717 albertel 14031: replaces a &store() version of data with a replacement set of data
14032: for a particular resource in a namespace passed in the $storehash hash
1.1269 raeburn 14033: reference. If $tolog is true, the transaction is logged in the courselog
14034: with an action=PUTSTORE.
1.717 albertel 14035:
14036: =item *
14037:
1.243 albertel 14038: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
14039: works very similar to store/cstore, but all data is stored in a
14040: temporary location and can be reset using tmpreset, $storehash should
14041: be a hash reference, returns nothing on success
1.191 harris41 14042:
14043: =item *
14044:
1.243 albertel 14045: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
14046: similar to restore, but all data is stored in a temporary location and
14047: can be reset using tmpreset. Returns a hash of values on success,
14048: error string otherwise.
1.191 harris41 14049:
14050: =item *
14051:
1.243 albertel 14052: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
14053: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 14054:
14055: =item *
14056:
1.243 albertel 14057: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
14058: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 14059:
14060: =item *
14061:
1.243 albertel 14062: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
14063: namesp ($udom and $uname are optional)
1.191 harris41 14064:
14065: =item *
14066:
1.702 albertel 14067: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 14068: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 14069: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 14070:
1.702 albertel 14071: $range should be either an integer '100' (give me the first 100
14072: matching records)
14073: or be two integers sperated by a - with no spaces
14074: '30-50' (give me the 30th through the 50th matching
14075: records)
1.449 matthew 14076: =item *
14077:
14078: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
14079: $store can be a scalar, an array reference, or if the amount to be
14080: incremented is > 1, a hash reference.
14081:
14082: ($udom and $uname are optional)
1.191 harris41 14083:
14084: =item *
14085:
1.243 albertel 14086: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
14087: ($udom and $uname are optional)
1.191 harris41 14088:
14089: =item *
14090:
1.243 albertel 14091: cput($namespace,$storehash,$udom,$uname) : critical put
14092: ($udom and $uname are optional)
1.191 harris41 14093:
14094: =item *
14095:
1.748 albertel 14096: newput($namespace,$storehash,$udom,$uname) :
14097:
14098: Attempts to store the items in the $storehash, but only if they don't
14099: currently exist, if this succeeds you can be certain that you have
14100: successfully created a new key value pair in the $namespace db.
14101:
14102:
14103: Args:
14104: $namespace: name of database to store values to
14105: $storehash: hashref to store to the db
14106: $udom: (optional) domain of user containing the db
14107: $uname: (optional) name of user caontaining the db
14108:
14109: Returns:
14110: 'ok' -> succeeded in storing all keys of $storehash
14111: 'key_exists: <key>' -> failed to anything out of $storehash, as at
14112: least <key> already existed in the db (other
14113: requested keys may also already exist)
1.967 bisitz 14114: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 14115: 'con_lost' -> unable to contact request server
14116: 'refused' -> action was not allowed by remote machine
14117:
14118:
14119: =item *
14120:
1.243 albertel 14121: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
14122: reference filled in from namesp (encrypts the return communication)
14123: ($udom and $uname are optional)
1.191 harris41 14124:
14125: =item *
14126:
1.243 albertel 14127: log($udom,$name,$home,$message) : write to permanent log for user; use
14128: critical subroutine
14129:
1.806 raeburn 14130: =item *
14131:
1.860 raeburn 14132: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
14133: array reference filled in from namespace found in domain level on either
14134: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 14135:
14136: =item *
14137:
1.860 raeburn 14138: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
14139: domain level either on specified domain server ($uhome) or primary domain
14140: server ($udom and $uhome are optional)
1.806 raeburn 14141:
1.943 raeburn 14142: =item *
14143:
1.1240 raeburn 14144: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
14145: for: authentication, language, quotas, timezone, date locale, and portal URL in
14146: the target domain.
14147:
14148: May also include additional key => value pairs for the following groups:
14149:
14150: =over
14151:
14152: =item
14153: disk quotas (MB allocated by default to portfolios and authoring spaces).
14154:
14155: =over
14156:
14157: =item defaultquota, authorquota
14158:
14159: =back
14160:
14161: =item
14162: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
14163: portfolio for users).
14164:
14165: =over
14166:
14167: =item
14168: aboutme, blog, webdav, portfolio
14169:
14170: =back
14171:
14172: =item
14173: requestcourses: ability to request courses, and how requests are processed.
14174:
14175: =over
14176:
14177: =item
1.1305 raeburn 14178: official, unofficial, community, textbook, placement
1.1240 raeburn 14179:
14180: =back
14181:
14182: =item
14183: inststatus: types of institutional affiliation, and order in which they are displayed.
14184:
14185: =over
14186:
14187: =item
1.1256 raeburn 14188: inststatustypes, inststatusorder, inststatusguest
1.1240 raeburn 14189:
14190: =back
14191:
14192: =item
14193: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
14194: for course's uploaded content.
14195:
14196: =over
14197:
14198: =item
1.1246 raeburn 14199: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
1.1305 raeburn 14200: communityquota, textbookquota, placementquota
1.1240 raeburn 14201:
14202: =back
14203:
14204: =item
14205: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
14206: on your servers.
14207:
14208: =over
14209:
14210: =item
14211: remotesessions, hostedsessions
14212:
14213: =back
14214:
14215: =back
14216:
14217: In cases where a domain coordinator has never used the "Set Domain Configuration"
14218: utility to create a configuration.db file on a domain's primary library server
14219: only the following domain defaults: auth_def, auth_arg_def, lang_def
14220: -- corresponding values are authentication type (internal, krb4, krb5,
14221: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
14222: will be available. Values are retrieved from cache (if current), unless the
14223: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
14224: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
14225:
14226: Typical usage:
1.943 raeburn 14227:
1.1240 raeburn 14228: %domdefaults = &get_domain_defaults($target_domain);
1.943 raeburn 14229:
1.243 albertel 14230: =back
14231:
14232: =head2 Network Status Functions
14233:
14234: =over 4
1.191 harris41 14235:
14236: =item *
14237:
1.1137 raeburn 14238: dirlist() : return directory list based on URI (first arg).
14239:
14240: Inputs: 1 required, 5 optional.
14241:
14242: =over
14243:
14244: =item
14245: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
14246:
14247: =item
14248: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
14249:
14250: =item
14251: $username - username of user/course to be listed. Extracted from $uri if absent.
14252:
14253: =item
14254: $getpropath - boolean: 1 if prepend path using &propath().
14255:
14256: =item
14257: $getuserdir - boolean: 1 if prepend path for "userfiles".
14258:
14259: =item
14260: $alternateRoot - path to prepend in place of path from $uri.
14261:
14262: =back
14263:
14264: Returns: Array of up to two items.
14265:
14266: =over
14267:
14268: a reference to an array of files/subdirectories
14269:
14270: =over
14271:
14272: Each element in the array of files/subdirectories is a & separated list of
14273: item name and the result of running stat on the item. If dirlist was requested
14274: for a file instead of a directory, the item name will be ''. For a directory
14275: listing, if the item is a metadata file, the element will end &N&M
14276: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
14277: default copyright set (1).
14278:
14279: =back
14280:
14281: a scalar containing error condition (if encountered).
14282:
14283: =over
14284:
14285: =item
14286: no_host (no homeserver identified for $username:$domain).
14287:
14288: =item
14289: no_such_host (server contacted for listing not identified as valid host).
14290:
14291: =item
14292: con_lost (connection to remote server failed).
14293:
14294: =item
14295: refused (invalid $username:$domain received on lond side).
14296:
14297: =item
14298: no_such_dir (directory at specified path on lond side does not exist).
14299:
14300: =item
14301: empty (directory at specified path on lond side is empty).
14302:
14303: =over
14304:
14305: This is currently not encountered because the &ls3, &ls2,
14306: &ls (_handler) routines on the lond side do not filter out
14307: . and .. from a directory listing.
14308:
14309: =back
14310:
14311: =back
14312:
14313: =back
1.191 harris41 14314:
14315: =item *
14316:
1.243 albertel 14317: spareserver() : find server with least workload from spare.tab
14318:
1.986 foxr 14319:
14320: =item *
14321:
14322: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
14323: if there is no corresponding loncapa host.
14324:
1.243 albertel 14325: =back
14326:
1.986 foxr 14327:
1.243 albertel 14328: =head2 Apache Request
14329:
14330: =over 4
1.191 harris41 14331:
14332: =item *
14333:
1.243 albertel 14334: ssi($url,%hash) : server side include, does a complete request cycle on url to
14335: localhost, posts hash
14336:
14337: =back
14338:
14339: =head2 Data to String to Data
14340:
14341: =over 4
1.191 harris41 14342:
14343: =item *
14344:
1.243 albertel 14345: hash2str(%hash) : convert a hash into a string complete with escaping and '='
14346: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 14347:
14348: =item *
14349:
1.243 albertel 14350: hashref2str($hashref) : convert a hashref into a string complete with
14351: escaping and '=' and '&' separators, supports elements that are
14352: arrayrefs and hashrefs
1.191 harris41 14353:
14354: =item *
14355:
1.243 albertel 14356: arrayref2str($arrayref) : convert an arrayref into a string complete
14357: with escaping and '&' separators, supports elements that are arrayrefs
14358: and hashrefs
1.191 harris41 14359:
14360: =item *
14361:
1.243 albertel 14362: str2hash($string) : convert string to hash using unescaping and
14363: splitting on '=' and '&', supports elements that are arrayrefs and
14364: hashrefs
1.191 harris41 14365:
14366: =item *
14367:
1.243 albertel 14368: str2array($string) : convert string to hash using unescaping and
14369: splitting on '&', supports elements that are arrayrefs and hashrefs
14370:
14371: =back
14372:
14373: =head2 Logging Routines
14374:
14375:
14376: These routines allow one to make log messages in the lonnet.log and
14377: lonnet.perm logfiles.
1.191 harris41 14378:
1.1119 foxr 14379: =over 4
14380:
1.191 harris41 14381: =item *
14382:
1.243 albertel 14383: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 14384:
14385: =item *
14386:
1.243 albertel 14387: logthis() : append message to the normal lonnet.log file, it gets
14388: preiodically rolled over and deleted.
1.191 harris41 14389:
14390: =item *
14391:
1.243 albertel 14392: logperm() : append a permanent message to lonnet.perm.log, this log
14393: file never gets deleted by any automated portion of the system, only
14394: messages of critical importance should go in here.
14395:
1.1119 foxr 14396:
1.243 albertel 14397: =back
14398:
14399: =head2 General File Helper Routines
14400:
14401: =over 4
1.191 harris41 14402:
14403: =item *
14404:
1.481 raeburn 14405: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
14406: (a) files in /uploaded
14407: (i) If a local copy of the file exists -
14408: compares modification date of local copy with last-modified date for
14409: definitive version stored on home server for course. If local copy is
14410: stale, requests a new version from the home server and stores it.
14411: If the original has been removed from the home server, then local copy
14412: is unlinked.
14413: (ii) If local copy does not exist -
14414: requests the file from the home server and stores it.
14415:
14416: If $caller is 'uploadrep':
14417: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
14418: for request for files originally uploaded via DOCS.
14419: - returns 'ok' if fresh local copy now available, -1 otherwise.
14420:
14421: Otherwise:
14422: This indicates a call from the content generation phase of the request.
14423: - returns the entire contents of the file or -1.
14424:
14425: (b) files in /res
14426: - returns the entire contents of a file or -1;
14427: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 14428:
1.712 albertel 14429:
14430: =item *
14431:
14432: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
14433: reference
14434:
14435: returns either a stat() list of data about the file or an empty list
14436: if the file doesn't exist or couldn't find out about it (connection
14437: problems or user unknown)
14438:
1.191 harris41 14439: =item *
14440:
1.243 albertel 14441: filelocation($dir,$file) : returns file system location of a file
14442: based on URI; meant to be "fairly clean" absolute reference, $dir is a
14443: directory that relative $file lookups are to looked in ($dir of /a/dir
14444: and a file of ../bob will become /a/bob)
1.191 harris41 14445:
14446: =item *
14447:
14448: hreflocation($dir,$file) : returns file system location or a URL; same as
14449: filelocation except for hrefs
14450:
14451: =item *
14452:
1.1261 raeburn 14453: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
14454: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191 harris41 14455:
1.243 albertel 14456: =back
14457:
1.608 albertel 14458: =head2 Usererfile file routines (/uploaded*)
14459:
14460: =over 4
14461:
14462: =item *
14463:
14464: userfileupload(): main rotine for putting a file in a user or course's
14465: filespace, arguments are,
14466:
1.620 albertel 14467: formname - required - this is the name of the element in $env where the
1.608 albertel 14468: filename, and the contents of the file to create/modifed exist
1.620 albertel 14469: the filename is in $env{'form.'.$formname.'.filename'} and the
14470: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 14471: context - if coursedoc, store the file in the course of the active role
14472: of the current user;
14473: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
14474: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 14475: subdir - required - subdirectory to put the file in under ../userfiles/
14476: if undefined, it will be placed in "unknown"
14477:
14478: (This routine calls clean_filename() to remove any dangerous
14479: characters from the filename, and then calls finuserfileupload() to
14480: complete the transaction)
14481:
14482: returns either the url of the uploaded file (/uploaded/....) if successful
14483: and /adm/notfound.html if unsuccessful
14484:
14485: =item *
14486:
14487: clean_filename(): routine for cleaing a filename up for storage in
14488: userfile space, argument is:
14489:
14490: filename - proposed filename
14491:
14492: returns: the new clean filename
14493:
14494: =item *
14495:
1.1090 raeburn 14496: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 14497: userspace, probably shouldn't be called directly
14498:
14499: docuname: username or courseid of destination for the file
14500: docudom: domain of user/course of destination for the file
14501: formname: same as for userfileupload()
1.1090 raeburn 14502: fname: filename (including subdirectories) for the file
14503: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
14504: allfiles: reference to hash used to store objects found by parser
14505: codebase: reference to hash used for codebases of java objects found by parser
14506: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
14507: thumbheight: height (pixels) of thumbnail to be created for uploaded image
14508: resizewidth: width to be used to resize image using resizeImage from ImageMagick
14509: resizeheight: height to be used to resize image using resizeImage from ImageMagick
14510: context: if 'overwrite', will move the uploaded file from its temporary location to
14511: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 14512: mimetype: reference to scalar to accommodate mime type determined
14513: from File::MMagic if $parser = parse.
1.608 albertel 14514:
14515: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 14516: and /adm/notfound.html if unsuccessful (or an error message if context
14517: was 'overwrite').
14518:
1.608 albertel 14519:
14520: =item *
14521:
14522: renameuserfile(): renames an existing userfile to a new name
14523:
14524: Args:
14525: docuname: username or courseid of destination for the file
14526: docudom: domain of user/course of destination for the file
14527: old: current file name (including any subdirs under userfiles)
14528: new: desired file name (including any subdirs under userfiles)
14529:
14530: =item *
14531:
14532: mkdiruserfile(): creates a directory is a userfiles dir
14533:
14534: Args:
14535: docuname: username or courseid of destination for the file
14536: docudom: domain of user/course of destination for the file
14537: dir: dir to create (including any subdirs under userfiles)
14538:
14539: =item *
14540:
14541: removeuserfile(): removes a file that exists in userfiles
14542:
14543: Args:
14544: docuname: username or courseid of destination for the file
14545: docudom: domain of user/course of destination for the file
14546: fname: filname to delete (including any subdirs under userfiles)
14547:
14548: =item *
14549:
14550: removeuploadedurl(): convience function for removeuserfile()
14551:
14552: Args:
14553: url: a full /uploaded/... url to delete
14554:
1.747 albertel 14555: =item *
14556:
14557: get_portfile_permissions():
14558: Args:
14559: domain: domain of user or course contain the portfolio files
14560: user: name of user or num of course contain the portfolio files
14561: Returns:
14562: hashref of a dump of the proper file_permissions.db
14563:
14564:
14565: =item *
14566:
14567: get_access_controls():
14568:
14569: Args:
14570: current_permissions: the hash ref returned from get_portfile_permissions()
14571: group: (optional) the group you want the files associated with
14572: file: (optional) the file you want access info on
14573:
14574: Returns:
1.749 raeburn 14575: a hash (keys are file names) of hashes containing
14576: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
14577: values are XML containing access control settings (see below)
1.747 albertel 14578:
14579: Internal notes:
14580:
1.749 raeburn 14581: access controls are stored in file_permissions.db as key=value pairs.
14582: key -> path to file/file_name\0uniqueID:scope_end_start
14583: where scope -> public,guest,course,group,domains or users.
14584: end -> UNIX time for end of access (0 -> no end date)
14585: start -> UNIX time for start of access
14586:
14587: value -> XML description of access control
14588: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
14589: <start></start>
14590: <end></end>
14591:
14592: <password></password> for scope type = guest
14593:
14594: <domain></domain> for scope type = course or group
14595: <number></number>
14596: <roles id="">
14597: <role></role>
14598: <access></access>
14599: <section></section>
14600: <group></group>
14601: </roles>
14602:
14603: <dom></dom> for scope type = domains
14604:
14605: <users> for scope type = users
14606: <user>
14607: <uname></uname>
14608: <udom></udom>
14609: </user>
14610: </users>
14611: </scope>
14612:
14613: Access data is also aggregated for each file in an additional key=value pair:
14614: key -> path to file/file_name\0accesscontrol
14615: value -> reference to hash
14616: hash contains key = value pairs
14617: where key = uniqueID:scope_end_start
14618: value = UNIX time record was last updated
14619:
14620: Used to improve speed of look-ups of access controls for each file.
14621:
14622: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
14623:
1.1198 raeburn 14624: =item *
14625:
1.749 raeburn 14626: modify_access_controls():
14627:
14628: Modifies access controls for a portfolio file
14629: Args
14630: 1. file name
14631: 2. reference to hash of required changes,
14632: 3. domain
14633: 4. username
14634: where domain,username are the domain of the portfolio owner
14635: (either a user or a course)
14636:
14637: Returns:
14638: 1. result of additions or updates ('ok' or 'error', with error message).
14639: 2. result of deletions ('ok' or 'error', with error message).
14640: 3. reference to hash of any new or updated access controls.
14641: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
14642: key = integer (inbound ID)
1.1198 raeburn 14643: value = uniqueID
14644:
14645: =item *
14646:
14647: get_timebased_id():
14648:
14649: Attempts to get a unique timestamp-based suffix for use with items added to a
14650: course via the Course Editor (e.g., folders, composite pages,
14651: group bulletin boards).
14652:
14653: Args: (first three required; six others optional)
14654:
14655: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
14656: docssequence, or name of group
14657:
14658: 2. keyid (alphanumeric): name of temporary locking key in hash,
14659: e.g., num, boardids
14660:
14661: 3. namespace: name of gdbm file used to store suffixes already assigned;
14662: file will be named nohist_namespace.db
14663:
14664: 4. cdom: domain of course; default is current course domain from %env
14665:
14666: 5. cnum: course number; default is current course number from %env
14667:
14668: 6. idtype: set to concat if an additional digit is to be appended to the
14669: unix timestamp to form the suffix, if the plain timestamp is already
14670: in use. Default is to not do this, but simply increment the unix
14671: timestamp by 1 until a unique key is obtained.
14672:
14673: 7. who: holder of locking key; defaults to user:domain for user.
14674:
14675: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
14676: retrying); default is 3.
14677:
14678: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
14679:
14680: Returns:
14681:
14682: 1. suffix obtained (numeric)
14683:
14684: 2. result of deleting locking key (ok if deleted, or lock never obtained)
14685:
14686: 3. error: contains (localized) error message if an error occurred.
14687:
1.747 albertel 14688:
1.608 albertel 14689: =back
14690:
1.243 albertel 14691: =head2 HTTP Helper Routines
14692:
14693: =over 4
14694:
1.191 harris41 14695: =item *
14696:
14697: escape() : unpack non-word characters into CGI-compatible hex codes
14698:
14699: =item *
14700:
14701: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
14702:
1.243 albertel 14703: =back
14704:
14705: =head1 PRIVATE SUBROUTINES
14706:
14707: =head2 Underlying communication routines (Shouldn't call)
14708:
14709: =over 4
14710:
14711: =item *
14712:
14713: subreply() : tries to pass a message to lonc, returns con_lost if incapable
14714:
14715: =item *
14716:
14717: reply() : uses subreply to send a message to remote machine, logs all failures
14718:
14719: =item *
14720:
14721: critical() : passes a critical message to another server; if cannot
14722: get through then place message in connection buffer directory and
14723: returns con_delayed, if incapable of saving message, returns
14724: con_failed
14725:
14726: =item *
14727:
14728: reconlonc() : tries to reconnect lonc client processes.
14729:
14730: =back
14731:
14732: =head2 Resource Access Logging
14733:
14734: =over 4
14735:
14736: =item *
14737:
14738: flushcourselogs() : flush (save) buffer logs and access logs
14739:
14740: =item *
14741:
14742: courselog($what) : save message for course in hash
14743:
14744: =item *
14745:
14746: courseacclog($what) : save message for course using &courselog(). Perform
14747: special processing for specific resource types (problems, exams, quizzes, etc).
14748:
1.191 harris41 14749: =item *
14750:
14751: goodbye() : flush course logs and log shutting down; it is called in srm.conf
14752: as a PerlChildExitHandler
1.243 albertel 14753:
14754: =back
14755:
14756: =head2 Other
14757:
14758: =over 4
14759:
14760: =item *
14761:
14762: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 14763:
14764: =back
14765:
14766: =cut
1.877 foxr 14767:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>