Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1305
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1305 ! raeburn 4: # $Id: lonnet.pm,v 1.1304 2016/03/23 02:19: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);
1291:
1292: my $cachetime = 60*60*24;
1293:
1294: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1295: $dom_in_use = $udom;
1296: $homeintdom = 1;
1297: } else {
1298: $dom_in_use = $serverhomedom;
1299: }
1300: my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
1301: unless (defined($cached)) {
1302: my %domconfig =
1303: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
1304: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1305: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129 raeburn 1306: }
1307: }
1308: if (ref($result) eq 'HASH') {
1.1191 raeburn 1309: ($is_balancer,$currtargets,$currrules) =
1310: &check_balancer_result($result,@hosts);
1.1129 raeburn 1311: if ($is_balancer) {
1312: if (ref($currrules) eq 'HASH') {
1313: if ($homeintdom) {
1314: if ($uname ne '') {
1315: if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
1316: my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
1317: if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
1318: $rule_in_effect = $currrules->{'_LC_author'};
1319: } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
1320: $rule_in_effect = $currrules->{'_LC_adv'}
1321: }
1322: }
1323: if ($rule_in_effect eq '') {
1324: my %userenv = &userenvironment($udom,$uname,'inststatus');
1325: if ($userenv{'inststatus'} ne '') {
1326: my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
1327: my ($othertitle,$usertypes,$types) =
1328: &Apache::loncommon::sorted_inst_types($udom);
1329: if (ref($types) eq 'ARRAY') {
1330: foreach my $type (@{$types}) {
1331: if (grep(/^\Q$type\E$/,@statuses)) {
1332: if (exists($currrules->{$type})) {
1333: $rule_in_effect = $currrules->{$type};
1334: }
1335: }
1336: }
1337: }
1338: } else {
1339: if (exists($currrules->{'default'})) {
1340: $rule_in_effect = $currrules->{'default'};
1341: }
1342: }
1343: }
1344: } else {
1345: if (exists($currrules->{'default'})) {
1346: $rule_in_effect = $currrules->{'default'};
1347: }
1348: }
1349: } else {
1350: if ($currrules->{'_LC_external'} ne '') {
1351: $rule_in_effect = $currrules->{'_LC_external'};
1352: }
1353: }
1354: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1355: $uname,$udom);
1356: }
1357: }
1358: } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1239 raeburn 1359: ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129 raeburn 1360: unless (defined($cached)) {
1361: my %domconfig =
1362: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
1363: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1364: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129 raeburn 1365: }
1366: }
1367: if (ref($result) eq 'HASH') {
1.1191 raeburn 1368: ($is_balancer,$currtargets,$currrules) =
1369: &check_balancer_result($result,@hosts);
1370: if ($is_balancer) {
1.1129 raeburn 1371: if (ref($currrules) eq 'HASH') {
1372: if ($currrules->{'_LC_internetdom'} ne '') {
1373: $rule_in_effect = $currrules->{'_LC_internetdom'};
1374: }
1375: }
1376: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1377: $uname,$udom);
1378: }
1379: } else {
1380: if ($perlvar{'lonBalancer'} eq 'yes') {
1381: $is_balancer = 1;
1382: $offloadto = &this_host_spares($dom_in_use);
1383: }
1384: }
1385: } else {
1386: if ($perlvar{'lonBalancer'} eq 'yes') {
1387: $is_balancer = 1;
1388: $offloadto = &this_host_spares($dom_in_use);
1389: }
1390: }
1.1176 raeburn 1391: if ($is_balancer) {
1392: my $lowest_load = 30000;
1393: if (ref($offloadto) eq 'HASH') {
1394: if (ref($offloadto->{'primary'}) eq 'ARRAY') {
1395: foreach my $try_server (@{$offloadto->{'primary'}}) {
1396: ($otherserver,$lowest_load) =
1397: &compare_server_load($try_server,$otherserver,$lowest_load);
1398: }
1.1129 raeburn 1399: }
1.1176 raeburn 1400: my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129 raeburn 1401:
1.1176 raeburn 1402: if (!$found_server) {
1403: if (ref($offloadto->{'default'}) eq 'ARRAY') {
1404: foreach my $try_server (@{$offloadto->{'default'}}) {
1405: ($otherserver,$lowest_load) =
1406: &compare_server_load($try_server,$otherserver,$lowest_load);
1407: }
1408: }
1409: }
1410: } elsif (ref($offloadto) eq 'ARRAY') {
1411: if (@{$offloadto} == 1) {
1412: $otherserver = $offloadto->[0];
1413: } elsif (@{$offloadto} > 1) {
1414: foreach my $try_server (@{$offloadto}) {
1.1129 raeburn 1415: ($otherserver,$lowest_load) =
1416: &compare_server_load($try_server,$otherserver,$lowest_load);
1417: }
1418: }
1419: }
1.1176 raeburn 1420: if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
1421: $is_balancer = 0;
1422: if ($uname ne '' && $udom ne '') {
1423: if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1424:
1425: &appenv({'user.loadbalexempt' => $lonhost,
1426: 'user.loadbalcheck.time' => time});
1427: }
1.1129 raeburn 1428: }
1429: }
1430: }
1431: return ($is_balancer,$otherserver);
1432: }
1433:
1.1191 raeburn 1434: sub check_balancer_result {
1435: my ($result,@hosts) = @_;
1436: my ($is_balancer,$currtargets,$currrules);
1437: if (ref($result) eq 'HASH') {
1438: if ($result->{'lonhost'} ne '') {
1439: my $currbalancer = $result->{'lonhost'};
1440: if (grep(/^\Q$currbalancer\E$/,@hosts)) {
1441: $is_balancer = 1;
1442: $currtargets = $result->{'targets'};
1443: $currrules = $result->{'rules'};
1444: }
1445: } else {
1446: foreach my $key (keys(%{$result})) {
1447: if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
1448: (ref($result->{$key}) eq 'HASH')) {
1449: $is_balancer = 1;
1450: $currrules = $result->{$key}{'rules'};
1451: $currtargets = $result->{$key}{'targets'};
1452: last;
1453: }
1454: }
1455: }
1456: }
1457: return ($is_balancer,$currtargets,$currrules);
1458: }
1459:
1.1129 raeburn 1460: sub get_loadbalancer_targets {
1461: my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
1462: my $offloadto;
1.1175 raeburn 1463: if ($rule_in_effect eq 'none') {
1464: return [$perlvar{'lonHostID'}];
1465: } elsif ($rule_in_effect eq '') {
1.1129 raeburn 1466: $offloadto = $currtargets;
1467: } else {
1468: if ($rule_in_effect eq 'homeserver') {
1469: my $homeserver = &homeserver($uname,$udom);
1470: if ($homeserver ne 'no_host') {
1471: $offloadto = [$homeserver];
1472: }
1473: } elsif ($rule_in_effect eq 'externalbalancer') {
1474: my %domconfig =
1475: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1476: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1477: if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
1478: if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
1479: $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
1480: }
1481: }
1482: } else {
1.1178 raeburn 1483: my %servers = &internet_dom_servers($udom);
1.1129 raeburn 1484: my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
1485: if (&hostname($remotebalancer) ne '') {
1486: $offloadto = [$remotebalancer];
1487: }
1488: }
1489: } elsif (&hostname($rule_in_effect) ne '') {
1490: $offloadto = [$rule_in_effect];
1491: }
1492: }
1493: return $offloadto;
1494: }
1495:
1.1127 raeburn 1496: sub internet_dom_servers {
1497: my ($dom) = @_;
1498: my (%uniqservers,%servers);
1499: my $primaryserver = &hostname(&domain($dom,'primary'));
1500: my @machinedoms = &machine_domains($primaryserver);
1501: foreach my $mdom (@machinedoms) {
1502: my %currservers = %servers;
1503: my %server = &get_servers($mdom);
1504: %servers = (%currservers,%server);
1505: }
1506: my %by_hostname;
1507: foreach my $id (keys(%servers)) {
1508: push(@{$by_hostname{$servers{$id}}},$id);
1509: }
1510: foreach my $hostname (sort(keys(%by_hostname))) {
1511: if (@{$by_hostname{$hostname}} > 1) {
1512: my $match = 0;
1513: foreach my $id (@{$by_hostname{$hostname}}) {
1514: if (&host_domain($id) eq $dom) {
1515: $uniqservers{$id} = $hostname;
1516: $match = 1;
1517: }
1518: }
1519: unless ($match) {
1520: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1521: }
1522: } else {
1523: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1524: }
1525: }
1526: return %uniqservers;
1527: }
1528:
1.1 albertel 1529: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 1530:
1.599 albertel 1531: my %homecache;
1.1 albertel 1532: sub homeserver {
1.230 stredwic 1533: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 1534: my $index="$uname:$udom";
1.426 albertel 1535:
1.599 albertel 1536: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 1537:
1538: my %servers = &get_servers($udom,'library');
1539: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 1540: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 1541: exists($badServerCache{$tryserver}));
1.841 albertel 1542:
1543: my $answer=reply("home:$udom:$uname",$tryserver);
1544: if ($answer eq 'found') {
1545: delete($badServerCache{$tryserver});
1546: return $homecache{$index}=$tryserver;
1547: } elsif ($answer eq 'no_host') {
1548: $badServerCache{$tryserver}=1;
1549: }
1.1 albertel 1550: }
1551: return 'no_host';
1.70 www 1552: }
1553:
1.1300 raeburn 1554: # ----- Find the usernames behind a list of student/employee IDs or clicker IDs
1.70 www 1555:
1556: sub idget {
1.1300 raeburn 1557: my ($udom,$idsref,$namespace)=@_;
1.70 www 1558: my %returnhash=();
1.1300 raeburn 1559: my @ids=();
1560: if (ref($idsref) eq 'ARRAY') {
1561: @ids = @{$idsref};
1562: } else {
1563: return %returnhash;
1564: }
1565: if ($namespace eq '') {
1566: $namespace = 'ids';
1567: }
1.70 www 1568:
1.841 albertel 1569: my %servers = &get_servers($udom,'library');
1570: foreach my $tryserver (keys(%servers)) {
1.1299 raeburn 1571: my $idlist=join('&', map { &escape($_); } @ids);
1.1300 raeburn 1572: if ($namespace eq 'ids') {
1573: $idlist=~tr/A-Z/a-z/;
1574: }
1575: my $reply;
1576: if ($namespace eq 'ids') {
1577: $reply=&reply("idget:$udom:".$idlist,$tryserver);
1578: } else {
1579: $reply=&reply("getdom:$udom:$namespace:$idlist",$tryserver);
1580: }
1.841 albertel 1581: my @answer=();
1582: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1583: @answer=split(/\&/,$reply);
1584: } ;
1585: my $i;
1586: for ($i=0;$i<=$#ids;$i++) {
1587: if ($answer[$i]) {
1.1299 raeburn 1588: $returnhash{$ids[$i]}=&unescape($answer[$i]);
1.1300 raeburn 1589: }
1.841 albertel 1590: }
1.1300 raeburn 1591: }
1.70 www 1592: return %returnhash;
1593: }
1594:
1595: # ------------------------------------- Find the IDs behind a list of usernames
1596:
1597: sub idrget {
1598: my ($udom,@unames)=@_;
1599: my %returnhash=();
1.800 albertel 1600: foreach my $uname (@unames) {
1601: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 1602: }
1.70 www 1603: return %returnhash;
1604: }
1605:
1.1300 raeburn 1606: # Store away a list of names and associated student/employee IDs or clicker IDs
1.70 www 1607:
1608: sub idput {
1.1300 raeburn 1609: my ($udom,$idsref,$uhom,$namespace)=@_;
1.70 www 1610: my %servers=();
1.1300 raeburn 1611: my %ids=();
1612: my %byid = ();
1613: if (ref($idsref) eq 'HASH') {
1614: %ids=%{$idsref};
1615: }
1616: if ($namespace eq '') {
1617: $namespace = 'ids';
1618: }
1.800 albertel 1619: foreach my $uname (keys(%ids)) {
1620: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1.1300 raeburn 1621: if ($uhom eq '') {
1622: $uhom=&homeserver($uname,$udom);
1623: }
1.70 www 1624: if ($uhom ne 'no_host') {
1.800 albertel 1625: my $esc_unam=&escape($uname);
1.1300 raeburn 1626: if ($namespace eq 'ids') {
1627: my $id=&escape($ids{$uname});
1628: $id=~tr/A-Z/a-z/;
1629: my $esc_unam=&escape($uname);
1630: $servers{$uhom}.=$id.'='.$esc_unam.'&';
1.70 www 1631: } else {
1.1300 raeburn 1632: my @currids = split(/,/,$ids{$uname});
1633: foreach my $id (@currids) {
1634: $byid{$uhom}{$id} .= $uname.',';
1635: }
1636: }
1637: }
1638: }
1639: if ($namespace eq 'clickers') {
1640: foreach my $server (keys(%byid)) {
1641: if (ref($byid{$server}) eq 'HASH') {
1642: foreach my $id (keys(%{$byid{$server}})) {
1643: $byid{$server} =~ s/,$//;
1644: $servers{$uhom}.=&escape($id).'='.&escape($byid{$server}).'&';
1645: }
1.70 www 1646: }
1647: }
1.191 harris41 1648: }
1.800 albertel 1649: foreach my $server (keys(%servers)) {
1.1300 raeburn 1650: $servers{$server} =~ s/\&$//;
1651: if ($namespace eq 'ids') {
1652: &critical('idput:'.$udom.':'.$servers{$server},$server);
1653: } else {
1654: &critical('updateclickers:'.$udom.':add:'.$servers{$server},$server);
1655: }
1.191 harris41 1656: }
1.344 www 1657: }
1658:
1.1300 raeburn 1659: # ------------- Delete unwanted student/employee IDs or clicker IDs from domain
1.1231 raeburn 1660:
1661: sub iddel {
1.1300 raeburn 1662: my ($udom,$idshashref,$uhome,$namespace)=@_;
1.1231 raeburn 1663: my %result=();
1.1300 raeburn 1664: my %ids=();
1665: my %byid = ();
1666: if (ref($idshashref) eq 'HASH') {
1667: %ids=%{$idshashref};
1668: } else {
1.1231 raeburn 1669: return %result;
1670: }
1.1300 raeburn 1671: if ($namespace eq '') {
1672: $namespace = 'ids';
1673: }
1.1231 raeburn 1674: my %servers=();
1.1300 raeburn 1675: while (my ($id,$unamestr) = each(%ids)) {
1676: if ($namespace eq 'ids') {
1677: my $uhom = $uhome;
1678: if ($uhom eq '') {
1679: $uhom=&homeserver($unamestr,$udom);
1680: }
1681: if ($uhom ne 'no_host') {
1682: $servers{$uhom}.='&'.&escape($id);
1683: }
1684: } else {
1685: my @curritems = split(/,/,$ids{$id});
1686: foreach my $uname (@curritems) {
1687: my $uhom = $uhome;
1688: if ($uhom eq '') {
1689: $uhom=&homeserver($uname,$udom);
1690: }
1691: if ($uhom ne 'no_host') {
1692: $byid{$uhom}{$id} .= $uname.',';
1693: }
1694: }
1.1231 raeburn 1695: }
1.1300 raeburn 1696: }
1697: if ($namespace eq 'clickers') {
1698: foreach my $server (keys(%byid)) {
1699: if (ref($byid{$server}) eq 'HASH') {
1700: foreach my $id (keys(%{$byid{$server}})) {
1701: $byid{$server}{$id} =~ s/,$//;
1702: $servers{$server}.=&escape($id).'='.&escape($byid{$server}{$id}).'&';
1703: }
1.1231 raeburn 1704: }
1705: }
1706: }
1707: foreach my $server (keys(%servers)) {
1.1300 raeburn 1708: $servers{$server} =~ s/\&$//;
1709: if ($namespace eq 'ids') {
1710: $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
1711: } elsif ($namespace eq 'clickers') {
1712: $result{$server} = &critical('updateclickers:'.$udom.':del:'.$servers{$server},$server);
1713: }
1.1231 raeburn 1714: }
1715: return %result;
1716: }
1717:
1.1300 raeburn 1718: # ----- Update clicker ID-to-username look-ups in clickers.db on library server
1719:
1720: sub updateclickers {
1721: my ($udom,$action,$idshashref,$uhome,$critical) = @_;
1722: my %clickers;
1723: if (ref($idshashref) eq 'HASH') {
1724: %clickers=%{$idshashref};
1725: } else {
1726: return;
1727: }
1728: my $items='';
1729: foreach my $item (keys(%clickers)) {
1730: $items.=&escape($item).'='.&escape($clickers{$item}).'&';
1731: }
1732: $items=~s/\&$//;
1733: my $request = "updateclickers:$udom:$action:$items";
1734: if ($critical) {
1735: return &critical($request,$uhome);
1736: } else {
1737: return &reply($request,$uhome);
1738: }
1739: }
1740:
1.1023 raeburn 1741: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 1742: sub dump_dom {
1.1165 droeschl 1743: my ($namespace, $udom, $regexp) = @_;
1744:
1745: $udom ||= $env{'user.domain'};
1746:
1747: return () unless $udom;
1748:
1749: return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012 raeburn 1750: }
1751:
1.1023 raeburn 1752: # ------------------------------------------ get items from domain db files
1.806 raeburn 1753:
1754: sub get_dom {
1.860 raeburn 1755: my ($namespace,$storearr,$udom,$uhome)=@_;
1.1267 raeburn 1756: return if ($udom eq 'public');
1.806 raeburn 1757: my $items='';
1758: foreach my $item (@$storearr) {
1759: $items.=&escape($item).'&';
1760: }
1761: $items=~s/\&$//;
1.860 raeburn 1762: if (!$udom) {
1763: $udom=$env{'user.domain'};
1.1267 raeburn 1764: return if ($udom eq 'public');
1.860 raeburn 1765: if (defined(&domain($udom,'primary'))) {
1766: $uhome=&domain($udom,'primary');
1767: } else {
1.874 albertel 1768: undef($uhome);
1.860 raeburn 1769: }
1770: } else {
1771: if (!$uhome) {
1772: if (defined(&domain($udom,'primary'))) {
1773: $uhome=&domain($udom,'primary');
1774: }
1775: }
1776: }
1777: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1778: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866 raeburn 1779: my %returnhash;
1.875 albertel 1780: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 1781: return %returnhash;
1782: }
1.806 raeburn 1783: my @pairs=split(/\&/,$rep);
1784: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1785: return @pairs;
1786: }
1787: my $i=0;
1788: foreach my $item (@$storearr) {
1789: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1790: $i++;
1791: }
1792: return %returnhash;
1793: } else {
1.880 banghart 1794: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 1795: }
1796: }
1797:
1798: # -------------------------------------------- put items in domain db files
1799:
1800: sub put_dom {
1.860 raeburn 1801: my ($namespace,$storehash,$udom,$uhome)=@_;
1802: if (!$udom) {
1803: $udom=$env{'user.domain'};
1804: if (defined(&domain($udom,'primary'))) {
1805: $uhome=&domain($udom,'primary');
1806: } else {
1.874 albertel 1807: undef($uhome);
1.860 raeburn 1808: }
1809: } else {
1810: if (!$uhome) {
1811: if (defined(&domain($udom,'primary'))) {
1812: $uhome=&domain($udom,'primary');
1813: }
1814: }
1815: }
1816: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1817: my $items='';
1818: foreach my $item (keys(%$storehash)) {
1819: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1820: }
1821: $items=~s/\&$//;
1822: return &reply("putdom:$udom:$namespace:$items",$uhome);
1823: } else {
1.860 raeburn 1824: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 1825: }
1826: }
1827:
1.1023 raeburn 1828: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 1829: sub newput_dom {
1.1023 raeburn 1830: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 1831: my $result;
1832: if (!$udom) {
1833: $udom=$env{'user.domain'};
1834: }
1.1023 raeburn 1835: if ($udom) {
1836: my $uname = &get_domainconfiguser($udom);
1837: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 1838: }
1839: return $result;
1840: }
1841:
1.1023 raeburn 1842: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 1843: sub del_dom {
1.1023 raeburn 1844: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 1845: if (ref($storearr) eq 'ARRAY') {
1846: if (!$udom) {
1847: $udom=$env{'user.domain'};
1848: }
1.1023 raeburn 1849: if ($udom) {
1850: my $uname = &get_domainconfiguser($udom);
1851: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 1852: }
1853: }
1854: }
1855:
1.1023 raeburn 1856: # ----------------------------------construct domainconfig user for a domain
1857: sub get_domainconfiguser {
1858: my ($udom) = @_;
1859: return $udom.'-domainconfig';
1860: }
1861:
1.837 raeburn 1862: sub retrieve_inst_usertypes {
1863: my ($udom) = @_;
1864: my (%returnhash,@order);
1.989 raeburn 1865: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1866: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1867: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1256 raeburn 1868: return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989 raeburn 1869: } else {
1870: if (defined(&domain($udom,'primary'))) {
1871: my $uhome=&domain($udom,'primary');
1872: my $rep=&reply("inst_usertypes:$udom",$uhome);
1873: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1256 raeburn 1874: &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989 raeburn 1875: return (\%returnhash,\@order);
1876: }
1877: my ($hashitems,$orderitems) = split(/:/,$rep);
1878: my @pairs=split(/\&/,$hashitems);
1879: foreach my $item (@pairs) {
1880: my ($key,$value)=split(/=/,$item,2);
1881: $key = &unescape($key);
1882: next if ($key =~ /^error: 2 /);
1883: $returnhash{$key}=&thaw_unescape($value);
1884: }
1885: my @esc_order = split(/\&/,$orderitems);
1886: foreach my $item (@esc_order) {
1887: push(@order,&unescape($item));
1888: }
1889: } else {
1.1256 raeburn 1890: &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837 raeburn 1891: }
1.1256 raeburn 1892: return (\%returnhash,\@order);
1.837 raeburn 1893: }
1894: }
1895:
1.868 raeburn 1896: sub is_domainimage {
1897: my ($url) = @_;
1898: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
1899: if (&domain($1) ne '') {
1900: return '1';
1901: }
1902: }
1903: return;
1904: }
1905:
1.899 raeburn 1906: sub inst_directory_query {
1907: my ($srch) = @_;
1908: my $udom = $srch->{'srchdomain'};
1909: my %results;
1910: my $homeserver = &domain($udom,'primary');
1.909 raeburn 1911: my $outcome;
1.899 raeburn 1912: if ($homeserver ne '') {
1.904 albertel 1913: my $queryid=&reply("querysend:instdirsearch:".
1914: &escape($srch->{'srchby'}).':'.
1915: &escape($srch->{'srchterm'}).':'.
1916: &escape($srch->{'srchtype'}),$homeserver);
1917: my $host=&hostname($homeserver);
1918: if ($queryid !~/^\Q$host\E\_/) {
1919: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1920: return;
1921: }
1922: my $response = &get_query_reply($queryid);
1923: my $maxtries = 5;
1924: my $tries = 1;
1925: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1926: $response = &get_query_reply($queryid);
1927: $tries ++;
1928: }
1929:
1930: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 1931: if ($response eq 'unavailable') {
1932: $outcome = $response;
1933: } else {
1934: $outcome = 'ok';
1935: my @matches = split(/\n/,$response);
1936: foreach my $match (@matches) {
1937: my ($key,$value) = split(/=/,$match);
1938: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1939: }
1.899 raeburn 1940: }
1941: }
1942: }
1.909 raeburn 1943: return ($outcome,%results);
1.899 raeburn 1944: }
1945:
1946: sub usersearch {
1947: my ($srch) = @_;
1948: my $dom = $srch->{'srchdomain'};
1949: my %results;
1950: my %libserv = &all_library();
1951: my $query = 'usersearch';
1952: foreach my $tryserver (keys(%libserv)) {
1953: if (&host_domain($tryserver) eq $dom) {
1954: my $host=&hostname($tryserver);
1955: my $queryid=
1.911 raeburn 1956: &reply("querysend:".&escape($query).':'.
1957: &escape($srch->{'srchby'}).':'.
1.899 raeburn 1958: &escape($srch->{'srchtype'}).':'.
1959: &escape($srch->{'srchterm'}),$tryserver);
1960: if ($queryid !~/^\Q$host\E\_/) {
1961: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 1962: next;
1.899 raeburn 1963: }
1964: my $reply = &get_query_reply($queryid);
1965: my $maxtries = 1;
1966: my $tries = 1;
1967: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1968: $reply = &get_query_reply($queryid);
1969: $tries ++;
1970: }
1971: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1972: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1973: } else {
1.911 raeburn 1974: my @matches;
1975: if ($reply =~ /\n/) {
1976: @matches = split(/\n/,$reply);
1977: } else {
1978: @matches = split(/\&/,$reply);
1979: }
1.899 raeburn 1980: foreach my $match (@matches) {
1981: my ($uname,$udom,%userhash);
1.911 raeburn 1982: foreach my $entry (split(/:/,$match)) {
1983: my ($key,$value) =
1984: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 1985: $userhash{$key} = $value;
1986: if ($key eq 'username') {
1987: $uname = $value;
1988: } elsif ($key eq 'domain') {
1989: $udom = $value;
1.911 raeburn 1990: }
1.899 raeburn 1991: }
1992: $results{$uname.':'.$udom} = \%userhash;
1993: }
1994: }
1995: }
1996: }
1997: return %results;
1998: }
1999:
1.912 raeburn 2000: sub get_instuser {
2001: my ($udom,$uname,$id) = @_;
2002: my $homeserver = &domain($udom,'primary');
2003: my ($outcome,%results);
2004: if ($homeserver ne '') {
2005: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
2006: &escape($id).':'.&escape($udom),$homeserver);
2007: my $host=&hostname($homeserver);
2008: if ($queryid !~/^\Q$host\E\_/) {
2009: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
2010: return;
2011: }
2012: my $response = &get_query_reply($queryid);
2013: my $maxtries = 5;
2014: my $tries = 1;
2015: while (($response=~/^timeout/) && ($tries < $maxtries)) {
2016: $response = &get_query_reply($queryid);
2017: $tries ++;
2018: }
2019: if (!&error($response) && $response ne 'refused') {
2020: if ($response eq 'unavailable') {
2021: $outcome = $response;
2022: } else {
2023: $outcome = 'ok';
2024: my @matches = split(/\n/,$response);
2025: foreach my $match (@matches) {
2026: my ($key,$value) = split(/=/,$match);
2027: $results{&unescape($key)} = &thaw_unescape($value);
2028: }
2029: }
2030: }
2031: }
2032: my %userinfo;
2033: if (ref($results{$uname}) eq 'HASH') {
2034: %userinfo = %{$results{$uname}};
2035: }
2036: return ($outcome,%userinfo);
2037: }
2038:
1.1290 raeburn 2039: sub get_multiple_instusers {
2040: my ($udom,$users,$caller) = @_;
2041: my ($outcome,$results);
2042: if (ref($users) eq 'HASH') {
2043: my $count = keys(%{$users});
2044: my $requested = &freeze_escape($users);
2045: my $homeserver = &domain($udom,'primary');
2046: if ($homeserver ne '') {
2047: my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
2048: my $host=&hostname($homeserver);
2049: if ($queryid !~/^\Q$host\E\_/) {
2050: &logthis('get_multiple_instusers invalid queryid: '.$queryid.
2051: ' for host: '.$homeserver.'in domain '.$udom);
2052: return ($outcome,$results);
2053: }
2054: my $response = &get_query_reply($queryid);
2055: my $maxtries = 5;
2056: if ($count > 100) {
2057: $maxtries = 1+int($count/20);
2058: }
2059: my $tries = 1;
2060: while (($response=~/^timeout/) && ($tries <= $maxtries)) {
2061: $response = &get_query_reply($queryid);
2062: $tries ++;
2063: }
2064: if ($response eq '') {
2065: $results = {};
2066: foreach my $key (keys(%{$users})) {
2067: my ($uname,$id);
2068: if ($caller eq 'id') {
2069: $id = $key;
2070: } else {
2071: $uname = $key;
2072: }
2073: my ($resp,%info) = &get_instuser($udom,$uname,$id);
1.1291 raeburn 2074: $outcome = $resp;
1.1290 raeburn 2075: if ($resp eq 'ok') {
2076: %{$results} = (%{$results}, %info);
2077: } else {
2078: last;
2079: }
2080: }
2081: } elsif(!&error($response) && ($response ne 'refused')) {
2082: if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
2083: $outcome = $response;
2084: } else {
1.1291 raeburn 2085: ($outcome,my $userdata) = split(/=/,$response,2);
1.1290 raeburn 2086: if ($outcome eq 'ok') {
2087: $results = &thaw_unescape($userdata);
2088: }
2089: }
2090: }
2091: }
2092: }
2093: return ($outcome,$results);
2094: }
2095:
1.912 raeburn 2096: sub inst_rulecheck {
1.923 raeburn 2097: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 2098: my %returnhash;
2099: if ($udom ne '') {
2100: if (ref($rules) eq 'ARRAY') {
2101: @{$rules} = map {&escape($_);} (@{$rules});
2102: my $rulestr = join(':',@{$rules});
2103: my $homeserver=&domain($udom,'primary');
2104: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 2105: my $response;
2106: if ($item eq 'username') {
2107: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
2108: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 2109: $homeserver));
1.923 raeburn 2110: } elsif ($item eq 'id') {
2111: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
2112: ':'.&escape($id).':'.$rulestr,
2113: $homeserver));
1.945 raeburn 2114: } elsif ($item eq 'selfcreate') {
2115: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 2116: &escape($udom).':'.&escape($uname).
2117: ':'.$rulestr,$homeserver));
1.923 raeburn 2118: }
1.912 raeburn 2119: if ($response ne 'refused') {
2120: my @pairs=split(/\&/,$response);
2121: foreach my $item (@pairs) {
2122: my ($key,$value)=split(/=/,$item,2);
2123: $key = &unescape($key);
2124: next if ($key =~ /^error: 2 /);
2125: $returnhash{$key}=&thaw_unescape($value);
2126: }
2127: }
2128: }
2129: }
2130: }
2131: return %returnhash;
2132: }
2133:
2134: sub inst_userrules {
1.923 raeburn 2135: my ($udom,$check) = @_;
1.912 raeburn 2136: my (%ruleshash,@ruleorder);
2137: if ($udom ne '') {
2138: my $homeserver=&domain($udom,'primary');
2139: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 2140: my $response;
2141: if ($check eq 'id') {
2142: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 2143: $homeserver);
1.943 raeburn 2144: } elsif ($check eq 'email') {
2145: $response=&reply('instemailrules:'.&escape($udom),
2146: $homeserver);
1.923 raeburn 2147: } else {
2148: $response=&reply('instuserrules:'.&escape($udom),
2149: $homeserver);
2150: }
1.912 raeburn 2151: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 2152: ($response ne 'unknown_cmd') &&
1.912 raeburn 2153: ($response ne 'no_such_host')) {
2154: my ($hashitems,$orderitems) = split(/:/,$response);
2155: my @pairs=split(/\&/,$hashitems);
2156: foreach my $item (@pairs) {
2157: my ($key,$value)=split(/=/,$item,2);
2158: $key = &unescape($key);
2159: next if ($key =~ /^error: 2 /);
2160: $ruleshash{$key}=&thaw_unescape($value);
2161: }
2162: my @esc_order = split(/\&/,$orderitems);
2163: foreach my $item (@esc_order) {
2164: push(@ruleorder,&unescape($item));
2165: }
2166: }
2167: }
2168: }
2169: return (\%ruleshash,\@ruleorder);
2170: }
2171:
1.976 raeburn 2172: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 2173:
2174: sub get_domain_defaults {
1.1240 raeburn 2175: my ($domain,$ignore_cache) = @_;
1.1242 raeburn 2176: return if (($domain eq '') || ($domain eq 'public'));
1.943 raeburn 2177: my $cachetime = 60*60*24;
1.1240 raeburn 2178: unless ($ignore_cache) {
2179: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
2180: if (defined($cached)) {
2181: if (ref($result) eq 'HASH') {
2182: return %{$result};
2183: }
1.943 raeburn 2184: }
2185: }
2186: my %domdefaults;
2187: my %domconfig =
1.989 raeburn 2188: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 2189: 'requestcourses','inststatus',
1.1183 raeburn 2190: 'coursedefaults','usersessions',
1.1258 raeburn 2191: 'requestauthor','selfenrollment',
2192: 'coursecategories'],$domain);
1.1305 ! raeburn 2193: my @coursetypes = ('official','unofficial','community','textbook','placement');
1.943 raeburn 2194: if (ref($domconfig{'defaults'}) eq 'HASH') {
2195: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
2196: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
2197: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 2198: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 2199: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147 raeburn 2200: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943 raeburn 2201: } else {
2202: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
2203: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
2204: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
2205: }
1.976 raeburn 2206: if (ref($domconfig{'quotas'}) eq 'HASH') {
2207: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
2208: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
2209: } else {
2210: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1229 raeburn 2211: }
1.1177 raeburn 2212: my @usertools = ('aboutme','blog','webdav','portfolio');
1.976 raeburn 2213: foreach my $item (@usertools) {
2214: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
2215: $domdefaults{$item} = $domconfig{'quotas'}{$item};
2216: }
2217: }
1.1229 raeburn 2218: if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
2219: $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
2220: }
1.976 raeburn 2221: }
1.985 raeburn 2222: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1305 ! raeburn 2223: foreach my $item ('official','unofficial','community','textbook','placement') {
1.985 raeburn 2224: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
2225: }
2226: }
1.1183 raeburn 2227: if (ref($domconfig{'requestauthor'}) eq 'HASH') {
2228: $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
2229: }
1.989 raeburn 2230: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1256 raeburn 2231: foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989 raeburn 2232: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
2233: }
2234: }
1.1047 raeburn 2235: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1230 raeburn 2236: $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
1.1277 raeburn 2237: $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
2238: $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
2239: if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
2240: $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
2241: }
1.1254 raeburn 2242: foreach my $type (@coursetypes) {
2243: if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
2244: unless ($type eq 'community') {
2245: $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
2246: }
2247: }
2248: if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
2249: $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
2250: }
1.1277 raeburn 2251: if ($domdefaults{'postsubmit'} eq 'on') {
2252: if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
2253: $domdefaults{$type.'postsubtimeout'} =
2254: $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
2255: }
2256: }
1.1230 raeburn 2257: }
1.1286 raeburn 2258: if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
2259: if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
2260: my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
2261: if (@clonecodes) {
2262: $domdefaults{'canclone'} = join('+',@clonecodes);
2263: }
2264: }
2265: } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
2266: $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
2267: }
1.1047 raeburn 2268: }
1.1073 raeburn 2269: if (ref($domconfig{'usersessions'}) eq 'HASH') {
2270: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
2271: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
2272: }
2273: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
2274: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
2275: }
1.1279 raeburn 2276: if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
2277: $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
2278: }
1.1073 raeburn 2279: }
1.1254 raeburn 2280: if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
2281: if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
2282: my @settings = ('types','registered','enroll_dates','access_dates','section',
2283: 'approval','limit');
2284: foreach my $type (@coursetypes) {
2285: if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
2286: my @mgrdc = ();
2287: foreach my $item (@settings) {
2288: if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
2289: push(@mgrdc,$item);
2290: }
2291: }
2292: if (@mgrdc) {
2293: $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
2294: }
2295: }
2296: }
2297: }
2298: if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
2299: foreach my $type (@coursetypes) {
2300: if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
2301: foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
2302: $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
2303: }
2304: }
2305: }
2306: }
2307: }
1.1258 raeburn 2308: if (ref($domconfig{'coursecategories'}) eq 'HASH') {
2309: $domdefaults{'catauth'} = 'std';
2310: $domdefaults{'catunauth'} = 'std';
2311: if ($domconfig{'coursecategories'}{'auth'}) {
2312: $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
2313: }
2314: if ($domconfig{'coursecategories'}{'unauth'}) {
2315: $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
2316: }
2317: }
1.1219 raeburn 2318: &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943 raeburn 2319: return %domdefaults;
2320: }
2321:
1.344 www 2322: # --------------------------------------------------- Assign a key to a student
2323:
2324: sub assign_access_key {
1.364 www 2325: #
2326: # a valid key looks like uname:udom#comments
2327: # comments are being appended
2328: #
1.498 www 2329: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
2330: $kdom=
1.620 albertel 2331: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 2332: $knum=
1.620 albertel 2333: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 2334: $cdom=
1.620 albertel 2335: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2336: $cnum=
1.620 albertel 2337: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2338: $udom=$env{'user.name'} unless (defined($udom));
2339: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 2340: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 2341: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 2342: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 2343: # assigned to this person
2344: # - this should not happen,
1.345 www 2345: # unless something went wrong
2346: # the first time around
2347: # ready to assign
1.364 www 2348: $logentry=$1.'; '.$logentry;
1.496 www 2349: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 2350: $kdom,$knum) eq 'ok') {
1.345 www 2351: # key now belongs to user
1.346 www 2352: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 2353: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 2354: &appenv({'environment.'.$envkey => $ckey});
1.345 www 2355: return 'ok';
2356: } else {
2357: return
2358: 'error: Count not permanently assign key, will need to be re-entered later.';
2359: }
2360: } else {
2361: return 'error: Could not assign key, try again later.';
2362: }
1.364 www 2363: } elsif (!$existing{$ckey}) {
1.345 www 2364: # the key does not exist
2365: return 'error: The key does not exist';
2366: } else {
2367: # the key is somebody else's
2368: return 'error: The key is already in use';
2369: }
1.344 www 2370: }
2371:
1.364 www 2372: # ------------------------------------------ put an additional comment on a key
2373:
2374: sub comment_access_key {
2375: #
2376: # a valid key looks like uname:udom#comments
2377: # comments are being appended
2378: #
2379: my ($ckey,$cdom,$cnum,$logentry)=@_;
2380: $cdom=
1.620 albertel 2381: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 2382: $cnum=
1.620 albertel 2383: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 2384: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2385: if ($existing{$ckey}) {
2386: $existing{$ckey}.='; '.$logentry;
2387: # ready to assign
1.367 www 2388: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 2389: $cdom,$cnum) eq 'ok') {
2390: return 'ok';
2391: } else {
2392: return 'error: Count not store comment.';
2393: }
2394: } else {
2395: # the key does not exist
2396: return 'error: The key does not exist';
2397: }
2398: }
2399:
1.344 www 2400: # ------------------------------------------------------ Generate a set of keys
2401:
2402: sub generate_access_keys {
1.364 www 2403: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 2404: $cdom=
1.620 albertel 2405: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2406: $cnum=
1.620 albertel 2407: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 2408: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 2409: unless (($cdom) && ($cnum)) { return 0; }
2410: if ($number>10000) { return 0; }
2411: sleep(2); # make sure don't get same seed twice
2412: srand(time()^($$+($$<<15))); # from "Programming Perl"
2413: my $total=0;
2414: for (my $i=1;$i<=$number;$i++) {
2415: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
2416: sprintf("%lx",int(100000*rand)).'-'.
2417: sprintf("%lx",int(100000*rand));
2418: $newkey=~s/1/g/g; # folks mix up 1 and l
2419: $newkey=~s/0/h/g; # and also 0 and O
2420: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
2421: if ($existing{$newkey}) {
2422: $i--;
2423: } else {
1.364 www 2424: if (&put('accesskeys',
2425: { $newkey => '# generated '.localtime().
1.620 albertel 2426: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 2427: '; '.$logentry },
2428: $cdom,$cnum) eq 'ok') {
1.344 www 2429: $total++;
2430: }
2431: }
2432: }
1.620 albertel 2433: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 2434: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
2435: return $total;
2436: }
2437:
2438: # ------------------------------------------------------- Validate an accesskey
2439:
2440: sub validate_access_key {
2441: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
2442: $cdom=
1.620 albertel 2443: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2444: $cnum=
1.620 albertel 2445: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2446: $udom=$env{'user.domain'} unless (defined($udom));
2447: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 2448: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 2449: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 2450: }
2451:
2452: # ------------------------------------- Find the section of student in a course
1.652 albertel 2453: sub devalidate_getsection_cache {
2454: my ($udom,$unam,$courseid)=@_;
2455: my $hashid="$udom:$unam:$courseid";
2456: &devalidate_cache_new('getsection',$hashid);
2457: }
1.298 matthew 2458:
1.815 albertel 2459: sub courseid_to_courseurl {
2460: my ($courseid) = @_;
2461: #already url style courseid
2462: return $courseid if ($courseid =~ m{^/});
2463:
2464: if (exists($env{'course.'.$courseid.'.num'})) {
2465: my $cnum = $env{'course.'.$courseid.'.num'};
2466: my $cdom = $env{'course.'.$courseid.'.domain'};
2467: return "/$cdom/$cnum";
2468: }
2469:
2470: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
2471: if (exists($courseinfo{'num'})) {
2472: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
2473: }
2474:
2475: return undef;
2476: }
2477:
1.298 matthew 2478: sub getsection {
2479: my ($udom,$unam,$courseid)=@_;
1.599 albertel 2480: my $cachetime=1800;
1.551 albertel 2481:
2482: my $hashid="$udom:$unam:$courseid";
1.599 albertel 2483: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 2484: if (defined($cached)) { return $result; }
2485:
1.298 matthew 2486: my %Pending;
2487: my %Expired;
2488: #
2489: # Each role can either have not started yet (pending), be active,
2490: # or have expired.
2491: #
2492: # If there is an active role, we are done.
2493: #
2494: # If there is more than one role which has not started yet,
2495: # choose the one which will start sooner
2496: # If there is one role which has not started yet, return it.
2497: #
2498: # If there is more than one expired role, choose the one which ended last.
2499: # If there is a role which has expired, return it.
2500: #
1.815 albertel 2501: $courseid = &courseid_to_courseurl($courseid);
1.1166 raeburn 2502: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817 raeburn 2503: foreach my $key (keys(%roleshash)) {
1.479 albertel 2504: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 2505: my $section=$1;
2506: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 2507: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 2508: my $now=time;
1.548 albertel 2509: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 2510: $Expired{$end}=$section;
2511: next;
2512: }
1.548 albertel 2513: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 2514: $Pending{$start}=$section;
2515: next;
2516: }
1.599 albertel 2517: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 2518: }
2519: #
2520: # Presumedly there will be few matching roles from the above
2521: # loop and the sorting time will be negligible.
2522: if (scalar(keys(%Pending))) {
2523: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 2524: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 2525: }
2526: if (scalar(keys(%Expired))) {
2527: my @sorted = sort {$a <=> $b} keys(%Expired);
2528: my $time = pop(@sorted);
1.599 albertel 2529: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 2530: }
1.599 albertel 2531: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 2532: }
1.70 www 2533:
1.599 albertel 2534: sub save_cache {
2535: &purge_remembered();
1.722 albertel 2536: #&Apache::loncommon::validate_page();
1.620 albertel 2537: undef(%env);
1.780 albertel 2538: undef($env_loaded);
1.599 albertel 2539: }
1.452 albertel 2540:
1.599 albertel 2541: my $to_remember=-1;
2542: my %remembered;
2543: my %accessed;
2544: my $kicks=0;
2545: my $hits=0;
1.849 albertel 2546: sub make_key {
2547: my ($name,$id) = @_;
1.872 albertel 2548: if (length($id) > 65
2549: && length(&escape($id)) > 200) {
2550: $id=length($id).':'.&Digest::MD5::md5_hex($id);
2551: }
1.849 albertel 2552: return &escape($name.':'.$id);
2553: }
2554:
1.599 albertel 2555: sub devalidate_cache_new {
2556: my ($name,$id,$debug) = @_;
2557: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849 albertel 2558: $id=&make_key($name,$id);
1.599 albertel 2559: $memcache->delete($id);
2560: delete($remembered{$id});
2561: delete($accessed{$id});
2562: }
2563:
2564: sub is_cached_new {
2565: my ($name,$id,$debug) = @_;
1.849 albertel 2566: $id=&make_key($name,$id);
1.599 albertel 2567: if (exists($remembered{$id})) {
1.1133 foxr 2568: if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
1.599 albertel 2569: $accessed{$id}=[&gettimeofday()];
2570: $hits++;
2571: return ($remembered{$id},1);
2572: }
2573: my $value = $memcache->get($id);
2574: if (!(defined($value))) {
2575: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 2576: return (undef,undef);
1.416 albertel 2577: }
1.599 albertel 2578: if ($value eq '__undef__') {
2579: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
2580: $value=undef;
2581: }
2582: &make_room($id,$value,$debug);
2583: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
2584: return ($value,1);
2585: }
2586:
2587: sub do_cache_new {
2588: my ($name,$id,$value,$time,$debug) = @_;
1.849 albertel 2589: $id=&make_key($name,$id);
1.599 albertel 2590: my $setvalue=$value;
2591: if (!defined($setvalue)) {
2592: $setvalue='__undef__';
2593: }
1.623 albertel 2594: if (!defined($time) ) {
2595: $time=600;
2596: }
1.599 albertel 2597: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 2598: my $result = $memcache->set($id,$setvalue,$time);
2599: if (! $result) {
1.872 albertel 2600: &logthis("caching of id -> $id failed");
1.910 albertel 2601: $memcache->disconnect_all();
1.872 albertel 2602: }
1.600 albertel 2603: # need to make a copy of $value
1.919 albertel 2604: &make_room($id,$value,$debug);
1.599 albertel 2605: return $value;
2606: }
2607:
2608: sub make_room {
2609: my ($id,$value,$debug)=@_;
1.919 albertel 2610:
2611: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
2612: : $value;
1.599 albertel 2613: if ($to_remember<0) { return; }
2614: $accessed{$id}=[&gettimeofday()];
2615: if (scalar(keys(%remembered)) <= $to_remember) { return; }
2616: my $to_kick;
2617: my $max_time=0;
2618: foreach my $other (keys(%accessed)) {
2619: if (&tv_interval($accessed{$other}) > $max_time) {
2620: $to_kick=$other;
2621: $max_time=&tv_interval($accessed{$other});
2622: }
2623: }
2624: delete($remembered{$to_kick});
2625: delete($accessed{$to_kick});
2626: $kicks++;
2627: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 2628: return;
2629: }
2630:
1.599 albertel 2631: sub purge_remembered {
1.604 albertel 2632: #&logthis("Tossing ".scalar(keys(%remembered)));
2633: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 2634: undef(%remembered);
2635: undef(%accessed);
1.428 albertel 2636: }
1.70 www 2637: # ------------------------------------- Read an entry from a user's environment
2638:
2639: sub userenvironment {
2640: my ($udom,$unam,@what)=@_;
1.976 raeburn 2641: my $items;
2642: foreach my $item (@what) {
2643: $items.=&escape($item).'&';
2644: }
2645: $items=~s/\&$//;
1.70 www 2646: my %returnhash=();
1.1009 raeburn 2647: my $uhome = &homeserver($unam,$udom);
2648: unless ($uhome eq 'no_host') {
2649: my @answer=split(/\&/,
2650: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 2651: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
2652: return %returnhash;
2653: }
1.1009 raeburn 2654: my $i;
2655: for ($i=0;$i<=$#what;$i++) {
2656: $returnhash{$what[$i]}=&unescape($answer[$i]);
2657: }
1.70 www 2658: }
2659: return %returnhash;
1.1 albertel 2660: }
2661:
1.617 albertel 2662: # ---------------------------------------------------------- Get a studentphoto
2663: sub studentphoto {
2664: my ($udom,$unam,$ext) = @_;
2665: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 2666: if (defined($env{'request.course.id'})) {
1.708 raeburn 2667: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 2668: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
2669: return(&retrievestudentphoto($udom,$unam,$ext));
2670: } else {
2671: my ($result,$perm_reqd)=
1.707 albertel 2672: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2673: if ($result eq 'ok') {
2674: if (!($perm_reqd eq 'yes')) {
2675: return(&retrievestudentphoto($udom,$unam,$ext));
2676: }
2677: }
2678: }
2679: }
2680: } else {
2681: my ($result,$perm_reqd) =
1.707 albertel 2682: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2683: if ($result eq 'ok') {
2684: if (!($perm_reqd eq 'yes')) {
2685: return(&retrievestudentphoto($udom,$unam,$ext));
2686: }
2687: }
2688: }
2689: return '/adm/lonKaputt/lonlogo_broken.gif';
2690: }
2691:
2692: sub retrievestudentphoto {
2693: my ($udom,$unam,$ext,$type) = @_;
2694: my $home=&Apache::lonnet::homeserver($unam,$udom);
2695: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
2696: if ($ret eq 'ok') {
2697: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
2698: if ($type eq 'thumbnail') {
2699: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
2700: }
2701: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
2702: return $tokenurl;
2703: } else {
2704: if ($type eq 'thumbnail') {
2705: return '/adm/lonKaputt/genericstudent_tn.gif';
2706: } else {
2707: return '/adm/lonKaputt/lonlogo_broken.gif';
2708: }
1.617 albertel 2709: }
2710: }
2711:
1.263 www 2712: # -------------------------------------------------------------------- New chat
2713:
2714: sub chatsend {
1.724 raeburn 2715: my ($newentry,$anon,$group)=@_;
1.620 albertel 2716: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
2717: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2718: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 2719: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 2720: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 2721: &escape($newentry)).':'.$group,$chome);
1.292 www 2722: }
2723:
2724: # ------------------------------------------ Find current version of a resource
2725:
2726: sub getversion {
2727: my $fname=&clutter(shift);
1.1189 raeburn 2728: unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292 www 2729: return ¤tversion(&filelocation('',$fname));
2730: }
2731:
2732: sub currentversion {
2733: my $fname=shift;
2734: my $author=$fname;
2735: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2736: my ($udom,$uname)=split(/\//,$author);
1.1112 www 2737: my $home=&homeserver($uname,$udom);
1.292 www 2738: if ($home eq 'no_host') {
2739: return -1;
2740: }
1.1112 www 2741: my $answer=&reply("currentversion:$fname",$home);
1.292 www 2742: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2743: return -1;
2744: }
1.1112 www 2745: return $answer;
1.263 www 2746: }
2747:
1.1111 www 2748: #
2749: # Return special version number of resource if set by override, empty otherwise
2750: #
2751: sub usedversion {
2752: my $fname=shift;
2753: unless ($fname) { $fname=$env{'request.uri'}; }
2754: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
2755: if ($urlversion) { return $urlversion; }
2756: return '';
2757: }
2758:
1.1 albertel 2759: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 2760:
1.1 albertel 2761: sub subscribe {
2762: my $fname=shift;
1.761 raeburn 2763: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 2764: $fname=~s/[\n\r]//g;
1.1 albertel 2765: my $author=$fname;
2766: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2767: my ($udom,$uname)=split(/\//,$author);
2768: my $home=homeserver($uname,$udom);
1.335 albertel 2769: if ($home eq 'no_host') {
2770: return 'not_found';
1.1 albertel 2771: }
2772: my $answer=reply("sub:$fname",$home);
1.64 www 2773: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2774: $answer.=' by '.$home;
2775: }
1.1 albertel 2776: return $answer;
2777: }
2778:
1.8 www 2779: # -------------------------------------------------------------- Replicate file
2780:
2781: sub repcopy {
2782: my $filename=shift;
1.23 www 2783: $filename=~s/\/+/\//g;
1.1142 raeburn 2784: my $londocroot = $perlvar{'lonDocRoot'};
2785: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164 raeburn 2786: if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142 raeburn 2787: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
2788: $filename=~m{^/*(uploaded|editupload)/}) {
1.538 albertel 2789: return &repcopy_userfile($filename);
2790: }
1.532 albertel 2791: $filename=~s/[\n\r]//g;
1.8 www 2792: my $transname="$filename.in.transfer";
1.828 www 2793: # FIXME: this should flock
1.607 raeburn 2794: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 2795: my $remoteurl=subscribe($filename);
1.64 www 2796: if ($remoteurl =~ /^con_lost by/) {
2797: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2798: return 'unavailable';
1.8 www 2799: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 2800: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 2801: return 'not_found';
1.64 www 2802: } elsif ($remoteurl =~ /^rejected by/) {
2803: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2804: return 'forbidden';
1.20 www 2805: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 2806: return 'ok';
1.8 www 2807: } else {
1.290 www 2808: my $author=$filename;
2809: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2810: my ($udom,$uname)=split(/\//,$author);
2811: my $home=homeserver($uname,$udom);
2812: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 2813: my @parts=split(/\//,$filename);
2814: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142 raeburn 2815: if ($path ne "$londocroot/res") {
1.8 www 2816: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 2817: return 'bad_request';
1.8 www 2818: }
2819: my $count;
2820: for ($count=5;$count<$#parts;$count++) {
2821: $path.="/$parts[$count]";
2822: if ((-e $path)!=1) {
2823: mkdir($path,0777);
2824: }
2825: }
2826: my $ua=new LWP::UserAgent;
2827: my $request=new HTTP::Request('GET',"$remoteurl");
2828: my $response=$ua->request($request,$transname);
2829: if ($response->is_error()) {
2830: unlink($transname);
2831: my $message=$response->status_line;
1.672 albertel 2832: &logthis("<font color=\"blue\">WARNING:"
1.12 www 2833: ." LWP get: $message: $filename</font>");
1.607 raeburn 2834: return 'unavailable';
1.8 www 2835: } else {
1.16 www 2836: if ($remoteurl!~/\.meta$/) {
2837: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2838: my $mresponse=$ua->request($mrequest,$filename.'.meta');
2839: if ($mresponse->is_error()) {
2840: unlink($filename.'.meta');
2841: &logthis(
1.672 albertel 2842: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 2843: }
2844: }
1.8 www 2845: rename($transname,$filename);
1.607 raeburn 2846: return 'ok';
1.8 www 2847: }
1.290 www 2848: }
1.8 www 2849: }
1.330 www 2850: }
2851:
2852: # ------------------------------------------------ Get server side include body
2853: sub ssi_body {
1.381 albertel 2854: my ($filelink,%form)=@_;
1.606 matthew 2855: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
2856: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
2857: }
1.953 www 2858: my $output='';
2859: my $response;
1.980 raeburn 2860: if ($filelink=~/^https?\:/) {
1.954 raeburn 2861: ($output,$response)=&externalssi($filelink);
1.953 www 2862: } else {
1.1004 droeschl 2863: $filelink .= $filelink=~/\?/ ? '&' : '?';
2864: $filelink .= 'inhibitmenu=yes';
1.953 www 2865: ($output,$response)=&ssi($filelink,%form);
2866: }
1.778 albertel 2867: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 2868: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 2869: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 2870: if (wantarray) {
2871: return ($output, $response);
2872: } else {
2873: return $output;
2874: }
1.8 www 2875: }
2876:
1.15 www 2877: # --------------------------------------------------------- Server Side Include
2878:
1.782 albertel 2879: sub absolute_url {
2880: my ($host_name) = @_;
2881: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
2882: if ($host_name eq '') {
2883: $host_name = $ENV{'SERVER_NAME'};
2884: }
2885: return $protocol.$host_name;
2886: }
2887:
1.942 foxr 2888: #
2889: # Server side include.
2890: # Parameters:
2891: # fn Possibly encrypted resource name/id.
2892: # form Hash that describes how the rendering should be done
2893: # and other things.
1.944 foxr 2894: # Returns:
1.950 raeburn 2895: # Scalar context: The content of the response.
2896: # Array context: 2 element list of the content and the full response object.
1.942 foxr 2897: #
1.15 www 2898: sub ssi {
2899:
1.944 foxr 2900: my ($fn,%form)=@_;
1.15 www 2901: my $ua=new LWP::UserAgent;
1.23 www 2902: my $request;
1.711 albertel 2903:
2904: $form{'no_update_last_known'}=1;
1.895 albertel 2905: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 2906: if (%form) {
1.782 albertel 2907: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1272 droeschl 2908: $request->content(join('&',map {
2909: my $name = escape($_);
2910: "$name=" . ( ref($form{$_}) eq 'ARRAY'
2911: ? join("&$name=", map {escape($_) } @{$form{$_}})
2912: : &escape($form{$_}) );
2913: } keys(%form)));
1.23 www 2914: } else {
1.782 albertel 2915: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 2916: }
2917:
1.15 www 2918: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1173 foxr 2919: my $response= $ua->request($request);
1.1182 foxr 2920: my $content = $response->content;
2921:
2922:
1.944 foxr 2923: if (wantarray) {
1.1173 foxr 2924: return ($content, $response);
1.944 foxr 2925: } else {
1.1173 foxr 2926: return $content;
1.942 foxr 2927: }
1.324 www 2928: }
2929:
2930: sub externalssi {
2931: my ($url)=@_;
2932: my $ua=new LWP::UserAgent;
2933: my $request=new HTTP::Request('GET',$url);
2934: my $response=$ua->request($request);
1.954 raeburn 2935: if (wantarray) {
2936: return ($response->content, $response);
2937: } else {
2938: return $response->content;
2939: }
1.15 www 2940: }
1.254 www 2941:
1.492 albertel 2942: # -------------------------------- Allow a /uploaded/ URI to be vouched for
2943:
2944: sub allowuploaded {
2945: my ($srcurl,$url)=@_;
2946: $url=&clutter(&declutter($url));
2947: my $dir=$url;
2948: $dir=~s/\/[^\/]+$//;
2949: my %httpref=();
2950: my $httpurl=&hreflocation('',$url);
2951: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 2952: &Apache::lonnet::appenv(\%httpref);
1.254 www 2953: }
1.477 raeburn 2954:
1.1193 raeburn 2955: #
2956: # Determine if the current user should be able to edit a particular resource,
2957: # when viewing in course context.
2958: # (a) When viewing resource used to determine if "Edit" item is included in
2959: # Functions.
2960: # (b) When displaying folder contents in course editor, used to determine if
2961: # "Edit" link will be displayed alongside resource.
2962: #
1.1196 raeburn 2963: # input: six args -- filename (decluttered), course number, course domain,
2964: # url, symb (if registered) and group (if this is a group
2965: # item -- e.g., bulletin board, group page etc.).
2966: # output: array of five scalars --
1.1193 raeburn 2967: # $cfile -- url for file editing if editable on current server
2968: # $home -- homeserver of resource (i.e., for author if published,
2969: # or course if uploaded.).
2970: # $switchserver -- 1 if server switch will be needed.
1.1196 raeburn 2971: # $forceedit -- 1 if icon/link should be to go to edit mode
2972: # $forceview -- 1 if icon/link should be to go to view mode
1.1193 raeburn 2973: #
2974:
2975: sub can_edit_resource {
1.1194 raeburn 2976: my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
2977: my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
2978: #
2979: # For aboutme pages user can only edit his/her own.
2980: #
1.1199 raeburn 2981: if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
1.1194 raeburn 2982: my ($sdom,$sname) = ($1,$2);
2983: if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
2984: $home = $env{'user.home'};
2985: $cfile = $resurl;
2986: if ($env{'form.forceedit'}) {
2987: $forceview = 1;
2988: } else {
2989: $forceedit = 1;
2990: }
2991: return ($cfile,$home,$switchserver,$forceedit,$forceview);
2992: } else {
2993: return;
2994: }
2995: }
2996:
2997: if ($env{'request.course.id'}) {
2998: my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
2999: if ($group ne '') {
3000: # if this is a group homepage or group bulletin board, check group privs
3001: my $allowed = 0;
1.1197 raeburn 3002: if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
3003: if ((&allowed('mdg',$env{'request.course.id'}.
1.1198 raeburn 3004: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
1.1194 raeburn 3005: (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
3006: $allowed = 1;
3007: }
1.1197 raeburn 3008: } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
3009: if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
3010: (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
1.1194 raeburn 3011: $allowed = 1;
3012: }
3013: }
3014: if ($allowed) {
3015: $home=&homeserver($cnum,$cdom);
3016: if ($env{'form.forceedit'}) {
3017: $forceview = 1;
3018: } else {
3019: $forceedit = 1;
3020: }
3021: $cfile = $resurl;
3022: } else {
3023: return;
3024: }
3025: } else {
1.1208 raeburn 3026: if ($resurl =~ m{^/?adm/viewclasslist$}) {
3027: unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
3028: return;
3029: }
3030: } elsif (!$crsedit) {
1.1194 raeburn 3031: #
3032: # No edit allowed where CC has switched to student role.
3033: #
3034: return;
3035: }
3036: }
3037: }
3038:
1.1193 raeburn 3039: if ($file ne '') {
3040: if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
1.1194 raeburn 3041: if (&is_course_upload($file,$cnum,$cdom)) {
3042: $uploaded = 1;
3043: $incourse = 1;
1.1193 raeburn 3044: if ($file =~/\.(htm|html|css|js|txt)$/) {
3045: $cfile = &hreflocation('',$file);
1.1201 raeburn 3046: if ($env{'form.forceedit'}) {
3047: $forceview = 1;
3048: } else {
3049: $forceedit = 1;
3050: }
1.1194 raeburn 3051: }
3052: } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
3053: $incourse = 1;
3054: if ($env{'form.forceedit'}) {
3055: $forceview = 1;
3056: } else {
3057: $forceedit = 1;
3058: }
3059: $cfile = $resurl;
3060: } elsif (($resurl ne '') && (&is_on_map($resurl))) {
3061: if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
3062: $incourse = 1;
3063: if ($env{'form.forceedit'}) {
3064: $forceview = 1;
3065: } else {
3066: $forceedit = 1;
3067: }
3068: $cfile = $resurl;
1.1199 raeburn 3069: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
1.1194 raeburn 3070: $incourse = 1;
3071: $cfile = $resurl.'/smpedit';
1.1199 raeburn 3072: } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
1.1194 raeburn 3073: $incourse = 1;
1.1199 raeburn 3074: if ($env{'form.forceedit'}) {
3075: $forceview = 1;
3076: } else {
3077: $forceedit = 1;
3078: }
3079: $cfile = $resurl;
1.1298 raeburn 3080: } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/exttools?$}) {
3081: $incourse = 1;
3082: if ($env{'form.forceedit'}) {
3083: $forceview = 1;
3084: } else {
3085: $forceedit = 1;
3086: }
3087: $cfile = $resurl;
1.1208 raeburn 3088: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3089: $incourse = 1;
3090: if ($env{'form.forceedit'}) {
3091: $forceview = 1;
3092: } else {
3093: $forceedit = 1;
3094: }
3095: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1194 raeburn 3096: }
3097: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
3098: my $template = '/res/lib/templates/simpleproblem.problem';
3099: if (&is_on_map($template)) {
3100: $incourse = 1;
3101: $forceview = 1;
3102: $cfile = $template;
1.1193 raeburn 3103: }
1.1199 raeburn 3104: } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
3105: $incourse = 1;
3106: if ($env{'form.forceedit'}) {
3107: $forceview = 1;
3108: } else {
3109: $forceedit = 1;
3110: }
3111: $cfile = $resurl;
1.1298 raeburn 3112: } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/exttools?$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
3113: $incourse = 1;
3114: if ($env{'form.forceedit'}) {
3115: $forceview = 1;
3116: } else {
3117: $forceedit = 1;
3118: }
3119: $cfile = $resurl;
1.1199 raeburn 3120: } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
3121: $incourse = 1;
3122: $forceview = 1;
3123: if ($symb) {
3124: my ($map,$id,$res)=&decode_symb($symb);
3125: $env{'request.symb'} = $symb;
3126: $cfile = &clutter($res);
3127: } else {
3128: $cfile = $env{'form.suppurl'};
1.1298 raeburn 3129: my $escfile = &unescape($cfile);
3130: if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/exttools?$}) {
3131: $cfile = '/adm/wrapper'.$escfile;
3132: } else {
3133: $escfile =~ s{^http://}{};
3134: $cfile = &escape("/adm/wrapper/ext/$escfile");
3135: }
1.1199 raeburn 3136: }
1.1234 raeburn 3137: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3138: if ($env{'form.forceedit'}) {
3139: $forceview = 1;
3140: } else {
3141: $forceedit = 1;
3142: }
3143: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1193 raeburn 3144: }
3145: }
1.1194 raeburn 3146: if ($uploaded || $incourse) {
3147: $home=&homeserver($cnum,$cdom);
1.1207 raeburn 3148: } elsif ($file !~ m{/$}) {
1.1193 raeburn 3149: $file=~s{^(priv/$match_domain/$match_username)}{/$1};
3150: $file=~s{^($match_domain/$match_username)}{/priv/$1};
3151: # Check that the user has permission to edit this resource
3152: my $setpriv = 1;
3153: my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
3154: if (defined($cfudom)) {
3155: $home=&homeserver($cfuname,$cfudom);
3156: $cfile=$file;
3157: }
3158: }
1.1194 raeburn 3159: if (($cfile ne '') && (!$incourse || $uploaded) &&
3160: (($home ne '') && ($home ne 'no_host'))) {
1.1193 raeburn 3161: my @ids=¤t_machine_ids();
3162: unless (grep(/^\Q$home\E$/,@ids)) {
3163: $switchserver=1;
3164: }
3165: }
3166: }
1.1194 raeburn 3167: return ($cfile,$home,$switchserver,$forceedit,$forceview);
1.1193 raeburn 3168: }
3169:
3170: sub is_course_upload {
3171: my ($file,$cnum,$cdom) = @_;
3172: my $uploadpath = &LONCAPA::propath($cdom,$cnum);
3173: $uploadpath =~ s{^\/}{};
1.1201 raeburn 3174: if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
3175: ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
1.1193 raeburn 3176: return 1;
3177: }
3178: return;
3179: }
3180:
1.1194 raeburn 3181: sub in_course {
1.1195 raeburn 3182: my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
3183: if ($hideprivileged) {
3184: my $skipuser;
1.1219 raeburn 3185: my %coursehash = &coursedescription($cdom.'_'.$cnum);
3186: my @possdoms = ($cdom);
3187: if ($coursehash{'checkforpriv'}) {
3188: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
3189: }
3190: if (&privileged($uname,$udom,\@possdoms)) {
1.1195 raeburn 3191: $skipuser = 1;
3192: if ($coursehash{'nothideprivileged'}) {
3193: foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3194: my $user;
3195: if ($item =~ /:/) {
3196: $user = $item;
3197: } else {
3198: $user = join(':',split(/[\@]/,$item));
3199: }
3200: if ($user eq $uname.':'.$udom) {
3201: undef($skipuser);
3202: last;
3203: }
3204: }
3205: }
3206: if ($skipuser) {
3207: return 0;
3208: }
3209: }
3210: }
1.1194 raeburn 3211: $type ||= 'any';
3212: if (!defined($cdom) || !defined($cnum)) {
3213: my $cid = $env{'request.course.id'};
3214: $cdom = $env{'course.'.$cid.'.domain'};
3215: $cnum = $env{'course.'.$cid.'.num'};
3216: }
3217: my $typesref;
1.1195 raeburn 3218: if (($type eq 'any') || ($type eq 'all')) {
1.1194 raeburn 3219: $typesref = ['active','previous','future'];
3220: } elsif ($type eq 'previous' || $type eq 'future') {
3221: $typesref = [$type];
3222: }
3223: my %roles = &get_my_roles($uname,$udom,'userroles',
3224: $typesref,undef,[$cdom]);
3225: my ($tmp) = keys(%roles);
3226: return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
3227: my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
3228: if (@course_roles > 0) {
3229: return 1;
3230: }
3231: return 0;
3232: }
3233:
1.478 albertel 3234: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 3235: # input: action, courseID, current domain, intended
1.637 raeburn 3236: # path to file, source of file, instruction to parse file for objects,
3237: # ref to hash for embedded objects,
3238: # ref to hash for codebase of java objects.
1.1095 raeburn 3239: # reference to scalar to accommodate mime type determined
3240: # from File::MMagic if $parser = parse.
1.637 raeburn 3241: #
1.485 raeburn 3242: # output: url to file (if action was uploaddoc),
3243: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 3244: #
1.478 albertel 3245: # Allows directory structure to be used within lonUsers/../userfiles/ for a
3246: # course.
1.477 raeburn 3247: #
1.478 albertel 3248: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3249: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
3250: # course's home server.
1.477 raeburn 3251: #
1.478 albertel 3252: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
3253: # be copied from $source (current location) to
3254: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3255: # and will then be copied to
3256: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
3257: # course's home server.
1.485 raeburn 3258: #
1.481 raeburn 3259: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 3260: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 3261: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3262: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
3263: # in course's home server.
1.637 raeburn 3264: #
1.477 raeburn 3265:
3266: sub process_coursefile {
1.1095 raeburn 3267: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
3268: $mimetype)=@_;
1.477 raeburn 3269: my $fetchresult;
1.638 albertel 3270: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 3271: if ($action eq 'propagate') {
1.638 albertel 3272: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
3273: $home);
1.481 raeburn 3274: } else {
1.477 raeburn 3275: my $fpath = '';
3276: my $fname = $file;
1.478 albertel 3277: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 3278: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 3279: my $filepath = &build_filepath($fpath);
1.481 raeburn 3280: if ($action eq 'copy') {
3281: if ($source eq '') {
3282: $fetchresult = 'no source file';
3283: return $fetchresult;
3284: } else {
3285: my $destination = $filepath.'/'.$fname;
3286: rename($source,$destination);
3287: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3288: $home);
1.481 raeburn 3289: }
3290: } elsif ($action eq 'uploaddoc') {
3291: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 3292: print $fh $env{'form.'.$source};
1.481 raeburn 3293: close($fh);
1.637 raeburn 3294: if ($parser eq 'parse') {
1.1024 raeburn 3295: my $mm = new File::MMagic;
1.1095 raeburn 3296: my $type = $mm->checktype_filename($filepath.'/'.$fname);
3297: if ($type eq 'text/html') {
1.1024 raeburn 3298: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
3299: unless ($parse_result eq 'ok') {
3300: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
3301: }
1.637 raeburn 3302: }
1.1095 raeburn 3303: if (ref($mimetype)) {
3304: $$mimetype = $type;
3305: }
1.637 raeburn 3306: }
1.477 raeburn 3307: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3308: $home);
1.481 raeburn 3309: if ($fetchresult eq 'ok') {
3310: return '/uploaded/'.$fpath.'/'.$fname;
3311: } else {
3312: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3313: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 3314: return '/adm/notfound.html';
3315: }
1.477 raeburn 3316: }
3317: }
1.485 raeburn 3318: unless ( $fetchresult eq 'ok') {
1.477 raeburn 3319: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3320: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 3321: }
3322: return $fetchresult;
3323: }
3324:
1.637 raeburn 3325: sub build_filepath {
3326: my ($fpath) = @_;
3327: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
3328: unless ($fpath eq '') {
3329: my @parts=split('/',$fpath);
3330: foreach my $part (@parts) {
3331: $filepath.= '/'.$part;
3332: if ((-e $filepath)!=1) {
3333: mkdir($filepath,0777);
3334: }
3335: }
3336: }
3337: return $filepath;
3338: }
3339:
3340: sub store_edited_file {
1.638 albertel 3341: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 3342: my $file = $primary_url;
3343: $file =~ s#^/uploaded/$docudom/$docuname/##;
3344: my $fpath = '';
3345: my $fname = $file;
3346: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
3347: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
3348: my $filepath = &build_filepath($fpath);
3349: open(my $fh,'>'.$filepath.'/'.$fname);
3350: print $fh $content;
3351: close($fh);
1.638 albertel 3352: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 3353: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3354: $home);
1.637 raeburn 3355: if ($$fetchresult eq 'ok') {
3356: return '/uploaded/'.$fpath.'/'.$fname;
3357: } else {
1.638 albertel 3358: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
3359: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 3360: return '/adm/notfound.html';
3361: }
3362: }
3363:
1.531 albertel 3364: sub clean_filename {
1.831 albertel 3365: my ($fname,$args)=@_;
1.315 www 3366: # Replace Windows backslashes by forward slashes
1.257 www 3367: $fname=~s/\\/\//g;
1.831 albertel 3368: if (!$args->{'keep_path'}) {
3369: # Get rid of everything but the actual filename
3370: $fname=~s/^.*\/([^\/]+)$/$1/;
3371: }
1.315 www 3372: # Replace spaces by underscores
3373: $fname=~s/\s+/\_/g;
3374: # Replace all other weird characters by nothing
1.831 albertel 3375: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 3376: # Replace all .\d. sequences with _\d. so they no longer look like version
3377: # numbers
3378: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 3379: return $fname;
3380: }
1.1051 raeburn 3381: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
3382: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
3383: # image with the same aspect ratio as the original, but with dimensions which do
3384: # not exceed $resizewidth and $resizeheight.
3385:
1.984 neumanie 3386: sub resizeImage {
1.1051 raeburn 3387: my ($img_path,$resizewidth,$resizeheight) = @_;
3388: my $ima = Image::Magick->new;
3389: my $resized;
3390: if (-e $img_path) {
3391: $ima->Read($img_path);
3392: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
3393: my $width = $ima->Get('width');
3394: my $height = $ima->Get('height');
3395: if ($width > $resizewidth) {
3396: my $factor = $width/$resizewidth;
3397: my $newheight = $height/$factor;
3398: $ima->Scale(width=>$resizewidth,height=>$newheight);
3399: $resized = 1;
3400: }
3401: }
3402: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
3403: my $width = $ima->Get('width');
3404: my $height = $ima->Get('height');
3405: if ($height > $resizeheight) {
3406: my $factor = $height/$resizeheight;
3407: my $newwidth = $width/$factor;
3408: $ima->Scale(width=>$newwidth,height=>$resizeheight);
3409: $resized = 1;
3410: }
3411: }
3412: if ($resized) {
3413: $ima->Write($img_path);
3414: }
3415: }
3416: return;
1.977 amueller 3417: }
3418:
1.608 albertel 3419: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 3420: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093 raeburn 3421: # the desired filename is in $env{"form.$formname.filename"}
1.1090 raeburn 3422: # $context - possible values: coursedoc, existingfile, overwrite,
3423: # canceloverwrite, or ''.
3424: # if 'coursedoc': upload to the current course
3425: # if 'existingfile': write file to tmp/overwrites directory
3426: # if 'canceloverwrite': delete file written to tmp/overwrites directory
3427: # $context is passed as argument to &finishuserfileupload
1.686 albertel 3428: # $subdir - directory in userfile to store the file into
1.858 raeburn 3429: # $parser - instruction to parse file for objects ($parser = parse)
3430: # $allfiles - reference to hash for embedded objects
3431: # $codebase - reference to hash for codebase of java objects
3432: # $desuname - username for permanent storage of uploaded file
3433: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 3434: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
3435: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 3436: # $resizewidth - width (pixels) to which to resize uploaded image
3437: # $resizeheight - height (pixels) to which to resize uploaded image
1.1095 raeburn 3438: # $mimetype - reference to scalar to accommodate mime type determined
1.1152 raeburn 3439: # from File::MMagic.
1.858 raeburn 3440: #
1.686 albertel 3441: # output: url of file in userspace, or error: <message>
3442: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 3443:
1.531 albertel 3444: sub userfileupload {
1.1090 raeburn 3445: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095 raeburn 3446: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531 albertel 3447: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 3448: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 3449: $fname=&clean_filename($fname);
1.1090 raeburn 3450: # See if there is anything left
1.257 www 3451: unless ($fname) { return 'error: no uploaded file'; }
1.1090 raeburn 3452: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
3453: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
3454: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
3455: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523 raeburn 3456: my $now = time;
1.1090 raeburn 3457: my $filepath;
1.1095 raeburn 3458: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090 raeburn 3459: $filepath = 'tmp/helprequests/'.$now;
3460: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
3461: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
3462: '_'.$env{'user.domain'}.'/pending';
3463: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
3464: my ($docuname,$docudom);
3465: if ($destudom) {
3466: $docudom = $destudom;
3467: } else {
3468: $docudom = $env{'user.domain'};
3469: }
3470: if ($destuname) {
3471: $docuname = $destuname;
3472: } else {
3473: $docuname = $env{'user.name'};
3474: }
3475: if (exists($env{'form.group'})) {
3476: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3477: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3478: }
3479: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
3480: if ($context eq 'canceloverwrite') {
3481: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
3482: if (-e $tempfile) {
3483: my @info = stat($tempfile);
3484: if ($info[9] eq $env{'form.timestamp'}) {
3485: unlink($tempfile);
3486: }
3487: }
3488: return;
1.523 raeburn 3489: }
3490: }
1.1090 raeburn 3491: # Create the directory if not present
1.741 raeburn 3492: my @parts=split(/\//,$filepath);
3493: my $fullpath = $perlvar{'lonDaemons'};
3494: for (my $i=0;$i<@parts;$i++) {
3495: $fullpath .= '/'.$parts[$i];
3496: if ((-e $fullpath)!=1) {
3497: mkdir($fullpath,0777);
3498: }
3499: }
3500: open(my $fh,'>'.$fullpath.'/'.$fname);
3501: print $fh $env{'form.'.$formname};
3502: close($fh);
1.1090 raeburn 3503: if ($context eq 'existingfile') {
3504: my @info = stat($fullpath.'/'.$fname);
3505: return ($fullpath.'/'.$fname,$info[9]);
3506: } else {
3507: return $fullpath.'/'.$fname;
3508: }
1.523 raeburn 3509: }
1.995 raeburn 3510: if ($subdir eq 'scantron') {
3511: $fname = 'scantron_orig_'.$fname;
1.1093 raeburn 3512: } else {
1.995 raeburn 3513: $fname="$subdir/$fname";
3514: }
1.1090 raeburn 3515: if ($context eq 'coursedoc') {
1.638 albertel 3516: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3517: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 3518: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 3519: return &finishuserfileupload($docuname,$docudom,
3520: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 3521: $codebase,$thumbwidth,$thumbheight,
1.1095 raeburn 3522: $resizewidth,$resizeheight,$context,$mimetype);
1.481 raeburn 3523: } else {
1.1218 raeburn 3524: if ($env{'form.folder'}) {
3525: $fname=$env{'form.folder'}.'/'.$fname;
3526: }
1.638 albertel 3527: return &process_coursefile('uploaddoc',$docuname,$docudom,
3528: $fname,$formname,$parser,
1.1095 raeburn 3529: $allfiles,$codebase,$mimetype);
1.481 raeburn 3530: }
1.719 banghart 3531: } elsif (defined($destuname)) {
3532: my $docuname=$destuname;
3533: my $docudom=$destudom;
1.860 raeburn 3534: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3535: $parser,$allfiles,$codebase,
1.1051 raeburn 3536: $thumbwidth,$thumbheight,
1.1095 raeburn 3537: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3538: } else {
1.638 albertel 3539: my $docuname=$env{'user.name'};
3540: my $docudom=$env{'user.domain'};
1.1220 raeburn 3541: if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714 raeburn 3542: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3543: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3544: }
1.860 raeburn 3545: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3546: $parser,$allfiles,$codebase,
1.1051 raeburn 3547: $thumbwidth,$thumbheight,
1.1095 raeburn 3548: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3549: }
1.271 www 3550: }
3551:
3552: sub finishuserfileupload {
1.860 raeburn 3553: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095 raeburn 3554: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477 raeburn 3555: my $path=$docudom.'/'.$docuname.'/';
1.258 www 3556: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 3557:
1.860 raeburn 3558: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 3559: $file=$fname;
3560: if ($fname=~m|/|) {
3561: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
3562: $path.=$fnamepath.'/';
3563: }
1.259 www 3564: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 3565: my $count;
3566: for ($count=4;$count<=$#parts;$count++) {
3567: $filepath.="/$parts[$count]";
3568: if ((-e $filepath)!=1) {
3569: mkdir($filepath,0777);
3570: }
3571: }
1.984 neumanie 3572:
1.258 www 3573: # Save the file
3574: {
1.701 albertel 3575: if (!open(FH,'>'.$filepath.'/'.$file)) {
3576: &logthis('Failed to create '.$filepath.'/'.$file);
3577: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
3578: return '/adm/notfound.html';
3579: }
1.1090 raeburn 3580: if ($context eq 'overwrite') {
1.1117 foxr 3581: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090 raeburn 3582: my $target = $filepath.'/'.$file;
3583: if (-e $source) {
3584: my @info = stat($source);
3585: if ($info[9] eq $env{'form.timestamp'}) {
3586: unless (&File::Copy::move($source,$target)) {
3587: &logthis('Failed to overwrite '.$filepath.'/'.$file);
3588: return "Moving from $source failed";
3589: }
3590: } else {
3591: return "Temporary file: $source had unexpected date/time for last modification";
3592: }
3593: } else {
3594: return "Temporary file: $source missing";
3595: }
3596: } elsif (!print FH ($env{'form.'.$formname})) {
1.701 albertel 3597: &logthis('Failed to write to '.$filepath.'/'.$file);
3598: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
3599: return '/adm/notfound.html';
3600: }
1.570 albertel 3601: close(FH);
1.1051 raeburn 3602: if ($resizewidth && $resizeheight) {
3603: my $mm = new File::MMagic;
3604: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
3605: if ($mime_type =~ m{^image/}) {
3606: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
3607: }
1.977 amueller 3608: }
1.258 www 3609: }
1.1152 raeburn 3610: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
3611: if (ref($mimetype)) {
3612: if ($$mimetype eq '') {
3613: my $mm = new File::MMagic;
3614: my $type = $mm->checktype_filename($filepath.'/'.$file);
3615: $$mimetype = $type;
3616: }
3617: }
3618: }
1.637 raeburn 3619: if ($parser eq 'parse') {
1.1152 raeburn 3620: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024 raeburn 3621: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
3622: $allfiles,$codebase);
3623: unless ($parse_result eq 'ok') {
3624: &logthis('Failed to parse '.$filepath.$file.
3625: ' for embedded media: '.$parse_result);
3626: }
1.637 raeburn 3627: }
3628: }
1.860 raeburn 3629: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
3630: my $input = $filepath.'/'.$file;
3631: my $output = $filepath.'/'.'tn-'.$file;
3632: my $thumbsize = $thumbwidth.'x'.$thumbheight;
3633: system("convert -sample $thumbsize $input $output");
3634: if (-e $filepath.'/'.'tn-'.$file) {
3635: $fetchthumb = 1;
3636: }
3637: }
1.858 raeburn 3638:
1.259 www 3639: # Notify homeserver to grep it
3640: #
1.984 neumanie 3641: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 3642: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 3643: if ($fetchresult eq 'ok') {
1.860 raeburn 3644: if ($fetchthumb) {
3645: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
3646: if ($thumbresult ne 'ok') {
3647: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
3648: $docuhome.': '.$thumbresult);
3649: }
3650: }
1.259 www 3651: #
1.258 www 3652: # Return the URL to it
1.494 albertel 3653: return '/uploaded/'.$path.$file;
1.263 www 3654: } else {
1.494 albertel 3655: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
3656: ': '.$fetchresult);
1.263 www 3657: return '/adm/notfound.html';
1.858 raeburn 3658: }
1.493 albertel 3659: }
3660:
1.637 raeburn 3661: sub extract_embedded_items {
1.961 raeburn 3662: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 3663: my @state = ();
1.1164 raeburn 3664: my (%lastids,%related,%shockwave,%flashvars);
1.637 raeburn 3665: my %javafiles = (
3666: codebase => '',
3667: code => '',
3668: archive => ''
3669: );
3670: my %mediafiles = (
3671: src => '',
3672: movie => '',
3673: );
1.648 raeburn 3674: my $p;
3675: if ($content) {
3676: $p = HTML::LCParser->new($content);
3677: } else {
1.961 raeburn 3678: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 3679: }
1.641 albertel 3680: while (my $t=$p->get_token()) {
1.640 albertel 3681: if ($t->[0] eq 'S') {
3682: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 3683: push(@state, $tagname);
1.648 raeburn 3684: if (lc($tagname) eq 'allow') {
3685: &add_filetype($allfiles,$attr->{'src'},'src');
3686: }
1.640 albertel 3687: if (lc($tagname) eq 'img') {
3688: &add_filetype($allfiles,$attr->{'src'},'src');
3689: }
1.886 albertel 3690: if (lc($tagname) eq 'a') {
1.1222 raeburn 3691: unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
1.1221 raeburn 3692: &add_filetype($allfiles,$attr->{'href'},'href');
3693: }
1.886 albertel 3694: }
1.645 raeburn 3695: if (lc($tagname) eq 'script') {
1.1164 raeburn 3696: my $src;
1.645 raeburn 3697: if ($attr->{'archive'} =~ /\.jar$/i) {
3698: &add_filetype($allfiles,$attr->{'archive'},'archive');
3699: } else {
1.1164 raeburn 3700: if ($attr->{'src'} ne '') {
3701: $src = $attr->{'src'};
3702: &add_filetype($allfiles,$src,'src');
3703: }
3704: }
3705: my $text = $p->get_trimmed_text();
3706: if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
3707: my @swfargs = split(/,/,$1);
3708: foreach my $item (@swfargs) {
3709: $item =~ s/["']//g;
3710: $item =~ s/^\s+//;
3711: $item =~ s/\s+$//;
3712: }
3713: if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
3714: if (ref($related{$swfargs[0]}) eq 'ARRAY') {
3715: push(@{$related{$swfargs[0]}},$swfargs[2]);
3716: } else {
3717: $related{$swfargs[0]} = [$swfargs[2]];
3718: }
3719: }
1.645 raeburn 3720: }
3721: }
3722: if (lc($tagname) eq 'link') {
3723: if (lc($attr->{'rel'}) eq 'stylesheet') {
3724: &add_filetype($allfiles,$attr->{'href'},'href');
3725: }
3726: }
1.640 albertel 3727: if (lc($tagname) eq 'object' ||
3728: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
3729: foreach my $item (keys(%javafiles)) {
3730: $javafiles{$item} = '';
3731: }
1.1164 raeburn 3732: if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
3733: $lastids{lc($tagname)} = $attr->{'id'};
3734: }
1.640 albertel 3735: }
3736: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
3737: my $name = lc($attr->{'name'});
3738: foreach my $item (keys(%javafiles)) {
3739: if ($name eq $item) {
3740: $javafiles{$item} = $attr->{'value'};
3741: last;
3742: }
3743: }
1.1164 raeburn 3744: my $pathfrom;
1.640 albertel 3745: foreach my $item (keys(%mediafiles)) {
3746: if ($name eq $item) {
1.1164 raeburn 3747: $pathfrom = $attr->{'value'};
3748: $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
3749: &add_filetype($allfiles,$pathfrom,$name);
1.640 albertel 3750: last;
3751: }
3752: }
1.1164 raeburn 3753: if ($name eq 'flashvars') {
3754: $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
3755: }
3756: if ($pathfrom ne '') {
3757: &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
3758: $pathfrom);
3759: }
1.640 albertel 3760: }
3761: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
3762: foreach my $item (keys(%javafiles)) {
3763: if ($attr->{$item}) {
3764: $javafiles{$item} = $attr->{$item};
3765: last;
3766: }
3767: }
3768: foreach my $item (keys(%mediafiles)) {
3769: if ($attr->{$item}) {
3770: &add_filetype($allfiles,$attr->{$item},$item);
3771: last;
3772: }
3773: }
1.1164 raeburn 3774: if (lc($tagname) eq 'embed') {
3775: if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
3776: &embedded_dependency($allfiles,\%related,$attr->{'name'},
3777: $attr->{'src'});
3778: }
3779: }
1.640 albertel 3780: }
1.1243 raeburn 3781: if (lc($tagname) eq 'iframe') {
3782: my $src = $attr->{'src'} ;
3783: if (($src ne '') && ($src !~ m{^(/|https?://)})) {
3784: &add_filetype($allfiles,$src,'src');
3785: } elsif ($src =~ m{^/}) {
3786: if ($env{'request.course.id'}) {
3787: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
3788: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
3789: my $url = &hreflocation('',$fullpath);
3790: if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
3791: my $relpath = $1;
3792: if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
3793: &add_filetype($allfiles,$1,'src');
3794: }
3795: }
3796: }
3797: }
3798: }
1.1164 raeburn 3799: if ($t->[4] =~ m{/>$}) {
1.1243 raeburn 3800: pop(@state);
1.1164 raeburn 3801: }
1.640 albertel 3802: } elsif ($t->[0] eq 'E') {
3803: my ($tagname) = ($t->[1]);
3804: if ($javafiles{'codebase'} ne '') {
3805: $javafiles{'codebase'} .= '/';
3806: }
3807: if (lc($tagname) eq 'applet' ||
3808: lc($tagname) eq 'object' ||
3809: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
3810: ) {
3811: foreach my $item (keys(%javafiles)) {
3812: if ($item ne 'codebase' && $javafiles{$item} ne '') {
3813: my $file=$javafiles{'codebase'}.$javafiles{$item};
3814: &add_filetype($allfiles,$file,$item);
3815: }
3816: }
3817: }
3818: pop @state;
3819: }
3820: }
1.1164 raeburn 3821: foreach my $id (sort(keys(%flashvars))) {
3822: if ($shockwave{$id} ne '') {
3823: my @pairs = split(/\&/,$flashvars{$id});
3824: foreach my $pair (@pairs) {
3825: my ($key,$value) = split(/\=/,$pair);
3826: if ($key eq 'thumb') {
3827: &add_filetype($allfiles,$value,$key);
3828: } elsif ($key eq 'content') {
3829: my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
3830: my ($ext) = ($value =~ /\.([^.]+)$/);
3831: if ($ext ne '') {
3832: &add_filetype($allfiles,$path.$value,$ext);
3833: }
3834: }
3835: }
3836: }
3837: }
1.637 raeburn 3838: return 'ok';
3839: }
3840:
1.639 albertel 3841: sub add_filetype {
3842: my ($allfiles,$file,$type)=@_;
3843: if (exists($allfiles->{$file})) {
3844: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
3845: push(@{$allfiles->{$file}}, &escape($type));
3846: }
3847: } else {
3848: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 3849: }
3850: }
3851:
1.1164 raeburn 3852: sub embedded_dependency {
3853: my ($allfiles,$related,$identifier,$pathfrom) = @_;
3854: if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
3855: if (($identifier ne '') &&
3856: (ref($related->{$identifier}) eq 'ARRAY') &&
3857: ($pathfrom ne '')) {
3858: my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
3859: foreach my $dep (@{$related->{$identifier}}) {
3860: &add_filetype($allfiles,$path.$dep,'object');
3861: }
3862: }
3863: }
3864: return;
3865: }
3866:
1.493 albertel 3867: sub removeuploadedurl {
1.984 neumanie 3868: my ($url)=@_;
3869: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 3870: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 3871: }
3872:
3873: sub removeuserfile {
3874: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 3875: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3876: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 3877: if ($result eq 'ok') {
1.798 raeburn 3878: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
3879: my $metafile = $fname.'.meta';
3880: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 3881: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 3882: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3883: my $sqlresult =
1.823 albertel 3884: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3885: 'portfolio_metadata',$group,
3886: 'delete');
1.798 raeburn 3887: }
3888: }
3889: return $result;
1.257 www 3890: }
1.15 www 3891:
1.530 albertel 3892: sub mkdiruserfile {
3893: my ($docuname,$docudom,$dir)=@_;
3894: my $home=&homeserver($docuname,$docudom);
3895: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
3896: }
3897:
1.531 albertel 3898: sub renameuserfile {
3899: my ($docuname,$docudom,$old,$new)=@_;
3900: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3901: my $result = &reply("renameuserfile:$docudom:$docuname:".
3902: &escape("$old").':'.&escape("$new"),$home);
3903: if ($result eq 'ok') {
3904: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
3905: my $oldmeta = $old.'.meta';
3906: my $newmeta = $new.'.meta';
3907: my $metaresult =
3908: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 3909: my $url = "/uploaded/$docudom/$docuname/$old";
3910: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3911: my $sqlresult =
1.823 albertel 3912: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3913: 'portfolio_metadata',$group,
3914: 'delete');
1.798 raeburn 3915: }
3916: }
3917: return $result;
1.531 albertel 3918: }
3919:
1.14 www 3920: # ------------------------------------------------------------------------- Log
3921:
3922: sub log {
3923: my ($dom,$nam,$hom,$what)=@_;
1.47 www 3924: return critical("log:$dom:$nam:$what",$hom);
1.157 www 3925: }
3926:
3927: # ------------------------------------------------------------------ Course Log
1.352 www 3928: #
3929: # This routine flushes several buffers of non-mission-critical nature
3930: #
1.157 www 3931:
3932: sub flushcourselogs {
1.352 www 3933: &logthis('Flushing log buffers');
3934: #
3935: # course logs
3936: # This is a log of all transactions in a course, which can be used
3937: # for data mining purposes
3938: #
3939: # It also collects the courseid database, which lists last transaction
3940: # times and course titles for all courseids
3941: #
3942: my %courseidbuffer=();
1.921 raeburn 3943: foreach my $crsid (keys(%courselogs)) {
1.352 www 3944: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 3945: &escape($courselogs{$crsid}),
3946: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 3947: delete $courselogs{$crsid};
3948: } else {
3949: &logthis('Failed to flush log buffer for '.$crsid);
3950: if (length($courselogs{$crsid})>40000) {
1.672 albertel 3951: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 3952: " exceeded maximum size, deleting.</font>");
3953: delete $courselogs{$crsid};
3954: }
1.352 www 3955: }
1.920 raeburn 3956: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 3957: 'description' => $coursedescrbuf{$crsid},
3958: 'inst_code' => $courseinstcodebuf{$crsid},
3959: 'type' => $coursetypebuf{$crsid},
3960: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 3961: };
1.191 harris41 3962: }
1.352 www 3963: #
3964: # Write course id database (reverse lookup) to homeserver of courses
3965: # Is used in pickcourse
3966: #
1.840 albertel 3967: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 3968: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 3969: $courseidbuffer{$crs_home},
3970: $crs_home,'timeonly');
1.352 www 3971: }
3972: #
3973: # File accesses
3974: # Writes to the dynamic metadata of resources to get hit counts, etc.
3975: #
1.449 matthew 3976: foreach my $entry (keys(%accesshash)) {
1.458 matthew 3977: if ($entry =~ /___count$/) {
3978: my ($dom,$name);
1.807 albertel 3979: ($dom,$name,undef)=
1.811 albertel 3980: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 3981: if (! defined($dom) || $dom eq '' ||
3982: ! defined($name) || $name eq '') {
1.620 albertel 3983: my $cid = $env{'request.course.id'};
3984: $dom = $env{'request.'.$cid.'.domain'};
3985: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 3986: }
1.450 matthew 3987: my $value = $accesshash{$entry};
3988: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
3989: my %temphash=($url => $value);
1.449 matthew 3990: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
3991: if ($result eq 'ok') {
3992: delete $accesshash{$entry};
3993: }
3994: } else {
1.811 albertel 3995: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159 www 3996: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450 matthew 3997: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 3998: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
3999: delete $accesshash{$entry};
4000: }
1.185 www 4001: }
1.191 harris41 4002: }
1.352 www 4003: #
4004: # Roles
4005: # Reverse lookup of user roles for course faculty/staff and co-authorship
4006: #
1.800 albertel 4007: foreach my $entry (keys(%userrolehash)) {
1.351 www 4008: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 4009: split(/\:/,$entry);
4010: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 4011: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 4012: $rudom,$runame) eq 'ok') {
4013: delete $userrolehash{$entry};
4014: }
4015: }
1.662 raeburn 4016: #
4017: # Reverse lookup of domain roles (dc, ad, li, sc, au)
4018: #
4019: my %domrolebuffer = ();
1.1000 raeburn 4020: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 4021: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 4022: if ($domrolebuffer{$rudom}) {
4023: $domrolebuffer{$rudom}.='&'.&escape($entry).
4024: '='.&escape($domainrolehash{$entry});
4025: } else {
4026: $domrolebuffer{$rudom}.=&escape($entry).
4027: '='.&escape($domainrolehash{$entry});
4028: }
4029: delete $domainrolehash{$entry};
4030: }
4031: foreach my $dom (keys(%domrolebuffer)) {
1.841 albertel 4032: my %servers = &get_servers($dom,'library');
4033: foreach my $tryserver (keys(%servers)) {
4034: unless (&reply('domroleput:'.$dom.':'.
4035: $domrolebuffer{$dom},$tryserver) eq 'ok') {
4036: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
4037: }
1.662 raeburn 4038: }
4039: }
1.186 www 4040: $dumpcount++;
1.157 www 4041: }
4042:
4043: sub courselog {
4044: my $what=shift;
1.158 www 4045: $what=time.':'.$what;
1.620 albertel 4046: unless ($env{'request.course.id'}) { return ''; }
4047: $coursedombuf{$env{'request.course.id'}}=
4048: $env{'course.'.$env{'request.course.id'}.'.domain'};
4049: $coursenumbuf{$env{'request.course.id'}}=
4050: $env{'course.'.$env{'request.course.id'}.'.num'};
4051: $coursehombuf{$env{'request.course.id'}}=
4052: $env{'course.'.$env{'request.course.id'}.'.home'};
4053: $coursedescrbuf{$env{'request.course.id'}}=
4054: $env{'course.'.$env{'request.course.id'}.'.description'};
4055: $courseinstcodebuf{$env{'request.course.id'}}=
4056: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
4057: $courseownerbuf{$env{'request.course.id'}}=
4058: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 4059: $coursetypebuf{$env{'request.course.id'}}=
4060: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 4061: if (defined $courselogs{$env{'request.course.id'}}) {
4062: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 4063: } else {
1.620 albertel 4064: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 4065: }
1.620 albertel 4066: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 4067: &flushcourselogs();
4068: }
1.158 www 4069: }
4070:
4071: sub courseacclog {
4072: my $fnsymb=shift;
1.620 albertel 4073: unless ($env{'request.course.id'}) { return ''; }
4074: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144 www 4075: if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187 www 4076: $what.=':POST';
1.583 matthew 4077: # FIXME: Probably ought to escape things....
1.800 albertel 4078: foreach my $key (keys(%env)) {
4079: if ($key=~/^form\.(.*)/) {
1.975 raeburn 4080: my $formitem = $1;
4081: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
4082: $what.=':'.$formitem.'='.$env{$key};
4083: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
4084: $what.=':'.$formitem.'='.$env{$key};
4085: }
1.158 www 4086: }
1.191 harris41 4087: }
1.583 matthew 4088: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
4089: # FIXME: We should not be depending on a form parameter that someone
4090: # editing lonsearchcat.pm might change in the future.
1.620 albertel 4091: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 4092: $what.= ':POST';
4093: # FIXME: Probably ought to escape things....
4094: foreach my $element ('courseexp','crsfulltext','crsrelated',
4095: 'crsdiscuss') {
1.620 albertel 4096: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 4097: }
4098: }
1.158 www 4099: }
4100: &courselog($what);
1.149 www 4101: }
4102:
1.185 www 4103: sub countacc {
4104: my $url=&declutter(shift);
1.458 matthew 4105: return if (! defined($url) || $url eq '');
1.620 albertel 4106: unless ($env{'request.course.id'}) { return ''; }
1.1158 www 4107: #
4108: # Mark that this url was used in this course
4109: #
1.620 albertel 4110: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158 www 4111: #
4112: # Increase the access count for this resource in this child process
4113: #
1.281 www 4114: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 4115: $accesshash{$key}++;
1.185 www 4116: }
1.349 www 4117:
1.361 www 4118: sub linklog {
4119: my ($from,$to)=@_;
4120: $from=&declutter($from);
4121: $to=&declutter($to);
4122: $accesshash{$from.'___'.$to.'___comefrom'}=1;
4123: $accesshash{$to.'___'.$from.'___goto'}=1;
4124: }
1.1160 www 4125:
4126: sub statslog {
4127: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
4128: if ($users<2) { return; }
4129: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
4130: 'course' => $env{'request.course.id'},
4131: 'sections' => '"all"',
4132: 'num_students' => $users,
4133: 'part' => $part,
4134: 'symb' => $symb,
4135: 'mean_tries' => $av_attempts,
4136: 'deg_of_diff' => $degdiff});
4137: foreach my $key (keys(%dynstore)) {
4138: $accesshash{$key}=$dynstore{$key};
4139: }
4140: }
1.361 www 4141:
1.349 www 4142: sub userrolelog {
4143: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169 droeschl 4144: if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350 www 4145: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
4146: $userrolehash
4147: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 4148: =$tend.':'.$tstart;
1.662 raeburn 4149: }
1.1169 droeschl 4150: if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898 albertel 4151: $userrolehash
4152: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
4153: =$tend.':'.$tstart;
4154: }
1.1169 droeschl 4155: if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
1.662 raeburn 4156: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
4157: $domainrolehash
4158: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
4159: = $tend.':'.$tstart;
4160: }
1.351 www 4161: }
4162:
1.957 raeburn 4163: sub courserolelog {
4164: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1184 raeburn 4165: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
4166: my $cdom = $1;
4167: my $cnum = $2;
4168: my $sec = $3;
4169: my $namespace = 'rolelog';
4170: my %storehash = (
4171: role => $trole,
4172: start => $tstart,
4173: end => $tend,
4174: selfenroll => $selfenroll,
4175: context => $context,
4176: );
4177: if ($trole eq 'gr') {
4178: $namespace = 'groupslog';
4179: $storehash{'group'} = $sec;
4180: } else {
4181: $storehash{'section'} = $sec;
4182: }
1.1188 raeburn 4183: &write_log('course',$namespace,\%storehash,$delflag,$username,
4184: $domain,$cnum,$cdom);
1.1184 raeburn 4185: if (($trole ne 'st') || ($sec ne '')) {
4186: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957 raeburn 4187: }
4188: }
4189: return;
4190: }
4191:
1.1184 raeburn 4192: sub domainrolelog {
4193: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4194: if ($area =~ m{^/($match_domain)/$}) {
4195: my $cdom = $1;
4196: my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
4197: my $namespace = 'rolelog';
4198: my %storehash = (
4199: role => $trole,
4200: start => $tstart,
4201: end => $tend,
4202: context => $context,
4203: );
1.1188 raeburn 4204: &write_log('domain',$namespace,\%storehash,$delflag,$username,
4205: $domain,$domconfiguser,$cdom);
1.1184 raeburn 4206: }
4207: return;
4208:
4209: }
4210:
4211: sub coauthorrolelog {
4212: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4213: if ($area =~ m{^/($match_domain)/($match_username)$}) {
4214: my $audom = $1;
4215: my $auname = $2;
4216: my $namespace = 'rolelog';
4217: my %storehash = (
4218: role => $trole,
4219: start => $tstart,
4220: end => $tend,
4221: context => $context,
4222: );
1.1188 raeburn 4223: &write_log('author',$namespace,\%storehash,$delflag,$username,
4224: $domain,$auname,$audom);
1.1184 raeburn 4225: }
4226: return;
4227: }
4228:
1.351 www 4229: sub get_course_adv_roles {
1.948 raeburn 4230: my ($cid,$codes) = @_;
1.620 albertel 4231: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 4232: my %coursehash=&coursedescription($cid);
1.988 raeburn 4233: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 4234: my %nothide=();
1.800 albertel 4235: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 4236: if ($user !~ /:/) {
4237: $nothide{join(':',split(/[\@]/,$user))}=1;
4238: } else {
4239: $nothide{$user}=1;
4240: }
1.470 www 4241: }
1.1219 raeburn 4242: my @possdoms = ($coursehash{'domain'});
4243: if ($coursehash{'checkforpriv'}) {
4244: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
4245: }
1.351 www 4246: my %returnhash=();
4247: my %dumphash=
4248: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
4249: my $now=time;
1.997 raeburn 4250: my %privileged;
1.1000 raeburn 4251: foreach my $entry (keys(%dumphash)) {
1.800 albertel 4252: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 4253: if (($tstart) && ($tstart<0)) { next; }
4254: if (($tend) && ($tend<$now)) { next; }
4255: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 4256: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 4257: if ($username eq '' || $domain eq '') { next; }
1.1219 raeburn 4258: if ((&privileged($username,$domain,\@possdoms)) &&
1.997 raeburn 4259: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 4260: if ($role eq 'cr') { next; }
1.948 raeburn 4261: if ($codes) {
4262: if ($section) { $role .= ':'.$section; }
4263: if ($returnhash{$role}) {
4264: $returnhash{$role}.=','.$username.':'.$domain;
4265: } else {
4266: $returnhash{$role}=$username.':'.$domain;
4267: }
1.351 www 4268: } else {
1.988 raeburn 4269: my $key=&plaintext($role,$crstype);
1.973 bisitz 4270: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 4271: if ($returnhash{$key}) {
4272: $returnhash{$key}.=','.$username.':'.$domain;
4273: } else {
4274: $returnhash{$key}=$username.':'.$domain;
4275: }
1.351 www 4276: }
1.948 raeburn 4277: }
1.400 www 4278: return %returnhash;
4279: }
4280:
4281: sub get_my_roles {
1.937 raeburn 4282: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 4283: unless (defined($uname)) { $uname=$env{'user.name'}; }
4284: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 4285: my (%dumphash,%nothide);
1.1086 raeburn 4286: if ($context eq 'userroles') {
1.1166 raeburn 4287: %dumphash = &dump('roles',$udom,$uname);
1.858 raeburn 4288: } else {
1.1219 raeburn 4289: %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 4290: if ($hidepriv) {
4291: my %coursehash=&coursedescription($udom.'_'.$uname);
4292: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
4293: if ($user !~ /:/) {
4294: $nothide{join(':',split(/[\@]/,$user))} = 1;
4295: } else {
4296: $nothide{$user} = 1;
4297: }
4298: }
4299: }
1.858 raeburn 4300: }
1.400 www 4301: my %returnhash=();
4302: my $now=time;
1.999 raeburn 4303: my %privileged;
1.800 albertel 4304: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 4305: my ($role,$tend,$tstart);
4306: if ($context eq 'userroles') {
1.1149 raeburn 4307: next if ($entry =~ /^rolesdef/);
1.867 raeburn 4308: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
4309: } else {
4310: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
4311: }
1.400 www 4312: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 4313: my $status = 'active';
1.939 raeburn 4314: if (($tend) && ($tend<=$now)) {
1.832 raeburn 4315: $status = 'previous';
4316: }
4317: if (($tstart) && ($now<$tstart)) {
4318: $status = 'future';
4319: }
4320: if (ref($types) eq 'ARRAY') {
4321: if (!grep(/^\Q$status\E$/,@{$types})) {
4322: next;
4323: }
4324: } else {
4325: if ($status ne 'active') {
4326: next;
4327: }
4328: }
1.867 raeburn 4329: my ($rolecode,$username,$domain,$section,$area);
4330: if ($context eq 'userroles') {
1.1186 raeburn 4331: ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867 raeburn 4332: (undef,$domain,$username,$section) = split(/\//,$area);
4333: } else {
4334: ($role,$username,$domain,$section) = split(/\:/,$entry);
4335: }
1.832 raeburn 4336: if (ref($roledoms) eq 'ARRAY') {
4337: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
4338: next;
4339: }
4340: }
4341: if (ref($roles) eq 'ARRAY') {
4342: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 4343: if ($role =~ /^cr\//) {
4344: if (!grep(/^cr$/,@{$roles})) {
4345: next;
4346: }
1.1104 raeburn 4347: } elsif ($role =~ /^gr\//) {
4348: if (!grep(/^gr$/,@{$roles})) {
4349: next;
4350: }
1.922 raeburn 4351: } else {
4352: next;
4353: }
1.832 raeburn 4354: }
1.867 raeburn 4355: }
1.937 raeburn 4356: if ($hidepriv) {
1.1219 raeburn 4357: my @privroles = ('dc','su');
1.999 raeburn 4358: if ($context eq 'userroles') {
1.1219 raeburn 4359: next if (grep(/^\Q$role\E$/,@privroles));
1.999 raeburn 4360: } else {
1.1219 raeburn 4361: my $possdoms = [$domain];
4362: if (ref($roledoms) eq 'ARRAY') {
4363: push(@{$possdoms},@{$roledoms});
1.999 raeburn 4364: }
1.1219 raeburn 4365: if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999 raeburn 4366: if (!$nothide{$username.':'.$domain}) {
4367: next;
4368: }
4369: }
1.937 raeburn 4370: }
4371: }
1.933 raeburn 4372: if ($withsec) {
4373: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
4374: $tstart.':'.$tend;
4375: } else {
4376: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
4377: }
1.832 raeburn 4378: }
1.373 www 4379: return %returnhash;
1.399 www 4380: }
4381:
4382: # ----------------------------------------------------- Frontpage Announcements
4383: #
4384: #
4385:
4386: sub postannounce {
4387: my ($server,$text)=@_;
1.844 albertel 4388: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 4389: unless ($text=~/\w/) { $text=''; }
4390: return &reply('setannounce:'.&escape($text),$server);
4391: }
4392:
4393: sub getannounce {
1.448 albertel 4394:
4395: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 4396: my $announcement='';
1.800 albertel 4397: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 4398: close($fh);
1.399 www 4399: if ($announcement=~/\w/) {
4400: return
4401: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 4402: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 4403: } else {
4404: return '';
4405: }
4406: } else {
4407: return '';
4408: }
1.351 www 4409: }
1.353 www 4410:
4411: # ---------------------------------------------------------- Course ID routines
4412: # Deal with domain's nohist_courseid.db files
4413: #
4414:
4415: sub courseidput {
1.921 raeburn 4416: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 4417: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 4418: my $outcome;
4419: if ($caller eq 'timeonly') {
4420: my $cids = '';
4421: foreach my $item (keys(%$storehash)) {
4422: $cids.=&escape($item).'&';
4423: }
4424: $cids=~s/\&$//;
4425: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
4426: $coursehome);
4427: } else {
4428: my $items = '';
4429: foreach my $item (keys(%$storehash)) {
4430: $items.= &escape($item).'='.
4431: &freeze_escape($$storehash{$item}).'&';
4432: }
4433: $items=~s/\&$//;
4434: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
4435: $coursehome);
1.918 raeburn 4436: }
4437: if ($outcome eq 'unknown_cmd') {
4438: my $what;
4439: foreach my $cid (keys(%$storehash)) {
4440: $what .= &escape($cid).'=';
1.921 raeburn 4441: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 4442: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 4443: }
4444: $what =~ s/\:$/&/;
4445: }
4446: $what =~ s/\&$//;
4447: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
4448: } else {
4449: return $outcome;
4450: }
1.353 www 4451: }
4452:
4453: sub courseiddump {
1.921 raeburn 4454: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 4455: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 4456: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1247 raeburn 4457: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1287 raeburn 4458: $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918 raeburn 4459: my $as_hash = 1;
4460: my %returnhash;
4461: if (!$domfilter) { $domfilter=''; }
1.845 albertel 4462: my %libserv = &all_library();
4463: foreach my $tryserver (keys(%libserv)) {
4464: if ( ( $hostidflag == 1
4465: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
4466: || (!defined($hostidflag)) ) {
4467:
1.918 raeburn 4468: if (($domfilter eq '') ||
4469: (&host_domain($tryserver) eq $domfilter)) {
1.1180 droeschl 4470: my $rep;
4471: if (grep { $_ eq $tryserver } current_machine_ids()) {
4472: $rep = LONCAPA::Lond::dump_course_id_handler(
4473: join(":", (&host_domain($tryserver), $sincefilter,
4474: &escape($descfilter), &escape($instcodefilter),
4475: &escape($ownerfilter), &escape($coursefilter),
4476: &escape($typefilter), &escape($regexp_ok),
4477: $as_hash, &escape($selfenrollonly),
4478: &escape($catfilter), $showhidden, $caller,
4479: &escape($cloner), &escape($cc_clone), $cloneonly,
4480: &escape($createdbefore), &escape($createdafter),
1.1287 raeburn 4481: &escape($creationcontext),$domcloner,$hasuniquecode,
4482: $reqcrsdom,&escape($reqinstcode))));
1.1180 droeschl 4483: } else {
4484: $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
4485: $sincefilter.':'.&escape($descfilter).':'.
4486: &escape($instcodefilter).':'.&escape($ownerfilter).
4487: ':'.&escape($coursefilter).':'.&escape($typefilter).
4488: ':'.&escape($regexp_ok).':'.$as_hash.':'.
4489: &escape($selfenrollonly).':'.&escape($catfilter).':'.
4490: $showhidden.':'.$caller.':'.&escape($cloner).':'.
4491: &escape($cc_clone).':'.$cloneonly.':'.
4492: &escape($createdbefore).':'.&escape($createdafter).':'.
1.1287 raeburn 4493: &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
4494: ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1180 droeschl 4495: }
4496:
1.918 raeburn 4497: my @pairs=split(/\&/,$rep);
4498: foreach my $item (@pairs) {
4499: my ($key,$value)=split(/\=/,$item,2);
4500: $key = &unescape($key);
4501: next if ($key =~ /^error: 2 /);
4502: my $result = &thaw_unescape($value);
4503: if (ref($result) eq 'HASH') {
4504: $returnhash{$key}=$result;
4505: } else {
1.921 raeburn 4506: my @responses = split(/:/,$value);
4507: my @items = ('description','inst_code','owner','type');
1.918 raeburn 4508: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 4509: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 4510: }
1.1008 raeburn 4511: }
1.353 www 4512: }
4513: }
4514: }
4515: }
4516: return %returnhash;
4517: }
4518:
1.1055 raeburn 4519: sub courselastaccess {
4520: my ($cdom,$cnum,$hostidref) = @_;
4521: my %returnhash;
4522: if ($cdom && $cnum) {
4523: my $chome = &homeserver($cnum,$cdom);
4524: if ($chome ne 'no_host') {
4525: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
4526: &extract_lastaccess(\%returnhash,$rep);
4527: }
4528: } else {
4529: if (!$cdom) { $cdom=''; }
4530: my %libserv = &all_library();
4531: foreach my $tryserver (keys(%libserv)) {
4532: if (ref($hostidref) eq 'ARRAY') {
4533: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
4534: }
4535: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
4536: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
4537: &extract_lastaccess(\%returnhash,$rep);
4538: }
4539: }
4540: }
4541: return %returnhash;
4542: }
4543:
4544: sub extract_lastaccess {
4545: my ($returnhash,$rep) = @_;
4546: if (ref($returnhash) eq 'HASH') {
4547: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
4548: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
4549: $rep eq '') {
4550: my @pairs=split(/\&/,$rep);
4551: foreach my $item (@pairs) {
4552: my ($key,$value)=split(/\=/,$item,2);
4553: $key = &unescape($key);
4554: next if ($key =~ /^error: 2 /);
4555: $returnhash->{$key} = &thaw_unescape($value);
4556: }
4557: }
4558: }
4559: return;
4560: }
4561:
1.658 raeburn 4562: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 4563:
4564: sub dcmailput {
1.685 raeburn 4565: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 4566: my $status = &Apache::lonnet::critical(
1.740 www 4567: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
4568: &escape($message),$server);
1.662 raeburn 4569: return $status;
4570: }
4571:
1.658 raeburn 4572: sub dcmaildump {
4573: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 4574: my %returnhash=();
1.846 albertel 4575:
4576: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 4577: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
4578: &escape($enddate).':';
4579: my @esc_senders=map { &escape($_)} @$senders;
4580: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 4581: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 4582: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 4583: if (($key) && ($value)) {
4584: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 4585: }
4586: }
4587: }
4588: return %returnhash;
4589: }
1.662 raeburn 4590: # ---------------------------------------------------------- Domain roles
4591:
4592: sub get_domain_roles {
4593: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 4594: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 4595: $startdate = '.';
4596: }
1.1018 raeburn 4597: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 4598: $enddate = '.';
4599: }
1.922 raeburn 4600: my $rolelist;
4601: if (ref($roles) eq 'ARRAY') {
1.1219 raeburn 4602: $rolelist = join('&',@{$roles});
1.922 raeburn 4603: }
1.662 raeburn 4604: my %personnel = ();
1.841 albertel 4605:
4606: my %servers = &get_servers($dom,'library');
4607: foreach my $tryserver (keys(%servers)) {
4608: %{$personnel{$tryserver}}=();
4609: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
4610: &escape($startdate).':'.
4611: &escape($enddate).':'.
4612: &escape($rolelist), $tryserver))) {
4613: my ($key,$value) = split(/\=/,$line,2);
4614: if (($key) && ($value)) {
4615: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
4616: }
4617: }
1.662 raeburn 4618: }
4619: return %personnel;
4620: }
1.658 raeburn 4621:
1.1057 www 4622: # ----------------------------------------------------------- Interval timing
1.149 www 4623:
1.1153 www 4624: {
4625: # Caches needed for speedup of navmaps
4626: # We don't want to cache this for very long at all (5 seconds at most)
4627: #
4628: # The user for whom we cache
4629: my $cachedkey='';
4630: # The cached times for this user
4631: my %cachedtimes=();
4632: # When this was last done
1.1282 raeburn 4633: my $cachedtime='';
1.1153 www 4634:
4635: sub load_all_first_access {
1.1154 raeburn 4636: my ($uname,$udom)=@_;
1.1156 www 4637: if (($cachedkey eq $uname.':'.$udom) &&
1.1174 raeburn 4638: (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154 raeburn 4639: return;
4640: }
4641: $cachedtime=time;
4642: $cachedkey=$uname.':'.$udom;
4643: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153 www 4644: }
4645:
1.504 albertel 4646: sub get_first_access {
1.1162 raeburn 4647: my ($type,$argsymb,$argmap)=@_;
1.790 albertel 4648: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4649: if ($argsymb) { $symb=$argsymb; }
4650: my ($map,$id,$res)=&decode_symb($symb);
1.1162 raeburn 4651: if ($argmap) { $map = $argmap; }
1.926 albertel 4652: if ($type eq 'course') {
4653: $res='course';
4654: } elsif ($type eq 'map') {
1.588 albertel 4655: $res=&symbread($map);
4656: } else {
4657: $res=$symb;
4658: }
1.1153 www 4659: &load_all_first_access($uname,$udom);
4660: return $cachedtimes{"$courseid\0$res"};
1.504 albertel 4661: }
4662:
4663: sub set_first_access {
1.1162 raeburn 4664: my ($type,$interval)=@_;
1.790 albertel 4665: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4666: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 4667: if ($type eq 'course') {
4668: $res='course';
4669: } elsif ($type eq 'map') {
1.588 albertel 4670: $res=&symbread($map);
4671: } else {
4672: $res=$symb;
4673: }
1.1153 www 4674: $cachedkey='';
1.1162 raeburn 4675: my $firstaccess=&get_first_access($type,$symb,$map);
1.505 albertel 4676: if (!$firstaccess) {
1.1162 raeburn 4677: my $start = time;
4678: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
4679: $udom,$uname);
4680: if ($putres eq 'ok') {
4681: &put('timerinterval',{"$courseid\0$res"=>$interval},
4682: $udom,$uname);
4683: &appenv(
4684: {
4685: 'course.'.$courseid.'.firstaccess.'.$res => $start,
4686: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
4687: }
4688: );
4689: }
4690: return $putres;
1.505 albertel 4691: }
4692: return 'already_set';
1.504 albertel 4693: }
1.1153 www 4694: }
1.1282 raeburn 4695:
1.110 www 4696: # --------------------------------------------- Set Expire Date for Spreadsheet
4697:
4698: sub expirespread {
4699: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 4700: my $cid=$env{'request.course.id'};
1.110 www 4701: if ($cid) {
4702: my $now=time;
4703: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 4704: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
4705: $env{'course.'.$cid.'.num'}.
1.110 www 4706: ':nohist_expirationdates:'.
4707: &escape($key).'='.$now,
1.620 albertel 4708: $env{'course.'.$cid.'.home'})
1.110 www 4709: }
4710: return 'ok';
1.14 www 4711: }
4712:
1.109 www 4713: # ----------------------------------------------------- Devalidate Spreadsheets
4714:
4715: sub devalidate {
1.325 www 4716: my ($symb,$uname,$udom)=@_;
1.620 albertel 4717: my $cid=$env{'request.course.id'};
1.109 www 4718: if ($cid) {
1.391 matthew 4719: # delete the stored spreadsheets for
4720: # - the student level sheet of this user in course's homespace
4721: # - the assessment level sheet for this resource
4722: # for this user in user's homespace
1.553 albertel 4723: # - current conditional state info
1.325 www 4724: my $key=$uname.':'.$udom.':';
1.109 www 4725: my $status=
1.299 matthew 4726: &del('nohist_calculatedsheets',
1.391 matthew 4727: [$key.'studentcalc:'],
1.620 albertel 4728: $env{'course.'.$cid.'.domain'},
4729: $env{'course.'.$cid.'.num'})
1.133 albertel 4730: .' '.
4731: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 4732: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 4733: unless ($status eq 'ok ok') {
4734: &logthis('Could not devalidate spreadsheet '.
1.325 www 4735: $uname.' at '.$udom.' for '.
1.109 www 4736: $symb.': '.$status);
1.133 albertel 4737: }
1.553 albertel 4738: &delenv('user.state.'.$cid);
1.109 www 4739: }
4740: }
4741:
1.265 albertel 4742: sub get_scalar {
4743: my ($string,$end) = @_;
4744: my $value;
4745: if ($$string =~ s/^([^&]*?)($end)/$2/) {
4746: $value = $1;
4747: } elsif ($$string =~ s/^([^&]*?)&//) {
4748: $value = $1;
4749: }
4750: return &unescape($value);
4751: }
4752:
4753: sub array2str {
4754: my (@array) = @_;
4755: my $result=&arrayref2str(\@array);
4756: $result=~s/^__ARRAY_REF__//;
4757: $result=~s/__END_ARRAY_REF__$//;
4758: return $result;
4759: }
4760:
1.204 albertel 4761: sub arrayref2str {
4762: my ($arrayref) = @_;
1.265 albertel 4763: my $result='__ARRAY_REF__';
1.204 albertel 4764: foreach my $elem (@$arrayref) {
1.265 albertel 4765: if(ref($elem) eq 'ARRAY') {
4766: $result.=&arrayref2str($elem).'&';
4767: } elsif(ref($elem) eq 'HASH') {
4768: $result.=&hashref2str($elem).'&';
4769: } elsif(ref($elem)) {
4770: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 4771: } else {
4772: $result.=&escape($elem).'&';
4773: }
4774: }
4775: $result=~s/\&$//;
1.265 albertel 4776: $result .= '__END_ARRAY_REF__';
1.204 albertel 4777: return $result;
4778: }
4779:
1.168 albertel 4780: sub hash2str {
1.204 albertel 4781: my (%hash) = @_;
4782: my $result=&hashref2str(\%hash);
1.265 albertel 4783: $result=~s/^__HASH_REF__//;
4784: $result=~s/__END_HASH_REF__$//;
1.204 albertel 4785: return $result;
4786: }
4787:
4788: sub hashref2str {
4789: my ($hashref)=@_;
1.265 albertel 4790: my $result='__HASH_REF__';
1.800 albertel 4791: foreach my $key (sort(keys(%$hashref))) {
4792: if (ref($key) eq 'ARRAY') {
4793: $result.=&arrayref2str($key).'=';
4794: } elsif (ref($key) eq 'HASH') {
4795: $result.=&hashref2str($key).'=';
4796: } elsif (ref($key)) {
1.265 albertel 4797: $result.='=';
1.800 albertel 4798: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 4799: } else {
1.1132 raeburn 4800: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 4801: }
4802:
1.800 albertel 4803: if(ref($hashref->{$key}) eq 'ARRAY') {
4804: $result.=&arrayref2str($hashref->{$key}).'&';
4805: } elsif(ref($hashref->{$key}) eq 'HASH') {
4806: $result.=&hashref2str($hashref->{$key}).'&';
4807: } elsif(ref($hashref->{$key})) {
1.265 albertel 4808: $result.='&';
1.800 albertel 4809: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 4810: } else {
1.800 albertel 4811: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 4812: }
4813: }
1.168 albertel 4814: $result=~s/\&$//;
1.265 albertel 4815: $result .= '__END_HASH_REF__';
1.168 albertel 4816: return $result;
4817: }
4818:
4819: sub str2hash {
1.265 albertel 4820: my ($string)=@_;
4821: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
4822: return %$hash;
4823: }
4824:
4825: sub str2hashref {
1.168 albertel 4826: my ($string) = @_;
1.265 albertel 4827:
4828: my %hash;
4829:
4830: if($string !~ /^__HASH_REF__/) {
4831: if (! ($string eq '' || !defined($string))) {
4832: $hash{'error'}='Not hash reference';
4833: }
4834: return (\%hash, $string);
4835: }
4836:
4837: $string =~ s/^__HASH_REF__//;
4838:
4839: while($string !~ /^__END_HASH_REF__/) {
4840: #key
4841: my $key='';
4842: if($string =~ /^__HASH_REF__/) {
4843: ($key, $string)=&str2hashref($string);
4844: if(defined($key->{'error'})) {
4845: $hash{'error'}='Bad data';
4846: return (\%hash, $string);
4847: }
4848: } elsif($string =~ /^__ARRAY_REF__/) {
4849: ($key, $string)=&str2arrayref($string);
4850: if($key->[0] eq 'Array reference error') {
4851: $hash{'error'}='Bad data';
4852: return (\%hash, $string);
4853: }
4854: } else {
4855: $string =~ s/^(.*?)=//;
1.267 albertel 4856: $key=&unescape($1);
1.265 albertel 4857: }
4858: $string =~ s/^=//;
4859:
4860: #value
4861: my $value='';
4862: if($string =~ /^__HASH_REF__/) {
4863: ($value, $string)=&str2hashref($string);
4864: if(defined($value->{'error'})) {
4865: $hash{'error'}='Bad data';
4866: return (\%hash, $string);
4867: }
4868: } elsif($string =~ /^__ARRAY_REF__/) {
4869: ($value, $string)=&str2arrayref($string);
4870: if($value->[0] eq 'Array reference error') {
4871: $hash{'error'}='Bad data';
4872: return (\%hash, $string);
4873: }
4874: } else {
4875: $value=&get_scalar(\$string,'__END_HASH_REF__');
4876: }
4877: $string =~ s/^&//;
4878:
4879: $hash{$key}=$value;
1.204 albertel 4880: }
1.265 albertel 4881:
4882: $string =~ s/^__END_HASH_REF__//;
4883:
4884: return (\%hash, $string);
1.204 albertel 4885: }
4886:
4887: sub str2array {
1.265 albertel 4888: my ($string)=@_;
4889: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
4890: return @$array;
4891: }
4892:
4893: sub str2arrayref {
1.204 albertel 4894: my ($string) = @_;
1.265 albertel 4895: my @array;
4896:
4897: if($string !~ /^__ARRAY_REF__/) {
4898: if (! ($string eq '' || !defined($string))) {
4899: $array[0]='Array reference error';
4900: }
4901: return (\@array, $string);
4902: }
4903:
4904: $string =~ s/^__ARRAY_REF__//;
4905:
4906: while($string !~ /^__END_ARRAY_REF__/) {
4907: my $value='';
4908: if($string =~ /^__HASH_REF__/) {
4909: ($value, $string)=&str2hashref($string);
4910: if(defined($value->{'error'})) {
4911: $array[0] ='Array reference error';
4912: return (\@array, $string);
4913: }
4914: } elsif($string =~ /^__ARRAY_REF__/) {
4915: ($value, $string)=&str2arrayref($string);
4916: if($value->[0] eq 'Array reference error') {
4917: $array[0] ='Array reference error';
4918: return (\@array, $string);
4919: }
4920: } else {
4921: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
4922: }
4923: $string =~ s/^&//;
4924:
4925: push(@array, $value);
1.191 harris41 4926: }
1.265 albertel 4927:
4928: $string =~ s/^__END_ARRAY_REF__//;
4929:
4930: return (\@array, $string);
1.168 albertel 4931: }
4932:
1.167 albertel 4933: # -------------------------------------------------------------------Temp Store
4934:
1.168 albertel 4935: sub tmpreset {
4936: my ($symb,$namespace,$domain,$stuname) = @_;
4937: if (!$symb) {
4938: $symb=&symbread();
1.620 albertel 4939: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4940: }
4941: $symb=escape($symb);
4942:
1.620 albertel 4943: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 4944: $namespace=~s/\//\_/g;
4945: $namespace=~s/\W//g;
4946:
1.620 albertel 4947: if (!$domain) { $domain=$env{'user.domain'}; }
4948: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4949: if ($domain eq 'public' && $stuname eq 'public') {
4950: $stuname=$ENV{'REMOTE_ADDR'};
4951: }
1.1117 foxr 4952: my $path=LONCAPA::tempdir();
1.168 albertel 4953: my %hash;
4954: if (tie(%hash,'GDBM_File',
4955: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4956: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 4957: foreach my $key (keys(%hash)) {
1.180 albertel 4958: if ($key=~ /:$symb/) {
1.168 albertel 4959: delete($hash{$key});
4960: }
4961: }
4962: }
4963: }
4964:
1.167 albertel 4965: sub tmpstore {
1.168 albertel 4966: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4967:
4968: if (!$symb) {
4969: $symb=&symbread();
1.620 albertel 4970: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4971: }
4972: $symb=escape($symb);
4973:
4974: if (!$namespace) {
4975: # I don't think we would ever want to store this for a course.
4976: # it seems this will only be used if we don't have a course.
1.620 albertel 4977: #$namespace=$env{'request.course.id'};
1.168 albertel 4978: #if (!$namespace) {
1.620 albertel 4979: $namespace=$env{'request.state'};
1.168 albertel 4980: #}
4981: }
4982: $namespace=~s/\//\_/g;
4983: $namespace=~s/\W//g;
1.620 albertel 4984: if (!$domain) { $domain=$env{'user.domain'}; }
4985: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4986: if ($domain eq 'public' && $stuname eq 'public') {
4987: $stuname=$ENV{'REMOTE_ADDR'};
4988: }
1.168 albertel 4989: my $now=time;
4990: my %hash;
1.1117 foxr 4991: my $path=LONCAPA::tempdir();
1.168 albertel 4992: if (tie(%hash,'GDBM_File',
4993: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4994: &GDBM_WRCREAT(),0640)) {
1.168 albertel 4995: $hash{"version:$symb"}++;
4996: my $version=$hash{"version:$symb"};
4997: my $allkeys='';
4998: foreach my $key (keys(%$storehash)) {
4999: $allkeys.=$key.':';
1.591 albertel 5000: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 5001: }
5002: $hash{"$version:$symb:timestamp"}=$now;
5003: $allkeys.='timestamp';
5004: $hash{"$version:keys:$symb"}=$allkeys;
5005: if (untie(%hash)) {
5006: return 'ok';
5007: } else {
5008: return "error:$!";
5009: }
5010: } else {
5011: return "error:$!";
5012: }
5013: }
1.167 albertel 5014:
1.168 albertel 5015: # -----------------------------------------------------------------Temp Restore
1.167 albertel 5016:
1.168 albertel 5017: sub tmprestore {
5018: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 5019:
1.168 albertel 5020: if (!$symb) {
5021: $symb=&symbread();
1.620 albertel 5022: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 5023: }
5024: $symb=escape($symb);
5025:
1.620 albertel 5026: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 5027:
1.620 albertel 5028: if (!$domain) { $domain=$env{'user.domain'}; }
5029: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 5030: if ($domain eq 'public' && $stuname eq 'public') {
5031: $stuname=$ENV{'REMOTE_ADDR'};
5032: }
1.168 albertel 5033: my %returnhash;
5034: $namespace=~s/\//\_/g;
5035: $namespace=~s/\W//g;
5036: my %hash;
1.1117 foxr 5037: my $path=LONCAPA::tempdir();
1.168 albertel 5038: if (tie(%hash,'GDBM_File',
5039: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 5040: &GDBM_READER(),0640)) {
1.168 albertel 5041: my $version=$hash{"version:$symb"};
5042: $returnhash{'version'}=$version;
5043: my $scope;
5044: for ($scope=1;$scope<=$version;$scope++) {
5045: my $vkeys=$hash{"$scope:keys:$symb"};
5046: my @keys=split(/:/,$vkeys);
5047: my $key;
5048: $returnhash{"$scope:keys"}=$vkeys;
5049: foreach $key (@keys) {
1.591 albertel 5050: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
5051: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 5052: }
5053: }
1.168 albertel 5054: if (!(untie(%hash))) {
5055: return "error:$!";
5056: }
5057: } else {
5058: return "error:$!";
5059: }
5060: return %returnhash;
1.167 albertel 5061: }
5062:
1.9 www 5063: # ----------------------------------------------------------------------- Store
5064:
5065: sub store {
1.1269 raeburn 5066: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 5067: my $home='';
5068:
1.168 albertel 5069: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 5070:
1.213 www 5071: $symb=&symbclean($symb);
1.122 albertel 5072: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 5073:
1.620 albertel 5074: if (!$domain) { $domain=$env{'user.domain'}; }
5075: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 5076:
5077: &devalidate($symb,$stuname,$domain);
1.109 www 5078:
5079: $symb=escape($symb);
1.187 www 5080: if (!$namespace) {
1.620 albertel 5081: unless ($namespace=$env{'request.course.id'}) {
1.187 www 5082: return '';
5083: }
5084: }
1.620 albertel 5085: if (!$home) { $home=$env{'user.home'}; }
1.447 www 5086:
5087: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
5088: $$storehash{'host'}=$perlvar{'lonHostID'};
5089:
1.12 www 5090: my $namevalue='';
1.800 albertel 5091: foreach my $key (keys(%$storehash)) {
5092: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 5093: }
1.12 www 5094: $namevalue=~s/\&$//;
1.187 www 5095: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1269 raeburn 5096: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9 www 5097: }
5098:
1.47 www 5099: # -------------------------------------------------------------- Critical Store
5100:
5101: sub cstore {
1.1269 raeburn 5102: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 5103: my $home='';
5104:
1.168 albertel 5105: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 5106:
1.213 www 5107: $symb=&symbclean($symb);
1.122 albertel 5108: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 5109:
1.620 albertel 5110: if (!$domain) { $domain=$env{'user.domain'}; }
5111: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 5112:
5113: &devalidate($symb,$stuname,$domain);
1.109 www 5114:
5115: $symb=escape($symb);
1.187 www 5116: if (!$namespace) {
1.620 albertel 5117: unless ($namespace=$env{'request.course.id'}) {
1.187 www 5118: return '';
5119: }
5120: }
1.620 albertel 5121: if (!$home) { $home=$env{'user.home'}; }
1.447 www 5122:
5123: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
5124: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 5125:
1.47 www 5126: my $namevalue='';
1.800 albertel 5127: foreach my $key (keys(%$storehash)) {
5128: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 5129: }
1.47 www 5130: $namevalue=~s/\&$//;
1.187 www 5131: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 5132: return critical
1.1269 raeburn 5133: ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47 www 5134: }
5135:
1.9 www 5136: # --------------------------------------------------------------------- Restore
5137:
5138: sub restore {
1.124 www 5139: my ($symb,$namespace,$domain,$stuname) = @_;
5140: my $home='';
5141:
1.168 albertel 5142: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 5143:
1.122 albertel 5144: if (!$symb) {
1.1224 raeburn 5145: return if ($namespace eq 'courserequests');
5146: unless ($symb=escape(&symbread())) { return ''; }
1.122 albertel 5147: } else {
1.1224 raeburn 5148: unless ($namespace eq 'courserequests') {
5149: $symb=&escape(&symbclean($symb));
5150: }
1.122 albertel 5151: }
1.188 www 5152: if (!$namespace) {
1.620 albertel 5153: unless ($namespace=$env{'request.course.id'}) {
1.188 www 5154: return '';
5155: }
5156: }
1.620 albertel 5157: if (!$domain) { $domain=$env{'user.domain'}; }
5158: if (!$stuname) { $stuname=$env{'user.name'}; }
5159: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 5160: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
5161:
1.12 www 5162: my %returnhash=();
1.800 albertel 5163: foreach my $line (split(/\&/,$answer)) {
5164: my ($name,$value)=split(/\=/,$line);
1.591 albertel 5165: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 5166: }
1.75 www 5167: my $version;
5168: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 5169: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
5170: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 5171: }
1.75 www 5172: }
1.13 www 5173: return %returnhash;
1.34 www 5174: }
5175:
5176: # ---------------------------------------------------------- Course Description
1.1118 foxr 5177: #
5178: #
1.34 www 5179:
5180: sub coursedescription {
1.731 albertel 5181: my ($courseid,$args)=@_;
1.34 www 5182: $courseid=~s/^\///;
1.49 www 5183: $courseid=~s/\_/\//g;
1.34 www 5184: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 5185: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 5186: my $normalid=$cdomain.'_'.$cnum;
5187: # need to always cache even if we get errors otherwise we keep
5188: # trying and trying and trying to get the course description.
5189: my %envhash=();
5190: my %returnhash=();
1.731 albertel 5191:
5192: my $expiretime=600;
5193: if ($env{'request.course.id'} eq $normalid) {
5194: $expiretime=120;
5195: }
5196:
5197: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
5198: if (!$args->{'freshen_cache'}
5199: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
5200: foreach my $key (keys(%env)) {
5201: next if ($key !~ /^\Q$prefix\E(.*)/);
5202: my ($setting) = $1;
5203: $returnhash{$setting} = $env{$key};
5204: }
5205: return %returnhash;
5206: }
5207:
1.1118 foxr 5208: # get the data again
5209:
1.731 albertel 5210: if (!$args->{'one_time'}) {
5211: $envhash{'course.'.$normalid.'.last_cache'}=time;
5212: }
1.811 albertel 5213:
1.34 www 5214: if ($chome ne 'no_host') {
1.302 albertel 5215: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 5216: if (!exists($returnhash{'con_lost'})) {
1.1118 foxr 5217: my $username = $env{'user.name'}; # Defult username
5218: if(defined $args->{'user'}) {
5219: $username = $args->{'user'};
5220: }
1.129 albertel 5221: $returnhash{'home'}= $chome;
5222: $returnhash{'domain'} = $cdomain;
5223: $returnhash{'num'} = $cnum;
1.741 raeburn 5224: if (!defined($returnhash{'type'})) {
5225: $returnhash{'type'} = 'Course';
5226: }
1.130 albertel 5227: while (my ($name,$value) = each %returnhash) {
1.53 www 5228: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 5229: }
1.270 www 5230: $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117 foxr 5231: $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118 foxr 5232: $username.'_'.$cdomain.'_'.$cnum;
1.60 www 5233: $envhash{'course.'.$normalid.'.home'}=$chome;
5234: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
5235: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 5236: }
5237: }
1.731 albertel 5238: if (!$args->{'one_time'}) {
1.949 raeburn 5239: &appenv(\%envhash);
1.731 albertel 5240: }
1.302 albertel 5241: return %returnhash;
1.461 www 5242: }
5243:
1.1080 raeburn 5244: sub update_released_required {
5245: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
5246: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
5247: $cid = $env{'request.course.id'};
5248: $cdom = $env{'course.'.$cid.'.domain'};
5249: $cnum = $env{'course.'.$cid.'.num'};
5250: $chome = $env{'course.'.$cid.'.home'};
5251: }
5252: if ($needsrelease) {
5253: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
5254: my $needsupdate;
5255: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
5256: $needsupdate = 1;
5257: } else {
5258: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
5259: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
5260: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
5261: $needsupdate = 1;
5262: }
5263: }
5264: if ($needsupdate) {
5265: my %needshash = (
5266: 'internal.releaserequired' => $needsrelease,
5267: );
5268: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
5269: if ($putresult eq 'ok') {
5270: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
5271: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
5272: if (ref($crsinfo{$cid}) eq 'HASH') {
5273: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
5274: &courseidput($cdom,\%crsinfo,$chome,'notime');
5275: }
5276: }
5277: }
5278: }
5279: return;
5280: }
5281:
1.461 www 5282: # -------------------------------------------------See if a user is privileged
5283:
5284: sub privileged {
1.1219 raeburn 5285: my ($username,$domain,$possdomains,$possroles)=@_;
1.1170 droeschl 5286: my $now = time;
1.1219 raeburn 5287: my $roles;
5288: if (ref($possroles) eq 'ARRAY') {
5289: $roles = $possroles;
5290: } else {
5291: $roles = ['dc','su'];
5292: }
5293: if (ref($possdomains) eq 'ARRAY') {
5294: my %privileged = &privileged_by_domain($possdomains,$roles);
5295: foreach my $dom (@{$possdomains}) {
5296: if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
5297: (ref($privileged{$dom}) eq 'HASH')) {
5298: foreach my $role (@{$roles}) {
5299: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5300: if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
5301: my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
5302: return 1 unless (($end && $end < $now) ||
5303: ($start && $start > $now));
5304: }
5305: }
5306: }
5307: }
5308: }
5309: } else {
5310: my %rolesdump = &dump("roles", $domain, $username) or return 0;
5311: my $now = time;
1.1170 droeschl 5312:
1.1275 musolffc 5313: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170 droeschl 5314: my ($trole, $tend, $tstart) = split(/_/, $role);
1.1219 raeburn 5315: if (grep(/^\Q$trole\E$/,@{$roles})) {
1.1170 droeschl 5316: return 1 unless ($tend && $tend < $now)
1.1219 raeburn 5317: or ($tstart && $tstart > $now);
1.1170 droeschl 5318: }
1.1219 raeburn 5319: }
5320: }
5321: return 0;
5322: }
1.1170 droeschl 5323:
1.1219 raeburn 5324: sub privileged_by_domain {
5325: my ($domains,$roles) = @_;
5326: my %privileged = ();
5327: my $cachetime = 60*60*24;
5328: my $now = time;
5329: unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
5330: return %privileged;
5331: }
5332: foreach my $dom (@{$domains}) {
5333: next if (ref($privileged{$dom}) eq 'HASH');
5334: my $needroles;
5335: foreach my $role (@{$roles}) {
5336: my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
5337: if (defined($cached)) {
5338: if (ref($result) eq 'HASH') {
5339: $privileged{$dom}{$role} = $result;
5340: }
5341: } else {
5342: $needroles = 1;
5343: }
5344: }
5345: if ($needroles) {
5346: my %dompersonnel = &get_domain_roles($dom,$roles);
5347: $privileged{$dom} = {};
5348: foreach my $server (keys(%dompersonnel)) {
5349: if (ref($dompersonnel{$server}) eq 'HASH') {
5350: foreach my $item (keys(%{$dompersonnel{$server}})) {
5351: my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
5352: my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
5353: next if ($end && $end < $now);
5354: $privileged{$dom}{$trole}{$uname.':'.$udom} =
5355: $dompersonnel{$server}{$item};
5356: }
5357: }
5358: }
5359: if (ref($privileged{$dom}) eq 'HASH') {
5360: foreach my $role (@{$roles}) {
5361: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5362: &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
5363: } else {
5364: my %hash = ();
5365: &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
5366: }
5367: }
5368: }
5369: }
5370: }
5371: return %privileged;
1.9 www 5372: }
1.1 albertel 5373:
1.103 harris41 5374: # -------------------------------------------------------- Get user privileges
1.11 www 5375:
5376: sub rolesinit {
1.1169 droeschl 5377: my ($domain, $username) = @_;
5378: my %userroles = ('user.login.time' => time);
5379: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
5380:
5381: # firstaccess and timerinterval are related to timed maps/resources.
5382: # also, blocking can be triggered by an activating timer
5383: # it's saved in the user's %env.
5384: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
5385: my %timerinterval = &dump('timerinterval', $domain, $username);
5386: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
5387: %timerintchk, %timerintenv);
5388:
1.1162 raeburn 5389: foreach my $key (keys(%firstaccess)) {
1.1169 droeschl 5390: my ($cid, $rest) = split(/\0/, $key);
1.1162 raeburn 5391: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
5392: }
1.1169 droeschl 5393:
1.1162 raeburn 5394: foreach my $key (keys(%timerinterval)) {
5395: my ($cid,$rest) = split(/\0/,$key);
5396: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
5397: }
1.1169 droeschl 5398:
1.11 www 5399: my %allroles=();
1.1162 raeburn 5400: my %allgroups=();
1.11 www 5401:
1.1274 raeburn 5402: for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169 droeschl 5403: my $role = $rolesdump{$area};
5404: $area =~ s/\_\w\w$//;
5405:
5406: my ($trole, $tend, $tstart, $group_privs);
5407:
5408: if ($role =~ /^cr/) {
5409: # Custom role, defined by a user
5410: # e.g., user.role.cr/msu/smith/mynewrole
5411: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
5412: $trole = $1;
5413: ($tend, $tstart) = split('_', $2);
5414: } else {
5415: $trole = $role;
5416: }
5417: } elsif ($role =~ m|^gr/|) {
5418: # Role of member in a group, defined within a course/community
5419: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
5420: ($trole, $tend, $tstart) = split(/_/, $role);
5421: next if $tstart eq '-1';
5422: ($trole, $group_privs) = split(/\//, $trole);
5423: $group_privs = &unescape($group_privs);
5424: } else {
5425: # Just a normal role, defined in roles.tab
5426: ($trole, $tend, $tstart) = split(/_/,$role);
5427: }
5428:
5429: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
5430: $username);
5431: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
5432:
5433: # role expired or not available yet?
5434: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
5435: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
5436:
5437: next if $area eq '' or $trole eq '';
5438:
5439: my $spec = "$trole.$area";
5440: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
5441:
5442: if ($trole =~ /^cr\//) {
5443: # Custom role, defined by a user
5444: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5445: } elsif ($trole eq 'gr') {
5446: # Role of a member in a group, defined within a course/community
5447: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
5448: next;
5449: } else {
5450: # Normal role, defined in roles.tab
5451: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5452: }
5453:
5454: my $cid = $tdomain.'_'.$trest;
5455: unless ($firstaccchk{$cid}) {
5456: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
5457: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
5458: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
5459: $coursetimerstarts{$cid}{$item};
5460: }
5461: }
5462: $firstaccchk{$cid} = 1;
5463: }
5464: unless ($timerintchk{$cid}) {
5465: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
5466: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
5467: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
5468: $coursetimerintervals{$cid}{$item};
1.1162 raeburn 5469: }
1.12 www 5470: }
1.1169 droeschl 5471: $timerintchk{$cid} = 1;
1.191 harris41 5472: }
1.11 www 5473: }
1.1169 droeschl 5474:
5475: @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
5476: \%allroles, \%allgroups);
5477: $env{'user.adv'} = $userroles{'user.adv'};
5478:
1.1162 raeburn 5479: return (\%userroles,\%firstaccenv,\%timerintenv);
1.11 www 5480: }
5481:
1.567 raeburn 5482: sub set_arearole {
1.1215 raeburn 5483: my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
5484: unless ($nolog) {
1.567 raeburn 5485: # log the associated role with the area
1.1215 raeburn 5486: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
5487: }
1.743 albertel 5488: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 5489: }
5490:
5491: sub custom_roleprivs {
5492: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
5493: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1250 raeburn 5494: my $homsvr = &homeserver($rauthor,$rdomain);
1.838 albertel 5495: if (&hostname($homsvr) ne '') {
1.567 raeburn 5496: my ($rdummy,$roledef)=
5497: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
5498: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
5499: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
5500: if (defined($syspriv)) {
1.1043 raeburn 5501: if ($trest =~ /^$match_community$/) {
5502: $syspriv =~ s/bre\&S//;
5503: }
1.567 raeburn 5504: $$allroles{'cm./'}.=':'.$syspriv;
5505: $$allroles{$spec.'./'}.=':'.$syspriv;
5506: }
5507: if ($tdomain ne '') {
5508: if (defined($dompriv)) {
5509: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
5510: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
5511: }
5512: if (($trest ne '') && (defined($coursepriv))) {
5513: $$allroles{'cm.'.$area}.=':'.$coursepriv;
5514: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
5515: }
5516: }
5517: }
5518: }
5519: }
5520:
1.678 raeburn 5521: sub group_roleprivs {
5522: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
5523: my $access = 1;
5524: my $now = time;
5525: if (($tend!=0) && ($tend<$now)) { $access = 0; }
5526: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
5527: if ($access) {
1.811 albertel 5528: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 5529: $$allgroups{$course}{$group} .=':'.$group_privs;
5530: }
5531: }
1.567 raeburn 5532:
5533: sub standard_roleprivs {
5534: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
5535: if (defined($pr{$trole.':s'})) {
5536: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
5537: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
5538: }
5539: if ($tdomain ne '') {
5540: if (defined($pr{$trole.':d'})) {
5541: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5542: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5543: }
5544: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
5545: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
5546: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
5547: }
5548: }
5549: }
5550:
5551: sub set_userprivs {
1.1064 raeburn 5552: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 5553: my $author=0;
5554: my $adv=0;
1.678 raeburn 5555: my %grouproles = ();
5556: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 5557: my @groupkeys;
1.1000 raeburn 5558: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 5559: push(@groupkeys,$role);
5560: }
5561: if (ref($groups_roles) eq 'HASH') {
5562: foreach my $key (keys(%{$groups_roles})) {
5563: unless (grep(/^\Q$key\E$/,@groupkeys)) {
5564: push(@groupkeys,$key);
5565: }
5566: }
5567: }
5568: if (@groupkeys > 0) {
5569: foreach my $role (@groupkeys) {
5570: my ($trole,$area,$sec,$extendedarea);
5571: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
5572: $trole = $1;
5573: $area = $2;
5574: $sec = $3;
5575: $extendedarea = $area.$sec;
5576: if (exists($$allgroups{$area})) {
5577: foreach my $group (keys(%{$$allgroups{$area}})) {
5578: my $spec = $trole.'.'.$extendedarea;
5579: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 5580: $$allgroups{$area}{$group};
1.1064 raeburn 5581: }
1.678 raeburn 5582: }
5583: }
5584: }
5585: }
5586: }
1.800 albertel 5587: foreach my $group (keys(%grouproles)) {
5588: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 5589: }
1.800 albertel 5590: foreach my $role (keys(%{$allroles})) {
5591: my %thesepriv;
1.941 raeburn 5592: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 5593: foreach my $item (split(/:/,$$allroles{$role})) {
5594: if ($item ne '') {
5595: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 5596: if ($restrictions eq '') {
5597: $thesepriv{$privilege}='F';
5598: } elsif ($thesepriv{$privilege} ne 'F') {
5599: $thesepriv{$privilege}.=$restrictions;
5600: }
5601: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
5602: }
5603: }
5604: my $thesestr='';
1.1104 raeburn 5605: foreach my $priv (sort(keys(%thesepriv))) {
1.800 albertel 5606: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
5607: }
5608: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 5609: }
5610: return ($author,$adv);
5611: }
5612:
1.994 raeburn 5613: sub role_status {
1.1104 raeburn 5614: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 5615: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1250 raeburn 5616: my ($one,$two) = split(m{\./},$rolekey,2);
5617: (undef,undef,$$role) = split(/\./,$one,3);
1.994 raeburn 5618: unless (!defined($$role) || $$role eq '') {
1.1251 raeburn 5619: $$where = '/'.$two;
1.994 raeburn 5620: $$trolecode=$$role.'.'.$$where;
5621: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
5622: $$tstatus='is';
1.1104 raeburn 5623: if ($$tstart && $$tstart>$update) {
1.994 raeburn 5624: $$tstatus='future';
1.1034 raeburn 5625: if ($$tstart<$now) {
5626: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 5627: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 5628: my (%allroles,%allgroups,$group_privs,
5629: %groups_roles,@rolecodes);
1.1002 raeburn 5630: my %userroles = (
5631: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
5632: );
1.1064 raeburn 5633: @rolecodes = ('cm');
1.1002 raeburn 5634: my $spec=$$role.'.'.$$where;
5635: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
5636: if ($$role =~ /^cr\//) {
5637: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 5638: push(@rolecodes,'cr');
1.1002 raeburn 5639: } elsif ($$role eq 'gr') {
1.1064 raeburn 5640: push(@rolecodes,$$role);
1.1002 raeburn 5641: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
5642: $env{'user.name'});
1.1064 raeburn 5643: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 5644: (undef,my $group_privs) = split(/\//,$trole);
5645: $group_privs = &unescape($group_privs);
5646: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 5647: 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 5648: &get_groups_roles($tdomain,$trest,
5649: \%course_roles,\@rolecodes,
5650: \%groups_roles);
1.1002 raeburn 5651: } else {
1.1064 raeburn 5652: push(@rolecodes,$$role);
1.1002 raeburn 5653: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
5654: }
1.1064 raeburn 5655: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
5656: &appenv(\%userroles,\@rolecodes);
1.1002 raeburn 5657: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
5658: }
5659: }
1.1034 raeburn 5660: $$tstatus = 'is';
1.1002 raeburn 5661: }
1.994 raeburn 5662: }
5663: if ($$tend) {
1.1104 raeburn 5664: if ($$tend<$update) {
1.994 raeburn 5665: $$tstatus='expired';
5666: } elsif ($$tend<$now) {
5667: $$tstatus='will_not';
5668: }
5669: }
5670: }
5671: }
5672: }
5673:
1.1104 raeburn 5674: sub get_groups_roles {
5675: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
5676: return unless((ref($cdom_courseroles) eq 'HASH') &&
5677: (ref($rolecodes) eq 'ARRAY') &&
5678: (ref($groups_roles) eq 'HASH'));
5679: if (keys(%{$cdom_courseroles}) > 0) {
5680: my ($cnum) = ($rest =~ /^($match_courseid)/);
5681: if ($cdom ne '' && $cnum ne '') {
5682: foreach my $key (keys(%{$cdom_courseroles})) {
5683: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
5684: my $crsrole = $1;
5685: my $crssec = $2;
5686: if ($crsrole =~ /^cr/) {
5687: unless (grep(/^cr$/,@{$rolecodes})) {
5688: push(@{$rolecodes},'cr');
5689: }
5690: } else {
5691: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
5692: push(@{$rolecodes},$crsrole);
5693: }
5694: }
5695: my $rolekey = "$crsrole./$cdom/$cnum";
5696: if ($crssec ne '') {
5697: $rolekey .= "/$crssec";
5698: }
5699: $rolekey .= './';
5700: $groups_roles->{$rolekey} = $rolecodes;
5701: }
5702: }
5703: }
5704: }
5705: return;
5706: }
5707:
5708: sub delete_env_groupprivs {
5709: my ($where,$courseroles,$possroles) = @_;
5710: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
5711: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
5712: unless (ref($courseroles->{$udom}) eq 'HASH') {
5713: %{$courseroles->{$udom}} =
5714: &get_my_roles('','','userroles',['active'],
5715: $possroles,[$udom],1);
5716: }
5717: if (ref($courseroles->{$udom}) eq 'HASH') {
5718: foreach my $item (keys(%{$courseroles->{$udom}})) {
5719: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
5720: my $area = '/'.$cdom.'/'.$cnum;
5721: my $privkey = "user.priv.$crsrole.$area";
5722: if ($crssec ne '') {
5723: $privkey .= '/'.$crssec;
5724: }
5725: $privkey .= ".$area/$group";
5726: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
5727: }
5728: }
5729: return;
5730: }
5731:
1.994 raeburn 5732: sub check_adhoc_privs {
1.1104 raeburn 5733: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994 raeburn 5734: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1185 raeburn 5735: my $setprivs;
1.994 raeburn 5736: if ($env{$cckey}) {
5737: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104 raeburn 5738: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 5739: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088 raeburn 5740: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185 raeburn 5741: $setprivs = 1;
1.994 raeburn 5742: }
5743: } else {
1.1088 raeburn 5744: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185 raeburn 5745: $setprivs = 1;
1.994 raeburn 5746: }
1.1185 raeburn 5747: return $setprivs;
1.994 raeburn 5748: }
5749:
5750: sub set_adhoc_privileges {
5751: # role can be cc or ca
1.1088 raeburn 5752: my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994 raeburn 5753: my $area = '/'.$dcdom.'/'.$pickedcourse;
5754: my $spec = $role.'.'.$area;
5755: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1215 raeburn 5756: $env{'user.name'},1);
1.994 raeburn 5757: my %ccrole = ();
5758: &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
5759: my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
5760: &appenv(\%userroles,[$role,'cm']);
5761: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088 raeburn 5762: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
5763: &appenv( {'request.role' => $spec,
5764: 'request.role.domain' => $dcdom,
5765: 'request.course.sec' => ''
5766: }
5767: );
5768: my $tadv=0;
5769: if (&allowed('adv') eq 'F') { $tadv=1; }
5770: &appenv({'request.role.adv' => $tadv});
5771: }
1.994 raeburn 5772: }
5773:
1.12 www 5774: # --------------------------------------------------------------- get interface
5775:
5776: sub get {
1.131 albertel 5777: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 5778: my $items='';
1.800 albertel 5779: foreach my $item (@$storearr) {
5780: $items.=&escape($item).'&';
1.191 harris41 5781: }
1.12 www 5782: $items=~s/\&$//;
1.620 albertel 5783: if (!$udomain) { $udomain=$env{'user.domain'}; }
5784: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 5785: my $uhome=&homeserver($uname,$udomain);
5786:
1.133 albertel 5787: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 5788: my @pairs=split(/\&/,$rep);
1.273 albertel 5789: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
5790: return @pairs;
5791: }
1.15 www 5792: my %returnhash=();
1.42 www 5793: my $i=0;
1.800 albertel 5794: foreach my $item (@$storearr) {
5795: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 5796: $i++;
1.191 harris41 5797: }
1.15 www 5798: return %returnhash;
1.27 www 5799: }
5800:
5801: # --------------------------------------------------------------- del interface
5802:
5803: sub del {
1.133 albertel 5804: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 5805: my $items='';
1.800 albertel 5806: foreach my $item (@$storearr) {
5807: $items.=&escape($item).'&';
1.191 harris41 5808: }
1.984 neumanie 5809:
1.27 www 5810: $items=~s/\&$//;
1.620 albertel 5811: if (!$udomain) { $udomain=$env{'user.domain'}; }
5812: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 5813: my $uhome=&homeserver($uname,$udomain);
5814: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 5815: }
5816:
5817: # -------------------------------------------------------------- dump interface
5818:
1.1180 droeschl 5819: sub unserialize {
5820: my ($rep, $escapedkeys) = @_;
5821:
5822: return {} if $rep =~ /^error/;
5823:
5824: my %returnhash=();
1.1252 raeburn 5825: foreach my $item (split(/\&/,$rep)) {
1.1180 droeschl 5826: my ($key, $value) = split(/=/, $item, 2);
5827: $key = unescape($key) unless $escapedkeys;
5828: next if $key =~ /^error: 2 /;
1.1252 raeburn 5829: $returnhash{$key} = &thaw_unescape($value);
1.1180 droeschl 5830: }
5831: #return %returnhash;
5832: return \%returnhash;
5833: }
5834:
5835: # see Lond::dump_with_regexp
5836: # if $escapedkeys hash keys won't get unescaped.
1.15 www 5837: sub dump {
1.1180 droeschl 5838: my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755 albertel 5839: if (!$udomain) { $udomain=$env{'user.domain'}; }
5840: if (!$uname) { $uname=$env{'user.name'}; }
5841: my $uhome=&homeserver($uname,$udomain);
1.1167 droeschl 5842:
1.1266 raeburn 5843: if ($regexp) {
5844: $regexp=&escape($regexp);
5845: } else {
5846: $regexp='.';
5847: }
1.1180 droeschl 5848: if (grep { $_ eq $uhome } current_machine_ids()) {
5849: # user is hosted on this machine
1.1266 raeburn 5850: my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
1.1226 raeburn 5851: $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1180 droeschl 5852: return %{unserialize($reply, $escapedkeys)};
5853: }
1.1166 raeburn 5854: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755 albertel 5855: my @pairs=split(/\&/,$rep);
5856: my %returnhash=();
1.1098 foxr 5857: if (!($rep =~ /^error/ )) {
5858: foreach my $item (@pairs) {
5859: my ($key,$value)=split(/=/,$item,2);
1.1180 droeschl 5860: $key = unescape($key) unless $escapedkeys;
5861: #$key = &unescape($key);
1.1098 foxr 5862: next if ($key =~ /^error: 2 /);
5863: $returnhash{$key}=&thaw_unescape($value);
5864: }
1.755 albertel 5865: }
5866: return %returnhash;
1.407 www 5867: }
5868:
1.1098 foxr 5869:
1.717 albertel 5870: # --------------------------------------------------------- dumpstore interface
5871:
5872: sub dumpstore {
5873: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180 droeschl 5874: # same as dump but keys must be escaped. They may contain colon separated
5875: # lists of values that may themself contain colons (e.g. symbs).
5876: return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717 albertel 5877: }
5878:
1.407 www 5879: # -------------------------------------------------------------- keys interface
5880:
5881: sub getkeys {
5882: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 5883: if (!$udomain) { $udomain=$env{'user.domain'}; }
5884: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 5885: my $uhome=&homeserver($uname,$udomain);
5886: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
5887: my @keyarray=();
1.800 albertel 5888: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 5889: next if ($key =~ /^error: 2 /);
1.800 albertel 5890: push(@keyarray,&unescape($key));
1.407 www 5891: }
5892: return @keyarray;
1.318 matthew 5893: }
5894:
1.319 matthew 5895: # --------------------------------------------------------------- currentdump
5896: sub currentdump {
1.328 matthew 5897: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 5898: $courseid = $env{'request.course.id'} if (! defined($courseid));
5899: $sdom = $env{'user.domain'} if (! defined($sdom));
5900: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 5901: my $uhome = &homeserver($sname,$sdom);
1.1180 droeschl 5902: my $rep;
5903:
5904: if (grep { $_ eq $uhome } current_machine_ids()) {
5905: $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
5906: $courseid)));
5907: } else {
5908: $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
5909: }
5910:
1.318 matthew 5911: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 5912: #
1.318 matthew 5913: my %returnhash=();
1.319 matthew 5914: #
5915: if ($rep eq "unknown_cmd") {
5916: # an old lond will not know currentdump
5917: # Do a dump and make it look like a currentdump
1.822 albertel 5918: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 5919: return if ($tmp[0] =~ /^(error:|no_such_host)/);
5920: my %hash = @tmp;
5921: @tmp=();
1.424 matthew 5922: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 5923: } else {
5924: my @pairs=split(/\&/,$rep);
1.800 albertel 5925: foreach my $pair (@pairs) {
5926: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 5927: my ($symb,$param) = split(/:/,$key);
5928: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 5929: &thaw_unescape($value);
1.319 matthew 5930: }
1.191 harris41 5931: }
1.12 www 5932: return %returnhash;
1.424 matthew 5933: }
5934:
5935: sub convert_dump_to_currentdump{
5936: my %hash = %{shift()};
5937: my %returnhash;
5938: # Code ripped from lond, essentially. The only difference
5939: # here is the unescaping done by lonnet::dump(). Conceivably
5940: # we might run in to problems with parameter names =~ /^v\./
5941: while (my ($key,$value) = each(%hash)) {
5942: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 5943: $symb = &unescape($symb);
5944: $param = &unescape($param);
1.424 matthew 5945: next if ($v eq 'version' || $symb eq 'keys');
5946: next if (exists($returnhash{$symb}) &&
5947: exists($returnhash{$symb}->{$param}) &&
5948: $returnhash{$symb}->{'v.'.$param} > $v);
5949: $returnhash{$symb}->{$param}=$value;
5950: $returnhash{$symb}->{'v.'.$param}=$v;
5951: }
5952: #
5953: # Remove all of the keys in the hashes which keep track of
5954: # the version of the parameter.
5955: while (my ($symb,$param_hash) = each(%returnhash)) {
5956: # use a foreach because we are going to delete from the hash.
5957: foreach my $key (keys(%$param_hash)) {
5958: delete($param_hash->{$key}) if ($key =~ /^v\./);
5959: }
5960: }
5961: return \%returnhash;
1.12 www 5962: }
5963:
1.627 albertel 5964: # ------------------------------------------------------ critical inc interface
5965:
5966: sub cinc {
5967: return &inc(@_,'critical');
5968: }
5969:
1.449 matthew 5970: # --------------------------------------------------------------- inc interface
5971:
5972: sub inc {
1.627 albertel 5973: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 5974: if (!$udomain) { $udomain=$env{'user.domain'}; }
5975: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 5976: my $uhome=&homeserver($uname,$udomain);
5977: my $items='';
5978: if (! ref($store)) {
5979: # got a single value, so use that instead
5980: $items = &escape($store).'=&';
5981: } elsif (ref($store) eq 'SCALAR') {
5982: $items = &escape($$store).'=&';
5983: } elsif (ref($store) eq 'ARRAY') {
5984: $items = join('=&',map {&escape($_);} @{$store});
5985: } elsif (ref($store) eq 'HASH') {
5986: while (my($key,$value) = each(%{$store})) {
5987: $items.= &escape($key).'='.&escape($value).'&';
5988: }
5989: }
5990: $items=~s/\&$//;
1.627 albertel 5991: if ($critical) {
5992: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
5993: } else {
5994: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
5995: }
1.449 matthew 5996: }
5997:
1.12 www 5998: # --------------------------------------------------------------- put interface
5999:
6000: sub put {
1.134 albertel 6001: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 6002: if (!$udomain) { $udomain=$env{'user.domain'}; }
6003: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 6004: my $uhome=&homeserver($uname,$udomain);
1.12 www 6005: my $items='';
1.800 albertel 6006: foreach my $item (keys(%$storehash)) {
6007: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 6008: }
1.12 www 6009: $items=~s/\&$//;
1.134 albertel 6010: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 6011: }
6012:
1.631 albertel 6013: # ------------------------------------------------------------ newput interface
6014:
6015: sub newput {
6016: my ($namespace,$storehash,$udomain,$uname)=@_;
6017: if (!$udomain) { $udomain=$env{'user.domain'}; }
6018: if (!$uname) { $uname=$env{'user.name'}; }
6019: my $uhome=&homeserver($uname,$udomain);
6020: my $items='';
6021: foreach my $key (keys(%$storehash)) {
6022: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
6023: }
6024: $items=~s/\&$//;
6025: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
6026: }
6027:
6028: # --------------------------------------------------------- putstore interface
6029:
1.524 raeburn 6030: sub putstore {
1.1269 raeburn 6031: my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620 albertel 6032: if (!$udomain) { $udomain=$env{'user.domain'}; }
6033: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 6034: my $uhome=&homeserver($uname,$udomain);
6035: my $items='';
1.715 albertel 6036: foreach my $key (keys(%$storehash)) {
6037: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 6038: }
1.715 albertel 6039: $items=~s/\&$//;
1.716 albertel 6040: my $esc_symb=&escape($symb);
6041: my $esc_v=&escape($version);
1.715 albertel 6042: my $reply =
1.716 albertel 6043: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 6044: $uhome);
1.1269 raeburn 6045: if (($tolog) && ($reply eq 'ok')) {
6046: my $namevalue='';
6047: foreach my $key (keys(%{$storehash})) {
6048: $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
6049: }
6050: $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
6051: '&host='.&escape($perlvar{'lonHostID'}).
6052: '&version='.$esc_v.
6053: '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
6054: &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
6055: }
1.715 albertel 6056: if ($reply eq 'unknown_cmd') {
1.716 albertel 6057: # gfall back to way things use to be done
1.715 albertel 6058: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
6059: $uname);
1.524 raeburn 6060: }
1.715 albertel 6061: return $reply;
6062: }
6063:
6064: sub old_putstore {
1.716 albertel 6065: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
6066: if (!$udomain) { $udomain=$env{'user.domain'}; }
6067: if (!$uname) { $uname=$env{'user.name'}; }
6068: my $uhome=&homeserver($uname,$udomain);
6069: my %newstorehash;
1.800 albertel 6070: foreach my $item (keys(%$storehash)) {
6071: my $key = $version.':'.&escape($symb).':'.$item;
6072: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 6073: }
6074: my $items='';
6075: my %allitems = ();
1.800 albertel 6076: foreach my $item (keys(%newstorehash)) {
6077: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 6078: my $key = $1.':keys:'.$2;
6079: $allitems{$key} .= $3.':';
6080: }
1.800 albertel 6081: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 6082: }
1.800 albertel 6083: foreach my $item (keys(%allitems)) {
6084: $allitems{$item} =~ s/\:$//;
6085: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 6086: }
6087: $items=~s/\&$//;
6088: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 6089: }
6090:
1.47 www 6091: # ------------------------------------------------------ critical put interface
6092:
6093: sub cput {
1.134 albertel 6094: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 6095: if (!$udomain) { $udomain=$env{'user.domain'}; }
6096: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 6097: my $uhome=&homeserver($uname,$udomain);
1.47 www 6098: my $items='';
1.800 albertel 6099: foreach my $item (keys(%$storehash)) {
6100: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 6101: }
1.47 www 6102: $items=~s/\&$//;
1.134 albertel 6103: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 6104: }
6105:
6106: # -------------------------------------------------------------- eget interface
6107:
6108: sub eget {
1.133 albertel 6109: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 6110: my $items='';
1.800 albertel 6111: foreach my $item (@$storearr) {
6112: $items.=&escape($item).'&';
1.191 harris41 6113: }
1.12 www 6114: $items=~s/\&$//;
1.620 albertel 6115: if (!$udomain) { $udomain=$env{'user.domain'}; }
6116: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 6117: my $uhome=&homeserver($uname,$udomain);
6118: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 6119: my @pairs=split(/\&/,$rep);
6120: my %returnhash=();
1.42 www 6121: my $i=0;
1.800 albertel 6122: foreach my $item (@$storearr) {
6123: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 6124: $i++;
1.191 harris41 6125: }
1.12 www 6126: return %returnhash;
6127: }
6128:
1.667 albertel 6129: # ------------------------------------------------------------ tmpput interface
6130: sub tmpput {
1.802 raeburn 6131: my ($storehash,$server,$context)=@_;
1.667 albertel 6132: my $items='';
1.800 albertel 6133: foreach my $item (keys(%$storehash)) {
6134: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 6135: }
6136: $items=~s/\&$//;
1.802 raeburn 6137: if (defined($context)) {
6138: $items .= ':'.&escape($context);
6139: }
1.667 albertel 6140: return &reply("tmpput:$items",$server);
6141: }
6142:
6143: # ------------------------------------------------------------ tmpget interface
6144: sub tmpget {
1.688 albertel 6145: my ($token,$server)=@_;
6146: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
6147: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 6148: my %returnhash;
6149: foreach my $item (split(/\&/,$rep)) {
6150: my ($key,$value)=split(/=/,$item);
1.951 raeburn 6151: next if ($key =~ /^error: 2 /);
1.667 albertel 6152: $returnhash{&unescape($key)}=&thaw_unescape($value);
6153: }
6154: return %returnhash;
6155: }
6156:
1.1113 raeburn 6157: # ------------------------------------------------------------ tmpdel interface
1.688 albertel 6158: sub tmpdel {
6159: my ($token,$server)=@_;
6160: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
6161: return &reply("tmpdel:$token",$server);
6162: }
6163:
1.1198 raeburn 6164: # ------------------------------------------------------------ get_timebased_id
6165:
6166: sub get_timebased_id {
6167: my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
6168: $maxtries) = @_;
6169: my ($newid,$error,$dellock);
6170: unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
6171: return ('','ok','invalid call to get suffix');
6172: }
6173:
6174: # set defaults for any optional args for which values were not supplied
6175: if ($who eq '') {
6176: $who = $env{'user.name'}.':'.$env{'user.domain'};
6177: }
6178: if (!$locktries) {
6179: $locktries = 3;
6180: }
6181: if (!$maxtries) {
6182: $maxtries = 10;
6183: }
6184:
6185: if (($cdom eq '') || ($cnum eq '')) {
6186: if ($env{'request.course.id'}) {
6187: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6188: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6189: }
6190: if (($cdom eq '') || ($cnum eq '')) {
6191: return ('','ok','call to get suffix not in course context');
6192: }
6193: }
6194:
6195: # construct locking item
6196: my $lockhash = {
6197: $prefix."\0".'locked_'.$keyid => $who,
6198: };
6199: my $tries = 0;
6200:
6201: # attempt to get lock on nohist_$namespace file
6202: my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
6203: while (($gotlock ne 'ok') && $tries <$locktries) {
6204: $tries ++;
6205: sleep 1;
6206: $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
6207: }
6208:
6209: # attempt to get unique identifier, based on current timestamp
6210: if ($gotlock eq 'ok') {
6211: my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
6212: my $id = time;
6213: $newid = $id;
1.1268 raeburn 6214: if ($idtype eq 'addcode') {
6215: $newid .= &sixnum_code();
6216: }
1.1198 raeburn 6217: my $idtries = 0;
6218: while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
6219: if ($idtype eq 'concat') {
6220: $newid = $id.$idtries;
1.1268 raeburn 6221: } elsif ($idtype eq 'addcode') {
6222: $newid = $newid.&sixnum_code();
1.1198 raeburn 6223: } else {
6224: $newid ++;
6225: }
6226: $idtries ++;
6227: }
6228: if (!exists($inuse{$prefix."\0".$newid})) {
6229: my %new_item = (
6230: $prefix."\0".$newid => $who,
6231: );
6232: my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
6233: $cdom,$cnum);
6234: if ($putresult ne 'ok') {
6235: undef($newid);
6236: $error = 'error saving new item: '.$putresult;
6237: }
6238: } else {
1.1268 raeburn 6239: undef($newid);
1.1198 raeburn 6240: $error = ('error: no unique suffix available for the new item ');
6241: }
6242: # remove lock
6243: my @del_lock = ($prefix."\0".'locked_'.$keyid);
6244: $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
6245: } else {
6246: $error = "error: could not obtain lockfile\n";
6247: $dellock = 'ok';
1.1276 raeburn 6248: if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
6249: $dellock = 'nolock';
6250: }
1.1198 raeburn 6251: }
6252: return ($newid,$dellock,$error);
6253: }
6254:
1.1268 raeburn 6255: sub sixnum_code {
6256: my $code;
6257: for (0..6) {
6258: $code .= int( rand(9) );
6259: }
6260: return $code;
6261: }
6262:
1.765 albertel 6263: # -------------------------------------------------- portfolio access checking
6264:
6265: sub portfolio_access {
1.1270 raeburn 6266: my ($requrl,$clientip) = @_;
1.765 albertel 6267: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1270 raeburn 6268: my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814 raeburn 6269: if ($result) {
6270: my %setters;
6271: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6272: my ($startblock,$endblock) =
6273: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
6274: if ($startblock && $endblock) {
6275: return 'B';
6276: }
6277: } else {
6278: my ($startblock,$endblock) =
6279: &Apache::loncommon::blockcheck(\%setters,'port');
6280: if ($startblock && $endblock) {
6281: return 'B';
6282: }
6283: }
6284: }
1.765 albertel 6285: if ($result eq 'ok') {
1.766 albertel 6286: return 'F';
1.765 albertel 6287: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 6288: return 'A';
1.765 albertel 6289: }
1.766 albertel 6290: return '';
1.765 albertel 6291: }
6292:
6293: sub get_portfolio_access {
1.1270 raeburn 6294: my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767 albertel 6295:
6296: if (!ref($access_hash)) {
6297: my $current_perms = &get_portfile_permissions($udom,$unum);
6298: my %access_controls = &get_access_controls($current_perms,$group,
6299: $file_name);
6300: $access_hash = $access_controls{$file_name};
6301: }
6302:
1.1270 raeburn 6303: my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765 albertel 6304: my $now = time;
6305: if (ref($access_hash) eq 'HASH') {
6306: foreach my $key (keys(%{$access_hash})) {
6307: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
6308: if ($start > $now) {
6309: next;
6310: }
6311: if ($end && $end<$now) {
6312: next;
6313: }
6314: if ($scope eq 'public') {
6315: $public = $key;
6316: last;
6317: } elsif ($scope eq 'guest') {
6318: $guest = $key;
6319: } elsif ($scope eq 'domains') {
6320: push(@domains,$key);
6321: } elsif ($scope eq 'users') {
6322: push(@users,$key);
6323: } elsif ($scope eq 'course') {
6324: push(@courses,$key);
6325: } elsif ($scope eq 'group') {
6326: push(@groups,$key);
1.1270 raeburn 6327: } elsif ($scope eq 'ip') {
6328: push(@ips,$key);
1.765 albertel 6329: }
6330: }
6331: if ($public) {
6332: return 'ok';
1.1270 raeburn 6333: } elsif (@ips > 0) {
6334: my $allowed;
6335: foreach my $ipkey (@ips) {
6336: if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
6337: if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
6338: $allowed = 1;
6339: last;
6340: }
6341: }
6342: }
6343: if ($allowed) {
6344: return 'ok';
6345: }
1.765 albertel 6346: }
6347: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6348: if ($guest) {
6349: return $guest;
6350: }
6351: } else {
6352: if (@domains > 0) {
6353: foreach my $domkey (@domains) {
6354: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
6355: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
6356: return 'ok';
6357: }
6358: }
6359: }
6360: }
6361: if (@users > 0) {
6362: foreach my $userkey (@users) {
1.865 raeburn 6363: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
6364: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
6365: if (ref($item) eq 'HASH') {
6366: if (($item->{'uname'} eq $env{'user.name'}) &&
6367: ($item->{'udom'} eq $env{'user.domain'})) {
6368: return 'ok';
6369: }
6370: }
6371: }
6372: }
1.765 albertel 6373: }
6374: }
6375: my %roleshash;
6376: my @courses_and_groups = @courses;
6377: push(@courses_and_groups,@groups);
6378: if (@courses_and_groups > 0) {
6379: my (%allgroups,%allroles);
6380: my ($start,$end,$role,$sec,$group);
6381: foreach my $envkey (%env) {
1.1060 raeburn 6382: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6383: my $cid = $2.'_'.$3;
6384: if ($1 eq 'gr') {
6385: $group = $4;
6386: $allgroups{$cid}{$group} = $env{$envkey};
6387: } else {
6388: if ($4 eq '') {
6389: $sec = 'none';
6390: } else {
6391: $sec = $4;
6392: }
6393: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6394: }
1.811 albertel 6395: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6396: my $cid = $2.'_'.$3;
6397: if ($4 eq '') {
6398: $sec = 'none';
6399: } else {
6400: $sec = $4;
6401: }
6402: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6403: }
6404: }
6405: if (keys(%allroles) == 0) {
6406: return;
6407: }
6408: foreach my $key (@courses_and_groups) {
6409: my %content = %{$$access_hash{$key}};
6410: my $cnum = $content{'number'};
6411: my $cdom = $content{'domain'};
6412: my $cid = $cdom.'_'.$cnum;
6413: if (!exists($allroles{$cid})) {
6414: next;
6415: }
6416: foreach my $role_id (keys(%{$content{'roles'}})) {
6417: my @sections = @{$content{'roles'}{$role_id}{'section'}};
6418: my @groups = @{$content{'roles'}{$role_id}{'group'}};
6419: my @status = @{$content{'roles'}{$role_id}{'access'}};
6420: my @roles = @{$content{'roles'}{$role_id}{'role'}};
6421: foreach my $role (keys(%{$allroles{$cid}})) {
6422: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
6423: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
6424: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
6425: if (grep/^all$/,@sections) {
6426: return 'ok';
6427: } else {
6428: if (grep/^$sec$/,@sections) {
6429: return 'ok';
6430: }
6431: }
6432: }
6433: }
6434: if (keys(%{$allgroups{$cid}}) == 0) {
6435: if (grep/^none$/,@groups) {
6436: return 'ok';
6437: }
6438: } else {
6439: if (grep/^all$/,@groups) {
6440: return 'ok';
6441: }
6442: foreach my $group (keys(%{$allgroups{$cid}})) {
6443: if (grep/^$group$/,@groups) {
6444: return 'ok';
6445: }
6446: }
6447: }
6448: }
6449: }
6450: }
6451: }
6452: }
6453: if ($guest) {
6454: return $guest;
6455: }
6456: }
6457: }
6458: return;
6459: }
6460:
6461: sub course_group_datechecker {
6462: my ($dates,$now,$status) = @_;
6463: my ($start,$end) = split(/\./,$dates);
6464: if (!$start && !$end) {
6465: return 'ok';
6466: }
6467: if (grep/^active$/,@{$status}) {
6468: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
6469: return 'ok';
6470: }
6471: }
6472: if (grep/^previous$/,@{$status}) {
6473: if ($end > $now ) {
6474: return 'ok';
6475: }
6476: }
6477: if (grep/^future$/,@{$status}) {
6478: if ($start > $now) {
6479: return 'ok';
6480: }
6481: }
6482: return;
6483: }
6484:
6485: sub parse_portfolio_url {
6486: my ($url) = @_;
6487:
6488: my ($type,$udom,$unum,$group,$file_name);
6489:
1.823 albertel 6490: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 6491: $type = 1;
6492: $udom = $1;
6493: $unum = $2;
6494: $file_name = $3;
1.823 albertel 6495: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 6496: $type = 2;
6497: $udom = $1;
6498: $unum = $2;
6499: $group = $3;
6500: $file_name = $3.'/'.$4;
6501: }
6502: if (wantarray) {
6503: return ($type,$udom,$unum,$file_name,$group);
6504: }
6505: return $type;
6506: }
6507:
6508: sub is_portfolio_url {
6509: my ($url) = @_;
6510: return scalar(&parse_portfolio_url($url));
6511: }
6512:
1.798 raeburn 6513: sub is_portfolio_file {
6514: my ($file) = @_;
1.820 raeburn 6515: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 6516: return 1;
6517: }
6518: return;
6519: }
6520:
1.976 raeburn 6521: sub usertools_access {
1.1084 raeburn 6522: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 6523: my ($access,%tools);
6524: if ($context eq '') {
6525: $context = 'tools';
6526: }
6527: if ($context eq 'requestcourses') {
6528: %tools = (
6529: official => 1,
6530: unofficial => 1,
1.1006 raeburn 6531: community => 1,
1.1246 raeburn 6532: textbook => 1,
1.1305 ! raeburn 6533: placement => 1,
1.985 raeburn 6534: );
1.1183 raeburn 6535: } elsif ($context eq 'requestauthor') {
6536: %tools = (
6537: requestauthor => 1,
6538: );
1.985 raeburn 6539: } else {
6540: %tools = (
6541: aboutme => 1,
6542: blog => 1,
1.1177 raeburn 6543: webdav => 1,
1.985 raeburn 6544: portfolio => 1,
6545: );
6546: }
1.976 raeburn 6547: return if (!defined($tools{$tool}));
6548:
1.1242 raeburn 6549: if (($udom eq '') || ($uname eq '')) {
1.976 raeburn 6550: $udom = $env{'user.domain'};
6551: $uname = $env{'user.name'};
6552: }
6553:
1.978 raeburn 6554: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
6555: if ($action ne 'reload') {
1.985 raeburn 6556: if ($context eq 'requestcourses') {
6557: return $env{'environment.canrequest.'.$tool};
1.1183 raeburn 6558: } elsif ($context eq 'requestauthor') {
6559: return $env{'environment.canrequest.author'};
1.985 raeburn 6560: } else {
6561: return $env{'environment.availabletools.'.$tool};
6562: }
6563: }
1.976 raeburn 6564: }
6565:
1.1183 raeburn 6566: my ($toolstatus,$inststatus,$envkey);
6567: if ($context eq 'requestauthor') {
6568: $envkey = $context;
6569: } else {
6570: $envkey = $context.'.'.$tool;
6571: }
1.976 raeburn 6572:
1.985 raeburn 6573: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
6574: ($action ne 'reload')) {
1.1183 raeburn 6575: $toolstatus = $env{'environment.'.$envkey};
1.976 raeburn 6576: $inststatus = $env{'environment.inststatus'};
6577: } else {
1.1084 raeburn 6578: if (ref($userenvref) eq 'HASH') {
1.1183 raeburn 6579: $toolstatus = $userenvref->{$envkey};
1.1084 raeburn 6580: $inststatus = $userenvref->{'inststatus'};
6581: } else {
1.1183 raeburn 6582: my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
6583: $toolstatus = $userenv{$envkey};
1.1084 raeburn 6584: $inststatus = $userenv{'inststatus'};
6585: }
1.976 raeburn 6586: }
6587:
6588: if ($toolstatus ne '') {
6589: if ($toolstatus) {
6590: $access = 1;
6591: } else {
6592: $access = 0;
6593: }
6594: return $access;
6595: }
6596:
1.1084 raeburn 6597: my ($is_adv,%domdef);
6598: if (ref($is_advref) eq 'HASH') {
6599: $is_adv = $is_advref->{'is_adv'};
6600: } else {
6601: $is_adv = &is_advanced_user($udom,$uname);
6602: }
6603: if (ref($domdefref) eq 'HASH') {
6604: %domdef = %{$domdefref};
6605: } else {
6606: %domdef = &get_domain_defaults($udom);
6607: }
1.976 raeburn 6608: if (ref($domdef{$tool}) eq 'HASH') {
6609: if ($is_adv) {
6610: if ($domdef{$tool}{'_LC_adv'} ne '') {
6611: if ($domdef{$tool}{'_LC_adv'}) {
6612: $access = 1;
6613: } else {
6614: $access = 0;
6615: }
6616: return $access;
6617: }
6618: }
6619: if ($inststatus ne '') {
6620: my ($hasaccess,$hasnoaccess);
6621: foreach my $affiliation (split(/:/,$inststatus)) {
6622: if ($domdef{$tool}{$affiliation} ne '') {
6623: if ($domdef{$tool}{$affiliation}) {
6624: $hasaccess = 1;
6625: } else {
6626: $hasnoaccess = 1;
6627: }
6628: }
6629: }
6630: if ($hasaccess || $hasnoaccess) {
6631: if ($hasaccess) {
6632: $access = 1;
6633: } elsif ($hasnoaccess) {
6634: $access = 0;
6635: }
6636: return $access;
6637: }
6638: } else {
6639: if ($domdef{$tool}{'default'} ne '') {
6640: if ($domdef{$tool}{'default'}) {
6641: $access = 1;
6642: } elsif ($domdef{$tool}{'default'} == 0) {
6643: $access = 0;
6644: }
6645: return $access;
6646: }
6647: }
6648: } else {
1.1177 raeburn 6649: if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985 raeburn 6650: $access = 1;
6651: } else {
6652: $access = 0;
6653: }
1.976 raeburn 6654: return $access;
6655: }
6656: }
6657:
1.1050 raeburn 6658: sub is_course_owner {
6659: my ($cdom,$cnum,$udom,$uname) = @_;
6660: if (($udom eq '') || ($uname eq '')) {
6661: $udom = $env{'user.domain'};
6662: $uname = $env{'user.name'};
6663: }
6664: unless (($udom eq '') || ($uname eq '')) {
6665: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
6666: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
6667: return 1;
6668: } else {
6669: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
6670: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
6671: return 1;
6672: }
6673: }
6674: }
6675: }
6676: return;
6677: }
6678:
1.976 raeburn 6679: sub is_advanced_user {
6680: my ($udom,$uname) = @_;
1.1085 raeburn 6681: if ($udom ne '' && $uname ne '') {
6682: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128 raeburn 6683: if (wantarray) {
6684: return ($env{'user.adv'},$env{'user.author'});
6685: } else {
6686: return $env{'user.adv'};
6687: }
1.1085 raeburn 6688: }
6689: }
1.976 raeburn 6690: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
6691: my %allroles;
1.1128 raeburn 6692: my ($is_adv,$is_author);
1.976 raeburn 6693: foreach my $role (keys(%roleshash)) {
6694: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
6695: my $area = '/'.$tdomain.'/'.$trest;
6696: if ($sec ne '') {
6697: $area .= '/'.$sec;
6698: }
6699: if (($area ne '') && ($trole ne '')) {
6700: my $spec=$trole.'.'.$area;
6701: if ($trole =~ /^cr\//) {
6702: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
6703: } elsif ($trole ne 'gr') {
6704: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
6705: }
1.1128 raeburn 6706: if ($trole eq 'au') {
6707: $is_author = 1;
6708: }
1.976 raeburn 6709: }
6710: }
6711: foreach my $role (keys(%allroles)) {
6712: last if ($is_adv);
6713: foreach my $item (split(/:/,$allroles{$role})) {
6714: if ($item ne '') {
6715: my ($privilege,$restrictions)=split(/&/,$item);
6716: if ($privilege eq 'adv') {
6717: $is_adv = 1;
6718: last;
6719: }
6720: }
6721: }
6722: }
1.1128 raeburn 6723: if (wantarray) {
6724: return ($is_adv,$is_author);
6725: }
1.976 raeburn 6726: return $is_adv;
6727: }
1.798 raeburn 6728:
1.1035 raeburn 6729: sub check_can_request {
1.1036 raeburn 6730: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 6731: my $canreq = 0;
6732: my ($types,$typename) = &Apache::loncommon::course_types();
6733: my @options = ('approval','validate','autolimit');
6734: my $optregex = join('|',@options);
6735: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
6736: foreach my $type (@{$types}) {
6737: if (&usertools_access($env{'user.name'},
6738: $env{'user.domain'},
6739: $type,undef,'requestcourses')) {
6740: $canreq ++;
1.1036 raeburn 6741: if (ref($request_domains) eq 'HASH') {
6742: push(@{$request_domains->{$type}},$env{'user.domain'});
6743: }
1.1035 raeburn 6744: if ($dom eq $env{'user.domain'}) {
6745: $can_request->{$type} = 1;
6746: }
6747: }
6748: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
6749: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
6750: if (@curr > 0) {
1.1036 raeburn 6751: foreach my $item (@curr) {
6752: if (ref($request_domains) eq 'HASH') {
6753: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
6754: if ($otherdom ne '') {
6755: if (ref($request_domains->{$type}) eq 'ARRAY') {
6756: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
6757: push(@{$request_domains->{$type}},$otherdom);
6758: }
6759: } else {
6760: push(@{$request_domains->{$type}},$otherdom);
6761: }
6762: }
6763: }
6764: }
6765: unless($dom eq $env{'user.domain'}) {
6766: $canreq ++;
1.1035 raeburn 6767: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
6768: $can_request->{$type} = 1;
6769: }
6770: }
6771: }
6772: }
6773: }
6774: }
6775: return $canreq;
6776: }
6777:
1.341 www 6778: # ---------------------------------------------- Custom access rule evaluation
6779:
6780: sub customaccess {
6781: my ($priv,$uri)=@_;
1.807 albertel 6782: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 6783: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 6784: $udom = &LONCAPA::clean_domain($udom);
6785: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 6786: my $access=0;
1.800 albertel 6787: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 6788: my ($effect,$realm,$role,$type)=split(/\:/,$right);
6789: if ($type eq 'user') {
6790: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 6791: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 6792: if ($tdom) {
6793: if ($tdom ne $env{'user.domain'}) { next; }
6794: }
1.896 albertel 6795: if ($tuname) {
6796: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 6797: }
6798: $access=($effect eq 'allow');
6799: last;
6800: }
6801: } else {
6802: if ($role) {
6803: if ($role ne $urole) { next; }
6804: }
6805: foreach my $scope (split(/\s*\,\s*/,$realm)) {
6806: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
6807: if ($tdom) {
6808: if ($tdom ne $udom) { next; }
6809: }
6810: if ($tcrs) {
6811: if ($tcrs ne $ucrs) { next; }
6812: }
6813: if ($tsec) {
6814: if ($tsec ne $usec) { next; }
6815: }
6816: $access=($effect eq 'allow');
6817: last;
6818: }
6819: if ($realm eq '' && $role eq '') {
6820: $access=($effect eq 'allow');
6821: }
1.402 bowersj2 6822: }
1.341 www 6823: }
6824: return $access;
6825: }
6826:
1.103 harris41 6827: # ------------------------------------------------- Check for a user privilege
1.12 www 6828:
6829: sub allowed {
1.1281 raeburn 6830: my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
1.705 albertel 6831: my $ver_orguri=$uri;
1.439 www 6832: $uri=&deversion($uri);
1.152 www 6833: my $orguri=$uri;
1.52 www 6834: $uri=&declutter($uri);
1.809 raeburn 6835:
1.810 raeburn 6836: if ($priv eq 'evb') {
6837: # Evade communication block restrictions for specified role in a course
6838: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
6839: return $1;
6840: } else {
6841: return;
6842: }
6843: }
6844:
1.620 albertel 6845: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 6846: # Free bre access to adm and meta resources
1.775 albertel 6847: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 6848: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
6849: && ($priv eq 'bre')) {
1.14 www 6850: return 'F';
1.159 www 6851: }
6852:
1.545 banghart 6853: # Free bre access to user's own portfolio contents
1.714 raeburn 6854: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 6855: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 6856: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 6857: my %setters;
6858: my ($startblock,$endblock) =
6859: &Apache::loncommon::blockcheck(\%setters,'port');
6860: if ($startblock && $endblock) {
6861: return 'B';
6862: } else {
6863: return 'F';
6864: }
1.545 banghart 6865: }
6866:
1.762 raeburn 6867: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 6868: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
6869: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
6870: if (exists($env{'request.course.id'})) {
6871: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6872: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6873: if (($domain eq $cdom) && ($name eq $cnum)) {
6874: my $courseprivid=$env{'request.course.id'};
6875: $courseprivid=~s/\_/\//;
6876: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
6877: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
6878: return $1;
1.762 raeburn 6879: } else {
6880: if ($env{'request.course.sec'}) {
6881: $courseprivid.='/'.$env{'request.course.sec'};
6882: }
6883: if ($env{'user.priv.'.$env{'request.role'}.'./'.
6884: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
6885: return $2;
6886: }
1.714 raeburn 6887: }
6888: }
6889: }
6890: }
6891:
1.159 www 6892: # Free bre to public access
6893:
6894: if ($priv eq 'bre') {
1.238 www 6895: my $copyright=&metadata($uri,'copyright');
1.620 albertel 6896: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 6897: return 'F';
6898: }
1.238 www 6899: if ($copyright eq 'priv') {
6900: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 6901: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 6902: return '';
6903: }
6904: }
6905: if ($copyright eq 'domain') {
6906: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 6907: unless (($env{'user.domain'} eq $1) ||
6908: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 6909: return '';
6910: }
1.262 matthew 6911: }
1.620 albertel 6912: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 6913: # Library role, so allow browsing of resources in this domain.
6914: return 'F';
1.238 www 6915: }
1.341 www 6916: if ($copyright eq 'custom') {
6917: unless (&customaccess($priv,$uri)) { return ''; }
6918: }
1.14 www 6919: }
1.264 matthew 6920: # Domain coordinator is trying to create a course
1.620 albertel 6921: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 6922: # uri is the requested domain in this case.
6923: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 6924: # a role of dc for the domain in question.
1.620 albertel 6925: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 6926: }
1.29 www 6927:
1.52 www 6928: my $thisallowed='';
6929: my $statecond=0;
6930: my $courseprivid='';
6931:
1.1039 raeburn 6932: my $ownaccess;
1.1043 raeburn 6933: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 6934: if (($priv eq 'bro') && ($env{'user.author'})) {
6935: if ($uri eq '') {
6936: $ownaccess = 1;
6937: } else {
6938: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
6939: my $udom = $env{'user.domain'};
6940: my $uname = $env{'user.name'};
6941: if ($uri =~ m{^\Q$udom\E/?$}) {
6942: $ownaccess = 1;
1.1040 raeburn 6943: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 6944: unless ($uri =~ m{\.\./}) {
6945: $ownaccess = 1;
6946: }
6947: } elsif (($udom ne 'public') && ($uname ne 'public')) {
6948: my $now = time;
6949: if ($uri =~ m{^([^/]+)/?$}) {
6950: my $adom = $1;
6951: foreach my $key (keys(%env)) {
1.1042 raeburn 6952: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 6953: my ($start,$end) = split('.',$env{$key});
6954: if (($now >= $start) && (!$end || $end < $now)) {
6955: $ownaccess = 1;
6956: last;
6957: }
6958: }
6959: }
6960: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
6961: my $adom = $1;
6962: my $aname = $2;
1.1042 raeburn 6963: foreach my $role ('ca','aa') {
6964: if ($env{"user.role.$role./$adom/$aname"}) {
6965: my ($start,$end) =
6966: split('.',$env{"user.role.$role./$adom/$aname"});
6967: if (($now >= $start) && (!$end || $end < $now)) {
6968: $ownaccess = 1;
6969: last;
6970: }
1.1039 raeburn 6971: }
6972: }
6973: }
6974: }
6975: }
6976: }
6977: }
6978:
1.52 www 6979: # Course
6980:
1.620 albertel 6981: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6982: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6983: $thisallowed.=$1;
6984: }
1.52 www 6985: }
1.29 www 6986:
1.52 www 6987: # Domain
6988:
1.620 albertel 6989: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 6990: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6991: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6992: $thisallowed.=$1;
6993: }
1.12 www 6994: }
1.52 www 6995:
1.1141 raeburn 6996: # User who is not author or co-author might still be able to edit
6997: # resource of an author in the domain (e.g., if Domain Coordinator).
6998: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
6999: (&allowed('mdc',$env{'request.course.id'}))) {
7000: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
7001: $thisallowed.=$1;
7002: }
7003: }
7004:
1.52 www 7005: # Course: uri itself is a course
1.66 www 7006: my $courseuri=$uri;
7007: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 7008: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 7009:
1.620 albertel 7010: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 7011: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 7012: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 7013: $thisallowed.=$1;
7014: }
1.12 www 7015: }
1.29 www 7016:
1.665 albertel 7017: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 7018: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 7019: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 7020: $thisallowed='';
1.671 raeburn 7021: my ($match)=&is_on_map($uri);
7022: if ($match) {
7023: if ($env{'user.priv.'.$env{'request.role'}.'./'}
7024: =~/\Q$priv\E\&([^\:]*)/) {
1.1281 raeburn 7025: my $value = $1;
7026: if ($noblockcheck) {
7027: $thisallowed.=$value;
1.1162 raeburn 7028: } else {
1.1281 raeburn 7029: my @blockers = &has_comm_blocking($priv,$symb,$uri);
7030: if (@blockers > 0) {
7031: $thisallowed = 'B';
7032: } else {
7033: $thisallowed.=$value;
7034: }
1.1162 raeburn 7035: }
1.671 raeburn 7036: }
7037: } else {
1.705 albertel 7038: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 7039: if ($refuri) {
7040: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 7041: $thisallowed='F';
1.671 raeburn 7042: } else {
7043: $refuri=&declutter($refuri);
7044: my ($match) = &is_on_map($refuri);
7045: if ($match) {
1.1281 raeburn 7046: if ($noblockcheck) {
7047: $thisallowed='F';
1.1162 raeburn 7048: } else {
1.1281 raeburn 7049: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
7050: if (@blockers > 0) {
7051: $thisallowed = 'B';
7052: } else {
7053: $thisallowed='F';
7054: }
1.1162 raeburn 7055: }
1.671 raeburn 7056: }
1.669 raeburn 7057: }
1.671 raeburn 7058: }
7059: }
1.314 www 7060: }
1.492 albertel 7061:
1.766 albertel 7062: if ($priv eq 'bre'
7063: && $thisallowed ne 'F'
7064: && $thisallowed ne '2'
7065: && &is_portfolio_url($uri)) {
1.1270 raeburn 7066: $thisallowed = &portfolio_access($uri,$clientip);
1.766 albertel 7067: }
1.1250 raeburn 7068:
1.52 www 7069: # Full access at system, domain or course-wide level? Exit.
1.29 www 7070: if ($thisallowed=~/F/) {
7071: return 'F';
7072: }
7073:
1.52 www 7074: # If this is generating or modifying users, exit with special codes
1.29 www 7075:
1.643 www 7076: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
7077: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 7078: my ($audom,$auname)=split('/',$uri);
1.643 www 7079: # no author name given, so this just checks on the general right to make a co-author in this domain
7080: unless ($auname) { return $thisallowed; }
7081: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 7082: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
7083: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
7084: ($audom ne $env{'request.role.domain'}))) { return ''; }
7085: }
1.52 www 7086: return $thisallowed;
7087: }
7088: #
1.103 harris41 7089: # Gathered so far: system, domain and course wide privileges
1.52 www 7090: #
7091: # Course: See if uri or referer is an individual resource that is part of
7092: # the course
7093:
1.620 albertel 7094: if ($env{'request.course.id'}) {
1.232 www 7095:
1.620 albertel 7096: $courseprivid=$env{'request.course.id'};
7097: if ($env{'request.course.sec'}) {
7098: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 7099: }
7100: $courseprivid=~s/\_/\//;
7101: my $checkreferer=1;
1.232 www 7102: my ($match,$cond)=&is_on_map($uri);
7103: if ($match) {
7104: $statecond=$cond;
1.620 albertel 7105: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 7106: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 7107: my $value = $1;
7108: if ($priv eq 'bre') {
1.1281 raeburn 7109: if ($noblockcheck) {
7110: $thisallowed.=$value;
1.1162 raeburn 7111: } else {
1.1281 raeburn 7112: my @blockers = &has_comm_blocking($priv,$symb,$uri);
7113: if (@blockers > 0) {
7114: $thisallowed = 'B';
7115: } else {
7116: $thisallowed.=$value;
7117: }
1.1162 raeburn 7118: }
7119: } else {
7120: $thisallowed.=$value;
7121: }
1.52 www 7122: $checkreferer=0;
7123: }
1.29 www 7124: }
1.83 www 7125:
1.148 www 7126: if ($checkreferer) {
1.620 albertel 7127: my $refuri=$env{'httpref.'.$orguri};
1.148 www 7128: unless ($refuri) {
1.800 albertel 7129: foreach my $key (keys(%env)) {
7130: if ($key=~/^httpref\..*\*/) {
7131: my $pattern=$key;
1.156 www 7132: $pattern=~s/^httpref\.\/res\///;
1.148 www 7133: $pattern=~s/\*/\[\^\/\]\+/g;
7134: $pattern=~s/\//\\\//g;
1.152 www 7135: if ($orguri=~/$pattern/) {
1.800 albertel 7136: $refuri=$env{$key};
1.148 www 7137: }
7138: }
1.191 harris41 7139: }
1.148 www 7140: }
1.232 www 7141:
1.148 www 7142: if ($refuri) {
1.152 www 7143: $refuri=&declutter($refuri);
1.232 www 7144: my ($match,$cond)=&is_on_map($refuri);
7145: if ($match) {
7146: my $refstatecond=$cond;
1.620 albertel 7147: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 7148: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 7149: my $value = $1;
7150: if ($priv eq 'bre') {
1.1281 raeburn 7151: if ($noblockcheck) {
7152: $thisallowed.=$value;
1.1162 raeburn 7153: } else {
1.1281 raeburn 7154: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
7155: if (@blockers > 0) {
7156: $thisallowed = 'B';
7157: } else {
7158: $thisallowed.=$value;
7159: }
1.1162 raeburn 7160: }
7161: } else {
7162: $thisallowed.=$value;
7163: }
1.53 www 7164: $uri=$refuri;
7165: $statecond=$refstatecond;
1.52 www 7166: }
7167: }
1.148 www 7168: }
1.29 www 7169: }
1.52 www 7170: }
1.29 www 7171:
1.52 www 7172: #
1.103 harris41 7173: # Gathered now: all privileges that could apply, and condition number
1.52 www 7174: #
7175: #
7176: # Full or no access?
7177: #
1.29 www 7178:
1.52 www 7179: if ($thisallowed=~/F/) {
7180: return 'F';
7181: }
1.29 www 7182:
1.52 www 7183: unless ($thisallowed) {
7184: return '';
7185: }
1.29 www 7186:
1.52 www 7187: # Restrictions exist, deal with them
7188: #
7189: # C:according to course preferences
7190: # R:according to resource settings
7191: # L:unless locked
7192: # X:according to user session state
7193: #
7194:
7195: # Possibly locked functionality, check all courses
1.54 www 7196: # Locks might take effect only after 10 minutes cache expiration for other
7197: # courses, and 2 minutes for current course
1.52 www 7198:
7199: my $envkey;
7200: if ($thisallowed=~/L/) {
1.1000 raeburn 7201: foreach $envkey (keys(%env)) {
1.54 www 7202: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
7203: my $courseid=$2;
7204: my $roleid=$1.'.'.$2;
1.92 www 7205: $courseid=~s/^\///;
1.54 www 7206: my $expiretime=600;
1.620 albertel 7207: if ($env{'request.role'} eq $roleid) {
1.54 www 7208: $expiretime=120;
7209: }
7210: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
7211: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 7212: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 7213: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 7214: }
1.620 albertel 7215: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
7216: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
7217: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
7218: &log($env{'user.domain'},$env{'user.name'},
7219: $env{'user.home'},
1.57 www 7220: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 7221: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 7222: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 7223: return '';
7224: }
7225: }
1.620 albertel 7226: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
7227: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
7228: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
7229: &log($env{'user.domain'},$env{'user.name'},
7230: $env{'user.home'},
1.57 www 7231: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 7232: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 7233: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 7234: return '';
7235: }
7236: }
7237: }
1.29 www 7238: }
1.52 www 7239: }
7240:
7241: #
7242: # Rest of the restrictions depend on selected course
7243: #
7244:
1.620 albertel 7245: unless ($env{'request.course.id'}) {
1.766 albertel 7246: if ($thisallowed eq 'A') {
7247: return 'A';
1.814 raeburn 7248: } elsif ($thisallowed eq 'B') {
7249: return 'B';
1.766 albertel 7250: } else {
7251: return '1';
7252: }
1.52 www 7253: }
1.29 www 7254:
1.52 www 7255: #
7256: # Now user is definitely in a course
7257: #
1.53 www 7258:
7259:
7260: # Course preferences
7261:
7262: if ($thisallowed=~/C/) {
1.620 albertel 7263: my $rolecode=(split(/\./,$env{'request.role'}))[0];
7264: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
7265: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 7266: =~/\Q$rolecode\E/) {
1.1304 raeburn 7267: if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689 albertel 7268: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
7269: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
7270: $env{'request.course.id'});
7271: }
1.237 www 7272: return '';
7273: }
7274:
1.620 albertel 7275: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 7276: =~/\Q$unamedom\E/) {
1.1304 raeburn 7277: if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689 albertel 7278: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
7279: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
7280: $env{'request.course.id'});
7281: }
1.54 www 7282: return '';
7283: }
1.53 www 7284: }
7285:
7286: # Resource preferences
7287:
7288: if ($thisallowed=~/R/) {
1.620 albertel 7289: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 7290: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103 raeburn 7291: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7292: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
7293: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
7294: }
7295: return '';
1.54 www 7296: }
1.53 www 7297: }
1.30 www 7298:
1.246 www 7299: # Restricted by state or randomout?
1.30 www 7300:
1.52 www 7301: if ($thisallowed=~/X/) {
1.620 albertel 7302: if ($env{'acc.randomout'}) {
1.579 albertel 7303: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 7304: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 7305: return '';
7306: }
1.247 www 7307: }
7308: if (&condval($statecond)) {
1.52 www 7309: return '2';
7310: } else {
7311: return '';
7312: }
7313: }
1.30 www 7314:
1.766 albertel 7315: if ($thisallowed eq 'A') {
7316: return 'A';
1.814 raeburn 7317: } elsif ($thisallowed eq 'B') {
7318: return 'B';
1.766 albertel 7319: }
1.52 www 7320: return 'F';
1.232 www 7321: }
1.1162 raeburn 7322:
1.1192 raeburn 7323: # ------------------------------------------- Check construction space access
7324:
7325: sub constructaccess {
7326: my ($url,$setpriv)=@_;
7327:
7328: # We do not allow editing of previous versions of files
7329: if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
7330:
7331: # Get username and domain from URL
7332: my ($ownername,$ownerdomain,$ownerhome);
7333:
7334: ($ownerdomain,$ownername) =
1.1297 damieng 7335: ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)/});
1.1192 raeburn 7336:
7337: # The URL does not really point to any authorspace, forget it
7338: unless (($ownername) && ($ownerdomain)) { return ''; }
7339:
7340: # Now we need to see if the user has access to the authorspace of
7341: # $ownername at $ownerdomain
7342:
7343: if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
7344: # Real author for this?
7345: $ownerhome = $env{'user.home'};
7346: if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
7347: return ($ownername,$ownerdomain,$ownerhome);
7348: }
7349: } else {
7350: # Co-author for this?
7351: if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
7352: exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
7353: $ownerhome = &homeserver($ownername,$ownerdomain);
7354: return ($ownername,$ownerdomain,$ownerhome);
7355: }
7356: }
7357:
7358: # We don't have any access right now. If we are not possibly going to do anything about this,
7359: # we might as well leave
7360: unless ($setpriv) { return ''; }
7361:
7362: # Backdoor access?
7363: my $allowed=&allowed('eco',$ownerdomain);
7364: # Nope
7365: unless ($allowed) { return ''; }
7366: # Looks like we may have access, but could be locked by the owner of the construction space
7367: if ($allowed eq 'U') {
7368: my %blocked=&get('environment',['domcoord.author'],
7369: $ownerdomain,$ownername);
7370: # Is blocked by owner
7371: if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
7372: }
7373: if (($allowed eq 'F') || ($allowed eq 'U')) {
7374: # Grant temporary access
7375: my $then=$env{'user.login.time'};
1.1209 raeburn 7376: my $update=$env{'user.update.time'};
1.1192 raeburn 7377: if (!$update) { $update = $then; }
7378: my $refresh=$env{'user.refresh.time'};
7379: if (!$refresh) { $refresh = $update; }
7380: my $now = time;
7381: &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
7382: $now,'ca','constructaccess');
7383: $ownerhome = &homeserver($ownername,$ownerdomain);
7384: return($ownername,$ownerdomain,$ownerhome);
7385: }
7386: # No business here
7387: return '';
7388: }
7389:
1.1282 raeburn 7390: # ----------------------------------------------------------- Content Blocking
7391:
7392: {
7393: # Caches for faster Course Contents display where content blocking
7394: # is in operation (i.e., interval param set) for timed quiz.
7395: #
7396: # User for whom data are being temporarily cached.
7397: my $cacheduser='';
7398: # Cached blockers for this user (a hash of blocking items).
7399: my %cachedblockers=();
7400: # When the data were last cached.
7401: my $cachedlast='';
7402:
7403: sub load_all_blockers {
7404: my ($uname,$udom,$blocks)=@_;
7405: if (($uname ne '') && ($udom ne '')) {
7406: if (($cacheduser eq $uname.':'.$udom) &&
7407: (abs($cachedlast-time)<5)) {
7408: return;
7409: }
7410: }
7411: $cachedlast=time;
7412: $cacheduser=$uname.':'.$udom;
7413: %cachedblockers = &get_commblock_resources($blocks);
7414: }
7415:
1.1162 raeburn 7416: sub get_comm_blocks {
7417: my ($cdom,$cnum) = @_;
7418: if ($cdom eq '' || $cnum eq '') {
7419: return unless ($env{'request.course.id'});
7420: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7421: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7422: }
7423: my %commblocks;
7424: my $hashid=$cdom.'_'.$cnum;
7425: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
7426: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
7427: %commblocks = %{$blocksref};
7428: } else {
7429: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
7430: my $cachetime = 600;
7431: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
7432: }
7433: return %commblocks;
7434: }
7435:
1.1282 raeburn 7436: sub get_commblock_resources {
7437: my ($blocks) = @_;
7438: my %blockers = ();
7439: return %blockers unless ($env{'request.course.id'});
7440: return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162 raeburn 7441: my %commblocks;
7442: if (ref($blocks) eq 'HASH') {
7443: %commblocks = %{$blocks};
7444: } else {
7445: %commblocks = &get_comm_blocks();
7446: }
1.1282 raeburn 7447: return %blockers unless (keys(%commblocks) > 0);
7448: my $navmap = Apache::lonnavmaps::navmap->new();
7449: return %blockers unless (ref($navmap));
1.1162 raeburn 7450: my $now = time;
7451: foreach my $block (keys(%commblocks)) {
7452: if ($block =~ /^(\d+)____(\d+)$/) {
7453: my ($start,$end) = ($1,$2);
7454: if ($start <= $now && $end >= $now) {
7455: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7456: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
7457: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1282 raeburn 7458: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
7459: $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162 raeburn 7460: }
7461: }
7462: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1282 raeburn 7463: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
7464: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162 raeburn 7465: }
7466: }
7467: }
7468: }
7469: }
7470: } elsif ($block =~ /^firstaccess____(.+)$/) {
7471: my $item = $1;
1.1163 raeburn 7472: my @to_test;
1.1162 raeburn 7473: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7474: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1282 raeburn 7475: my @interval;
7476: my $type = 'map';
7477: if ($item eq 'course') {
7478: $type = 'course';
7479: @interval=&EXT("resource.0.interval");
7480: } else {
7481: if ($item =~ /___\d+___/) {
7482: $type = 'resource';
7483: @interval=&EXT("resource.0.interval",$item);
7484: if (ref($navmap)) {
7485: my $res = $navmap->getBySymb($item);
7486: push(@to_test,$res);
7487: }
1.1162 raeburn 7488: } else {
1.1282 raeburn 7489: my $mapsymb = &symbread($item,1);
7490: if ($mapsymb) {
7491: if (ref($navmap)) {
7492: my $mapres = $navmap->getBySymb($mapsymb);
7493: @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
7494: foreach my $res (@to_test) {
7495: my $symb = $res->symb();
7496: next if ($symb eq $mapsymb);
7497: if ($symb ne '') {
7498: @interval=&EXT("resource.0.interval",$symb);
7499: if ($interval[1] eq 'map') {
7500: last;
1.1162 raeburn 7501: }
7502: }
7503: }
7504: }
7505: }
7506: }
1.1282 raeburn 7507: }
1.1292 raeburn 7508: if ($interval[0] =~ /^\d+/) {
7509: my ($timelimit) = split(/_/,$interval[0]);
1.1282 raeburn 7510: my $first_access;
7511: if ($type eq 'resource') {
7512: $first_access=&get_first_access($interval[1],$item);
7513: } elsif ($type eq 'map') {
7514: $first_access=&get_first_access($interval[1],undef,$item);
7515: } else {
7516: $first_access=&get_first_access($interval[1]);
7517: }
7518: if ($first_access) {
1.1292 raeburn 7519: my $timesup = $first_access+$timelimit;
1.1282 raeburn 7520: if ($timesup > $now) {
7521: my $activeblock;
7522: foreach my $res (@to_test) {
1.1283 raeburn 7523: if ($res->answerable()) {
1.1282 raeburn 7524: $activeblock = 1;
7525: last;
7526: }
7527: }
7528: if ($activeblock) {
7529: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
7530: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
7531: $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
7532: }
7533: }
7534: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
7535: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
7536: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163 raeburn 7537: }
1.1162 raeburn 7538: }
7539: }
7540: }
7541: }
7542: }
7543: }
7544: }
7545: }
7546: }
1.1282 raeburn 7547: return %blockers;
1.1162 raeburn 7548: }
7549:
1.1282 raeburn 7550: sub has_comm_blocking {
7551: my ($priv,$symb,$uri,$blocks) = @_;
7552: my @blockers;
7553: return unless ($env{'request.course.id'});
7554: return unless ($priv eq 'bre');
7555: return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
7556: return if ($env{'request.state'} eq 'construct');
7557: &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
7558: return unless (keys(%cachedblockers) > 0);
7559: my (%possibles,@symbs);
7560: if (!$symb) {
7561: $symb = &symbread($uri,1,1,1,\%possibles);
1.1162 raeburn 7562: }
1.1282 raeburn 7563: if ($symb) {
7564: @symbs = ($symb);
7565: } elsif (keys(%possibles)) {
7566: @symbs = keys(%possibles);
7567: }
7568: my $noblock;
7569: foreach my $symb (@symbs) {
7570: last if ($noblock);
7571: my ($map,$resid,$resurl)=&decode_symb($symb);
7572: foreach my $block (keys(%cachedblockers)) {
7573: if ($block =~ /^firstaccess____(.+)$/) {
7574: my $item = $1;
7575: if (($item eq $map) || ($item eq $symb)) {
7576: $noblock = 1;
7577: last;
7578: }
7579: }
7580: if (ref($cachedblockers{$block}) eq 'HASH') {
7581: if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
7582: if ($cachedblockers{$block}{'resources'}{$symb}) {
7583: unless (grep(/^\Q$block\E$/,@blockers)) {
7584: push(@blockers,$block);
7585: }
7586: }
7587: }
1.1162 raeburn 7588: }
1.1282 raeburn 7589: if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
7590: if ($cachedblockers{$block}{'maps'}{$map}) {
7591: unless (grep(/^\Q$block\E$/,@blockers)) {
7592: push(@blockers,$block);
7593: }
7594: }
1.1162 raeburn 7595: }
7596: }
7597: }
1.1282 raeburn 7598: return if ($noblock);
7599: return @blockers;
7600: }
1.1162 raeburn 7601: }
7602:
1.1282 raeburn 7603: # -------------------------------- Deversion and split uri into path an filename
7604:
1.1133 foxr 7605: #
1.1282 raeburn 7606: # Removes the version from a URI and
1.1133 foxr 7607: # splits it in to its filename and path to the filename.
7608: # Seems like File::Basename could have done this more clearly.
7609: # Parameters:
7610: # $uri - input URI
7611: # Returns:
7612: # Two element list consisting of
7613: # $pathname - the URI up to and excluding the trailing /
7614: # $filename - The part of the URI following the last /
7615: # NOTE:
7616: # Another realization of this is simply:
7617: # use File::Basename;
7618: # ...
7619: # $uri = shift;
7620: # $filename = basename($uri);
7621: # $path = dirname($uri);
7622: # return ($filename, $path);
7623: #
7624: # The implementation below is probably faster however.
7625: #
1.710 albertel 7626: sub split_uri_for_cond {
7627: my $uri=&deversion(&declutter(shift));
7628: my @uriparts=split(/\//,$uri);
7629: my $filename=pop(@uriparts);
7630: my $pathname=join('/',@uriparts);
7631: return ($pathname,$filename);
7632: }
1.232 www 7633: # --------------------------------------------------- Is a resource on the map?
7634:
7635: sub is_on_map {
1.710 albertel 7636: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 7637: #Trying to find the conditional for the file
1.620 albertel 7638: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 7639: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 7640: if ($match) {
1.289 bowersj2 7641: return (1,$1);
7642: } else {
1.434 www 7643: return (0,0);
1.289 bowersj2 7644: }
1.12 www 7645: }
7646:
1.427 www 7647: # --------------------------------------------------------- Get symb from alias
7648:
7649: sub get_symb_from_alias {
7650: my $symb=shift;
7651: my ($map,$resid,$url)=&decode_symb($symb);
7652: # Already is a symb
7653: if ($url) { return $symb; }
7654: # Must be an alias
7655: my $aliassymb='';
7656: my %bighash;
1.620 albertel 7657: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 7658: &GDBM_READER(),0640)) {
7659: my $rid=$bighash{'mapalias_'.$symb};
7660: if ($rid) {
7661: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 7662: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
7663: $resid,$bighash{'src_'.$rid});
1.427 www 7664: }
7665: untie %bighash;
7666: }
7667: return $aliassymb;
7668: }
7669:
1.12 www 7670: # ----------------------------------------------------------------- Define Role
7671:
7672: sub definerole {
7673: if (allowed('mcr','/')) {
7674: my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800 albertel 7675: foreach my $role (split(':',$sysrole)) {
7676: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7677: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
7678: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
7679: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 7680: return "refused:s:$crole&$cqual";
7681: }
7682: }
1.191 harris41 7683: }
1.800 albertel 7684: foreach my $role (split(':',$domrole)) {
7685: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7686: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
7687: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
7688: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 7689: return "refused:d:$crole&$cqual";
7690: }
7691: }
1.191 harris41 7692: }
1.800 albertel 7693: foreach my $role (split(':',$courole)) {
7694: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7695: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
7696: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
7697: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 7698: return "refused:c:$crole&$cqual";
7699: }
7700: }
1.191 harris41 7701: }
1.620 albertel 7702: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
7703: "$env{'user.domain'}:$env{'user.name'}:".
1.21 www 7704: "rolesdef_$rolename=".
7705: escape($sysrole.'_'.$domrole.'_'.$courole);
1.620 albertel 7706: return reply($command,$env{'user.home'});
1.12 www 7707: } else {
7708: return 'refused';
7709: }
1.105 harris41 7710: }
7711:
7712: # ---------------- Make a metadata query against the network of library servers
7713:
7714: sub metadata_query {
1.1237 raeburn 7715: my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120 harris41 7716: my %rhash;
1.845 albertel 7717: my %libserv = &all_library();
1.244 matthew 7718: my @server_list = (defined($server_array) ? @$server_array
7719: : keys(%libserv) );
7720: for my $server (@server_list) {
1.1237 raeburn 7721: my $domains = '';
7722: if (ref($domains_hash) eq 'HASH') {
7723: $domains = $domains_hash->{$server};
7724: }
1.118 harris41 7725: unless ($custom or $customshow) {
1.1237 raeburn 7726: my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118 harris41 7727: $rhash{$server}=$reply;
7728: }
7729: else {
7730: my $reply=&reply("querysend:".&escape($query).':'.
1.1237 raeburn 7731: &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118 harris41 7732: $server);
7733: $rhash{$server}=$reply;
7734: }
1.112 harris41 7735: }
1.118 harris41 7736: return \%rhash;
1.240 www 7737: }
7738:
7739: # ----------------------------------------- Send log queries and wait for reply
7740:
7741: sub log_query {
7742: my ($uname,$udom,$query,%filters)=@_;
7743: my $uhome=&homeserver($uname,$udom);
7744: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 7745: my $uhost=&hostname($uhome);
1.800 albertel 7746: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 7747: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
7748: $uhome);
1.479 albertel 7749: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 7750: return get_query_reply($queryid);
7751: }
7752:
1.818 raeburn 7753: # -------------------------- Update MySQL table for portfolio file
7754:
7755: sub update_portfolio_table {
1.821 raeburn 7756: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 7757: if ($group ne '') {
7758: $file_name =~s /^\Q$group\E//;
7759: }
1.818 raeburn 7760: my $homeserver = &homeserver($uname,$udom);
7761: my $queryid=
1.821 raeburn 7762: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
7763: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 7764: my $reply = &get_query_reply($queryid);
7765: return $reply;
7766: }
7767:
1.899 raeburn 7768: # -------------------------- Update MySQL allusers table
7769:
7770: sub update_allusers_table {
7771: my ($uname,$udom,$names) = @_;
7772: my $homeserver = &homeserver($uname,$udom);
7773: my $queryid=
7774: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
7775: 'lastname='.&escape($names->{'lastname'}).'%%'.
7776: 'firstname='.&escape($names->{'firstname'}).'%%'.
7777: 'middlename='.&escape($names->{'middlename'}).'%%'.
7778: 'generation='.&escape($names->{'generation'}).'%%'.
7779: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
7780: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 7781: return;
1.899 raeburn 7782: }
7783:
1.508 raeburn 7784: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 7785:
7786: sub fetch_enrollment_query {
1.511 raeburn 7787: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508 raeburn 7788: my $homeserver;
1.547 raeburn 7789: my $maxtries = 1;
1.508 raeburn 7790: if ($context eq 'automated') {
7791: $homeserver = $perlvar{'lonHostID'};
1.547 raeburn 7792: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 7793: } else {
7794: $homeserver = &homeserver($cnum,$dom);
7795: }
1.838 albertel 7796: my $host=&hostname($homeserver);
1.506 raeburn 7797: my $cmd = '';
1.1000 raeburn 7798: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 7799: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 7800: }
7801: $cmd =~ s/%%$//;
7802: $cmd = &escape($cmd);
7803: my $query = 'fetchenrollment';
1.620 albertel 7804: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 7805: unless ($queryid=~/^\Q$host\E\_/) {
7806: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
7807: return 'error: '.$queryid;
7808: }
1.506 raeburn 7809: my $reply = &get_query_reply($queryid);
1.547 raeburn 7810: my $tries = 1;
7811: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
7812: $reply = &get_query_reply($queryid);
7813: $tries ++;
7814: }
1.526 raeburn 7815: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 7816: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 7817: } else {
1.901 albertel 7818: my @responses = split(/:/,$reply);
1.515 raeburn 7819: if ($homeserver eq $perlvar{'lonHostID'}) {
1.800 albertel 7820: foreach my $line (@responses) {
7821: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 7822: $$replyref{$key} = $value;
7823: }
7824: } else {
1.1117 foxr 7825: my $pathname = LONCAPA::tempdir();
1.800 albertel 7826: foreach my $line (@responses) {
7827: my ($key,$value) = split(/=/,$line);
1.506 raeburn 7828: $$replyref{$key} = $value;
7829: if ($value > 0) {
1.800 albertel 7830: foreach my $item (@{$$affiliatesref{$key}}) {
7831: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 7832: my $destname = $pathname.'/'.$filename;
7833: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 7834: if ($xml_classlist =~ /^error/) {
7835: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
7836: } else {
1.506 raeburn 7837: if ( open(FILE,">$destname") ) {
7838: print FILE &unescape($xml_classlist);
7839: close(FILE);
1.526 raeburn 7840: } else {
7841: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 7842: }
7843: }
7844: }
7845: }
7846: }
7847: }
7848: return 'ok';
7849: }
7850: return 'error';
7851: }
7852:
1.242 www 7853: sub get_query_reply {
7854: my $queryid=shift;
1.1117 foxr 7855: my $replyfile=LONCAPA::tempdir().$queryid;
1.240 www 7856: my $reply='';
7857: for (1..100) {
1.1289 damieng 7858: sleep(0.2);
1.240 www 7859: if (-e $replyfile.'.end') {
1.448 albertel 7860: if (open(my $fh,$replyfile)) {
1.904 albertel 7861: $reply = join('',<$fh>);
7862: close($fh);
1.240 www 7863: } else { return 'error: reply_file_error'; }
1.242 www 7864: return &unescape($reply);
7865: }
1.240 www 7866: }
1.242 www 7867: return 'timeout:'.$queryid;
1.240 www 7868: }
7869:
7870: sub courselog_query {
1.241 www 7871: #
7872: # possible filters:
7873: # url: url or symb
7874: # username
7875: # domain
7876: # action: view, submit, grade
7877: # start: timestamp
7878: # end: timestamp
7879: #
1.240 www 7880: my (%filters)=@_;
1.620 albertel 7881: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 7882: if ($filters{'url'}) {
7883: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
7884: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
7885: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
7886: }
1.620 albertel 7887: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
7888: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 7889: return &log_query($cname,$cdom,'courselog',%filters);
7890: }
7891:
7892: sub userlog_query {
1.858 raeburn 7893: #
7894: # possible filters:
7895: # action: log check role
7896: # start: timestamp
7897: # end: timestamp
7898: #
1.240 www 7899: my ($uname,$udom,%filters)=@_;
7900: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 7901: }
7902:
1.506 raeburn 7903: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
7904:
7905: sub auto_run {
1.508 raeburn 7906: my ($cnum,$cdom) = @_;
1.876 raeburn 7907: my $response = 0;
7908: my $settings;
7909: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
7910: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
7911: $settings = $domconfig{'autoenroll'};
7912: if ($settings->{'run'} eq '1') {
7913: $response = 1;
7914: }
7915: } else {
1.934 raeburn 7916: my $homeserver;
7917: if (&is_course($cdom,$cnum)) {
7918: $homeserver = &homeserver($cnum,$cdom);
7919: } else {
7920: $homeserver = &domain($cdom,'primary');
7921: }
7922: if ($homeserver ne 'no_host') {
7923: $response = &reply('autorun:'.$cdom,$homeserver);
7924: }
1.876 raeburn 7925: }
1.506 raeburn 7926: return $response;
7927: }
1.776 albertel 7928:
1.506 raeburn 7929: sub auto_get_sections {
1.508 raeburn 7930: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 7931: my $homeserver;
7932: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7933: $homeserver = &homeserver($cnum,$cdom);
7934: }
7935: if (!defined($homeserver)) {
7936: if ($cdom =~ /^$match_domain$/) {
7937: $homeserver = &domain($cdom,'primary');
7938: }
7939: }
7940: my @secs;
7941: if (defined($homeserver)) {
7942: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
7943: unless ($response eq 'refused') {
7944: @secs = split(/:/,$response);
7945: }
1.506 raeburn 7946: }
7947: return @secs;
7948: }
1.776 albertel 7949:
1.506 raeburn 7950: sub auto_new_course {
1.1099 raeburn 7951: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 7952: my $homeserver = &homeserver($cnum,$cdom);
1.1099 raeburn 7953: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 7954: return $response;
7955: }
1.776 albertel 7956:
1.506 raeburn 7957: sub auto_validate_courseID {
1.508 raeburn 7958: my ($cnum,$cdom,$inst_course_id) = @_;
7959: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 7960: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 7961: return $response;
7962: }
1.776 albertel 7963:
1.1007 raeburn 7964: sub auto_validate_instcode {
1.1020 raeburn 7965: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 7966: my ($homeserver,$response);
7967: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7968: $homeserver = &homeserver($cnum,$cdom);
7969: }
7970: if (!defined($homeserver)) {
7971: if ($cdom =~ /^$match_domain$/) {
7972: $homeserver = &domain($cdom,'primary');
7973: }
7974: }
1.1065 raeburn 7975: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
7976: &escape($instcode).':'.&escape($owner),$homeserver));
1.1216 raeburn 7977: my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
7978: return ($outcome,$description,$defaultcredits);
1.1007 raeburn 7979: }
7980:
1.506 raeburn 7981: sub auto_create_password {
1.873 raeburn 7982: my ($cnum,$cdom,$authparam,$udom) = @_;
7983: my ($homeserver,$response);
1.506 raeburn 7984: my $create_passwd = 0;
7985: my $authchk = '';
1.873 raeburn 7986: if ($udom =~ /^$match_domain$/) {
7987: $homeserver = &domain($udom,'primary');
7988: }
7989: if ($homeserver eq '') {
7990: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7991: $homeserver = &homeserver($cnum,$cdom);
7992: }
7993: }
7994: if ($homeserver eq '') {
7995: $authchk = 'nodomain';
1.506 raeburn 7996: } else {
1.873 raeburn 7997: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
7998: if ($response eq 'refused') {
7999: $authchk = 'refused';
8000: } else {
1.901 albertel 8001: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 8002: }
1.506 raeburn 8003: }
8004: return ($authparam,$create_passwd,$authchk);
8005: }
8006:
1.706 raeburn 8007: sub auto_photo_permission {
8008: my ($cnum,$cdom,$students) = @_;
8009: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 8010: my ($outcome,$perm_reqd,$conditions) =
8011: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 8012: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
8013: return (undef,undef);
8014: }
1.706 raeburn 8015: return ($outcome,$perm_reqd,$conditions);
8016: }
8017:
8018: sub auto_checkphotos {
8019: my ($uname,$udom,$pid) = @_;
8020: my $homeserver = &homeserver($uname,$udom);
8021: my ($result,$resulttype);
8022: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 8023: &escape($uname).':'.&escape($pid),
8024: $homeserver));
1.709 albertel 8025: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
8026: return (undef,undef);
8027: }
1.706 raeburn 8028: if ($outcome) {
8029: ($result,$resulttype) = split(/:/,$outcome);
8030: }
8031: return ($result,$resulttype);
8032: }
8033:
8034: sub auto_photochoice {
8035: my ($cnum,$cdom) = @_;
8036: my $homeserver = &homeserver($cnum,$cdom);
8037: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 8038: &escape($cdom),
8039: $homeserver)));
1.709 albertel 8040: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
8041: return (undef,undef);
8042: }
1.706 raeburn 8043: return ($update,$comment);
8044: }
8045:
8046: sub auto_photoupdate {
8047: my ($affiliatesref,$dom,$cnum,$photo) = @_;
8048: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 8049: my $host=&hostname($homeserver);
1.706 raeburn 8050: my $cmd = '';
8051: my $maxtries = 1;
1.800 albertel 8052: foreach my $affiliate (keys(%{$affiliatesref})) {
8053: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 8054: }
8055: $cmd =~ s/%%$//;
8056: $cmd = &escape($cmd);
8057: my $query = 'institutionalphotos';
8058: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
8059: unless ($queryid=~/^\Q$host\E\_/) {
8060: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
8061: return 'error: '.$queryid;
8062: }
8063: my $reply = &get_query_reply($queryid);
8064: my $tries = 1;
8065: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
8066: $reply = &get_query_reply($queryid);
8067: $tries ++;
8068: }
8069: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
8070: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
8071: } else {
8072: my @responses = split(/:/,$reply);
8073: my $outcome = shift(@responses);
8074: foreach my $item (@responses) {
8075: my ($key,$value) = split(/=/,$item);
8076: $$photo{$key} = $value;
8077: }
8078: return $outcome;
8079: }
8080: return 'error';
8081: }
8082:
1.521 raeburn 8083: sub auto_instcode_format {
1.793 albertel 8084: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
8085: $cat_order) = @_;
1.521 raeburn 8086: my $courses = '';
1.772 raeburn 8087: my @homeservers;
1.521 raeburn 8088: if ($caller eq 'global') {
1.841 albertel 8089: my %servers = &get_servers($codedom,'library');
8090: foreach my $tryserver (keys(%servers)) {
8091: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
8092: push(@homeservers,$tryserver);
8093: }
1.584 raeburn 8094: }
1.1022 raeburn 8095: } elsif ($caller eq 'requests') {
8096: if ($codedom =~ /^$match_domain$/) {
8097: my $chome = &domain($codedom,'primary');
8098: unless ($chome eq 'no_host') {
8099: push(@homeservers,$chome);
8100: }
8101: }
1.521 raeburn 8102: } else {
1.772 raeburn 8103: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 8104: }
1.793 albertel 8105: foreach my $code (keys(%{$instcodes})) {
8106: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 8107: }
8108: chop($courses);
1.772 raeburn 8109: my $ok_response = 0;
8110: my $response;
8111: while (@homeservers > 0 && $ok_response == 0) {
8112: my $server = shift(@homeservers);
8113: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
8114: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
8115: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 8116: split(/:/,$response);
1.772 raeburn 8117: %{$codes} = (%{$codes},&str2hash($codes_str));
8118: push(@{$codetitles},&str2array($codetitles_str));
8119: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
8120: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
8121: $ok_response = 1;
8122: }
8123: }
8124: if ($ok_response) {
1.521 raeburn 8125: return 'ok';
1.772 raeburn 8126: } else {
8127: return $response;
1.521 raeburn 8128: }
8129: }
8130:
1.792 raeburn 8131: sub auto_instcode_defaults {
8132: my ($domain,$returnhash,$code_order) = @_;
8133: my @homeservers;
1.841 albertel 8134:
8135: my %servers = &get_servers($domain,'library');
8136: foreach my $tryserver (keys(%servers)) {
8137: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
8138: push(@homeservers,$tryserver);
8139: }
1.792 raeburn 8140: }
1.841 albertel 8141:
1.792 raeburn 8142: my $response;
1.841 albertel 8143: foreach my $server (@homeservers) {
1.792 raeburn 8144: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 8145: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
8146:
8147: foreach my $pair (split(/\&/,$response)) {
8148: my ($name,$value)=split(/\=/,$pair);
8149: if ($name eq 'code_order') {
8150: @{$code_order} = split(/\&/,&unescape($value));
8151: } else {
8152: $returnhash->{&unescape($name)}=&unescape($value);
8153: }
8154: }
8155: return 'ok';
1.792 raeburn 8156: }
1.841 albertel 8157:
8158: return $response;
1.1003 raeburn 8159: }
8160:
8161: sub auto_possible_instcodes {
1.1007 raeburn 8162: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
8163: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
8164: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
8165: return;
8166: }
1.1003 raeburn 8167: my (@homeservers,$uhome);
8168: if (defined(&domain($domain,'primary'))) {
8169: $uhome=&domain($domain,'primary');
8170: push(@homeservers,&domain($domain,'primary'));
8171: } else {
8172: my %servers = &get_servers($domain,'library');
8173: foreach my $tryserver (keys(%servers)) {
8174: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
8175: push(@homeservers,$tryserver);
8176: }
8177: }
8178: }
8179: my $response;
8180: foreach my $server (@homeservers) {
8181: $response=&reply('autopossibleinstcodes:'.$domain,$server);
8182: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 8183: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
8184: split(':',$response);
8185: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
8186: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 8187: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 8188: my ($name,$value)=split('=',$item);
8189: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 8190: }
8191: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 8192: my ($name,$value)=split('=',$item);
8193: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 8194: }
8195: return 'ok';
8196: }
8197: return $response;
8198: }
1.792 raeburn 8199:
1.1010 raeburn 8200: sub auto_courserequest_checks {
8201: my ($dom) = @_;
1.1020 raeburn 8202: my ($homeserver,%validations);
8203: if ($dom =~ /^$match_domain$/) {
8204: $homeserver = &domain($dom,'primary');
8205: }
8206: unless ($homeserver eq 'no_host') {
8207: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
8208: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
8209: my @items = split(/&/,$response);
8210: foreach my $item (@items) {
8211: my ($key,$value) = split('=',$item);
8212: $validations{&unescape($key)} = &thaw_unescape($value);
8213: }
8214: }
8215: }
1.1010 raeburn 8216: return %validations;
8217: }
8218:
1.1020 raeburn 8219: sub auto_courserequest_validation {
1.1255 raeburn 8220: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020 raeburn 8221: my ($homeserver,$response);
8222: if ($dom =~ /^$match_domain$/) {
8223: $homeserver = &domain($dom,'primary');
8224: }
1.1255 raeburn 8225: unless ($homeserver eq 'no_host') {
8226: my $customdata;
8227: if (ref($custominfo) eq 'HASH') {
8228: $customdata = &freeze_escape($custominfo);
8229: }
1.1020 raeburn 8230: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 8231: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1255 raeburn 8232: ':'.&escape($instcode).':'.&escape($instseclist).':'.
8233: $customdata,$homeserver));
1.1020 raeburn 8234: }
8235: return $response;
8236: }
8237:
1.777 albertel 8238: sub auto_validate_class_sec {
1.918 raeburn 8239: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 8240: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 8241: my $ownerlist;
8242: if (ref($owners) eq 'ARRAY') {
8243: $ownerlist = join(',',@{$owners});
8244: } else {
8245: $ownerlist = $owners;
8246: }
1.773 raeburn 8247: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 8248: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 8249: return $response;
8250: }
8251:
1.1248 raeburn 8252: sub auto_crsreq_update {
8253: my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1257 raeburn 8254: $code,$accessstart,$accessend,$inbound) = @_;
1.1248 raeburn 8255: my ($homeserver,%crsreqresponse);
8256: if ($cdom =~ /^$match_domain$/) {
8257: $homeserver = &domain($cdom,'primary');
8258: }
8259: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
8260: my $info;
8261: if (ref($inbound) eq 'HASH') {
8262: $info = &freeze_escape($inbound);
8263: }
8264: my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
8265: ':'.&escape($action).':'.&escape($ownername).':'.
8266: &escape($ownerdomain).':'.&escape($fullname).':'.
1.1257 raeburn 8267: &escape($title).':'.&escape($code).':'.
8268: &escape($accessstart).':'.&escape($accessend).':'.$info,
8269: $homeserver);
1.1248 raeburn 8270: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
8271: my @items = split(/&/,$response);
8272: foreach my $item (@items) {
8273: my ($key,$value) = split('=',$item);
8274: $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
8275: }
8276: }
8277: }
8278: return \%crsreqresponse;
8279: }
8280:
1.1305 ! raeburn 8281: sub auto_export_grades {
! 8282: my ($cnum,$cdom,$gradesref) = @_;
! 8283: return;
! 8284: }
! 8285:
1.1287 raeburn 8286: sub check_instcode_cloning {
8287: my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
8288: unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
8289: return;
8290: }
8291: my $canclone;
8292: if (@{$code_order} > 0) {
8293: my $instcoderegexp ='^';
8294: my @clonecodes = split(/\&/,$cloner);
8295: foreach my $item (@{$code_order}) {
8296: if (grep(/^\Q$item\E=/,@clonecodes)) {
8297: foreach my $pair (@clonecodes) {
8298: my ($key,$val) = split(/\=/,$pair,2);
8299: $val = &unescape($val);
8300: if ($key eq $item) {
8301: $instcoderegexp .= '('.$val.')';
8302: last;
8303: }
8304: }
8305: } else {
8306: $instcoderegexp .= $codedefaults->{$item};
8307: }
8308: }
8309: $instcoderegexp .= '$';
8310: my (@from,@to);
8311: eval {
8312: (@from) = ($clonefromcode =~ /$instcoderegexp/);
8313: (@to) = ($clonetocode =~ /$instcoderegexp/);
8314: };
8315: if ((@from > 0) && (@to > 0)) {
8316: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
8317: if (!@diffs) {
8318: $canclone = 1;
8319: }
8320: }
8321: }
8322: return $canclone;
8323: }
8324:
8325: sub default_instcode_cloning {
8326: my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
8327: my (%codedefaults,@code_order,$canclone);
8328: if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
8329: %codedefaults = %{$codedefaultsref};
8330: @code_order = @{$codeorderref};
8331: } elsif ($clonedom) {
8332: &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
8333: }
8334: if (($domdefclone) && (@code_order)) {
8335: my @clonecodes = split(/\+/,$domdefclone);
8336: my $instcoderegexp ='^';
8337: foreach my $item (@code_order) {
8338: if (grep(/^\Q$item\E$/,@clonecodes)) {
8339: $instcoderegexp .= '('.$codedefaults{$item}.')';
8340: } else {
8341: $instcoderegexp .= $codedefaults{$item};
8342: }
8343: }
8344: $instcoderegexp .= '$';
8345: my (@from,@to);
8346: eval {
8347: (@from) = ($clonefromcode =~ /$instcoderegexp/);
8348: (@to) = ($clonetocode =~ /$instcoderegexp/);
8349: };
8350: if ((@from > 0) && (@to > 0)) {
8351: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
8352: if (!@diffs) {
8353: $canclone = 1;
8354: }
8355: }
8356: }
8357: return $canclone;
8358: }
8359:
1.679 raeburn 8360: # ------------------------------------------------------- Course Group routines
8361:
8362: sub get_coursegroups {
1.809 raeburn 8363: my ($cdom,$cnum,$group,$namespace) = @_;
8364: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 8365: }
8366:
1.679 raeburn 8367: sub modify_coursegroup {
8368: my ($cdom,$cnum,$groupsettings) = @_;
8369: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
8370: }
8371:
1.809 raeburn 8372: sub toggle_coursegroup_status {
8373: my ($cdom,$cnum,$group,$action) = @_;
8374: my ($from_namespace,$to_namespace);
8375: if ($action eq 'delete') {
8376: $from_namespace = 'coursegroups';
8377: $to_namespace = 'deleted_groups';
8378: } else {
8379: $from_namespace = 'deleted_groups';
8380: $to_namespace = 'coursegroups';
8381: }
8382: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 8383: if (my $tmp = &error(%curr_group)) {
8384: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
8385: return ('read error',$tmp);
8386: } else {
8387: my %savedsettings = %curr_group;
1.809 raeburn 8388: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 8389: my $deloutcome;
8390: if ($result eq 'ok') {
1.809 raeburn 8391: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 8392: } else {
8393: return ('write error',$result);
8394: }
8395: if ($deloutcome eq 'ok') {
8396: return 'ok';
8397: } else {
8398: return ('delete error',$deloutcome);
8399: }
8400: }
8401: }
8402:
1.679 raeburn 8403: sub modify_group_roles {
1.957 raeburn 8404: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 8405: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
8406: my $role = 'gr/'.&escape($userprivs);
8407: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 8408: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 8409: if ($result eq 'ok') {
8410: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
8411: }
1.679 raeburn 8412: return $result;
8413: }
8414:
8415: sub modify_coursegroup_membership {
8416: my ($cdom,$cnum,$membership) = @_;
8417: my $result = &put('groupmembership',$membership,$cdom,$cnum);
8418: return $result;
8419: }
8420:
1.682 raeburn 8421: sub get_active_groups {
8422: my ($udom,$uname,$cdom,$cnum) = @_;
8423: my $now = time;
8424: my %groups = ();
8425: foreach my $key (keys(%env)) {
1.811 albertel 8426: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 8427: my ($start,$end) = split(/\./,$env{$key});
8428: if (($end!=0) && ($end<$now)) { next; }
8429: if (($start!=0) && ($start>$now)) { next; }
8430: if ($1 eq $cdom && $2 eq $cnum) {
8431: $groups{$3} = $env{$key} ;
8432: }
8433: }
8434: }
8435: return %groups;
8436: }
8437:
1.683 raeburn 8438: sub get_group_membership {
8439: my ($cdom,$cnum,$group) = @_;
8440: return(&dump('groupmembership',$cdom,$cnum,$group));
8441: }
8442:
8443: sub get_users_groups {
8444: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 8445: my @usersgroups;
1.683 raeburn 8446: my $cachetime=1800;
8447:
8448: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 8449: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
8450: if (defined($cached)) {
1.734 albertel 8451: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 8452: } else {
8453: $grouplist = '';
1.816 raeburn 8454: my $courseurl = &courseid_to_courseurl($courseid);
1.1166 raeburn 8455: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 8456: my $access_end = $env{'course.'.$courseid.
8457: '.default_enrollment_end_date'};
8458: my $now = time;
8459: foreach my $key (keys(%roleshash)) {
8460: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
8461: my $group = $1;
8462: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
8463: my $start = $2;
8464: my $end = $1;
8465: if ($start == -1) { next; } # deleted from group
8466: if (($start!=0) && ($start>$now)) { next; }
8467: if (($end!=0) && ($end<$now)) {
8468: if ($access_end && $access_end < $now) {
8469: if ($access_end - $end < 86400) {
8470: push(@usersgroups,$group);
1.733 raeburn 8471: }
8472: }
1.817 raeburn 8473: next;
1.733 raeburn 8474: }
1.817 raeburn 8475: push(@usersgroups,$group);
1.683 raeburn 8476: }
8477: }
8478: }
1.817 raeburn 8479: @usersgroups = &sort_course_groups($courseid,@usersgroups);
8480: $grouplist = join(':',@usersgroups);
8481: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 8482: }
1.733 raeburn 8483: return @usersgroups;
1.683 raeburn 8484: }
8485:
8486: sub devalidate_getgroups_cache {
8487: my ($udom,$uname,$cdom,$cnum)=@_;
8488: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 8489:
1.683 raeburn 8490: my $hashid="$udom:$uname:$courseid";
8491: &devalidate_cache_new('getgroups',$hashid);
8492: }
8493:
1.12 www 8494: # ------------------------------------------------------------------ Plain Text
8495:
8496: sub plaintext {
1.988 raeburn 8497: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 8498: if ($short =~ m{^cr/}) {
1.758 albertel 8499: return (split('/',$short))[-1];
8500: }
1.742 raeburn 8501: if (!defined($cid)) {
8502: $cid = $env{'request.course.id'};
8503: }
8504: my %rolenames = (
1.1008 raeburn 8505: Course => 'std',
8506: Community => 'alt1',
1.1305 ! raeburn 8507: Placement => 'std',
1.742 raeburn 8508: );
1.1037 raeburn 8509: if ($cid ne '') {
8510: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
8511: unless ($forcedefault) {
8512: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
8513: &Apache::lonlocal::mt_escape(\$roletext);
8514: return &Apache::lonlocal::mt($roletext);
8515: }
8516: }
8517: }
8518: if ((defined($type)) && (defined($rolenames{$type})) &&
8519: (defined($rolenames{$type})) &&
8520: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 8521: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 8522: } elsif ($cid ne '') {
8523: my $crstype = $env{'course.'.$cid.'.type'};
8524: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
8525: (defined($prp{$short}{$rolenames{$crstype}}))) {
8526: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
8527: }
1.742 raeburn 8528: }
1.1037 raeburn 8529: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 8530: }
8531:
8532: # ----------------------------------------------------------------- Assign Role
8533:
8534: sub assignrole {
1.957 raeburn 8535: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
8536: $context)=@_;
1.21 www 8537: my $mrole;
8538: if ($role =~ /^cr\//) {
1.393 www 8539: my $cwosec=$url;
1.811 albertel 8540: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 8541: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 8542: my $refused = 1;
8543: if ($context eq 'requestcourses') {
8544: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
8545: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
8546: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
8547: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8548: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8549: if ($crsenv{'internal.courseowner'} eq
8550: $env{'user.name'}.':'.$env{'user.domain'}) {
8551: $refused = '';
8552: }
8553: }
8554: }
8555: }
8556: }
8557: if ($refused) {
8558: &logthis('Refused custom assignrole: '.
8559: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
8560: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
8561: return 'refused';
8562: }
1.104 www 8563: }
1.21 www 8564: $mrole='cr';
1.678 raeburn 8565: } elsif ($role =~ /^gr\//) {
8566: my $cwogrp=$url;
1.811 albertel 8567: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 8568: unless (&allowed('mdg',$cwogrp)) {
8569: &logthis('Refused group assignrole: '.
8570: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
8571: $env{'user.name'}.' at '.$env{'user.domain'});
8572: return 'refused';
8573: }
8574: $mrole='gr';
1.21 www 8575: } else {
1.82 www 8576: my $cwosec=$url;
1.811 albertel 8577: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 8578: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
8579: my $refused;
8580: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
8581: if (!(&allowed('c'.$role,$url))) {
8582: $refused = 1;
8583: }
8584: } else {
8585: $refused = 1;
8586: }
1.947 raeburn 8587: if ($refused) {
1.1045 raeburn 8588: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8589: if (!$selfenroll && $context eq 'course') {
8590: my %crsenv;
8591: if ($role eq 'cc' || $role eq 'co') {
8592: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8593: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
8594: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
8595: if ($crsenv{'internal.courseowner'} eq
8596: $env{'user.name'}.':'.$env{'user.domain'}) {
8597: $refused = '';
8598: }
8599: }
8600: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
8601: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
8602: if ($crsenv{'internal.courseowner'} eq
8603: $env{'user.name'}.':'.$env{'user.domain'}) {
8604: $refused = '';
8605: }
8606: }
8607: }
8608: }
8609: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 8610: $refused = '';
1.1017 raeburn 8611: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 8612: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 8613: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 8614: my $wrongcc;
8615: if ($cnum =~ /^$match_community$/) {
8616: $wrongcc = 1 if ($role eq 'cc');
8617: } else {
8618: $wrongcc = 1 if ($role eq 'co');
8619: }
8620: unless ($wrongcc) {
8621: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8622: if ($crsenv{'internal.courseowner'} eq
8623: $env{'user.name'}.':'.$env{'user.domain'}) {
8624: $refused = '';
8625: }
1.1017 raeburn 8626: }
8627: }
1.1183 raeburn 8628: } elsif ($context eq 'requestauthor') {
8629: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
8630: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
8631: if ($env{'environment.requestauthor'} eq 'automatic') {
8632: $refused = '';
8633: } else {
8634: my %domdefaults = &get_domain_defaults($udom);
8635: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
8636: my $checkbystatus;
8637: if ($env{'user.adv'}) {
8638: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
8639: if ($disposition eq 'automatic') {
8640: $refused = '';
8641: } elsif ($disposition eq '') {
8642: $checkbystatus = 1;
8643: }
8644: } else {
8645: $checkbystatus = 1;
8646: }
8647: if ($checkbystatus) {
8648: if ($env{'environment.inststatus'}) {
8649: my @inststatuses = split(/,/,$env{'environment.inststatus'});
8650: foreach my $type (@inststatuses) {
8651: if (($type ne '') &&
8652: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
8653: $refused = '';
8654: }
8655: }
8656: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
8657: $refused = '';
8658: }
8659: }
8660: }
8661: }
8662: }
1.1017 raeburn 8663: }
8664: if ($refused) {
1.947 raeburn 8665: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
8666: ' '.$role.' '.$end.' '.$start.' by '.
8667: $env{'user.name'}.' at '.$env{'user.domain'});
8668: return 'refused';
8669: }
1.932 raeburn 8670: }
1.1131 raeburn 8671: } elsif ($role eq 'au') {
8672: if ($url ne '/'.$udom.'/') {
8673: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
8674: ' to assign author role for '.$uname.':'.$udom.
8675: ' in domain: '.$url.' refused (wrong domain).');
8676: return 'refused';
8677: }
1.104 www 8678: }
1.21 www 8679: $mrole=$role;
8680: }
1.620 albertel 8681: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 8682: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 8683: if ($end) { $command.='_'.$end; }
1.21 www 8684: if ($start) {
8685: if ($end) {
1.81 www 8686: $command.='_'.$start;
1.21 www 8687: } else {
1.81 www 8688: $command.='_0_'.$start;
1.21 www 8689: }
8690: }
1.739 raeburn 8691: my $origstart = $start;
8692: my $origend = $end;
1.957 raeburn 8693: my $delflag;
1.357 www 8694: # actually delete
8695: if ($deleteflag) {
1.373 www 8696: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 8697: # modify command to delete the role
1.620 albertel 8698: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 8699: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 8700: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 8701: # set start and finish to negative values for userrolelog
8702: $start=-1;
8703: $end=-1;
1.957 raeburn 8704: $delflag = 1;
1.357 www 8705: }
8706: }
8707: # send command
1.349 www 8708: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 8709: # log new user role if status is ok
1.349 www 8710: if ($answer eq 'ok') {
1.663 raeburn 8711: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.1184 raeburn 8712: if (($role eq 'cc') || ($role eq 'in') ||
8713: ($role eq 'ep') || ($role eq 'ad') ||
8714: ($role eq 'ta') || ($role eq 'st') ||
8715: ($role=~/^cr/) || ($role eq 'gr') ||
8716: ($role eq 'co')) {
1.1200 raeburn 8717: # for course roles, perform group memberships changes triggered by role change.
8718: unless ($role =~ /^gr/) {
8719: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
8720: $origstart,$selfenroll,$context);
8721: }
1.1184 raeburn 8722: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8723: $selfenroll,$context);
8724: } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
8725: ($role eq 'au') || ($role eq 'dc')) {
8726: &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8727: $context);
8728: } elsif (($role eq 'ca') || ($role eq 'aa')) {
8729: &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8730: $context);
8731: }
1.1053 raeburn 8732: if ($role eq 'cc') {
8733: &autoupdate_coowners($url,$end,$start,$uname,$udom);
8734: }
1.349 www 8735: }
8736: return $answer;
1.169 harris41 8737: }
8738:
1.1053 raeburn 8739: sub autoupdate_coowners {
8740: my ($url,$end,$start,$uname,$udom) = @_;
8741: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
8742: if (($cdom ne '') && ($cnum ne '')) {
8743: my $now = time;
8744: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
8745: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
8746: my %coursehash = &coursedescription($cdom.'_'.$cnum);
8747: my $instcode = $coursehash{'internal.coursecode'};
8748: if ($instcode ne '') {
1.1056 raeburn 8749: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
8750: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 8751: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 8752: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
8753: if ($result eq 'valid') {
8754: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 8755: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
8756: push(@newcoowners,$coowner);
8757: }
8758: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
8759: push(@newcoowners,$uname.':'.$udom);
8760: }
8761: @newcoowners = sort(@newcoowners);
8762: } else {
8763: push(@newcoowners,$uname.':'.$udom);
8764: }
8765: } else {
8766: if ($coursehash{'internal.co-owners'}) {
8767: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
8768: unless ($coowner eq $uname.':'.$udom) {
8769: push(@newcoowners,$coowner);
8770: }
8771: }
8772: unless (@newcoowners > 0) {
8773: $delcoowners = 1;
8774: $coowners = '';
8775: }
8776: }
8777: }
8778: if (@newcoowners || $delcoowners) {
8779: &store_coowners($cdom,$cnum,$coursehash{'home'},
8780: $delcoowners,@newcoowners);
8781: }
8782: }
8783: }
8784: }
8785: }
8786: }
8787: }
8788:
8789: sub store_coowners {
8790: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
8791: my $cid = $cdom.'_'.$cnum;
8792: my ($coowners,$delresult,$putresult);
8793: if (@newcoowners) {
8794: $coowners = join(',',@newcoowners);
8795: my %coownershash = (
8796: 'internal.co-owners' => $coowners,
8797: );
8798: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
8799: if ($putresult eq 'ok') {
8800: if ($env{'course.'.$cid.'.num'} eq $cnum) {
8801: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
8802: }
8803: }
8804: }
8805: if ($delcoowners) {
8806: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
8807: if ($delresult eq 'ok') {
8808: if ($env{'course.'.$cid.'.internal.co-owners'}) {
8809: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
8810: }
8811: }
8812: }
8813: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
8814: my %crsinfo =
8815: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
8816: if (ref($crsinfo{$cid}) eq 'HASH') {
8817: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
8818: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
8819: }
8820: }
8821: }
8822:
1.169 harris41 8823: # -------------------------------------------------- Modify user authentication
1.197 www 8824: # Overrides without validation
8825:
1.169 harris41 8826: sub modifyuserauth {
8827: my ($udom,$uname,$umode,$upass)=@_;
8828: my $uhome=&homeserver($uname,$udom);
1.197 www 8829: unless (&allowed('mau',$udom)) { return 'refused'; }
8830: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 8831: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
8832: ' in domain '.$env{'request.role.domain'});
1.169 harris41 8833: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
8834: &escape($upass),$uhome);
1.620 albertel 8835: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 8836: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
8837: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
8838: &log($udom,,$uname,$uhome,
1.620 albertel 8839: 'Authentication changed by '.$env{'user.domain'}.', '.
8840: $env{'user.name'}.', '.$umode.
1.197 www 8841: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 8842: unless ($reply eq 'ok') {
1.197 www 8843: &logthis('Authentication mode error: '.$reply);
1.169 harris41 8844: return 'error: '.$reply;
8845: }
1.170 harris41 8846: return 'ok';
1.80 www 8847: }
8848:
1.81 www 8849: # --------------------------------------------------------------- Modify a user
1.80 www 8850:
1.81 www 8851: sub modifyuser {
1.206 matthew 8852: my ($udom, $uname, $uid,
8853: $umode, $upass, $first,
8854: $middle, $last, $gene,
1.1058 raeburn 8855: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 8856: $udom= &LONCAPA::clean_domain($udom);
8857: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 8858: my $showcandelete = 'none';
8859: if (ref($candelete) eq 'ARRAY') {
8860: if (@{$candelete} > 0) {
8861: $showcandelete = join(', ',@{$candelete});
8862: }
8863: }
1.81 www 8864: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 8865: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 8866: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 8867: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
8868: ' desiredhome not specified').
1.620 albertel 8869: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
8870: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 8871: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 8872: my $newuser;
8873: if ($uhome eq 'no_host') {
8874: $newuser = 1;
8875: }
1.80 www 8876: # ----------------------------------------------------------------- Create User
1.406 albertel 8877: if (($uhome eq 'no_host') &&
8878: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 8879: my $unhome='';
1.844 albertel 8880: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 8881: $unhome = $desiredhome;
1.620 albertel 8882: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
8883: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 8884: } else { # load balancing routine for determining $unhome
1.81 www 8885: my $loadm=10000000;
1.841 albertel 8886: my %servers = &get_servers($udom,'library');
8887: foreach my $tryserver (keys(%servers)) {
8888: my $answer=reply('load',$tryserver);
8889: if (($answer=~/\d+/) && ($answer<$loadm)) {
8890: $loadm=$answer;
8891: $unhome=$tryserver;
8892: }
1.80 www 8893: }
8894: }
8895: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 8896: return 'error: unable to find a home server for '.$uname.
8897: ' in domain '.$udom;
1.80 www 8898: }
8899: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
8900: &escape($upass),$unhome);
8901: unless ($reply eq 'ok') {
8902: return 'error: '.$reply;
8903: }
1.230 stredwic 8904: $uhome=&homeserver($uname,$udom,'true');
1.80 www 8905: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 8906: return 'error: unable verify users home machine.';
1.80 www 8907: }
1.209 matthew 8908: } # End of creation of new user
1.80 www 8909: # ---------------------------------------------------------------------- Add ID
8910: if ($uid) {
8911: $uid=~tr/A-Z/a-z/;
8912: my %uidhash=&idrget($udom,$uname);
1.196 www 8913: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
8914: && (!$forceid)) {
1.80 www 8915: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 8916: return 'error: user id "'.$uid.'" does not match '.
8917: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 8918: }
8919: } else {
1.1300 raeburn 8920: &idput($udom,{$uname => $uid},$uhome,'ids');
1.80 www 8921: }
8922: }
8923: # -------------------------------------------------------------- Add names, etc
1.313 matthew 8924: my @tmp=&get('environment',
1.899 raeburn 8925: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 8926: 'permanentemail','inststatus'],
1.134 albertel 8927: $udom,$uname);
1.1075 raeburn 8928: my (%names,%oldnames);
1.313 matthew 8929: if ($tmp[0] =~ m/^error:.*/) {
8930: %names=();
8931: } else {
8932: %names = @tmp;
1.1075 raeburn 8933: %oldnames = %names;
1.313 matthew 8934: }
1.388 www 8935: #
1.1058 raeburn 8936: # If name, email and/or uid are blank (e.g., because an uploaded file
8937: # of users did not contain them), do not overwrite existing values
8938: # unless field is in $candelete array ref.
8939: #
8940:
8941: my @fields = ('firstname','middlename','lastname','generation',
8942: 'permanentemail','id');
8943: my %newvalues;
8944: if (ref($candelete) eq 'ARRAY') {
8945: foreach my $field (@fields) {
8946: if (grep(/^\Q$field\E$/,@{$candelete})) {
8947: if ($field eq 'firstname') {
8948: $names{$field} = $first;
8949: } elsif ($field eq 'middlename') {
8950: $names{$field} = $middle;
8951: } elsif ($field eq 'lastname') {
8952: $names{$field} = $last;
8953: } elsif ($field eq 'generation') {
8954: $names{$field} = $gene;
8955: } elsif ($field eq 'permanentemail') {
8956: $names{$field} = $email;
8957: } elsif ($field eq 'id') {
8958: $names{$field} = $uid;
8959: }
8960: }
8961: }
8962: }
1.388 www 8963: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 8964: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 8965: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 8966: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 8967: if ($email) {
8968: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 8969: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 8970: }
1.899 raeburn 8971: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 8972: if (defined($inststatus)) {
8973: $names{'inststatus'} = '';
8974: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
8975: if (ref($usertypes) eq 'HASH') {
8976: my @okstatuses;
8977: foreach my $item (split(/:/,$inststatus)) {
8978: if (defined($usertypes->{$item})) {
8979: push(@okstatuses,$item);
8980: }
8981: }
8982: if (@okstatuses) {
8983: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
8984: }
8985: }
8986: }
1.1075 raeburn 8987: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 8988: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 8989: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 8990: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
8991: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
8992: } else {
8993: $logmsg .= ' during self creation';
8994: }
1.1075 raeburn 8995: my $changed;
8996: if ($newuser) {
8997: $changed = 1;
8998: } else {
8999: foreach my $field (@fields) {
9000: if ($names{$field} ne $oldnames{$field}) {
9001: $changed = 1;
9002: last;
9003: }
9004: }
9005: }
9006: unless ($changed) {
9007: $logmsg = 'No changes in user information needed for: '.$logmsg;
9008: &logthis($logmsg);
9009: return 'ok';
9010: }
9011: my $reply = &put('environment', \%names, $udom,$uname);
9012: if ($reply ne 'ok') {
9013: return 'error: '.$reply;
9014: }
1.1087 raeburn 9015: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
9016: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
9017: }
1.1075 raeburn 9018: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
9019: &devalidate_cache_new('namescache',$uname.':'.$udom);
9020: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 9021: &logthis($logmsg);
1.134 albertel 9022: return 'ok';
1.80 www 9023: }
9024:
1.81 www 9025: # -------------------------------------------------------------- Modify student
1.80 www 9026:
1.81 www 9027: sub modifystudent {
9028: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 9029: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1216 raeburn 9030: $selfenroll,$context,$inststatus,$credits)=@_;
1.455 albertel 9031: if (!$cid) {
1.620 albertel 9032: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 9033: return 'not_in_class';
9034: }
1.80 www 9035: }
9036: # --------------------------------------------------------------- Make the user
1.81 www 9037: my $reply=&modifyuser
1.209 matthew 9038: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 9039: $desiredhome,$email,$inststatus);
1.80 www 9040: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 9041: # This will cause &modify_student_enrollment to get the uid from the
1.1235 raeburn 9042: # student's environment
1.297 matthew 9043: $uid = undef if (!$forceid);
1.455 albertel 9044: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1216 raeburn 9045: $gene,$usec,$end,$start,$type,$locktype,
9046: $cid,$selfenroll,$context,$credits);
1.297 matthew 9047: return $reply;
9048: }
9049:
9050: sub modify_student_enrollment {
1.1216 raeburn 9051: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
9052: $locktype,$cid,$selfenroll,$context,$credits) = @_;
1.455 albertel 9053: my ($cdom,$cnum,$chome);
9054: if (!$cid) {
1.620 albertel 9055: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 9056: return 'not_in_class';
9057: }
1.620 albertel 9058: $cdom=$env{'course.'.$cid.'.domain'};
9059: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 9060: } else {
9061: ($cdom,$cnum)=split(/_/,$cid);
9062: }
1.620 albertel 9063: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 9064: if (!$chome) {
1.457 raeburn 9065: $chome=&homeserver($cnum,$cdom);
1.297 matthew 9066: }
1.455 albertel 9067: if (!$chome) { return 'unknown_course'; }
1.297 matthew 9068: # Make sure the user exists
1.81 www 9069: my $uhome=&homeserver($uname,$udom);
9070: if (($uhome eq '') || ($uhome eq 'no_host')) {
9071: return 'error: no such user';
9072: }
1.297 matthew 9073: # Get student data if we were not given enough information
9074: if (!defined($first) || $first eq '' ||
9075: !defined($last) || $last eq '' ||
9076: !defined($uid) || $uid eq '' ||
9077: !defined($middle) || $middle eq '' ||
9078: !defined($gene) || $gene eq '') {
1.294 matthew 9079: # They did not supply us with enough data to enroll the student, so
9080: # we need to pick up more information.
1.297 matthew 9081: my %tmp = &get('environment',
1.294 matthew 9082: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 9083: ,$udom,$uname);
9084:
1.800 albertel 9085: #foreach my $key (keys(%tmp)) {
9086: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 9087: #}
1.294 matthew 9088: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
9089: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
9090: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 9091: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 9092: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
9093: }
1.556 albertel 9094: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148 raeburn 9095: my $user = "$uname:$udom";
9096: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487 albertel 9097: my $reply=cput('classlist',
1.1148 raeburn 9098: {$user =>
1.1216 raeburn 9099: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits) },
1.487 albertel 9100: $cdom,$cnum);
1.1148 raeburn 9101: if (($reply eq 'ok') || ($reply eq 'delayed')) {
9102: &devalidate_getsection_cache($udom,$uname,$cid);
9103: } else {
1.81 www 9104: return 'error: '.$reply;
9105: }
1.297 matthew 9106: # Add student role to user
1.83 www 9107: my $uurl='/'.$cid;
1.81 www 9108: $uurl=~s/\_/\//g;
9109: if ($usec) {
9110: $uurl.='/'.$usec;
9111: }
1.1148 raeburn 9112: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
9113: $selfenroll,$context);
9114: if ($result ne 'ok') {
9115: if ($old_entry{$user} ne '') {
9116: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
9117: } else {
9118: $reply = &del('classlist',[$user],$cdom,$cnum);
9119: }
9120: }
9121: return $result;
1.21 www 9122: }
9123:
1.556 albertel 9124: sub format_name {
9125: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
9126: my $name;
9127: if ($first ne 'lastname') {
9128: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
9129: } else {
9130: if ($lastname=~/\S/) {
9131: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
9132: $name=~s/\s+,/,/;
9133: } else {
9134: $name.= $firstname.' '.$middlename.' '.$generation;
9135: }
9136: }
9137: $name=~s/^\s+//;
9138: $name=~s/\s+$//;
9139: $name=~s/\s+/ /g;
9140: return $name;
9141: }
9142:
1.84 www 9143: # ------------------------------------------------- Write to course preferences
9144:
9145: sub writecoursepref {
9146: my ($courseid,%prefs)=@_;
9147: $courseid=~s/^\///;
9148: $courseid=~s/\_/\//g;
9149: my ($cdomain,$cnum)=split(/\//,$courseid);
9150: my $chome=homeserver($cnum,$cdomain);
9151: if (($chome eq '') || ($chome eq 'no_host')) {
9152: return 'error: no such course';
9153: }
9154: my $cstring='';
1.800 albertel 9155: foreach my $pref (keys(%prefs)) {
9156: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 9157: }
1.84 www 9158: $cstring=~s/\&$//;
9159: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
9160: }
9161:
9162: # ---------------------------------------------------------- Make/modify course
9163:
9164: sub createcourse {
1.741 raeburn 9165: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 9166: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 9167: $url=&declutter($url);
9168: my $cid='';
1.1028 raeburn 9169: if ($context eq 'requestcourses') {
9170: my $can_create = 0;
9171: my ($ownername,$ownerdom) = split(':',$course_owner);
9172: if ($udom eq $ownerdom) {
9173: if (&usertools_access($ownername,$ownerdom,$category,undef,
9174: $context)) {
9175: $can_create = 1;
9176: }
9177: } else {
9178: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
9179: $category);
9180: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
9181: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
9182: if (@curr > 0) {
9183: my @options = qw(approval validate autolimit);
9184: my $optregex = join('|',@options);
9185: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
9186: $can_create = 1;
9187: }
9188: }
9189: }
9190: }
9191: if ($can_create) {
9192: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
9193: unless (&allowed('ccc',$udom)) {
9194: return 'refused';
9195: }
1.1017 raeburn 9196: }
9197: } else {
9198: return 'refused';
9199: }
1.1028 raeburn 9200: } elsif (!&allowed('ccc',$udom)) {
9201: return 'refused';
1.84 www 9202: }
1.1011 raeburn 9203: # --------------------------------------------------------------- Get Unique ID
9204: my $uname;
9205: if ($cnum =~ /^$match_courseid$/) {
9206: my $chome=&homeserver($cnum,$udom,'true');
9207: if (($chome eq '') || ($chome eq 'no_host')) {
9208: $uname = $cnum;
9209: } else {
1.1038 raeburn 9210: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 9211: }
9212: } else {
1.1038 raeburn 9213: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 9214: }
9215: return $uname if ($uname =~ /^error/);
9216: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 9217: if (!defined($course_server)) {
9218: if (defined(&domain($udom,'primary'))) {
9219: $course_server = &domain($udom,'primary');
9220: } else {
9221: $course_server = $env{'user.home'};
9222: }
9223: }
9224: my %host_servers =
9225: &Apache::lonnet::get_servers($udom,'library');
9226: unless ($host_servers{$course_server}) {
9227: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 9228: }
1.84 www 9229: # ------------------------------------------------------------- Make the course
9230: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 9231: $course_server);
1.84 www 9232: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 9233: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 9234: if (($uhome eq '') || ($uhome eq 'no_host')) {
9235: return 'error: no such course';
9236: }
1.271 www 9237: # ----------------------------------------------------------------- Course made
1.516 raeburn 9238: # log existence
1.1029 raeburn 9239: my $now = time;
1.918 raeburn 9240: my $newcourse = {
9241: $udom.'_'.$uname => {
1.921 raeburn 9242: description => $description,
9243: inst_code => $inst_code,
9244: owner => $course_owner,
9245: type => $crstype,
1.1029 raeburn 9246: creator => $env{'user.name'}.':'.
9247: $env{'user.domain'},
9248: created => $now,
9249: context => $context,
1.918 raeburn 9250: },
9251: };
1.921 raeburn 9252: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 9253: # set toplevel url
1.271 www 9254: my $topurl=$url;
9255: unless ($nonstandard) {
9256: # ------------------------------------------ For standard courses, make top url
9257: my $mapurl=&clutter($url);
1.278 www 9258: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 9259: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 9260: <map>
9261: <resource id="1" type="start"></resource>
9262: <resource id="2" src="$mapurl"></resource>
9263: <resource id="3" type="finish"></resource>
9264: <link index="1" from="1" to="2"></link>
9265: <link index="2" from="2" to="3"></link>
9266: </map>
9267: ENDINITMAP
9268: $topurl=&declutter(
1.638 albertel 9269: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 9270: );
9271: }
9272: # ----------------------------------------------------------- Write preferences
1.84 www 9273: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 9274: ('description' => $description,
9275: 'url' => $topurl,
9276: 'internal.creator' => $env{'user.name'}.':'.
9277: $env{'user.domain'},
9278: 'internal.created' => $now,
9279: 'internal.creationcontext' => $context)
9280: );
1.84 www 9281: return '/'.$udom.'/'.$uname;
9282: }
9283:
1.1011 raeburn 9284: # ------------------------------------------------------------------- Create ID
9285: sub generate_coursenum {
1.1038 raeburn 9286: my ($udom,$crstype) = @_;
1.1011 raeburn 9287: my $domdesc = &domain($udom);
9288: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 9289: my $first;
9290: if ($crstype eq 'Community') {
9291: $first = '0';
9292: } else {
9293: $first = int(1+rand(9));
9294: }
9295: my $uname=$first.
1.1011 raeburn 9296: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
9297: substr($$.time,0,5).unpack("H8",pack("I32",time)).
9298: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
9299: # ----------------------------------------------- Make sure that does not exist
9300: my $uhome=&homeserver($uname,$udom,'true');
9301: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 9302: if ($crstype eq 'Community') {
9303: $first = '0';
9304: } else {
9305: $first = int(1+rand(9));
9306: }
9307: $uname=$first.
1.1011 raeburn 9308: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
9309: substr($$.time,0,5).unpack("H8",pack("I32",time)).
9310: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
9311: $uhome=&homeserver($uname,$udom,'true');
9312: unless (($uhome eq '') || ($uhome eq 'no_host')) {
9313: return 'error: unable to generate unique course-ID';
9314: }
9315: }
9316: return $uname;
9317: }
9318:
1.813 albertel 9319: sub is_course {
1.1167 droeschl 9320: my ($cdom, $cnum) = scalar(@_) == 1 ?
9321: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
9322:
9323: return unless $cdom and $cnum;
9324:
9325: my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
9326: '.');
9327:
1.1219 raeburn 9328: return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167 droeschl 9329: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813 albertel 9330: }
9331:
1.1015 raeburn 9332: sub store_userdata {
9333: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 9334: my $result;
1.1016 raeburn 9335: if ($datakey ne '') {
1.1013 raeburn 9336: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 9337: if ($udom eq '' || $uname eq '') {
9338: $udom = $env{'user.domain'};
9339: $uname = $env{'user.name'};
9340: }
9341: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 9342: if (($uhome eq '') || ($uhome eq 'no_host')) {
9343: $result = 'error: no_host';
9344: } else {
9345: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
9346: $storehash->{'host'} = $perlvar{'lonHostID'};
9347:
9348: my $namevalue='';
9349: foreach my $key (keys(%{$storehash})) {
9350: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
9351: }
9352: $namevalue=~s/\&$//;
1.1224 raeburn 9353: unless ($namespace eq 'courserequests') {
9354: $datakey = &escape($datakey);
9355: }
1.1105 raeburn 9356: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
9357: $namevalue,$uhome);
1.1013 raeburn 9358: }
9359: } else {
9360: $result = 'error: data to store was not a hash reference';
9361: }
9362: } else {
9363: $result= 'error: invalid requestkey';
9364: }
9365: return $result;
9366: }
9367:
1.21 www 9368: # ---------------------------------------------------------- Assign Custom Role
9369:
9370: sub assigncustomrole {
1.957 raeburn 9371: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9372: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 9373: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 9374: }
9375:
9376: # ----------------------------------------------------------------- Revoke Role
9377:
9378: sub revokerole {
1.957 raeburn 9379: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9380: my $now=time;
1.965 raeburn 9381: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 9382: }
9383:
9384: # ---------------------------------------------------------- Revoke Custom Role
9385:
9386: sub revokecustomrole {
1.957 raeburn 9387: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9388: my $now=time;
1.357 www 9389: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 9390: $deleteflag,$selfenroll,$context);
1.17 www 9391: }
9392:
1.533 banghart 9393: # ------------------------------------------------------------ Disk usage
1.535 albertel 9394: sub diskusage {
1.955 raeburn 9395: my ($udom,$uname,$directorypath,$getpropath)=@_;
9396: $directorypath =~ s/\/$//;
9397: my $listing=&reply('du2:'.&escape($directorypath).':'
9398: .&escape($getpropath).':'.&escape($uname).':'
9399: .&escape($udom),homeserver($uname,$udom));
9400: if ($listing eq 'unknown_cmd') {
9401: if ($getpropath) {
9402: $directorypath = &propath($udom,$uname).'/'.$directorypath;
9403: }
9404: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
9405: }
1.514 albertel 9406: return $listing;
1.512 banghart 9407: }
9408:
1.566 banghart 9409: sub is_locked {
1.1096 raeburn 9410: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 9411: my @check;
9412: my $is_locked;
1.1093 raeburn 9413: push (@check,$file_name);
1.613 albertel 9414: my %locked = &get('file_permissions',\@check,
1.620 albertel 9415: $env{'user.domain'},$env{'user.name'});
1.615 albertel 9416: my ($tmp)=keys(%locked);
9417: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 9418:
1.566 banghart 9419: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 9420: $is_locked = 'false';
9421: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 9422: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 9423: $is_locked = 'true';
1.1096 raeburn 9424: if (ref($which) eq 'ARRAY') {
9425: push(@{$which},$entry);
9426: } else {
9427: last;
9428: }
1.745 raeburn 9429: }
9430: }
1.566 banghart 9431: } else {
9432: $is_locked = 'false';
9433: }
1.1093 raeburn 9434: return $is_locked;
1.566 banghart 9435: }
9436:
1.759 albertel 9437: sub declutter_portfile {
9438: my ($file) = @_;
1.833 albertel 9439: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 9440: return $file;
9441: }
9442:
1.559 banghart 9443: # ------------------------------------------------------------- Mark as Read Only
9444:
9445: sub mark_as_readonly {
9446: my ($domain,$user,$files,$what) = @_;
1.613 albertel 9447: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 9448: my ($tmp)=keys(%current_permissions);
9449: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 9450: foreach my $file (@{$files}) {
1.759 albertel 9451: $file = &declutter_portfile($file);
1.561 banghart 9452: push(@{$current_permissions{$file}},$what);
1.559 banghart 9453: }
1.613 albertel 9454: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 9455: return;
9456: }
9457:
1.572 banghart 9458: # ------------------------------------------------------------Save Selected Files
9459:
9460: sub save_selected_files {
9461: my ($user, $path, @files) = @_;
9462: my $filename = $user."savedfiles";
1.573 banghart 9463: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 9464: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 9465: foreach my $file (@files) {
1.620 albertel 9466: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 9467: }
9468: foreach my $file (@other_files) {
1.574 banghart 9469: print (OUT $file."\n");
1.572 banghart 9470: }
1.574 banghart 9471: close (OUT);
1.572 banghart 9472: return 'ok';
9473: }
9474:
1.574 banghart 9475: sub clear_selected_files {
9476: my ($user) = @_;
9477: my $filename = $user."savedfiles";
1.1117 foxr 9478: open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574 banghart 9479: print (OUT undef);
9480: close (OUT);
9481: return ("ok");
9482: }
9483:
1.572 banghart 9484: sub files_in_path {
9485: my ($user, $path) = @_;
9486: my $filename = $user."savedfiles";
9487: my %return_files;
1.1117 foxr 9488: open (IN, '<'.LONCAPA::tempdir().$filename);
1.573 banghart 9489: while (my $line_in = <IN>) {
1.574 banghart 9490: chomp ($line_in);
9491: my @paths_and_file = split (m!/!, $line_in);
9492: my $file_part = pop (@paths_and_file);
9493: my $path_part = join ('/', @paths_and_file);
1.573 banghart 9494: $path_part.='/';
9495: my $path_and_file = $path_part.$file_part;
9496: if ($path_part eq $path) {
9497: $return_files{$file_part}= 'selected';
9498: }
9499: }
1.574 banghart 9500: close (IN);
9501: return (\%return_files);
1.572 banghart 9502: }
9503:
9504: # called in portfolio select mode, to show files selected NOT in current directory
9505: sub files_not_in_path {
9506: my ($user, $path) = @_;
9507: my $filename = $user."savedfiles";
9508: my @return_files;
9509: my $path_part;
1.1117 foxr 9510: open(IN, '<'.LONCAPA::.$filename);
1.800 albertel 9511: while (my $line = <IN>) {
1.572 banghart 9512: #ok, I know it's clunky, but I want it to work
1.800 albertel 9513: my @paths_and_file = split(m|/|, $line);
9514: my $file_part = pop(@paths_and_file);
9515: chomp($file_part);
9516: my $path_part = join('/', @paths_and_file);
1.572 banghart 9517: $path_part .= '/';
9518: my $path_and_file = $path_part.$file_part;
9519: if ($path_part ne $path) {
1.800 albertel 9520: push(@return_files, ($path_and_file));
1.572 banghart 9521: }
9522: }
1.800 albertel 9523: close(OUT);
1.574 banghart 9524: return (@return_files);
1.572 banghart 9525: }
9526:
1.1273 raeburn 9527: #------------------------------Submitted/Handedback Portfolio Files Versioning
9528:
9529: sub portfiles_versioning {
9530: my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
9531: my $portfolio_root = '/userfiles/portfolio';
9532: return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
9533: foreach my $file (@{$portfiles}) {
9534: &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
9535: my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
9536: my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
9537: my $getpropath = 1;
9538: my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
9539: $stu_name,$getpropath);
9540: my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
9541: my $new_answer =
9542: &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
9543: if ($new_answer ne 'problem getting file') {
9544: push(@{$versioned_portfiles}, $directory.$new_answer);
9545: &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
9546: [$symb,$env{'request.course.id'},'graded']);
9547: }
9548: }
9549: }
9550:
9551: sub get_next_version {
9552: my ($answer_name, $answer_ext, $dir_list) = @_;
9553: my $version;
9554: if (ref($dir_list) eq 'ARRAY') {
9555: foreach my $row (@{$dir_list}) {
9556: my ($file) = split(/\&/,$row,2);
9557: my ($file_name,$file_version,$file_ext) =
9558: &file_name_version_ext($file);
9559: if (($file_name eq $answer_name) &&
9560: ($file_ext eq $answer_ext)) {
9561: # gets here if filename and extension match,
9562: # regardless of version
9563: if ($file_version ne '') {
9564: # a versioned file is found so save it for later
9565: if ($file_version > $version) {
9566: $version = $file_version;
9567: }
9568: }
9569: }
9570: }
9571: }
9572: $version ++;
9573: return($version);
9574: }
9575:
9576: sub version_selected_portfile {
9577: my ($domain,$stu_name,$directory,$file_name,$version) = @_;
9578: my ($answer_name,$answer_ver,$answer_ext) =
9579: &file_name_version_ext($file_name);
9580: my $new_answer;
9581: $env{'form.copy'} =
9582: &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
9583: if($env{'form.copy'} eq '-1') {
9584: $new_answer = 'problem getting file';
9585: } else {
9586: $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
9587: my $copy_result =
9588: &finishuserfileupload($stu_name,$domain,'copy',
9589: '/portfolio'.$directory.$new_answer);
9590: }
9591: undef($env{'form.copy'});
9592: return ($new_answer);
9593: }
9594:
9595: sub file_name_version_ext {
9596: my ($file)=@_;
9597: my @file_parts = split(/\./, $file);
9598: my ($name,$version,$ext);
9599: if (@file_parts > 1) {
9600: $ext=pop(@file_parts);
9601: if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
9602: $version=pop(@file_parts);
9603: }
9604: $name=join('.',@file_parts);
9605: } else {
9606: $name=join('.',@file_parts);
9607: }
9608: return($name,$version,$ext);
9609: }
9610:
1.745 raeburn 9611: #----------------------------------------------Get portfolio file permissions
1.629 banghart 9612:
1.745 raeburn 9613: sub get_portfile_permissions {
9614: my ($domain,$user) = @_;
1.613 albertel 9615: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 9616: my ($tmp)=keys(%current_permissions);
9617: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 9618: return \%current_permissions;
9619: }
9620:
9621: #---------------------------------------------Get portfolio file access controls
9622:
1.749 raeburn 9623: sub get_access_controls {
1.745 raeburn 9624: my ($current_permissions,$group,$file) = @_;
1.769 albertel 9625: my %access;
9626: my $real_file = $file;
9627: $file =~ s/\.meta$//;
1.745 raeburn 9628: if (defined($file)) {
1.749 raeburn 9629: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
9630: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 9631: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 9632: }
9633: }
1.745 raeburn 9634: } else {
1.749 raeburn 9635: foreach my $key (keys(%{$current_permissions})) {
9636: if ($key =~ /\0accesscontrol$/) {
9637: if (defined($group)) {
9638: if ($key !~ m-^\Q$group\E/-) {
9639: next;
9640: }
9641: }
9642: my ($fullpath) = split(/\0/,$key);
9643: if (ref($$current_permissions{$key}) eq 'HASH') {
9644: foreach my $control (keys(%{$$current_permissions{$key}})) {
9645: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
9646: }
9647: }
9648: }
9649: }
9650: }
9651: return %access;
9652: }
9653:
9654: sub modify_access_controls {
9655: my ($file_name,$changes,$domain,$user)=@_;
9656: my ($outcome,$deloutcome);
9657: my %store_permissions;
9658: my %new_values;
9659: my %new_control;
9660: my %translation;
9661: my @deletions = ();
9662: my $now = time;
9663: if (exists($$changes{'activate'})) {
9664: if (ref($$changes{'activate'}) eq 'HASH') {
9665: my @newitems = sort(keys(%{$$changes{'activate'}}));
9666: my $numnew = scalar(@newitems);
9667: for (my $i=0; $i<$numnew; $i++) {
9668: my $newkey = $newitems[$i];
9669: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 9670: if ($newkey =~ /^\d+:/) {
9671: $newkey =~ s/^(\d+)/$newid/;
9672: $translation{$1} = $newid;
9673: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
9674: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
9675: $translation{$1} = $newid;
9676: }
1.749 raeburn 9677: $new_values{$file_name."\0".$newkey} =
9678: $$changes{'activate'}{$newitems[$i]};
9679: $new_control{$newkey} = $now;
9680: }
9681: }
9682: }
9683: my %todelete;
9684: my %changed_items;
9685: foreach my $action ('delete','update') {
9686: if (exists($$changes{$action})) {
9687: if (ref($$changes{$action}) eq 'HASH') {
9688: foreach my $key (keys(%{$$changes{$action}})) {
9689: my ($itemnum) = ($key =~ /^([^:]+):/);
9690: if ($action eq 'delete') {
9691: $todelete{$itemnum} = 1;
9692: } else {
9693: $changed_items{$itemnum} = $key;
9694: }
9695: }
1.745 raeburn 9696: }
9697: }
1.749 raeburn 9698: }
9699: # get lock on access controls for file.
9700: my $lockhash = {
9701: $file_name."\0".'locked_access_records' => $env{'user.name'}.
9702: ':'.$env{'user.domain'},
9703: };
9704: my $tries = 0;
9705: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9706:
1.1288 damieng 9707: while (($gotlock ne 'ok') && $tries < 10) {
1.749 raeburn 9708: $tries ++;
1.1289 damieng 9709: sleep(0.1);
1.749 raeburn 9710: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9711: }
9712: if ($gotlock eq 'ok') {
9713: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
9714: my ($tmp)=keys(%curr_permissions);
9715: if ($tmp=~/^error:/) { undef(%curr_permissions); }
9716: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
9717: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
9718: if (ref($curr_controls) eq 'HASH') {
9719: foreach my $control_item (keys(%{$curr_controls})) {
9720: my ($itemnum) = ($control_item =~ /^([^:]+):/);
9721: if (defined($todelete{$itemnum})) {
9722: push(@deletions,$file_name."\0".$control_item);
9723: } else {
9724: if (defined($changed_items{$itemnum})) {
9725: $new_control{$changed_items{$itemnum}} = $now;
9726: push(@deletions,$file_name."\0".$control_item);
9727: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
9728: } else {
9729: $new_control{$control_item} = $$curr_controls{$control_item};
9730: }
9731: }
1.745 raeburn 9732: }
9733: }
9734: }
1.970 raeburn 9735: my ($group);
9736: if (&is_course($domain,$user)) {
9737: ($group,my $file) = split(/\//,$file_name,2);
9738: }
1.749 raeburn 9739: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
9740: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
9741: $outcome = &put('file_permissions',\%new_values,$domain,$user);
9742: # remove lock
9743: my @del_lock = ($file_name."\0".'locked_access_records');
9744: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 9745: my $sqlresult =
1.970 raeburn 9746: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 9747: $group);
1.749 raeburn 9748: } else {
9749: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 9750: }
1.749 raeburn 9751: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 9752: }
9753:
1.827 raeburn 9754: sub make_public_indefinitely {
1.1271 raeburn 9755: my (@requrl) = @_;
9756: return &automated_portfile_access('public',\@requrl);
9757: }
9758:
9759: sub automated_portfile_access {
9760: my ($accesstype,$addsref,$delsref,$info) = @_;
1.1273 raeburn 9761: unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
9762: return 'invalid';
9763: }
1.1271 raeburn 9764: my %urls;
9765: if (ref($addsref) eq 'ARRAY') {
9766: foreach my $requrl (@{$addsref}) {
9767: if (&is_portfolio_url($requrl)) {
9768: unless (exists($urls{$requrl})) {
9769: $urls{$requrl} = 'add';
9770: }
9771: }
9772: }
9773: }
9774: if (ref($delsref) eq 'ARRAY') {
9775: foreach my $requrl (@{$delsref}) {
9776: if (&is_portfolio_url($requrl)) {
9777: unless (exists($urls{$requrl})) {
9778: $urls{$requrl} = 'delete';
9779: }
9780: }
9781: }
9782: }
9783: unless (keys(%urls)) {
9784: return 'invalid';
9785: }
9786: my $ip;
9787: if ($accesstype eq 'ip') {
9788: if (ref($info) eq 'HASH') {
9789: if ($info->{'ip'} ne '') {
9790: $ip = $info->{'ip'};
9791: }
9792: }
9793: if ($ip eq '') {
9794: return 'invalid';
9795: }
9796: }
9797: my $errors;
1.827 raeburn 9798: my $now = time;
1.1271 raeburn 9799: my %current_perms;
9800: foreach my $requrl (sort(keys(%urls))) {
9801: my $action;
9802: if ($urls{$requrl} eq 'add') {
9803: $action = 'activate';
9804: } else {
9805: $action = 'none';
9806: }
9807: my $aclnum = 0;
1.827 raeburn 9808: my (undef,$udom,$unum,$file_name,$group) =
9809: &parse_portfolio_url($requrl);
1.1271 raeburn 9810: unless (exists($current_perms{$unum.':'.$udom})) {
9811: $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
9812: }
9813: my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
1.827 raeburn 9814: $group,$file_name);
9815: foreach my $key (keys(%{$access_controls{$file_name}})) {
9816: my ($num,$scope,$end,$start) =
9817: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
1.1271 raeburn 9818: if ($scope eq $accesstype) {
9819: if (($start <= $now) && ($end == 0)) {
9820: if ($accesstype eq 'ip') {
9821: if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
9822: if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
9823: if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
9824: if ($urls{$requrl} eq 'add') {
9825: $action = 'none';
9826: last;
9827: } else {
9828: $action = 'delete';
9829: $aclnum = $num;
9830: last;
9831: }
9832: }
9833: }
9834: }
9835: } elsif ($accesstype eq 'public') {
9836: if ($urls{$requrl} eq 'add') {
9837: $action = 'none';
9838: last;
9839: } else {
9840: $action = 'delete';
9841: $aclnum = $num;
9842: last;
9843: }
9844: }
9845: } elsif ($accesstype eq 'public') {
1.827 raeburn 9846: $action = 'update';
9847: $aclnum = $num;
1.1271 raeburn 9848: last;
1.827 raeburn 9849: }
9850: }
9851: }
9852: if ($action eq 'none') {
1.1271 raeburn 9853: next;
1.827 raeburn 9854: } else {
9855: my %changes;
9856: my $newend = 0;
9857: my $newstart = $now;
1.1271 raeburn 9858: my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
1.827 raeburn 9859: $changes{$action}{$newkey} = {
1.1271 raeburn 9860: type => $accesstype,
1.827 raeburn 9861: time => {
9862: start => $newstart,
9863: end => $newend,
9864: },
9865: };
1.1271 raeburn 9866: if ($accesstype eq 'ip') {
9867: $changes{$action}{$newkey}{'ip'} = [$ip];
9868: }
1.827 raeburn 9869: my ($outcome,$deloutcome,$new_values,$translation) =
9870: &modify_access_controls($file_name,\%changes,$udom,$unum);
1.1271 raeburn 9871: unless ($outcome eq 'ok') {
9872: $errors .= $outcome.' ';
9873: }
1.827 raeburn 9874: }
1.1271 raeburn 9875: }
9876: if ($errors) {
9877: $errors =~ s/\s$//;
9878: return $errors;
1.827 raeburn 9879: } else {
1.1271 raeburn 9880: return 'ok';
1.827 raeburn 9881: }
9882: }
9883:
1.745 raeburn 9884: #------------------------------------------------------Get Marked as Read Only
9885:
9886: sub get_marked_as_readonly {
9887: my ($domain,$user,$what,$group) = @_;
9888: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 9889: my @readonly_files;
1.629 banghart 9890: my $cmp1=$what;
9891: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 9892: while (my ($file_name,$value) = each(%{$current_permissions})) {
9893: if (defined($group)) {
9894: if ($file_name !~ m-^\Q$group\E/-) {
9895: next;
9896: }
9897: }
1.561 banghart 9898: if (ref($value) eq "ARRAY"){
9899: foreach my $stored_what (@{$value}) {
1.629 banghart 9900: my $cmp2=$stored_what;
1.759 albertel 9901: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 9902: $cmp2=join('',@{$stored_what});
1.745 raeburn 9903: }
1.629 banghart 9904: if ($cmp1 eq $cmp2) {
1.561 banghart 9905: push(@readonly_files, $file_name);
1.745 raeburn 9906: last;
1.563 banghart 9907: } elsif (!defined($what)) {
9908: push(@readonly_files, $file_name);
1.745 raeburn 9909: last;
1.561 banghart 9910: }
9911: }
1.745 raeburn 9912: }
1.561 banghart 9913: }
9914: return @readonly_files;
9915: }
1.577 banghart 9916: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 9917:
1.577 banghart 9918: sub get_marked_as_readonly_hash {
1.745 raeburn 9919: my ($current_permissions,$group,$what) = @_;
1.577 banghart 9920: my %readonly_files;
1.745 raeburn 9921: while (my ($file_name,$value) = each(%{$current_permissions})) {
9922: if (defined($group)) {
9923: if ($file_name !~ m-^\Q$group\E/-) {
9924: next;
9925: }
9926: }
1.577 banghart 9927: if (ref($value) eq "ARRAY"){
9928: foreach my $stored_what (@{$value}) {
1.745 raeburn 9929: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 9930: foreach my $lock_descriptor(@{$stored_what}) {
9931: if ($lock_descriptor eq 'graded') {
9932: $readonly_files{$file_name} = 'graded';
9933: } elsif ($lock_descriptor eq 'handback') {
9934: $readonly_files{$file_name} = 'handback';
9935: } else {
9936: if (!exists($readonly_files{$file_name})) {
9937: $readonly_files{$file_name} = 'locked';
9938: }
9939: }
1.745 raeburn 9940: }
1.750 banghart 9941: }
1.577 banghart 9942: }
9943: }
9944: }
9945: return %readonly_files;
9946: }
1.559 banghart 9947: # ------------------------------------------------------------ Unmark as Read Only
9948:
9949: sub unmark_as_readonly {
1.629 banghart 9950: # unmarks $file_name (if $file_name is defined), or all files locked by $what
9951: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 9952: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 9953: $file_name = &declutter_portfile($file_name);
1.634 albertel 9954: my $symb_crs = $what;
9955: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 9956: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 9957: my ($tmp)=keys(%current_permissions);
9958: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 9959: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 9960: foreach my $file (@readonly_files) {
1.759 albertel 9961: my $clean_file = &declutter_portfile($file);
9962: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 9963: my $current_locks = $current_permissions{$file};
1.563 banghart 9964: my @new_locks;
9965: my @del_keys;
9966: if (ref($current_locks) eq "ARRAY"){
9967: foreach my $locker (@{$current_locks}) {
1.632 albertel 9968: my $compare=$locker;
1.749 raeburn 9969: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 9970: $compare=join('',@{$locker});
1.746 raeburn 9971: if ($compare ne $symb_crs) {
9972: push(@new_locks, $locker);
9973: }
1.563 banghart 9974: }
9975: }
1.650 albertel 9976: if (scalar(@new_locks) > 0) {
1.563 banghart 9977: $current_permissions{$file} = \@new_locks;
9978: } else {
9979: push(@del_keys, $file);
1.613 albertel 9980: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 9981: delete($current_permissions{$file});
1.563 banghart 9982: }
9983: }
1.561 banghart 9984: }
1.613 albertel 9985: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 9986: return;
9987: }
1.512 banghart 9988:
1.17 www 9989: # ------------------------------------------------------------ Directory lister
9990:
9991: sub dirlist {
1.955 raeburn 9992: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 9993: $uri=~s/^\///;
9994: $uri=~s/\/$//;
1.253 stredwic 9995: my ($udom, $uname);
1.955 raeburn 9996: if ($getuserdir) {
1.253 stredwic 9997: $udom = $userdomain;
9998: $uname = $username;
1.955 raeburn 9999: } else {
10000: (undef,$udom,$uname)=split(/\//,$uri);
10001: if(defined($userdomain)) {
10002: $udom = $userdomain;
10003: }
10004: if(defined($username)) {
10005: $uname = $username;
10006: }
1.253 stredwic 10007: }
1.955 raeburn 10008: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 10009:
1.955 raeburn 10010: $dirRoot = $perlvar{'lonDocRoot'};
10011: if (defined($getpropath)) {
10012: $dirRoot = &propath($udom,$uname);
1.253 stredwic 10013: $dirRoot =~ s/\/$//;
1.955 raeburn 10014: } elsif (defined($getuserdir)) {
10015: my $subdir=$uname.'__';
10016: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
10017: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
10018: ."/$udom/$subdir/$uname";
10019: } elsif (defined($alternateRoot)) {
10020: $dirRoot = $alternateRoot;
1.751 banghart 10021: }
1.253 stredwic 10022:
10023: if($udom) {
10024: if($uname) {
1.1135 raeburn 10025: my $uhome = &homeserver($uname,$udom);
1.1136 raeburn 10026: if ($uhome eq 'no_host') {
10027: return ([],'no_host');
10028: }
1.955 raeburn 10029: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 10030: .$getuserdir.':'.&escape($dirRoot)
1.1135 raeburn 10031: .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955 raeburn 10032: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 10033: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955 raeburn 10034: } else {
10035: @listing_results = map { &unescape($_); } split(/:/,$listing);
10036: }
1.605 matthew 10037: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 10038: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605 matthew 10039: @listing_results = split(/:/,$listing);
10040: } else {
10041: @listing_results = map { &unescape($_); } split(/:/,$listing);
10042: }
1.1135 raeburn 10043: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
1.1136 raeburn 10044: ($listing eq 'rejected') || ($listing eq 'refused') ||
10045: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
10046: return ([],$listing);
10047: } else {
10048: return (\@listing_results);
1.1135 raeburn 10049: }
1.955 raeburn 10050: } elsif(!$alternateRoot) {
1.1136 raeburn 10051: my (%allusers,%listerror);
1.841 albertel 10052: my %servers = &get_servers($udom,'library');
1.955 raeburn 10053: foreach my $tryserver (keys(%servers)) {
10054: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
10055: &escape($udom),$tryserver);
10056: if ($listing eq 'unknown_cmd') {
10057: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
10058: $udom, $tryserver);
10059: } else {
10060: @listing_results = map { &unescape($_); } split(/:/,$listing);
10061: }
1.841 albertel 10062: if ($listing eq 'unknown_cmd') {
10063: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
10064: $udom, $tryserver);
10065: @listing_results = split(/:/,$listing);
10066: } else {
10067: @listing_results =
10068: map { &unescape($_); } split(/:/,$listing);
10069: }
1.1136 raeburn 10070: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
10071: ($listing eq 'rejected') || ($listing eq 'refused') ||
10072: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
10073: $listerror{$tryserver} = $listing;
10074: } else {
1.841 albertel 10075: foreach my $line (@listing_results) {
10076: my ($entry) = split(/&/,$line,2);
10077: $allusers{$entry} = 1;
10078: }
10079: }
1.253 stredwic 10080: }
1.1136 raeburn 10081: my @alluserslist=();
1.800 albertel 10082: foreach my $user (sort(keys(%allusers))) {
1.1136 raeburn 10083: push(@alluserslist,$user.'&user');
1.253 stredwic 10084: }
1.1136 raeburn 10085: return (\@alluserslist);
1.253 stredwic 10086: } else {
1.1136 raeburn 10087: return ([],'missing username');
1.253 stredwic 10088: }
1.955 raeburn 10089: } elsif(!defined($getpropath)) {
1.1136 raeburn 10090: my $path = $perlvar{'lonDocRoot'}.'/res/';
10091: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
10092: return (\@all_domains);
1.955 raeburn 10093: } else {
1.1136 raeburn 10094: return ([],'missing domain');
1.275 stredwic 10095: }
10096: }
10097:
10098: # --------------------------------------------- GetFileTimestamp
10099: # This function utilizes dirlist and returns the date stamp for
10100: # when it was last modified. It will also return an error of -1
10101: # if an error occurs
10102:
10103: sub GetFileTimestamp {
1.955 raeburn 10104: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 10105: $studentDomain = &LONCAPA::clean_domain($studentDomain);
10106: $studentName = &LONCAPA::clean_username($studentName);
1.1136 raeburn 10107: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
10108: undef,$getuserdir);
10109: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
10110: return -1;
10111: }
10112: if (ref($fileref) eq 'ARRAY') {
10113: my @stats = split('&',$fileref->[0]);
1.375 matthew 10114: # @stats contains first the filename, then the stat output
10115: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 10116: } else {
10117: return -1;
1.253 stredwic 10118: }
1.26 www 10119: }
10120:
1.712 albertel 10121: sub stat_file {
10122: my ($uri) = @_;
1.787 albertel 10123: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 10124:
1.955 raeburn 10125: my ($udom,$uname,$file);
1.712 albertel 10126: if ($uri =~ m-^/(uploaded|editupload)/-) {
10127: ($udom,$uname,$file) =
1.811 albertel 10128: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 10129: $file = 'userfiles/'.$file;
10130: }
10131: if ($uri =~ m-^/res/-) {
10132: ($udom,$uname) =
1.807 albertel 10133: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 10134: $file = $uri;
10135: }
10136:
10137: if (!$udom || !$uname || !$file) {
10138: # unable to handle the uri
10139: return ();
10140: }
1.956 raeburn 10141: my $getpropath;
10142: if ($file =~ /^userfiles\//) {
10143: $getpropath = 1;
10144: }
1.1136 raeburn 10145: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
10146: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
10147: return ();
10148: } else {
10149: if (ref($listref) eq 'ARRAY') {
10150: my @stats = split('&',$listref->[0]);
10151: shift(@stats); #filename is first
10152: return @stats;
10153: }
1.712 albertel 10154: }
10155: return ();
10156: }
10157:
1.26 www 10158: # -------------------------------------------------------- Value of a Condition
10159:
1.713 albertel 10160: # gets the value of a specific preevaluated condition
10161: # stored in the string $env{user.state.<cid>}
10162: # or looks up a condition reference in the bighash and if if hasn't
10163: # already been evaluated recurses into docondval to get the value of
10164: # the condition, then memoizing it to
10165: # $env{user.state.<cid>.<condition>}
1.40 www 10166: sub directcondval {
10167: my $number=shift;
1.620 albertel 10168: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 10169: &Apache::lonuserstate::evalstate();
10170: }
1.713 albertel 10171: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
10172: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
10173: } elsif ($number =~ /^_/) {
10174: my $sub_condition;
10175: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10176: &GDBM_READER(),0640)) {
10177: $sub_condition=$bighash{'conditions'.$number};
10178: untie(%bighash);
10179: }
10180: my $value = &docondval($sub_condition);
1.949 raeburn 10181: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 10182: return $value;
10183: }
1.620 albertel 10184: if ($env{'user.state.'.$env{'request.course.id'}}) {
10185: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 10186: } else {
10187: return 2;
10188: }
10189: }
10190:
1.713 albertel 10191: # get the collection of conditions for this resource
1.26 www 10192: sub condval {
10193: my $condidx=shift;
1.54 www 10194: my $allpathcond='';
1.713 albertel 10195: foreach my $cond (split(/\|/,$condidx)) {
10196: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
10197: $allpathcond.=
10198: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
10199: }
1.191 harris41 10200: }
1.54 www 10201: $allpathcond=~s/\|$//;
1.713 albertel 10202: return &docondval($allpathcond);
10203: }
10204:
10205: #evaluates an expression of conditions
10206: sub docondval {
10207: my ($allpathcond) = @_;
10208: my $result=0;
10209: if ($env{'request.course.id'}
10210: && defined($allpathcond)) {
10211: my $operand='|';
10212: my @stack;
10213: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
10214: if ($chunk eq '(') {
10215: push @stack,($operand,$result);
10216: } elsif ($chunk eq ')') {
10217: my $before=pop @stack;
10218: if (pop @stack eq '&') {
10219: $result=$result>$before?$before:$result;
10220: } else {
10221: $result=$result>$before?$result:$before;
10222: }
10223: } elsif (($chunk eq '&') || ($chunk eq '|')) {
10224: $operand=$chunk;
10225: } else {
10226: my $new=directcondval($chunk);
10227: if ($operand eq '&') {
10228: $result=$result>$new?$new:$result;
10229: } else {
10230: $result=$result>$new?$result:$new;
10231: }
10232: }
10233: }
1.26 www 10234: }
10235: return $result;
1.421 albertel 10236: }
10237:
10238: # ---------------------------------------------------- Devalidate courseresdata
10239:
10240: sub devalidatecourseresdata {
10241: my ($coursenum,$coursedomain)=@_;
10242: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 10243: &devalidate_cache_new('courseres',$hashid);
1.28 www 10244: }
10245:
1.763 www 10246:
1.200 www 10247: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 10248: #
10249: # Parameters:
10250: # $coursenum - Number of the course.
10251: # $coursedomain - Domain at which the course was created.
10252: # Returns:
10253: # A hash of the course parameters along (I think) with timestamps
10254: # and version info.
1.877 foxr 10255:
1.624 albertel 10256: sub get_courseresdata {
10257: my ($coursenum,$coursedomain)=@_;
1.200 www 10258: my $coursehom=&homeserver($coursenum,$coursedomain);
10259: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 10260: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 10261: my %dumpreply;
1.417 albertel 10262: unless (defined($cached)) {
1.624 albertel 10263: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 10264: $result=\%dumpreply;
1.251 albertel 10265: my ($tmp) = keys(%dumpreply);
10266: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 10267: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 10268: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
10269: return $tmp;
1.416 albertel 10270: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 10271: $result=undef;
1.599 albertel 10272: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 10273: }
10274: }
1.624 albertel 10275: return $result;
10276: }
10277:
1.633 albertel 10278: sub devalidateuserresdata {
10279: my ($uname,$udom)=@_;
10280: my $hashid="$udom:$uname";
10281: &devalidate_cache_new('userres',$hashid);
10282: }
10283:
1.624 albertel 10284: sub get_userresdata {
10285: my ($uname,$udom)=@_;
10286: #most student don\'t have any data set, check if there is some data
10287: if (&EXT_cache_status($udom,$uname)) { return undef; }
10288:
10289: my $hashid="$udom:$uname";
10290: my ($result,$cached)=&is_cached_new('userres',$hashid);
10291: if (!defined($cached)) {
10292: my %resourcedata=&dump('resourcedata',$udom,$uname);
10293: $result=\%resourcedata;
10294: &do_cache_new('userres',$hashid,$result,600);
10295: }
10296: my ($tmp)=keys(%$result);
10297: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
10298: return $result;
10299: }
10300: #error 2 occurs when the .db doesn't exist
10301: if ($tmp!~/error: 2 /) {
1.1294 raeburn 10302: if ((!defined($cached)) || ($tmp ne 'con_lost')) {
10303: &logthis("<font color=\"blue\">WARNING:".
10304: " Trying to get resource data for ".
10305: $uname." at ".$udom.": ".
10306: $tmp."</font>");
10307: }
1.624 albertel 10308: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 10309: #&EXT_cache_set($udom,$uname);
10310: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 10311: undef($tmp); # not really an error so don't send it back
1.624 albertel 10312: }
10313: return $tmp;
10314: }
1.879 foxr 10315: #----------------------------------------------- resdata - return resource data
10316: # Purpose:
10317: # Return resource data for either users or for a course.
10318: # Parameters:
10319: # $name - Course/user name.
10320: # $domain - Name of the domain the user/course is registered on.
10321: # $type - Type of thing $name is (must be 'course' or 'user'
1.1301 raeburn 10322: # $mapp - decluttered URL of enclosing map
10323: # $recursed - Ref to scalar -- set to 1, if nested maps have been recursed.
10324: # $recurseup - Ref to array of map URLs, starting with map containing
10325: # $mapp up through hierarchy of nested maps to top level map.
10326: # $courseid - CourseID (first part of param identifier).
10327: # $modifier - Middle part of param identifier.
10328: # $what - Last part of param identifier.
1.879 foxr 10329: # @which - Array of names of resources desired.
10330: # Returns:
10331: # The value of the first reasource in @which that is found in the
10332: # resource hash.
10333: # Exceptional Conditions:
10334: # If the $type passed in is not valid (not the string 'course' or
10335: # 'user', an undefined reference is returned.
10336: # If none of the resources are found, an undef is returned
1.624 albertel 10337: sub resdata {
1.1301 raeburn 10338: my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
10339: $modifier,$what,@which)=@_;
1.624 albertel 10340: my $result;
10341: if ($type eq 'course') {
10342: $result=&get_courseresdata($name,$domain);
10343: } elsif ($type eq 'user') {
10344: $result=&get_userresdata($name,$domain);
10345: }
10346: if (!ref($result)) { return $result; }
1.251 albertel 10347: foreach my $item (@which) {
1.1301 raeburn 10348: if ($item->[1] eq 'course') {
10349: if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
10350: unless ($$recursed) {
1.1302 raeburn 10351: @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
1.1301 raeburn 10352: $$recursed = 1;
10353: }
10354: foreach my $item (@${recurseup}) {
10355: my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
10356: last if (defined($result->{$norecursechk}));
10357: my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
10358: if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
10359: }
10360: }
10361: }
10362: if (defined($result->{$item->[0]})) {
1.927 albertel 10363: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 10364: }
1.250 albertel 10365: }
1.291 albertel 10366: return undef;
1.200 www 10367: }
10368:
1.1298 raeburn 10369: sub get_domain_ltitools {
10370: my ($cdom) = @_;
10371: my %ltitools;
10372: my ($result,$cached)=&is_cached_new('ltitools',$cdom);
10373: if (defined($cached)) {
10374: if (ref($result) eq 'HASH') {
10375: %ltitools = %{$result};
10376: }
10377: } else {
10378: my %domconfig = &get_dom('configuration',['ltitools'],$cdom);
10379: if (ref($domconfig{'ltitools'}) eq 'HASH') {
10380: %ltitools = %{$domconfig{'ltitools'}};
10381: }
10382: my $cachetime = 24*60*60;
10383: &do_cache_new('ltitools',$cdom,\%ltitools,$cachetime);
10384: }
10385: return %ltitools;
10386: }
10387:
1.1236 raeburn 10388: sub get_numsuppfiles {
10389: my ($cnum,$cdom,$ignorecache)=@_;
10390: my $hashid=$cnum.':'.$cdom;
10391: my ($suppcount,$cached);
10392: unless ($ignorecache) {
10393: ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
10394: }
10395: unless (defined($cached)) {
10396: my $chome=&homeserver($cnum,$cdom);
10397: unless ($chome eq 'no_host') {
10398: ($suppcount,my $errors) = (0,0);
10399: my $suppmap = 'supplemental.sequence';
10400: ($suppcount,$errors) =
10401: &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
10402: }
10403: &do_cache_new('suppcount',$hashid,$suppcount,600);
10404: }
10405: return $suppcount;
10406: }
10407:
1.379 matthew 10408: #
10409: # EXT resource caching routines
10410: #
10411:
1.1302 raeburn 10412: {
10413: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
10414: #
10415: # The course for which we cache
10416: my $cachedmapkey='';
10417: # The cached recursive maps for this course
10418: my %cachedmaps=();
10419: # When this was last done
10420: my $cachedmaptime='';
10421:
1.379 matthew 10422: sub clear_EXT_cache_status {
1.383 albertel 10423: &delenv('cache.EXT.');
1.379 matthew 10424: }
10425:
10426: sub EXT_cache_status {
10427: my ($target_domain,$target_user) = @_;
1.383 albertel 10428: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 10429: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 10430: # We know already the user has no data
10431: return 1;
10432: } else {
10433: return 0;
10434: }
10435: }
10436:
10437: sub EXT_cache_set {
10438: my ($target_domain,$target_user) = @_;
1.383 albertel 10439: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 10440: #&appenv({$cachename => time});
1.379 matthew 10441: }
10442:
1.28 www 10443: # --------------------------------------------------------- Value of a Variable
1.58 www 10444: sub EXT {
1.715 albertel 10445:
1.1228 raeburn 10446: my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68 www 10447: unless ($varname) { return ''; }
1.218 albertel 10448: #get real user name/domain, courseid and symb
10449: my $courseid;
1.359 albertel 10450: my $publicuser;
1.427 www 10451: if ($symbparm) {
10452: $symbparm=&get_symb_from_alias($symbparm);
10453: }
1.218 albertel 10454: if (!($uname && $udom)) {
1.790 albertel 10455: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 10456: if (!$symbparm) { $symbparm=$cursymb; }
10457: } else {
1.620 albertel 10458: $courseid=$env{'request.course.id'};
1.218 albertel 10459: }
1.48 www 10460: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
10461: my $rest;
1.320 albertel 10462: if (defined($therest[0])) {
1.48 www 10463: $rest=join('.',@therest);
10464: } else {
10465: $rest='';
10466: }
1.320 albertel 10467:
1.57 www 10468: my $qualifierrest=$qualifier;
10469: if ($rest) { $qualifierrest.='.'.$rest; }
10470: my $spacequalifierrest=$space;
10471: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 10472: if ($realm eq 'user') {
1.48 www 10473: # --------------------------------------------------------------- user.resource
10474: if ($space eq 'resource') {
1.651 albertel 10475: if ( (defined($Apache::lonhomework::parsing_a_problem)
10476: || defined($Apache::lonhomework::parsing_a_task))
10477: &&
1.744 albertel 10478: ($symbparm eq &symbread()) ) {
10479: # if we are in the middle of processing the resource the
10480: # get the value we are planning on committing
10481: if (defined($Apache::lonhomework::results{$qualifierrest})) {
10482: return $Apache::lonhomework::results{$qualifierrest};
10483: } else {
10484: return $Apache::lonhomework::history{$qualifierrest};
10485: }
1.335 albertel 10486: } else {
1.359 albertel 10487: my %restored;
1.620 albertel 10488: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 10489: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
10490: } else {
10491: %restored=&restore($symbparm,$courseid,$udom,$uname);
10492: }
1.335 albertel 10493: return $restored{$qualifierrest};
10494: }
1.48 www 10495: # ----------------------------------------------------------------- user.access
10496: } elsif ($space eq 'access') {
1.218 albertel 10497: # FIXME - not supporting calls for a specific user
1.48 www 10498: return &allowed($qualifier,$rest);
10499: # ------------------------------------------ user.preferences, user.environment
10500: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 10501: if (($uname eq $env{'user.name'}) &&
10502: ($udom eq $env{'user.domain'})) {
10503: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 10504: } else {
1.359 albertel 10505: my %returnhash;
10506: if (!$publicuser) {
10507: %returnhash=&userenvironment($udom,$uname,
10508: $qualifierrest);
10509: }
1.218 albertel 10510: return $returnhash{$qualifierrest};
10511: }
1.48 www 10512: # ----------------------------------------------------------------- user.course
10513: } elsif ($space eq 'course') {
1.218 albertel 10514: # FIXME - not supporting calls for a specific user
1.620 albertel 10515: return $env{join('.',('request.course',$qualifier))};
1.48 www 10516: # ------------------------------------------------------------------- user.role
10517: } elsif ($space eq 'role') {
1.218 albertel 10518: # FIXME - not supporting calls for a specific user
1.620 albertel 10519: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 10520: if ($qualifier eq 'value') {
10521: return $role;
10522: } elsif ($qualifier eq 'extent') {
10523: return $where;
10524: }
10525: # ----------------------------------------------------------------- user.domain
10526: } elsif ($space eq 'domain') {
1.218 albertel 10527: return $udom;
1.48 www 10528: # ------------------------------------------------------------------- user.name
10529: } elsif ($space eq 'name') {
1.218 albertel 10530: return $uname;
1.48 www 10531: # ---------------------------------------------------- Any other user namespace
1.29 www 10532: } else {
1.359 albertel 10533: my %reply;
10534: if (!$publicuser) {
10535: %reply=&get($space,[$qualifierrest],$udom,$uname);
10536: }
10537: return $reply{$qualifierrest};
1.48 www 10538: }
1.236 www 10539: } elsif ($realm eq 'query') {
10540: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 10541: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
10542: [$spacequalifierrest]);
1.620 albertel 10543: return $env{'form.'.$spacequalifierrest};
1.236 www 10544: } elsif ($realm eq 'request') {
1.48 www 10545: # ------------------------------------------------------------- request.browser
10546: if ($space eq 'browser') {
1.1145 bisitz 10547: return $env{'browser.'.$qualifier};
1.57 www 10548: # ------------------------------------------------------------ request.filename
10549: } else {
1.620 albertel 10550: return $env{'request.'.$spacequalifierrest};
1.29 www 10551: }
1.28 www 10552: } elsif ($realm eq 'course') {
1.48 www 10553: # ---------------------------------------------------------- course.description
1.620 albertel 10554: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 10555: } elsif ($realm eq 'resource') {
1.165 www 10556:
1.620 albertel 10557: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 10558: if (!$symbparm) { $symbparm=&symbread(); }
10559: }
1.693 albertel 10560:
1.1232 raeburn 10561: if ($qualifier eq '') {
10562: if ($space eq 'title') {
10563: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
10564: return &gettitle($symbparm);
10565: }
1.693 albertel 10566:
1.1232 raeburn 10567: if ($space eq 'map') {
10568: my ($map) = &decode_symb($symbparm);
10569: return &symbread($map);
10570: }
10571: if ($space eq 'maptitle') {
10572: my ($map) = &decode_symb($symbparm);
10573: return &gettitle($map);
10574: }
10575: if ($space eq 'filename') {
10576: if ($symbparm) {
10577: return &clutter((&decode_symb($symbparm))[2]);
10578: }
10579: return &hreflocation('',$env{'request.filename'});
1.905 albertel 10580: }
1.1232 raeburn 10581:
1.1233 raeburn 10582: if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
10583: if ($space eq 'visibleparts') {
10584: my $navmap = Apache::lonnavmaps::navmap->new();
10585: my $item;
10586: if (ref($navmap)) {
10587: my $res = $navmap->getBySymb($symbparm);
10588: my $parts = $res->parts();
10589: if (ref($parts) eq 'ARRAY') {
10590: $item = join(',',@{$parts});
10591: }
10592: undef($navmap);
1.1232 raeburn 10593: }
1.1233 raeburn 10594: return $item;
1.1232 raeburn 10595: }
10596: }
10597: }
1.693 albertel 10598:
1.1301 raeburn 10599: my ($section, $group, @groups, @recurseup, $recursed);
10600: my ($courselevelm,$courseleveli,$courselevel,$mapp);
1.1228 raeburn 10601: if (($courseid eq '') && ($cid)) {
10602: $courseid = $cid;
10603: }
10604: if (($symbparm && $courseid) &&
10605: (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165 www 10606:
1.218 albertel 10607: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 10608:
1.60 www 10609: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 10610: my $symbp=$symbparm;
1.1301 raeburn 10611: $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 10612: my $symbparm=$symbp.'.'.$spacequalifierrest;
1.1301 raeburn 10613: my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
1.218 albertel 10614: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
1.620 albertel 10615: if (($env{'user.name'} eq $uname) &&
10616: ($env{'user.domain'} eq $udom)) {
10617: $section=$env{'request.course.sec'};
1.733 raeburn 10618: @groups = split(/:/,$env{'request.course.groups'});
10619: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 10620: } else {
1.539 albertel 10621: if (! defined($usection)) {
1.551 albertel 10622: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 10623: } else {
10624: $section = $usection;
10625: }
1.733 raeburn 10626: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 10627: }
10628:
10629: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
10630: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
1.1301 raeburn 10631: my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
1.218 albertel 10632: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
10633:
1.593 albertel 10634: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 10635: my $courselevelr=$courseid.'.'.$symbparm;
1.1301 raeburn 10636: $courseleveli=$courseid.'.'.$recurseparm;
1.593 albertel 10637: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 10638:
1.60 www 10639: # ----------------------------------------------------------- first, check user
1.624 albertel 10640:
1.1301 raeburn 10641: my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
10642: \@recurseup,$courseid,'.',$spacequalifierrest,
1.927 albertel 10643: ([$courselevelr,'resource'],
10644: [$courselevelm,'map' ],
1.1301 raeburn 10645: [$courseleveli,'map' ],
1.927 albertel 10646: [$courselevel, 'course' ]));
1.931 albertel 10647: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 10648:
1.594 albertel 10649: # ------------------------------------------------ second, check some of course
1.684 raeburn 10650: my $coursereply;
1.691 raeburn 10651: if (@groups > 0) {
10652: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
1.1301 raeburn 10653: $recurseparm,$mapparm,$spacequalifierrest,
10654: $mapp,\$recursed,\@recurseup);
10655: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 10656: }
1.96 www 10657:
1.684 raeburn 10658: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 10659: $env{'course.'.$courseid.'.domain'},
1.1301 raeburn 10660: 'course',$mapp,\$recursed,\@recurseup,
10661: $courseid,'.['.$section.'].',$spacequalifierrest,
1.927 albertel 10662: ([$seclevelr, 'resource'],
10663: [$seclevelm, 'map' ],
1.1301 raeburn 10664: [$secleveli, 'map' ],
1.927 albertel 10665: [$seclevel, 'course' ],
10666: [$courselevelr,'resource']));
10667: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 10668:
1.60 www 10669: # ------------------------------------------------------ third, check map parms
1.218 albertel 10670: my %parmhash=();
10671: my $thisparm='';
10672: if (tie(%parmhash,'GDBM_File',
1.620 albertel 10673: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 10674: &GDBM_READER(),0640)) {
1.218 albertel 10675: $thisparm=$parmhash{$symbparm};
10676: untie(%parmhash);
10677: }
1.927 albertel 10678: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 10679: }
1.594 albertel 10680: # ------------------------------------------ fourth, look in resource metadata
1.1301 raeburn 10681:
10682: my $what = $spacequalifierrest;
10683: $what=~s/\./\_/;
1.282 albertel 10684: my $filename;
10685: if (!$symbparm) { $symbparm=&symbread(); }
10686: if ($symbparm) {
1.409 www 10687: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 10688: } else {
1.620 albertel 10689: $filename=$env{'request.filename'};
1.282 albertel 10690: }
1.1301 raeburn 10691: my $metadata=&metadata($filename,$what);
1.927 albertel 10692: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.1301 raeburn 10693: $metadata=&metadata($filename,'parameter_'.$what);
1.927 albertel 10694: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 10695:
1.1301 raeburn 10696: # ----------------------------------------------- fifth, look in rest of course
1.593 albertel 10697: if ($symbparm && defined($courseid) &&
1.620 albertel 10698: $courseid eq $env{'request.course.id'}) {
1.624 albertel 10699: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
10700: $env{'course.'.$courseid.'.domain'},
1.1301 raeburn 10701: 'course',$mapp,\$recursed,\@recurseup,
10702: $courseid,'.',$spacequalifierrest,
1.927 albertel 10703: ([$courselevelm,'map' ],
1.1301 raeburn 10704: [$courseleveli,'map' ],
1.927 albertel 10705: [$courselevel, 'course']));
10706: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 10707: }
1.145 www 10708: # ------------------------------------------------------------------ Cascade up
1.218 albertel 10709: unless ($space eq '0') {
1.336 albertel 10710: my @parts=split(/_/,$space);
10711: my $id=pop(@parts);
10712: my $part=join('_',@parts);
10713: if ($part eq '') { $part='0'; }
1.927 albertel 10714: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 10715: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 10716: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 10717: }
1.395 albertel 10718: if ($recurse) { return undef; }
10719: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 10720: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 10721: # ---------------------------------------------------- Any other user namespace
10722: } elsif ($realm eq 'environment') {
10723: # ----------------------------------------------------------------- environment
1.620 albertel 10724: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
10725: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 10726: } else {
1.770 albertel 10727: if ($uname eq 'anonymous' && $udom eq '') {
10728: return '';
10729: }
1.219 albertel 10730: my %returnhash=&userenvironment($udom,$uname,
10731: $spacequalifierrest);
10732: return $returnhash{$spacequalifierrest};
10733: }
1.28 www 10734: } elsif ($realm eq 'system') {
1.48 www 10735: # ----------------------------------------------------------------- system.time
10736: if ($space eq 'time') {
10737: return time;
10738: }
1.696 albertel 10739: } elsif ($realm eq 'server') {
10740: # ----------------------------------------------------------------- system.time
10741: if ($space eq 'name') {
10742: return $ENV{'SERVER_NAME'};
10743: }
1.28 www 10744: }
1.48 www 10745: return '';
1.61 www 10746: }
10747:
1.927 albertel 10748: sub get_reply {
10749: my ($reply_value) = @_;
1.940 raeburn 10750: if (ref($reply_value) eq 'ARRAY') {
10751: if (wantarray) {
10752: return @$reply_value;
10753: }
10754: return $reply_value->[0];
10755: } else {
10756: return $reply_value;
1.927 albertel 10757: }
10758: }
10759:
1.691 raeburn 10760: sub check_group_parms {
1.1301 raeburn 10761: my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
10762: $recursed,$recurseupref) = @_;
10763: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
10764: [$what,'course']);
10765: my $coursereply;
1.691 raeburn 10766: foreach my $group (@{$groups}) {
1.1301 raeburn 10767: my @groupitems = ();
1.691 raeburn 10768: foreach my $level (@levels) {
1.927 albertel 10769: my $item = $courseid.'.['.$group.'].'.$level->[0];
10770: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 10771: }
1.1301 raeburn 10772: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
10773: $env{'course.'.$courseid.'.domain'},
10774: 'course',$mapp,$recursed,$recurseupref,
10775: $courseid,'.['.$group.'].',$what,
10776: @groupitems);
10777: last if (defined($coursereply));
1.691 raeburn 10778: }
10779: return $coursereply;
10780: }
10781:
1.1301 raeburn 10782: sub get_map_hierarchy {
1.1302 raeburn 10783: my ($mapname,$courseid) = @_;
10784: my @recurseup = ();
1.1301 raeburn 10785: if ($mapname) {
1.1302 raeburn 10786: if (($cachedmapkey eq $courseid) &&
10787: (abs($cachedmaptime-time)<5)) {
10788: if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
10789: return @{$cachedmaps{$mapname}};
10790: }
10791: }
1.1301 raeburn 10792: my $navmap = Apache::lonnavmaps::navmap->new();
10793: if (ref($navmap)) {
10794: @recurseup = $navmap->recurseup_maps($mapname);
10795: undef($navmap);
1.1302 raeburn 10796: $cachedmaps{$mapname} = \@recurseup;
10797: $cachedmaptime=time;
10798: $cachedmapkey=$courseid;
1.1301 raeburn 10799: }
10800: }
10801: return @recurseup;
10802: }
10803:
1.1302 raeburn 10804: }
10805:
1.691 raeburn 10806: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 10807: my ($courseid,@groups) = @_;
10808: @groups = sort(@groups);
1.691 raeburn 10809: return @groups;
10810: }
10811:
1.395 albertel 10812: sub packages_tab_default {
10813: my ($uri,$varname)=@_;
10814: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 10815:
10816: my (@extension,@specifics,$do_default);
10817: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 10818: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 10819: if ($pack_type eq 'default') {
10820: $do_default=1;
10821: } elsif ($pack_type eq 'extension') {
10822: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 10823: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 10824: # only look at packages defaults for packages that this id is
1.738 albertel 10825: push(@specifics,[$package,$pack_type,$pack_part]);
10826: }
10827: }
10828: # first look for a package that matches the requested part id
10829: foreach my $package (@specifics) {
10830: my (undef,$pack_type,$pack_part)=@{$package};
10831: next if ($pack_part ne $part);
10832: if (defined($packagetab{"$pack_type&$name&default"})) {
10833: return $packagetab{"$pack_type&$name&default"};
10834: }
10835: }
10836: # look for any possible matching non extension_ package
10837: foreach my $package (@specifics) {
10838: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 10839: if (defined($packagetab{"$pack_type&$name&default"})) {
10840: return $packagetab{"$pack_type&$name&default"};
10841: }
1.585 albertel 10842: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 10843: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
10844: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 10845: }
10846: }
1.738 albertel 10847: # look for any posible extension_ match
10848: foreach my $package (@extension) {
10849: my ($package,$pack_type)=@{$package};
10850: if (defined($packagetab{"$pack_type&$name&default"})) {
10851: return $packagetab{"$pack_type&$name&default"};
10852: }
10853: if (defined($packagetab{$package."&$name&default"})) {
10854: return $packagetab{$package."&$name&default"};
10855: }
10856: }
10857: # look for a global default setting
10858: if ($do_default && defined($packagetab{"default&$name&default"})) {
10859: return $packagetab{"default&$name&default"};
10860: }
1.395 albertel 10861: return undef;
10862: }
10863:
1.334 albertel 10864: sub add_prefix_and_part {
10865: my ($prefix,$part)=@_;
10866: my $keyroot;
10867: if (defined($prefix) && $prefix !~ /^__/) {
10868: # prefix that has a part already
10869: $keyroot=$prefix;
10870: } elsif (defined($prefix)) {
10871: # prefix that is missing a part
10872: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
10873: } else {
10874: # no prefix at all
10875: if (defined($part)) { $keyroot='_'.$part; }
10876: }
10877: return $keyroot;
10878: }
10879:
1.71 www 10880: # ---------------------------------------------------------------- Get metadata
10881:
1.599 albertel 10882: my %metaentry;
1.1070 www 10883: my %importedpartids;
1.71 www 10884: sub metadata {
1.176 www 10885: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 10886: $uri=&declutter($uri);
1.288 albertel 10887: # if it is a non metadata possible uri return quickly
1.529 albertel 10888: if (($uri eq '') ||
10889: (($uri =~ m|^/*adm/|) &&
1.1298 raeburn 10890: ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|exttools?)$})) ||
1.1108 raeburn 10891: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 10892: return undef;
10893: }
1.1261 raeburn 10894: if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv})
1.924 albertel 10895: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 10896: return undef;
1.288 albertel 10897: }
1.73 www 10898: my $filename=$uri;
10899: $uri=~s/\.meta$//;
1.172 www 10900: #
10901: # Is the metadata already cached?
1.177 www 10902: # Look at timestamp of caching
1.172 www 10903: # Everything is cached by the main uri, libraries are never directly cached
10904: #
1.428 albertel 10905: if (!defined($liburi)) {
1.599 albertel 10906: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 10907: if (defined($cached)) { return $result->{':'.$what}; }
10908: }
10909: {
1.1069 www 10910: # Imported parts would go here
1.1070 www 10911: my %importedids=();
10912: my @origfileimportpartids=();
1.1069 www 10913: my $importedparts=0;
1.172 www 10914: #
10915: # Is this a recursive call for a library?
10916: #
1.599 albertel 10917: # if (! exists($metacache{$uri})) {
10918: # $metacache{$uri}={};
10919: # }
1.924 albertel 10920: my $cachetime = 60*60;
1.171 www 10921: if ($liburi) {
10922: $liburi=&declutter($liburi);
10923: $filename=$liburi;
1.401 bowersj2 10924: } else {
1.599 albertel 10925: &devalidate_cache_new('meta',$uri);
10926: undef(%metaentry);
1.401 bowersj2 10927: }
1.140 www 10928: my %metathesekeys=();
1.73 www 10929: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 10930: my $metastring;
1.1140 www 10931: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929 albertel 10932: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 10933: $metastring =
1.929 albertel 10934: &Apache::lonnet::ssi_body($which,
1.924 albertel 10935: ('grade_target' => 'meta'));
10936: $cachetime = 1; # only want this cached in the child not long term
1.1108 raeburn 10937: } elsif (($uri !~ m -^(editupload)/-) &&
10938: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 10939: my $file=&filelocation('',&clutter($filename));
1.599 albertel 10940: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 10941: $metastring=&getfile($file);
1.489 albertel 10942: }
1.208 albertel 10943: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 10944: my $token;
1.140 www 10945: undef %metathesekeys;
1.71 www 10946: while ($token=$parser->get_token) {
1.339 albertel 10947: if ($token->[0] eq 'S') {
10948: if (defined($token->[2]->{'package'})) {
1.172 www 10949: #
10950: # This is a package - get package info
10951: #
1.339 albertel 10952: my $package=$token->[2]->{'package'};
10953: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10954: if (defined($token->[2]->{'id'})) {
10955: $keyroot.='_'.$token->[2]->{'id'};
10956: }
1.599 albertel 10957: if ($metaentry{':packages'}) {
10958: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 10959: } else {
1.599 albertel 10960: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 10961: }
1.736 albertel 10962: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 10963: my $part=$keyroot;
10964: $part=~s/^\_//;
1.736 albertel 10965: if ($pack_entry=~/^\Q$package\E\&/ ||
10966: $pack_entry=~/^\Q$package\E_0\&/) {
10967: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 10968: # ignore package.tab specified default values
10969: # here &package_tab_default() will fetch those
10970: if ($subp eq 'default') { next; }
1.736 albertel 10971: my $value=$packagetab{$pack_entry};
1.432 albertel 10972: my $unikey;
10973: if ($pack =~ /_0$/) {
10974: $unikey='parameter_0_'.$name;
10975: $part=0;
10976: } else {
10977: $unikey='parameter'.$keyroot.'_'.$name;
10978: }
1.339 albertel 10979: if ($subp eq 'display') {
10980: $value.=' [Part: '.$part.']';
10981: }
1.599 albertel 10982: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 10983: $metathesekeys{$unikey}=1;
1.599 albertel 10984: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10985: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 10986: }
1.599 albertel 10987: if (defined($metaentry{':'.$unikey.'.default'})) {
10988: $metaentry{':'.$unikey}=
10989: $metaentry{':'.$unikey.'.default'};
1.356 albertel 10990: }
1.339 albertel 10991: }
10992: }
10993: } else {
1.172 www 10994: #
10995: # This is not a package - some other kind of start tag
1.339 albertel 10996: #
10997: my $entry=$token->[1];
1.1068 www 10998: my $unikey='';
1.175 www 10999:
1.339 albertel 11000: if ($entry eq 'import') {
1.175 www 11001: #
11002: # Importing a library here
1.339 albertel 11003: #
1.1067 www 11004: my $location=$parser->get_text('/import');
11005: my $dir=$filename;
11006: $dir=~s|[^/]*$||;
11007: $location=&filelocation($dir,$location);
1.1069 www 11008:
1.1068 www 11009: my $importmode=$token->[2]->{'importmode'};
11010: if ($importmode eq 'problem') {
1.1069 www 11011: # Import as problem/response
1.1068 www 11012: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11013: } elsif ($importmode eq 'part') {
11014: # Import as part(s)
1.1069 www 11015: $importedparts=1;
11016: # We need to get the original file and the imported file to get the part order correct
11017: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
11018: # Load and inspect original file
1.1070 www 11019: if ($#origfileimportpartids<0) {
11020: undef(%importedpartids);
11021: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
11022: my $origfile=&getfile($origfilelocation);
11023: @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
11024: }
11025:
1.1069 www 11026: # Load and inspect imported file
11027: my $impfile=&getfile($location);
11028: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
11029: if ($#impfilepartids>=0) {
11030: # This problem had parts
1.1070 www 11031: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 11032: } else {
11033: # Importing by turning a single problem into a problem part
11034: # It gets the import-tags ID as part-ID
11035: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 11036: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 11037: }
1.1068 www 11038: } else {
11039: # Normal import
11040: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11041: if (defined($token->[2]->{'id'})) {
11042: $unikey.='_'.$token->[2]->{'id'};
11043: }
1.1067 www 11044: }
11045:
1.339 albertel 11046: if ($depthcount<20) {
1.736 albertel 11047: my $metadata =
11048: &metadata($uri,'keys', $location,$unikey,
11049: $depthcount+1);
11050: foreach my $meta (split(',',$metadata)) {
11051: $metaentry{':'.$meta}=$metaentry{':'.$meta};
11052: $metathesekeys{$meta}=1;
1.339 albertel 11053: }
1.1068 www 11054:
11055: }
1.1067 www 11056: } else {
11057: #
11058: # Not importing, some other kind of non-package, non-library start tag
11059: #
11060: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
11061: if (defined($token->[2]->{'id'})) {
11062: $unikey.='_'.$token->[2]->{'id'};
11063: }
1.339 albertel 11064: if (defined($token->[2]->{'name'})) {
11065: $unikey.='_'.$token->[2]->{'name'};
11066: }
11067: $metathesekeys{$unikey}=1;
1.736 albertel 11068: foreach my $param (@{$token->[3]}) {
11069: $metaentry{':'.$unikey.'.'.$param} =
11070: $token->[2]->{$param};
1.339 albertel 11071: }
11072: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 11073: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 11074: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
11075: # only ws inside the tag, and not in default, so use default
11076: # as value
1.599 albertel 11077: $metaentry{':'.$unikey}=$default;
1.908 albertel 11078: } elsif ( $internaltext =~ /\S/ ) {
11079: # something interesting inside the tag
11080: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 11081: } else {
1.908 albertel 11082: # no interesting values, don't set a default
1.339 albertel 11083: }
1.172 www 11084: # end of not-a-package not-a-library import
1.339 albertel 11085: }
1.172 www 11086: # end of not-a-package start tag
1.339 albertel 11087: }
1.172 www 11088: # the next is the end of "start tag"
1.339 albertel 11089: }
11090: }
1.483 albertel 11091: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 11092: $extension = lc($extension);
11093: if ($extension eq 'htm') { $extension='html'; }
11094:
1.737 albertel 11095: foreach my $key (keys(%packagetab)) {
1.483 albertel 11096: #no specific packages #how's our extension
11097: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 11098: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 11099: \%metathesekeys);
11100: }
1.883 albertel 11101:
11102: if (!exists($metaentry{':packages'})
11103: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 11104: foreach my $key (keys(%packagetab)) {
1.483 albertel 11105: #no specific packages well let's get default then
11106: if ($key!~/^default&/) { next; }
1.488 albertel 11107: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 11108: \%metathesekeys);
11109: }
11110: }
1.338 www 11111: # are there custom rights to evaluate
1.599 albertel 11112: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 11113:
1.338 www 11114: #
11115: # Importing a rights file here
1.339 albertel 11116: #
11117: unless ($depthcount) {
1.599 albertel 11118: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 11119: my $dir=$filename;
11120: $dir=~s|[^/]*$||;
11121: $location=&filelocation($dir,$location);
1.736 albertel 11122: my $rights_metadata =
11123: &metadata($uri,'keys',$location,'_rights',
11124: $depthcount+1);
11125: foreach my $rights (split(',',$rights_metadata)) {
11126: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
11127: $metathesekeys{$rights}=1;
1.339 albertel 11128: }
11129: }
11130: }
1.737 albertel 11131: # uniqifiy package listing
11132: my %seen;
11133: my @uniq_packages =
11134: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
11135: $metaentry{':packages'} = join(',',@uniq_packages);
11136:
1.1070 www 11137: if ($importedparts) {
11138: # We had imported parts and need to rebuild partorder
11139: $metaentry{':partorder'}='';
11140: $metathesekeys{'partorder'}=1;
11141: for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
11142: if ($origfileimportpartids[$index] eq 'part') {
11143: # original part, part of the problem
11144: $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
11145: } else {
11146: # we have imported parts at this position
11147: $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
11148: }
11149: }
11150: $metaentry{':partorder'}=~s/^\,//;
11151: }
11152:
1.737 albertel 11153: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 11154: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1274 raeburn 11155: $metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924 albertel 11156: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 11157: # this is the end of "was not already recently cached
1.71 www 11158: }
1.599 albertel 11159: return $metaentry{':'.$what};
1.261 albertel 11160: }
11161:
1.488 albertel 11162: sub metadata_create_package_def {
1.483 albertel 11163: my ($uri,$key,$package,$metathesekeys)=@_;
11164: my ($pack,$name,$subp)=split(/\&/,$key);
11165: if ($subp eq 'default') { next; }
11166:
1.599 albertel 11167: if (defined($metaentry{':packages'})) {
11168: $metaentry{':packages'}.=','.$package;
1.483 albertel 11169: } else {
1.599 albertel 11170: $metaentry{':packages'}=$package;
1.483 albertel 11171: }
11172: my $value=$packagetab{$key};
11173: my $unikey;
11174: $unikey='parameter_0_'.$name;
1.599 albertel 11175: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 11176: $$metathesekeys{$unikey}=1;
1.599 albertel 11177: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
11178: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 11179: }
1.599 albertel 11180: if (defined($metaentry{':'.$unikey.'.default'})) {
11181: $metaentry{':'.$unikey}=
11182: $metaentry{':'.$unikey.'.default'};
1.483 albertel 11183: }
11184: }
11185:
1.261 albertel 11186: sub metadata_generate_part0 {
11187: my ($metadata,$metacache,$uri) = @_;
11188: my %allnames;
1.737 albertel 11189: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 11190: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 11191: my $part=$$metacache{':'.$metakey.'.part'};
11192: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 11193: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 11194: $allnames{$name}=$part;
11195: }
11196: }
11197: }
11198: foreach my $name (keys(%allnames)) {
11199: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 11200: my $key=":parameter_0_$name";
1.261 albertel 11201: $$metacache{"$key.part"}='0';
11202: $$metacache{"$key.name"}=$name;
1.428 albertel 11203: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 11204: $allnames{$name}.'_'.$name.
11205: '.type'};
1.428 albertel 11206: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 11207: '.display'};
1.644 www 11208: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 11209: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 11210: $$metacache{"$key.display"}=$olddis;
11211: }
1.71 www 11212: }
11213:
1.764 albertel 11214: # ------------------------------------------------------ Devalidate title cache
11215:
11216: sub devalidate_title_cache {
11217: my ($url)=@_;
11218: if (!$env{'request.course.id'}) { return; }
11219: my $symb=&symbread($url);
11220: if (!$symb) { return; }
11221: my $key=$env{'request.course.id'}."\0".$symb;
11222: &devalidate_cache_new('title',$key);
11223: }
11224:
1.1014 droeschl 11225: # ------------------------------------------------- Get the title of a course
11226:
11227: sub current_course_title {
11228: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
11229: }
1.301 www 11230: # ------------------------------------------------- Get the title of a resource
11231:
11232: sub gettitle {
11233: my $urlsymb=shift;
11234: my $symb=&symbread($urlsymb);
1.534 albertel 11235: if ($symb) {
1.620 albertel 11236: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 11237: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 11238: if (defined($cached)) {
11239: return $result;
11240: }
1.534 albertel 11241: my ($map,$resid,$url)=&decode_symb($symb);
11242: my $title='';
1.907 albertel 11243: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
11244: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
11245: } else {
11246: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11247: &GDBM_READER(),0640)) {
11248: my $mapid=$bighash{'map_pc_'.&clutter($map)};
11249: $title=$bighash{'title_'.$mapid.'.'.$resid};
11250: untie(%bighash);
11251: }
1.534 albertel 11252: }
11253: $title=~s/\&colon\;/\:/gs;
11254: if ($title) {
1.1159 www 11255: # Remember both $symb and $title for dynamic metadata
11256: $accesshash{$symb.'___crstitle'}=$title;
1.1161 www 11257: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159 www 11258: # Cache this title and then return it
1.599 albertel 11259: return &do_cache_new('title',$key,$title,600);
1.534 albertel 11260: }
11261: $urlsymb=$url;
11262: }
11263: my $title=&metadata($urlsymb,'title');
11264: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
11265: return $title;
1.301 www 11266: }
1.613 albertel 11267:
1.614 albertel 11268: sub get_slot {
11269: my ($which,$cnum,$cdom)=@_;
11270: if (!$cnum || !$cdom) {
1.790 albertel 11271: (undef,my $courseid)=&whichuser();
1.620 albertel 11272: $cdom=$env{'course.'.$courseid.'.domain'};
11273: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 11274: }
1.703 albertel 11275: my $key=join("\0",'slots',$cdom,$cnum,$which);
11276: my %slotinfo;
11277: if (exists($remembered{$key})) {
11278: $slotinfo{$which} = $remembered{$key};
11279: } else {
11280: %slotinfo=&get('slots',[$which],$cdom,$cnum);
11281: &Apache::lonhomework::showhash(%slotinfo);
11282: my ($tmp)=keys(%slotinfo);
11283: if ($tmp=~/^error:/) { return (); }
11284: $remembered{$key} = $slotinfo{$which};
11285: }
1.616 albertel 11286: if (ref($slotinfo{$which}) eq 'HASH') {
11287: return %{$slotinfo{$which}};
11288: }
11289: return $slotinfo{$which};
1.614 albertel 11290: }
1.1150 raeburn 11291:
11292: sub get_reservable_slots {
11293: my ($cnum,$cdom,$uname,$udom) = @_;
11294: my $now = time;
11295: my $reservable_info;
11296: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
11297: if (exists($remembered{$key})) {
11298: $reservable_info = $remembered{$key};
11299: } else {
11300: my %resv;
11301: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
11302: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
11303: $reservable_info = \%resv;
11304: $remembered{$key} = $reservable_info;
11305: }
11306: return $reservable_info;
11307: }
11308:
11309: sub get_course_slots {
11310: my ($cnum,$cdom) = @_;
11311: my $hashid=$cnum.':'.$cdom;
11312: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
11313: if (defined($cached)) {
11314: if (ref($result) eq 'HASH') {
11315: return %{$result};
11316: }
11317: } else {
11318: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
11319: my ($tmp) = keys(%slots);
11320: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1219 raeburn 11321: &do_cache_new('allslots',$hashid,\%slots,600);
1.1150 raeburn 11322: return %slots;
11323: }
11324: }
11325: return;
11326: }
11327:
11328: sub devalidate_slots_cache {
11329: my ($cnum,$cdom)=@_;
11330: my $hashid=$cnum.':'.$cdom;
11331: &devalidate_cache_new('allslots',$hashid);
11332: }
11333:
1.1181 raeburn 11334: sub get_coursechange {
11335: my ($cdom,$cnum) = @_;
11336: if ($cdom eq '' || $cnum eq '') {
11337: return unless ($env{'request.course.id'});
11338: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
11339: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
11340: }
11341: my $hashid=$cdom.'_'.$cnum;
11342: my ($change,$cached)=&is_cached_new('crschange',$hashid);
11343: if ((defined($cached)) && ($change ne '')) {
11344: return $change;
11345: } else {
11346: my %crshash;
11347: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
11348: if ($crshash{'internal.contentchange'} eq '') {
11349: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
11350: if ($change eq '') {
11351: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
11352: $change = $crshash{'internal.created'};
11353: }
11354: } else {
11355: $change = $crshash{'internal.contentchange'};
11356: }
11357: my $cachetime = 600;
11358: &do_cache_new('crschange',$hashid,$change,$cachetime);
11359: }
11360: return $change;
11361: }
11362:
11363: sub devalidate_coursechange_cache {
11364: my ($cnum,$cdom)=@_;
11365: my $hashid=$cnum.':'.$cdom;
11366: &devalidate_cache_new('crschange',$hashid);
11367: }
11368:
1.31 www 11369: # ------------------------------------------------- Update symbolic store links
11370:
11371: sub symblist {
11372: my ($mapname,%newhash)=@_;
1.438 www 11373: $mapname=&deversion(&declutter($mapname));
1.31 www 11374: my %hash;
1.620 albertel 11375: if (($env{'request.course.fn'}) && (%newhash)) {
11376: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 11377: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 11378: foreach my $url (keys(%newhash)) {
1.711 albertel 11379: next if ($url eq 'last_known'
11380: && $env{'form.no_update_last_known'});
11381: $hash{declutter($url)}=&encode_symb($mapname,
11382: $newhash{$url}->[1],
11383: $newhash{$url}->[0]);
1.191 harris41 11384: }
1.31 www 11385: if (untie(%hash)) {
11386: return 'ok';
11387: }
11388: }
11389: }
11390: return 'error';
1.212 www 11391: }
11392:
11393: # --------------------------------------------------------------- Verify a symb
11394:
11395: sub symbverify {
1.1190 raeburn 11396: my ($symb,$thisurl,$encstate)=@_;
1.510 www 11397: my $thisfn=$thisurl;
1.439 www 11398: $thisfn=&declutter($thisfn);
1.215 www 11399: # direct jump to resource in page or to a sequence - will construct own symbs
11400: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
11401: # check URL part
1.409 www 11402: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 11403:
1.431 www 11404: unless ($url eq $thisfn) { return 0; }
1.213 www 11405:
1.216 www 11406: $symb=&symbclean($symb);
1.510 www 11407: $thisurl=&deversion($thisurl);
1.439 www 11408: $thisfn=&deversion($thisfn);
1.213 www 11409:
11410: my %bighash;
11411: my $okay=0;
1.431 www 11412:
1.620 albertel 11413: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 11414: &GDBM_READER(),0640)) {
1.1204 raeburn 11415: my $noclutter;
1.1032 raeburn 11416: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
11417: $thisurl =~ s/\?.+$//;
1.1204 raeburn 11418: if ($map =~ m{^uploaded/.+\.page$}) {
11419: $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
11420: $thisurl =~ s{^\Qhttp://https://\E}{https://};
11421: $noclutter = 1;
11422: }
11423: }
11424: my $ids;
11425: if ($noclutter) {
11426: $ids=$bighash{'ids_'.$thisurl};
11427: } else {
11428: $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032 raeburn 11429: }
1.1102 raeburn 11430: unless ($ids) {
11431: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
11432: $ids=$bighash{$idkey};
1.216 www 11433: }
11434: if ($ids) {
11435: # ------------------------------------------------------------------- Has ID(s)
1.1202 raeburn 11436: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
1.1203 raeburn 11437: $symb =~ s/\?.+$//;
1.1202 raeburn 11438: }
1.800 albertel 11439: foreach my $id (split(/\,/,$ids)) {
11440: my ($mapid,$resid)=split(/\./,$id);
1.216 www 11441: if (
11442: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190 raeburn 11443: eq $symb) {
11444: if (ref($encstate)) {
11445: $$encstate = $bighash{'encrypted_'.$id};
11446: }
1.620 albertel 11447: if (($env{'request.role.adv'}) ||
1.1101 raeburn 11448: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
11449: ($thisurl eq '/adm/navmaps')) {
1.1190 raeburn 11450: $okay=1;
1.1202 raeburn 11451: last;
1.582 albertel 11452: }
11453: }
1.216 www 11454: }
11455: }
1.213 www 11456: untie(%bighash);
11457: }
11458: return $okay;
1.31 www 11459: }
11460:
1.210 www 11461: # --------------------------------------------------------------- Clean-up symb
11462:
11463: sub symbclean {
11464: my $symb=shift;
1.568 albertel 11465: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 11466: # remove version from map
11467: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 11468:
1.210 www 11469: # remove version from URL
11470: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 11471:
1.507 www 11472: # remove wrapper
11473:
1.510 www 11474: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 11475: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 11476: return $symb;
1.409 www 11477: }
11478:
11479: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 11480:
11481: sub encode_symb {
11482: my ($map,$resid,$url)=@_;
11483: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
11484: }
1.409 www 11485:
11486: sub decode_symb {
1.568 albertel 11487: my $symb=shift;
11488: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
11489: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 11490: return (&fixversion($map),$resid,&fixversion($url));
11491: }
11492:
11493: sub fixversion {
11494: my $fn=shift;
1.609 banghart 11495: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 11496: my %bighash;
11497: my $uri=&clutter($fn);
1.620 albertel 11498: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 11499: # is this cached?
1.599 albertel 11500: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 11501: if (defined($cached)) { return $result; }
11502: # unfortunately not cached, or expired
1.620 albertel 11503: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 11504: &GDBM_READER(),0640)) {
11505: if ($bighash{'version_'.$uri}) {
11506: my $version=$bighash{'version_'.$uri};
1.444 www 11507: unless (($version eq 'mostrecent') ||
11508: ($version==&getversion($uri))) {
1.440 www 11509: $uri=~s/\.(\w+)$/\.$version\.$1/;
11510: }
11511: }
11512: untie %bighash;
1.413 www 11513: }
1.599 albertel 11514: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 11515: }
11516:
11517: sub deversion {
11518: my $url=shift;
11519: $url=~s/\.\d+\.(\w+)$/\.$1/;
11520: return $url;
1.210 www 11521: }
11522:
1.31 www 11523: # ------------------------------------------------------ Return symb list entry
11524:
11525: sub symbread {
1.1282 raeburn 11526: my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
1.1265 raeburn 11527: my $cache_str='request.symbread.cached.'.$thisfn;
1.1282 raeburn 11528: if (defined($env{$cache_str})) {
11529: if ($ignorecachednull) {
11530: return $env{$cache_str} unless ($env{$cache_str} eq '');
11531: } else {
11532: return $env{$cache_str};
11533: }
11534: }
1.242 www 11535: # no filename provided? try from environment
1.1265 raeburn 11536: unless ($thisfn) {
1.620 albertel 11537: if ($env{'request.symb'}) {
11538: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 11539: }
1.620 albertel 11540: $thisfn=$env{'request.filename'};
1.44 www 11541: }
1.569 albertel 11542: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 11543: # is that filename actually a symb? Verify, clean, and return
11544: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 11545: if (&symbverify($thisfn,$1)) {
1.620 albertel 11546: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 11547: }
1.242 www 11548: }
1.44 www 11549: $thisfn=declutter($thisfn);
1.31 www 11550: my %hash;
1.37 www 11551: my %bighash;
11552: my $syval='';
1.620 albertel 11553: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 11554: my $targetfn = $thisfn;
1.609 banghart 11555: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 11556: $targetfn = 'adm/wrapper/'.$thisfn;
11557: }
1.687 albertel 11558: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
11559: $targetfn=$1;
11560: }
1.620 albertel 11561: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 11562: &GDBM_READER(),0640)) {
1.481 raeburn 11563: $syval=$hash{$targetfn};
1.37 www 11564: untie(%hash);
11565: }
11566: # ---------------------------------------------------------- There was an entry
11567: if ($syval) {
1.601 albertel 11568: #unless ($syval=~/\_\d+$/) {
1.620 albertel 11569: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 11570: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 11571: #return $env{$cache_str}='';
1.601 albertel 11572: #}
11573: #$syval.=$1;
11574: #}
1.37 www 11575: } else {
11576: # ------------------------------------------------------- Was not in symb table
1.620 albertel 11577: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 11578: &GDBM_READER(),0640)) {
1.37 www 11579: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 11580: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 11581: unless ($ids) {
11582: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 11583: }
11584: unless ($ids) {
11585: # alias?
11586: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 11587: }
1.37 www 11588: if ($ids) {
11589: # ------------------------------------------------------------------- Has ID(s)
11590: my @possibilities=split(/\,/,$ids);
1.39 www 11591: if ($#possibilities==0) {
11592: # ----------------------------------------------- There is only one possibility
1.37 www 11593: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 11594: $syval=&encode_symb($bighash{'map_id_'.$mapid},
11595: $resid,$thisfn);
1.1282 raeburn 11596: if (ref($possibles) eq 'HASH') {
11597: $possibles->{$syval} = 1;
11598: }
11599: if ($checkforblock) {
11600: my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
11601: if (@blockers) {
11602: $syval = '';
11603: return;
11604: }
11605: }
11606: } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39 www 11607: # ------------------------------------------ There is more than one possibility
11608: my $realpossible=0;
1.800 albertel 11609: foreach my $id (@possibilities) {
11610: my $file=$bighash{'src_'.$id};
1.1282 raeburn 11611: my $canaccess;
11612: if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
11613: $canaccess = 1;
11614: } else {
11615: $canaccess = &allowed('bre',$file);
11616: }
11617: if ($canaccess) {
11618: my ($mapid,$resid)=split(/\./,$id);
11619: if ($bighash{'map_type_'.$mapid} ne 'page') {
11620: my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
11621: $resid,$thisfn);
11622: if (ref($possibles) eq 'HASH') {
11623: $possibles->{$syval} = 1;
11624: }
11625: if ($checkforblock) {
11626: my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
11627: unless (@blockers > 0) {
11628: $syval = $poss_syval;
11629: $realpossible++;
11630: }
11631: } else {
11632: $syval = $poss_syval;
11633: $realpossible++;
11634: }
11635: }
1.39 www 11636: }
1.191 harris41 11637: }
1.39 www 11638: if ($realpossible!=1) { $syval=''; }
1.249 www 11639: } else {
11640: $syval='';
1.37 www 11641: }
11642: }
1.1282 raeburn 11643: untie(%bighash);
1.481 raeburn 11644: }
1.31 www 11645: }
1.62 www 11646: if ($syval) {
1.620 albertel 11647: return $env{$cache_str}=$syval;
1.62 www 11648: }
1.31 www 11649: }
1.949 raeburn 11650: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 11651: return $env{$cache_str}='';
1.31 www 11652: }
11653:
11654: # ---------------------------------------------------------- Return random seed
11655:
1.32 www 11656: sub numval {
11657: my $txt=shift;
11658: $txt=~tr/A-J/0-9/;
11659: $txt=~tr/a-j/0-9/;
11660: $txt=~tr/K-T/0-9/;
11661: $txt=~tr/k-t/0-9/;
11662: $txt=~tr/U-Z/0-5/;
11663: $txt=~tr/u-z/0-5/;
11664: $txt=~s/\D//g;
1.564 albertel 11665: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 11666: return int($txt);
1.368 albertel 11667: }
11668:
1.484 albertel 11669: sub numval2 {
11670: my $txt=shift;
11671: $txt=~tr/A-J/0-9/;
11672: $txt=~tr/a-j/0-9/;
11673: $txt=~tr/K-T/0-9/;
11674: $txt=~tr/k-t/0-9/;
11675: $txt=~tr/U-Z/0-5/;
11676: $txt=~tr/u-z/0-5/;
11677: $txt=~s/\D//g;
11678: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
11679: my $total;
11680: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 11681: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 11682: return int($total);
11683: }
11684:
1.575 albertel 11685: sub numval3 {
11686: use integer;
11687: my $txt=shift;
11688: $txt=~tr/A-J/0-9/;
11689: $txt=~tr/a-j/0-9/;
11690: $txt=~tr/K-T/0-9/;
11691: $txt=~tr/k-t/0-9/;
11692: $txt=~tr/U-Z/0-5/;
11693: $txt=~tr/u-z/0-5/;
11694: $txt=~s/\D//g;
11695: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
11696: my $total;
11697: foreach my $val (@txts) { $total+=$val; }
11698: if ($_64bit) { $total=(($total<<32)>>32); }
11699: return $total;
11700: }
11701:
1.675 albertel 11702: sub digest {
11703: my ($data)=@_;
11704: my $digest=&Digest::MD5::md5($data);
11705: my ($a,$b,$c,$d)=unpack("iiii",$digest);
11706: my ($e,$f);
11707: {
11708: use integer;
11709: $e=($a+$b);
11710: $f=($c+$d);
11711: if ($_64bit) {
11712: $e=(($e<<32)>>32);
11713: $f=(($f<<32)>>32);
11714: }
11715: }
11716: if (wantarray) {
11717: return ($e,$f);
11718: } else {
11719: my $g;
11720: {
11721: use integer;
11722: $g=($e+$f);
11723: if ($_64bit) {
11724: $g=(($g<<32)>>32);
11725: }
11726: }
11727: return $g;
11728: }
11729: }
11730:
1.368 albertel 11731: sub latest_rnd_algorithm_id {
1.675 albertel 11732: return '64bit5';
1.366 albertel 11733: }
1.32 www 11734:
1.503 albertel 11735: sub get_rand_alg {
11736: my ($courseid)=@_;
1.790 albertel 11737: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 11738: if ($courseid) {
1.620 albertel 11739: return $env{"course.$courseid.rndseed"};
1.503 albertel 11740: }
11741: return &latest_rnd_algorithm_id();
11742: }
11743:
1.562 albertel 11744: sub validCODE {
11745: my ($CODE)=@_;
11746: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
11747: return 0;
11748: }
11749:
1.491 albertel 11750: sub getCODE {
1.620 albertel 11751: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 11752: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
11753: defined($Apache::lonhomework::parsing_a_task) ) &&
11754: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 11755: return $Apache::lonhomework::history{'resource.CODE'};
11756: }
11757: return undef;
11758: }
1.1133 foxr 11759: #
11760: # Determines the random seed for a specific context:
11761: #
11762: # parameters:
11763: # symb - in course context the symb for the seed.
11764: # course_id - The course id of the form domain_coursenum.
11765: # domain - Domain for the user.
11766: # course - Course for the user.
11767: # cenv - environment of the course.
11768: #
11769: # NOTE:
11770: # All parameters are picked out of the environment if missing
11771: # or not defined.
11772: # If a symb cannot be determined the current time is used instead.
11773: #
11774: # For a given well defined symb, courside, domain, username,
11775: # and course environment, the seed is reproducible.
11776: #
1.31 www 11777: sub rndseed {
1.1133 foxr 11778: my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790 albertel 11779: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 11780: if (!defined($symb)) {
1.366 albertel 11781: unless ($symb=$wsymb) { return time; }
11782: }
1.1146 foxr 11783: if (!defined $courseid) {
11784: $courseid=$wcourseid;
11785: }
11786: if (!defined $domain) { $domain=$wdomain; }
11787: if (!defined $username) { $username=$wusername }
1.1133 foxr 11788:
11789: my $which;
11790: if (defined($cenv->{'rndseed'})) {
11791: $which = $cenv->{'rndseed'};
11792: } else {
11793: $which =&get_rand_alg($courseid);
11794: }
1.491 albertel 11795: if (defined(&getCODE())) {
1.1133 foxr 11796:
1.675 albertel 11797: if ($which eq '64bit5') {
11798: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
11799: } elsif ($which eq '64bit4') {
1.575 albertel 11800: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
11801: } else {
11802: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
11803: }
1.675 albertel 11804: } elsif ($which eq '64bit5') {
11805: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 11806: } elsif ($which eq '64bit4') {
11807: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 11808: } elsif ($which eq '64bit3') {
11809: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 11810: } elsif ($which eq '64bit2') {
11811: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 11812: } elsif ($which eq '64bit') {
11813: return &rndseed_64bit($symb,$courseid,$domain,$username);
11814: }
11815: return &rndseed_32bit($symb,$courseid,$domain,$username);
11816: }
11817:
11818: sub rndseed_32bit {
11819: my ($symb,$courseid,$domain,$username)=@_;
11820: {
11821: use integer;
11822: my $symbchck=unpack("%32C*",$symb) << 27;
11823: my $symbseed=numval($symb) << 22;
11824: my $namechck=unpack("%32C*",$username) << 17;
11825: my $nameseed=numval($username) << 12;
11826: my $domainseed=unpack("%32C*",$domain) << 7;
11827: my $courseseed=unpack("%32C*",$courseid);
11828: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 11829: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11830: #&logthis("rndseed :$num:$symb");
1.564 albertel 11831: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 11832: return $num;
11833: }
11834: }
11835:
11836: sub rndseed_64bit {
11837: my ($symb,$courseid,$domain,$username)=@_;
11838: {
11839: use integer;
11840: my $symbchck=unpack("%32S*",$symb) << 21;
11841: my $symbseed=numval($symb) << 10;
11842: my $namechck=unpack("%32S*",$username);
11843:
11844: my $nameseed=numval($username) << 21;
11845: my $domainseed=unpack("%32S*",$domain) << 10;
11846: my $courseseed=unpack("%32S*",$courseid);
11847:
11848: my $num1=$symbchck+$symbseed+$namechck;
11849: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11850: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11851: #&logthis("rndseed :$num:$symb");
1.564 albertel 11852: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 11853: return "$num1,$num2";
1.155 albertel 11854: }
1.366 albertel 11855: }
11856:
1.443 albertel 11857: sub rndseed_64bit2 {
11858: my ($symb,$courseid,$domain,$username)=@_;
11859: {
11860: use integer;
11861: # strings need to be an even # of cahracters long, it it is odd the
11862: # last characters gets thrown away
11863: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11864: my $symbseed=numval($symb) << 10;
11865: my $namechck=unpack("%32S*",$username.' ');
11866:
11867: my $nameseed=numval($username) << 21;
1.501 albertel 11868: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11869: my $courseseed=unpack("%32S*",$courseid.' ');
11870:
11871: my $num1=$symbchck+$symbseed+$namechck;
11872: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11873: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11874: #&logthis("rndseed :$num:$symb");
1.803 albertel 11875: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 11876: return "$num1,$num2";
11877: }
11878: }
11879:
11880: sub rndseed_64bit3 {
11881: my ($symb,$courseid,$domain,$username)=@_;
11882: {
11883: use integer;
11884: # strings need to be an even # of cahracters long, it it is odd the
11885: # last characters gets thrown away
11886: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11887: my $symbseed=numval2($symb) << 10;
11888: my $namechck=unpack("%32S*",$username.' ');
11889:
11890: my $nameseed=numval2($username) << 21;
1.443 albertel 11891: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11892: my $courseseed=unpack("%32S*",$courseid.' ');
11893:
11894: my $num1=$symbchck+$symbseed+$namechck;
11895: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11896: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11897: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 11898: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 11899:
1.503 albertel 11900: return "$num1:$num2";
1.443 albertel 11901: }
11902: }
11903:
1.575 albertel 11904: sub rndseed_64bit4 {
11905: my ($symb,$courseid,$domain,$username)=@_;
11906: {
11907: use integer;
11908: # strings need to be an even # of cahracters long, it it is odd the
11909: # last characters gets thrown away
11910: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11911: my $symbseed=numval3($symb) << 10;
11912: my $namechck=unpack("%32S*",$username.' ');
11913:
11914: my $nameseed=numval3($username) << 21;
11915: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11916: my $courseseed=unpack("%32S*",$courseid.' ');
11917:
11918: my $num1=$symbchck+$symbseed+$namechck;
11919: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11920: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11921: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 11922: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 11923:
1.575 albertel 11924: return "$num1:$num2";
11925: }
11926: }
11927:
1.675 albertel 11928: sub rndseed_64bit5 {
11929: my ($symb,$courseid,$domain,$username)=@_;
11930: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
11931: return "$num1:$num2";
11932: }
11933:
1.366 albertel 11934: sub rndseed_CODE_64bit {
11935: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 11936: {
1.366 albertel 11937: use integer;
1.443 albertel 11938: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 11939: my $symbseed=numval2($symb);
1.491 albertel 11940: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11941: my $CODEseed=numval(&getCODE());
1.443 albertel 11942: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 11943: my $num1=$symbseed+$CODEchck;
11944: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 11945: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11946: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 11947: if ($_64bit) { $num1=(($num1<<32)>>32); }
11948: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 11949: return "$num1:$num2";
1.366 albertel 11950: }
11951: }
11952:
1.575 albertel 11953: sub rndseed_CODE_64bit4 {
11954: my ($symb,$courseid,$domain,$username)=@_;
11955: {
11956: use integer;
11957: my $symbchck=unpack("%32S*",$symb.' ') << 16;
11958: my $symbseed=numval3($symb);
11959: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11960: my $CODEseed=numval3(&getCODE());
11961: my $courseseed=unpack("%32S*",$courseid.' ');
11962: my $num1=$symbseed+$CODEchck;
11963: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 11964: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11965: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 11966: if ($_64bit) { $num1=(($num1<<32)>>32); }
11967: if ($_64bit) { $num2=(($num2<<32)>>32); }
11968: return "$num1:$num2";
11969: }
11970: }
11971:
1.675 albertel 11972: sub rndseed_CODE_64bit5 {
11973: my ($symb,$courseid,$domain,$username)=@_;
11974: my $code = &getCODE();
11975: my ($num1,$num2)=&digest("$symb,$courseid,$code");
11976: return "$num1:$num2";
11977: }
11978:
1.366 albertel 11979: sub setup_random_from_rndseed {
11980: my ($rndseed)=@_;
1.503 albertel 11981: if ($rndseed =~/([,:])/) {
1.1262 raeburn 11982: my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
11983: if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
11984: &Math::Random::random_set_seed_from_phrase($rndseed);
11985: } else {
11986: &Math::Random::random_set_seed($num1,$num2);
11987: }
1.366 albertel 11988: } else {
11989: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 11990: }
1.36 albertel 11991: }
11992:
1.474 albertel 11993: sub latest_receipt_algorithm_id {
1.835 albertel 11994: return 'receipt3';
1.474 albertel 11995: }
11996:
1.480 www 11997: sub recunique {
11998: my $fucourseid=shift;
11999: my $unique;
1.835 albertel 12000: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
12001: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 12002: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 12003: } else {
12004: $unique=$perlvar{'lonReceipt'};
12005: }
12006: return unpack("%32C*",$unique);
12007: }
12008:
12009: sub recprefix {
12010: my $fucourseid=shift;
12011: my $prefix;
1.835 albertel 12012: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
12013: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 12014: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 12015: } else {
12016: $prefix=$perlvar{'lonHostID'};
12017: }
12018: return unpack("%32C*",$prefix);
12019: }
12020:
1.76 www 12021: sub ireceipt {
1.474 albertel 12022: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 12023:
12024: my $return =&recprefix($fucourseid).'-';
12025:
12026: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
12027: $env{'request.state'} eq 'construct') {
12028: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
12029: return $return;
12030: }
12031:
1.76 www 12032: my $cuname=unpack("%32C*",$funame);
12033: my $cudom=unpack("%32C*",$fudom);
12034: my $cucourseid=unpack("%32C*",$fucourseid);
12035: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 12036: my $cunique=&recunique($fucourseid);
1.474 albertel 12037: my $cpart=unpack("%32S*",$part);
1.835 albertel 12038: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
12039:
1.790 albertel 12040: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 12041:
12042: $return.= ($cunique%$cuname+
12043: $cunique%$cudom+
12044: $cusymb%$cuname+
12045: $cusymb%$cudom+
12046: $cucourseid%$cuname+
12047: $cucourseid%$cudom+
12048: $cpart%$cuname+
12049: $cpart%$cudom);
12050: } else {
12051: $return.= ($cunique%$cuname+
12052: $cunique%$cudom+
12053: $cusymb%$cuname+
12054: $cusymb%$cudom+
12055: $cucourseid%$cuname+
12056: $cucourseid%$cudom);
12057: }
12058: return $return;
1.76 www 12059: }
12060:
12061: sub receipt {
1.474 albertel 12062: my ($part)=@_;
1.790 albertel 12063: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 12064: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 12065: }
1.260 ng 12066:
1.790 albertel 12067: sub whichuser {
12068: my ($passedsymb)=@_;
12069: my ($symb,$courseid,$domain,$name,$publicuser);
12070: if (defined($env{'form.grade_symb'})) {
12071: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
12072: my $allowed=&allowed('vgr',$tmp_courseid);
12073: if (!$allowed &&
12074: exists($env{'request.course.sec'}) &&
12075: $env{'request.course.sec'} !~ /^\s*$/) {
12076: $allowed=&allowed('vgr',$tmp_courseid.
12077: '/'.$env{'request.course.sec'});
12078: }
12079: if ($allowed) {
12080: ($symb)=&get_env_multiple('form.grade_symb');
12081: $courseid=$tmp_courseid;
12082: ($domain)=&get_env_multiple('form.grade_domain');
12083: ($name)=&get_env_multiple('form.grade_username');
12084: return ($symb,$courseid,$domain,$name,$publicuser);
12085: }
12086: }
12087: if (!$passedsymb) {
12088: $symb=&symbread();
12089: } else {
12090: $symb=$passedsymb;
12091: }
12092: $courseid=$env{'request.course.id'};
12093: $domain=$env{'user.domain'};
12094: $name=$env{'user.name'};
12095: if ($name eq 'public' && $domain eq 'public') {
12096: if (!defined($env{'form.username'})) {
12097: $env{'form.username'}.=time.rand(10000000);
12098: }
12099: $name.=$env{'form.username'};
12100: }
12101: return ($symb,$courseid,$domain,$name,$publicuser);
12102:
12103: }
12104:
1.36 albertel 12105: # ------------------------------------------------------------ Serves up a file
1.472 albertel 12106: # returns either the contents of the file or
12107: # -1 if the file doesn't exist
1.481 raeburn 12108: #
12109: # if the target is a file that was uploaded via DOCS,
12110: # a check will be made to see if a current copy exists on the local server,
12111: # if it does this will be served, otherwise a copy will be retrieved from
12112: # the home server for the course and stored in /home/httpd/html/userfiles on
12113: # the local server.
1.472 albertel 12114:
1.36 albertel 12115: sub getfile {
1.538 albertel 12116: my ($file) = @_;
1.609 banghart 12117: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 12118: &repcopy($file);
12119: return &readfile($file);
12120: }
12121:
12122: sub repcopy_userfile {
12123: my ($file)=@_;
1.1142 raeburn 12124: my $londocroot = $perlvar{'lonDocRoot'};
12125: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164 raeburn 12126: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538 albertel 12127: my ($cdom,$cnum,$filename) =
1.811 albertel 12128: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 12129: my $uri="/uploaded/$cdom/$cnum/$filename";
12130: if (-e "$file") {
1.828 www 12131: # we already have a local copy, check it out
1.538 albertel 12132: my @fileinfo = stat($file);
1.828 www 12133: my $rtncode;
12134: my $info;
1.538 albertel 12135: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 12136: if ($lwpresp ne 'ok') {
1.828 www 12137: # there is no such file anymore, even though we had a local copy
1.482 albertel 12138: if ($rtncode eq '404') {
1.538 albertel 12139: unlink($file);
1.482 albertel 12140: }
12141: return -1;
12142: }
12143: if ($info < $fileinfo[9]) {
1.828 www 12144: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 12145: return 'ok';
1.828 www 12146: } else {
12147: # the file is outdated, get rid of it
12148: unlink($file);
1.482 albertel 12149: }
1.828 www 12150: }
12151: # one way or the other, at this point, we don't have the file
12152: # construct the correct path for the file
12153: my @parts = ($cdom,$cnum);
12154: if ($filename =~ m|^(.+)/[^/]+$|) {
12155: push @parts, split(/\//,$1);
12156: }
12157: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
12158: foreach my $part (@parts) {
12159: $path .= '/'.$part;
12160: if (!-e $path) {
12161: mkdir($path,0770);
1.482 albertel 12162: }
12163: }
1.828 www 12164: # now the path exists for sure
12165: # get a user agent
12166: my $ua=new LWP::UserAgent;
12167: my $transferfile=$file.'.in.transfer';
12168: # FIXME: this should flock
12169: if (-e $transferfile) { return 'ok'; }
12170: my $request;
12171: $uri=~s/^\///;
1.980 raeburn 12172: my $homeserver = &homeserver($cnum,$cdom);
12173: my $protocol = $protocol{$homeserver};
12174: $protocol = 'http' if ($protocol ne 'https');
12175: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 12176: my $response=$ua->request($request,$transferfile);
12177: # did it work?
12178: if ($response->is_error()) {
12179: unlink($transferfile);
12180: &logthis("Userfile repcopy failed for $uri");
12181: return -1;
12182: }
12183: # worked, rename the transfer file
12184: rename($transferfile,$file);
1.607 raeburn 12185: return 'ok';
1.481 raeburn 12186: }
12187:
1.517 albertel 12188: sub tokenwrapper {
12189: my $uri=shift;
1.980 raeburn 12190: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 12191: $uri=~s|^/||;
1.620 albertel 12192: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 12193: my $token=$1;
1.552 albertel 12194: my (undef,$udom,$uname,$file)=split('/',$uri,4);
12195: if ($udom && $uname && $file) {
12196: $file=~s|(\?\.*)*$||;
1.949 raeburn 12197: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 12198: my $homeserver = &homeserver($uname,$udom);
12199: my $protocol = $protocol{$homeserver};
12200: $protocol = 'http' if ($protocol ne 'https');
12201: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 12202: (($uri=~/\?/)?'&':'?').'token='.$token.
12203: '&tokenissued='.$perlvar{'lonHostID'};
12204: } else {
12205: return '/adm/notfound.html';
12206: }
12207: }
12208:
1.828 www 12209: # call with reqtype HEAD: get last modification time
12210: # call with reqtype GET: get the file contents
12211: # Do not call this with reqtype GET for large files! It loads everything into memory
12212: #
1.481 raeburn 12213: sub getuploaded {
12214: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
12215: $uri=~s/^\///;
1.980 raeburn 12216: my $homeserver = &homeserver($cnum,$cdom);
12217: my $protocol = $protocol{$homeserver};
12218: $protocol = 'http' if ($protocol ne 'https');
12219: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 12220: my $ua=new LWP::UserAgent;
12221: my $request=new HTTP::Request($reqtype,$uri);
12222: my $response=$ua->request($request);
12223: $$rtncode = $response->code;
1.482 albertel 12224: if (! $response->is_success()) {
12225: return 'failed';
12226: }
12227: if ($reqtype eq 'HEAD') {
1.486 www 12228: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 12229: } elsif ($reqtype eq 'GET') {
12230: $$info = $response->content;
1.472 albertel 12231: }
1.482 albertel 12232: return 'ok';
1.36 albertel 12233: }
12234:
1.481 raeburn 12235: sub readfile {
12236: my $file = shift;
12237: if ( (! -e $file ) || ($file eq '') ) { return -1; };
12238: my $fh;
12239: open($fh,"<$file");
12240: my $a='';
1.800 albertel 12241: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 12242: return $a;
12243: }
12244:
1.36 albertel 12245: sub filelocation {
1.590 banghart 12246: my ($dir,$file) = @_;
12247: my $location;
12248: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 12249:
12250: if ($file =~ m-^/adm/-) {
12251: $file=~s-^/adm/wrapper/-/-;
12252: $file=~s-^/adm/coursedocs/showdoc/-/-;
12253: }
1.882 albertel 12254:
1.1139 www 12255: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956 raeburn 12256: $location = $file;
1.609 banghart 12257: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 12258: my ($udom,$uname,$filename)=
1.811 albertel 12259: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 12260: my $home=&homeserver($uname,$udom);
12261: my $is_me=0;
12262: my @ids=¤t_machine_ids();
12263: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
12264: if ($is_me) {
1.1117 foxr 12265: $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 12266: } else {
12267: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
12268: $udom.'/'.$uname.'/'.$filename;
12269: }
1.882 albertel 12270: } elsif ($file =~ m-^/adm/-) {
12271: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 12272: } else {
12273: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139 www 12274: $file=~s:^/(res|priv)/:/:;
12275: my $space=$1;
1.590 banghart 12276: if ( !( $file =~ m:^/:) ) {
12277: $location = $dir. '/'.$file;
12278: } else {
1.1142 raeburn 12279: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590 banghart 12280: }
1.59 albertel 12281: }
1.590 banghart 12282: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 12283: while ($location=~m{/\.\./}) {
12284: if ($location =~ m{/[^/]+/\.\./}) {
12285: $location=~ s{/[^/]+/\.\./}{/}g;
12286: } else {
12287: $location=~ s{/\.\./}{/}g;
12288: }
12289: } #remove dir/..
1.590 banghart 12290: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
12291: return $location;
1.46 www 12292: }
1.36 albertel 12293:
1.46 www 12294: sub hreflocation {
12295: my ($dir,$file)=@_;
1.980 raeburn 12296: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 12297: $file=filelocation($dir,$file);
1.700 albertel 12298: } elsif ($file=~m-^/adm/-) {
12299: $file=~s-^/adm/wrapper/-/-;
12300: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 12301: }
12302: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
12303: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
12304: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143 raeburn 12305: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
12306: {/uploaded/$1/$2/}x;
1.46 www 12307: }
1.913 albertel 12308: if ($file=~ m{^/userfiles/}) {
12309: $file =~ s{^/userfiles/}{/uploaded/};
12310: }
1.462 albertel 12311: return $file;
1.465 albertel 12312: }
12313:
1.1139 www 12314:
12315:
12316:
12317:
1.465 albertel 12318: sub current_machine_domains {
1.853 albertel 12319: return &machine_domains(&hostname($perlvar{'lonHostID'}));
12320: }
12321:
12322: sub machine_domains {
12323: my ($hostname) = @_;
1.465 albertel 12324: my @domains;
1.838 albertel 12325: my %hostname = &all_hostnames();
1.465 albertel 12326: while( my($id, $name) = each(%hostname)) {
1.467 matthew 12327: # &logthis("-$id-$name-$hostname-");
1.465 albertel 12328: if ($hostname eq $name) {
1.844 albertel 12329: push(@domains,&host_domain($id));
1.465 albertel 12330: }
12331: }
12332: return @domains;
12333: }
12334:
12335: sub current_machine_ids {
1.853 albertel 12336: return &machine_ids(&hostname($perlvar{'lonHostID'}));
12337: }
12338:
12339: sub machine_ids {
12340: my ($hostname) = @_;
12341: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 12342: my @ids;
1.888 albertel 12343: my %name_to_host = &all_names();
1.889 albertel 12344: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
12345: return @{ $name_to_host{$hostname} };
12346: }
12347: return;
1.31 www 12348: }
12349:
1.824 raeburn 12350: sub additional_machine_domains {
12351: my @domains;
12352: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
12353: while( my $line = <$fh>) {
12354: $line =~ s/\s//g;
12355: push(@domains,$line);
12356: }
12357: return @domains;
12358: }
12359:
12360: sub default_login_domain {
12361: my $domain = $perlvar{'lonDefDomain'};
12362: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
12363: foreach my $posdom (¤t_machine_domains(),
12364: &additional_machine_domains()) {
12365: if (lc($posdom) eq lc($testdomain)) {
12366: $domain=$posdom;
12367: last;
12368: }
12369: }
12370: return $domain;
12371: }
12372:
1.31 www 12373: # ------------------------------------------------------------- Declutters URLs
12374:
12375: sub declutter {
12376: my $thisfn=shift;
1.569 albertel 12377: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1261 raeburn 12378: unless ($thisfn=~m{^/home/httpd/html/priv/}) {
12379: $thisfn=~s{^/home/httpd/html}{};
12380: }
1.31 www 12381: $thisfn=~s/^\///;
1.697 albertel 12382: $thisfn=~s|^adm/wrapper/||;
12383: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 12384: $thisfn=~s/^res\///;
1.1172 bisitz 12385: $thisfn=~s/^priv\///;
1.1032 raeburn 12386: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
12387: $thisfn=~s/\?.+$//;
12388: }
1.268 www 12389: return $thisfn;
12390: }
12391:
12392: # ------------------------------------------------------------- Clutter up URLs
12393:
12394: sub clutter {
12395: my $thisfn='/'.&declutter(shift);
1.887 albertel 12396: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 12397: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 12398: $thisfn='/res'.$thisfn;
12399: }
1.1031 raeburn 12400: if ($thisfn !~m|^/adm|) {
12401: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 12402: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 12403: } else {
12404: my ($ext) = ($thisfn =~ /\.(\w+)$/);
12405: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 12406: if ($embstyle eq 'ssi'
12407: || ($embstyle eq 'hdn')
12408: || ($embstyle eq 'rat')
12409: || ($embstyle eq 'prv')
12410: || ($embstyle eq 'ign')) {
12411: #do nothing with these
12412: } elsif (($embstyle eq 'img')
1.695 albertel 12413: || ($embstyle eq 'emb')
12414: || ($embstyle eq 'wrp')) {
12415: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 12416: } elsif ($embstyle eq 'unk'
12417: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 12418: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 12419: } else {
1.718 www 12420: # &logthis("Got a blank emb style");
1.695 albertel 12421: }
1.694 albertel 12422: }
1.1298 raeburn 12423: } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/exttools?$}) {
12424: $thisfn='/adm/wrapper'.$thisfn;
1.694 albertel 12425: }
1.31 www 12426: return $thisfn;
1.12 www 12427: }
12428:
1.787 albertel 12429: sub clutter_with_no_wrapper {
12430: my $uri = &clutter(shift);
12431: if ($uri =~ m-^/adm/-) {
12432: $uri =~ s-^/adm/wrapper/-/-;
12433: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
12434: }
12435: return $uri;
12436: }
12437:
1.557 albertel 12438: sub freeze_escape {
12439: my ($value)=@_;
12440: if (ref($value)) {
12441: $value=&nfreeze($value);
12442: return '__FROZEN__'.&escape($value);
12443: }
12444: return &escape($value);
12445: }
12446:
1.11 www 12447:
1.557 albertel 12448: sub thaw_unescape {
12449: my ($value)=@_;
12450: if ($value =~ /^__FROZEN__/) {
12451: substr($value,0,10,undef);
12452: $value=&unescape($value);
12453: return &thaw($value);
12454: }
12455: return &unescape($value);
12456: }
12457:
1.436 albertel 12458: sub correct_line_ends {
12459: my ($result)=@_;
12460: $$result =~s/\r\n/\n/mg;
12461: $$result =~s/\r/\n/mg;
1.415 albertel 12462: }
1.1 albertel 12463: # ================================================================ Main Program
12464:
1.184 www 12465: sub goodbye {
1.204 albertel 12466: &logthis("Starting Shut down");
1.443 albertel 12467: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 12468: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 12469: #converted
1.599 albertel 12470: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 12471: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
12472: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
12473: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 12474: #1.1 only
1.870 albertel 12475: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
12476: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
12477: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
12478: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
12479: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 12480: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
12481: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 12482: &flushcourselogs();
12483: &logthis("Shutting down");
12484: }
12485:
1.852 albertel 12486: sub get_dns {
1.1210 raeburn 12487: my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869 albertel 12488: if (!$ignore_cache) {
12489: my ($content,$cached)=
12490: &Apache::lonnet::is_cached_new('dns',$url);
12491: if ($cached) {
1.1210 raeburn 12492: &$func($content,$hashref);
1.869 albertel 12493: return;
12494: }
12495: }
12496:
12497: my %alldns;
1.852 albertel 12498: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
12499: foreach my $dns (<$config>) {
12500: next if ($dns !~ /^\^(\S*)/x);
1.979 raeburn 12501: my $line = $1;
12502: my ($host,$protocol) = split(/:/,$line);
12503: if ($protocol ne 'https') {
12504: $protocol = 'http';
12505: }
12506: $alldns{$host} = $protocol;
1.869 albertel 12507: }
12508: while (%alldns) {
1.1263 raeburn 12509: my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852 albertel 12510: my $ua=new LWP::UserAgent;
1.1134 raeburn 12511: $ua->timeout(30);
1.979 raeburn 12512: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 12513: my $response=$ua->request($request);
1.979 raeburn 12514: delete($alldns{$dns});
1.852 albertel 12515: next if ($response->is_error());
12516: my @content = split("\n",$response->content);
1.1210 raeburn 12517: unless ($nocache) {
1.1219 raeburn 12518: &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1210 raeburn 12519: }
12520: &$func(\@content,$hashref);
1.869 albertel 12521: return;
1.852 albertel 12522: }
12523: close($config);
1.871 albertel 12524: my $which = (split('/',$url))[3];
12525: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
12526: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 12527: my @content = <$config>;
1.1210 raeburn 12528: &$func(\@content,$hashref);
12529: return;
12530: }
12531:
12532: # ------------------------------------------------------Get DNS checksums file
1.1211 raeburn 12533: sub parse_dns_checksums_tab {
1.1210 raeburn 12534: my ($lines,$hashref) = @_;
1.1264 raeburn 12535: my $lonhost = $perlvar{'lonHostID'};
12536: my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1210 raeburn 12537: my $loncaparev = &get_server_loncaparev($machine_dom);
1.1264 raeburn 12538: my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
12539: my $webconfdir = '/etc/httpd/conf';
12540: if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
12541: $webconfdir = '/etc/apache2';
12542: } elsif ($distro =~ /^sles(\d+)$/) {
12543: if ($1 >= 10) {
12544: $webconfdir = '/etc/apache2';
12545: }
12546: } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
12547: if ($1 >= 10.0) {
12548: $webconfdir = '/etc/apache2';
12549: }
12550: }
1.1210 raeburn 12551: my ($release,$timestamp) = split(/\-/,$loncaparev);
12552: my (%chksum,%revnum);
12553: if (ref($lines) eq 'ARRAY') {
12554: chomp(@{$lines});
1.1238 raeburn 12555: my $version = shift(@{$lines});
12556: if ($version eq $release) {
1.1210 raeburn 12557: foreach my $line (@{$lines}) {
1.1238 raeburn 12558: my ($file,$version,$shasum) = split(/,/,$line);
1.1264 raeburn 12559: if ($file =~ m{^/etc/httpd/conf}) {
12560: if ($webconfdir eq '/etc/apache2') {
12561: $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
12562: }
12563: }
1.1238 raeburn 12564: $chksum{$file} = $shasum;
12565: $revnum{$file} = $version;
1.1210 raeburn 12566: }
12567: if (ref($hashref) eq 'HASH') {
12568: %{$hashref} = (
12569: sums => \%chksum,
12570: versions => \%revnum,
12571: );
12572: }
12573: }
12574: }
1.869 albertel 12575: return;
1.852 albertel 12576: }
1.1210 raeburn 12577:
12578: sub fetch_dns_checksums {
1.1238 raeburn 12579: my %checksums;
12580: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1260 raeburn 12581: my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1238 raeburn 12582: my ($release,$timestamp) = split(/\-/,$loncaparev);
12583: &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1211 raeburn 12584: \%checksums);
1.1210 raeburn 12585: return \%checksums;
12586: }
12587:
1.327 albertel 12588: # ------------------------------------------------------------ Read domain file
12589: {
1.852 albertel 12590: my $loaded;
1.846 albertel 12591: my %domain;
12592:
1.852 albertel 12593: sub parse_domain_tab {
12594: my ($lines) = @_;
12595: foreach my $line (@$lines) {
12596: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 12597:
1.846 albertel 12598: chomp($line);
1.852 albertel 12599: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 12600: my %this_domain;
12601: foreach my $field ('description', 'auth_def', 'auth_arg_def',
12602: 'lang_def', 'city', 'longi', 'lati',
12603: 'primary') {
12604: $this_domain{$field} = shift(@elements);
12605: }
12606: $domain{$name} = \%this_domain;
1.852 albertel 12607: }
12608: }
1.864 albertel 12609:
12610: sub reset_domain_info {
12611: undef($loaded);
12612: undef(%domain);
12613: }
12614:
1.852 albertel 12615: sub load_domain_tab {
1.1293 raeburn 12616: my ($ignore_cache,$nocache) = @_;
12617: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852 albertel 12618: my $fh;
12619: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
12620: my @lines = <$fh>;
12621: &parse_domain_tab(\@lines);
1.448 albertel 12622: }
1.852 albertel 12623: close($fh);
12624: $loaded = 1;
1.327 albertel 12625: }
1.846 albertel 12626:
12627: sub domain {
1.852 albertel 12628: &load_domain_tab() if (!$loaded);
12629:
1.846 albertel 12630: my ($name,$what) = @_;
12631: return if ( !exists($domain{$name}) );
12632:
12633: if (!$what) {
12634: return $domain{$name}{'description'};
12635: }
12636: return $domain{$name}{$what};
12637: }
1.974 raeburn 12638:
12639: sub domain_info {
12640: &load_domain_tab() if (!$loaded);
12641: return %domain;
12642: }
12643:
1.327 albertel 12644: }
12645:
12646:
1.1 albertel 12647: # ------------------------------------------------------------- Read hosts file
12648: {
1.838 albertel 12649: my %hostname;
1.844 albertel 12650: my %hostdom;
1.845 albertel 12651: my %libserv;
1.852 albertel 12652: my $loaded;
1.888 albertel 12653: my %name_to_host;
1.1074 raeburn 12654: my %internetdom;
1.1107 raeburn 12655: my %LC_dns_serv;
1.852 albertel 12656:
12657: sub parse_hosts_tab {
12658: my ($file) = @_;
12659: foreach my $configline (@$file) {
12660: next if ($configline =~ /^(\#|\s*$ )/x);
1.1107 raeburn 12661: chomp($configline);
12662: if ($configline =~ /^\^/) {
12663: if ($configline =~ /^\^([\w.\-]+)/) {
12664: $LC_dns_serv{$1} = 1;
12665: }
12666: next;
12667: }
1.1074 raeburn 12668: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 12669: $name=~s/\s//g;
12670: if ($id && $domain && $role && $name) {
12671: $hostname{$id}=$name;
1.888 albertel 12672: push(@{$name_to_host{$name}}, $id);
1.852 albertel 12673: $hostdom{$id}=$domain;
12674: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 12675: if (defined($protocol)) {
12676: if ($protocol eq 'https') {
12677: $protocol{$id} = $protocol;
12678: } else {
12679: $protocol{$id} = 'http';
12680: }
1.968 raeburn 12681: } else {
1.969 raeburn 12682: $protocol{$id} = 'http';
1.968 raeburn 12683: }
1.1074 raeburn 12684: if (defined($intdom)) {
12685: $internetdom{$id} = $intdom;
12686: }
1.852 albertel 12687: }
12688: }
12689: }
1.864 albertel 12690:
12691: sub reset_hosts_info {
1.897 albertel 12692: &purge_remembered();
1.864 albertel 12693: &reset_domain_info();
12694: &reset_hosts_ip_info();
1.892 albertel 12695: undef(%name_to_host);
1.864 albertel 12696: undef(%hostname);
12697: undef(%hostdom);
12698: undef(%libserv);
12699: undef($loaded);
12700: }
1.1 albertel 12701:
1.852 albertel 12702: sub load_hosts_tab {
1.1293 raeburn 12703: my ($ignore_cache,$nocache) = @_;
12704: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.852 albertel 12705: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
12706: my @config = <$config>;
12707: &parse_hosts_tab(\@config);
12708: close($config);
12709: $loaded=1;
1.1 albertel 12710: }
1.852 albertel 12711:
1.838 albertel 12712: sub hostname {
1.852 albertel 12713: &load_hosts_tab() if (!$loaded);
12714:
1.838 albertel 12715: my ($lonid) = @_;
12716: return $hostname{$lonid};
12717: }
1.845 albertel 12718:
1.838 albertel 12719: sub all_hostnames {
1.852 albertel 12720: &load_hosts_tab() if (!$loaded);
12721:
1.838 albertel 12722: return %hostname;
12723: }
1.845 albertel 12724:
1.888 albertel 12725: sub all_names {
1.1293 raeburn 12726: my ($ignore_cache,$nocache) = @_;
12727: &load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888 albertel 12728:
12729: return %name_to_host;
12730: }
12731:
1.974 raeburn 12732: sub all_host_domain {
12733: &load_hosts_tab() if (!$loaded);
12734: return %hostdom;
12735: }
12736:
1.845 albertel 12737: sub is_library {
1.852 albertel 12738: &load_hosts_tab() if (!$loaded);
12739:
1.845 albertel 12740: return exists($libserv{$_[0]});
12741: }
12742:
12743: sub all_library {
1.852 albertel 12744: &load_hosts_tab() if (!$loaded);
12745:
1.845 albertel 12746: return %libserv;
12747: }
12748:
1.1062 droeschl 12749: sub unique_library {
12750: #2x reverse removes all hostnames that appear more than once
12751: my %unique = reverse &all_library();
12752: return reverse %unique;
12753: }
12754:
1.841 albertel 12755: sub get_servers {
1.852 albertel 12756: &load_hosts_tab() if (!$loaded);
12757:
1.841 albertel 12758: my ($domain,$type) = @_;
12759: my %possible_hosts = ($type eq 'library') ? %libserv
12760: : %hostname;
12761: my %result;
1.842 albertel 12762: if (ref($domain) eq 'ARRAY') {
12763: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 12764: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 12765: $result{$host} = $hostname;
12766: }
12767: }
12768: } else {
12769: while ( my ($host,$hostname) = each(%possible_hosts)) {
12770: if ($hostdom{$host} eq $domain) {
12771: $result{$host} = $hostname;
12772: }
1.841 albertel 12773: }
12774: }
12775: return %result;
12776: }
1.845 albertel 12777:
1.1062 droeschl 12778: sub get_unique_servers {
12779: my %unique = reverse &get_servers(@_);
12780: return reverse %unique;
12781: }
12782:
1.844 albertel 12783: sub host_domain {
1.852 albertel 12784: &load_hosts_tab() if (!$loaded);
12785:
1.844 albertel 12786: my ($lonid) = @_;
12787: return $hostdom{$lonid};
12788: }
12789:
1.841 albertel 12790: sub all_domains {
1.852 albertel 12791: &load_hosts_tab() if (!$loaded);
12792:
1.841 albertel 12793: my %seen;
12794: my @uniq = grep(!$seen{$_}++, values(%hostdom));
12795: return @uniq;
12796: }
1.1074 raeburn 12797:
12798: sub internet_dom {
12799: &load_hosts_tab() if (!$loaded);
12800:
12801: my ($lonid) = @_;
12802: return $internetdom{$lonid};
12803: }
1.1107 raeburn 12804:
12805: sub is_LC_dns {
12806: &load_hosts_tab() if (!$loaded);
12807:
12808: my ($hostname) = @_;
12809: return exists($LC_dns_serv{$hostname});
12810: }
12811:
1.1 albertel 12812: }
12813:
1.847 albertel 12814: {
12815: my %iphost;
1.856 albertel 12816: my %name_to_ip;
12817: my %lonid_to_ip;
1.869 albertel 12818:
1.847 albertel 12819: sub get_hosts_from_ip {
12820: my ($ip) = @_;
12821: my %iphosts = &get_iphost();
12822: if (ref($iphosts{$ip})) {
12823: return @{$iphosts{$ip}};
12824: }
12825: return;
1.839 albertel 12826: }
1.864 albertel 12827:
12828: sub reset_hosts_ip_info {
12829: undef(%iphost);
12830: undef(%name_to_ip);
12831: undef(%lonid_to_ip);
12832: }
1.856 albertel 12833:
12834: sub get_host_ip {
12835: my ($lonid) = @_;
12836: if (exists($lonid_to_ip{$lonid})) {
12837: return $lonid_to_ip{$lonid};
12838: }
12839: my $name=&hostname($lonid);
12840: my $ip = gethostbyname($name);
12841: return if (!$ip || length($ip) ne 4);
12842: $ip=inet_ntoa($ip);
12843: $name_to_ip{$name} = $ip;
12844: $lonid_to_ip{$lonid} = $ip;
12845: return $ip;
12846: }
1.847 albertel 12847:
12848: sub get_iphost {
1.1293 raeburn 12849: my ($ignore_cache,$nocache) = @_;
1.894 albertel 12850:
1.869 albertel 12851: if (!$ignore_cache) {
12852: if (%iphost) {
12853: return %iphost;
12854: }
12855: my ($ip_info,$cached)=
12856: &Apache::lonnet::is_cached_new('iphost','iphost');
12857: if ($cached) {
12858: %iphost = %{$ip_info->[0]};
12859: %name_to_ip = %{$ip_info->[1]};
12860: %lonid_to_ip = %{$ip_info->[2]};
12861: return %iphost;
12862: }
12863: }
1.894 albertel 12864:
12865: # get yesterday's info for fallback
12866: my %old_name_to_ip;
12867: my ($ip_info,$cached)=
12868: &Apache::lonnet::is_cached_new('iphost','iphost');
12869: if ($cached) {
12870: %old_name_to_ip = %{$ip_info->[1]};
12871: }
12872:
1.1293 raeburn 12873: my %name_to_host = &all_names($ignore_cache,$nocache);
1.888 albertel 12874: foreach my $name (keys(%name_to_host)) {
1.847 albertel 12875: my $ip;
12876: if (!exists($name_to_ip{$name})) {
12877: $ip = gethostbyname($name);
12878: if (!$ip || length($ip) ne 4) {
1.894 albertel 12879: if (defined($old_name_to_ip{$name})) {
12880: $ip = $old_name_to_ip{$name};
12881: &logthis("Can't find $name defaulting to old $ip");
12882: } else {
12883: &logthis("Name $name no IP found");
12884: next;
12885: }
12886: } else {
12887: $ip=inet_ntoa($ip);
1.847 albertel 12888: }
12889: $name_to_ip{$name} = $ip;
12890: } else {
12891: $ip = $name_to_ip{$name};
1.653 albertel 12892: }
1.888 albertel 12893: foreach my $id (@{ $name_to_host{$name} }) {
12894: $lonid_to_ip{$id} = $ip;
12895: }
12896: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 12897: }
1.1293 raeburn 12898: unless ($nocache) {
12899: &do_cache_new('iphost','iphost',
12900: [\%iphost,\%name_to_ip,\%lonid_to_ip],
12901: 48*60*60);
12902: }
1.869 albertel 12903:
1.847 albertel 12904: return %iphost;
1.598 albertel 12905: }
12906:
1.992 raeburn 12907: #
12908: # Given a DNS returns the loncapa host name for that DNS
12909: #
12910: sub host_from_dns {
12911: my ($dns) = @_;
12912: my @hosts;
12913: my $ip;
12914:
1.993 raeburn 12915: if (exists($name_to_ip{$dns})) {
1.992 raeburn 12916: $ip = $name_to_ip{$dns};
12917: }
12918: if (!$ip) {
12919: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
12920: if (length($ip) == 4) {
12921: $ip = &IO::Socket::inet_ntoa($ip);
12922: }
12923: }
12924: if ($ip) {
12925: @hosts = get_hosts_from_ip($ip);
12926: return $hosts[0];
12927: }
12928: return undef;
1.986 foxr 12929: }
1.992 raeburn 12930:
1.1074 raeburn 12931: sub get_internet_names {
12932: my ($lonid) = @_;
12933: return if ($lonid eq '');
12934: my ($idnref,$cached)=
12935: &Apache::lonnet::is_cached_new('internetnames',$lonid);
12936: if ($cached) {
12937: return $idnref;
12938: }
12939: my $ip = &get_host_ip($lonid);
12940: my @hosts = &get_hosts_from_ip($ip);
12941: my %iphost = &get_iphost();
12942: my (@idns,%seen);
12943: foreach my $id (@hosts) {
12944: my $dom = &host_domain($id);
12945: my $prim_id = &domain($dom,'primary');
12946: my $prim_ip = &get_host_ip($prim_id);
12947: next if ($seen{$prim_ip});
12948: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
12949: foreach my $id (@{$iphost{$prim_ip}}) {
12950: my $intdom = &internet_dom($id);
12951: unless (grep(/^\Q$intdom\E$/,@idns)) {
12952: push(@idns,$intdom);
12953: }
12954: }
12955: }
12956: $seen{$prim_ip} = 1;
12957: }
1.1219 raeburn 12958: return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074 raeburn 12959: }
12960:
1.986 foxr 12961: }
12962:
1.1079 raeburn 12963: sub all_loncaparevs {
1.1249 raeburn 12964: 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 12965: }
12966:
1.1227 raeburn 12967: # ---------------------------------------------------------- Read loncaparev table
12968: {
12969: sub load_loncaparevs {
12970: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
12971: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
12972: while (my $configline=<$config>) {
12973: chomp($configline);
12974: my ($hostid,$loncaparev)=split(/:/,$configline);
12975: $loncaparevs{$hostid}=$loncaparev;
12976: }
12977: close($config);
12978: }
12979: }
12980: }
12981: }
12982:
12983: # ---------------------------------------------------------- Read serverhostID table
12984: {
12985: sub load_serverhomeIDs {
12986: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
12987: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
12988: while (my $configline=<$config>) {
12989: chomp($configline);
12990: my ($name,$id)=split(/:/,$configline);
12991: $serverhomeIDs{$name}=$id;
12992: }
12993: close($config);
12994: }
12995: }
12996: }
12997: }
12998:
12999:
1.862 albertel 13000: BEGIN {
13001:
13002: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
13003: unless ($readit) {
13004: {
13005: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
13006: %perlvar = (%perlvar,%{$configvars});
13007: }
13008:
13009:
1.1 albertel 13010: # ------------------------------------------------------ Read spare server file
13011: {
1.448 albertel 13012: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 13013:
13014: while (my $configline=<$config>) {
13015: chomp($configline);
1.284 matthew 13016: if ($configline) {
1.784 albertel 13017: my ($host,$type) = split(':',$configline,2);
1.785 albertel 13018: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 13019: push(@{ $spareid{$type} }, $host);
1.1 albertel 13020: }
13021: }
1.448 albertel 13022: close($config);
1.1 albertel 13023: }
1.11 www 13024: # ------------------------------------------------------------ Read permissions
13025: {
1.448 albertel 13026: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 13027:
13028: while (my $configline=<$config>) {
1.448 albertel 13029: chomp($configline);
13030: if ($configline) {
13031: my ($role,$perm)=split(/ /,$configline);
13032: if ($perm ne '') { $pr{$role}=$perm; }
13033: }
1.11 www 13034: }
1.448 albertel 13035: close($config);
1.11 www 13036: }
13037:
13038: # -------------------------------------------- Read plain texts for permissions
13039: {
1.448 albertel 13040: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 13041:
13042: while (my $configline=<$config>) {
1.448 albertel 13043: chomp($configline);
13044: if ($configline) {
1.742 raeburn 13045: my ($short,@plain)=split(/:/,$configline);
13046: %{$prp{$short}} = ();
13047: if (@plain > 0) {
13048: $prp{$short}{'std'} = $plain[0];
13049: for (my $i=1; $i<@plain; $i++) {
13050: $prp{$short}{'alt'.$i} = $plain[$i];
13051: }
13052: }
1.448 albertel 13053: }
1.135 www 13054: }
1.448 albertel 13055: close($config);
1.135 www 13056: }
13057:
13058: # ---------------------------------------------------------- Read package table
13059: {
1.448 albertel 13060: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 13061:
13062: while (my $configline=<$config>) {
1.483 albertel 13063: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 13064: chomp($configline);
13065: my ($short,$plain)=split(/:/,$configline);
13066: my ($pack,$name)=split(/\&/,$short);
13067: if ($plain ne '') {
13068: $packagetab{$pack.'&'.$name.'&name'}=$name;
13069: $packagetab{$short}=$plain;
13070: }
1.11 www 13071: }
1.448 albertel 13072: close($config);
1.329 matthew 13073: }
13074:
1.1073 raeburn 13075: # ---------------------------------------------------------- Read loncaparev table
1.1227 raeburn 13076:
13077: &load_loncaparevs();
1.1073 raeburn 13078:
1.1074 raeburn 13079: # ---------------------------------------------------------- Read serverhostID table
13080:
1.1227 raeburn 13081: &load_serverhomeIDs();
13082:
13083: # ---------------------------------------------------------- Read releaseslist XML
1.1079 raeburn 13084: {
13085: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
13086: if (-e $file) {
13087: my $parser = HTML::LCParser->new($file);
13088: while (my $token = $parser->get_token()) {
13089: if ($token->[0] eq 'S') {
13090: my $item = $token->[1];
13091: my $name = $token->[2]{'name'};
13092: my $value = $token->[2]{'value'};
1.1285 raeburn 13093: my $valuematch = $token->[2]{'valuematch'};
1.1303 raeburn 13094: my $namematch = $token->[2]{'namematch'};
13095: if ($item eq 'parameter') {
13096: if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
13097: my $release = $parser->get_text();
13098: $release =~ s/(^\s*|\s*$ )//gx;
13099: $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
13100: }
13101: } elsif ($item ne '' && $name ne '') {
1.1079 raeburn 13102: my $release = $parser->get_text();
13103: $release =~ s/(^\s*|\s*$ )//gx;
1.1303 raeburn 13104: $needsrelease{$item.':'.$name.':'.$value} = $release;
1.1079 raeburn 13105: }
13106: }
13107: }
13108: }
1.1073 raeburn 13109: }
13110:
1.1138 raeburn 13111: # ---------------------------------------------------------- Read managers table
13112: {
13113: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
13114: if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
13115: while (my $configline=<$config>) {
13116: chomp($configline);
13117: next if ($configline =~ /^\#/);
13118: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
13119: $managerstab{$configline} = 1;
13120: }
13121: }
13122: close($config);
13123: }
13124: }
13125: }
13126:
1.329 matthew 13127: # ------------- set up temporary directory
13128: {
1.1117 foxr 13129: $tmpdir = LONCAPA::tempdir();
1.329 matthew 13130:
1.11 www 13131: }
13132:
1.794 albertel 13133: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
13134: 'compress_threshold'=> 20_000,
13135: });
1.185 www 13136:
1.281 www 13137: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 13138: $dumpcount=0;
1.958 www 13139: $locknum=0;
1.22 www 13140:
1.163 harris41 13141: &logtouch();
1.672 albertel 13142: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 13143: $readit=1;
1.564 albertel 13144: {
13145: use integer;
13146: my $test=(2**32)+1;
1.568 albertel 13147: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 13148: &logthis(" Detected 64bit platform ($_64bit)");
13149: }
1.195 www 13150: }
1.1 albertel 13151: }
1.179 www 13152:
1.1 albertel 13153: 1;
1.191 harris41 13154: __END__
13155:
1.243 albertel 13156: =pod
13157:
1.191 harris41 13158: =head1 NAME
13159:
1.243 albertel 13160: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 13161:
13162: =head1 SYNOPSIS
13163:
1.243 albertel 13164: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 13165:
13166: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
13167:
1.243 albertel 13168: Common parameters:
13169:
13170: =over 4
13171:
13172: =item *
13173:
13174: $uname : an internal username (if $cname expecting a course Id specifically)
13175:
13176: =item *
13177:
13178: $udom : a domain (if $cdom expecting a course's domain specifically)
13179:
13180: =item *
13181:
13182: $symb : a resource instance identifier
13183:
13184: =item *
13185:
13186: $namespace : the name of a .db file that contains the data needed or
13187: being set.
13188:
13189: =back
13190:
1.394 bowersj2 13191: =head1 OVERVIEW
1.191 harris41 13192:
1.394 bowersj2 13193: lonnet provides subroutines which interact with the
13194: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
13195: about classes, users, and resources.
1.243 albertel 13196:
13197: For many of these objects you can also use this to store data about
13198: them or modify them in various ways.
1.191 harris41 13199:
1.394 bowersj2 13200: =head2 Symbs
1.191 harris41 13201:
1.394 bowersj2 13202: To identify a specific instance of a resource, LON-CAPA uses symbols
13203: or "symbs"X<symb>. These identifiers are built from the URL of the
13204: map, the resource number of the resource in the map, and the URL of
13205: the resource itself. The latter is somewhat redundant, but might help
13206: if maps change.
13207:
13208: An example is
13209:
13210: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
13211:
13212: The respective map entry is
13213:
13214: <resource id="19" src="/res/msu/korte/tests/part12.problem"
13215: title="Problem 2">
13216: </resource>
13217:
13218: Symbs are used by the random number generator, as well as to store and
13219: restore data specific to a certain instance of for example a problem.
13220:
13221: =head2 Storing And Retrieving Data
13222:
13223: X<store()>X<cstore()>X<restore()>Three of the most important functions
13224: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
13225: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
13226: is is the non-critical message twin of cstore. These functions are for
13227: handlers to store a perl hash to a user's permanent data space in an
13228: easy manner, and to retrieve it again on another call. It is expected
13229: that a handler would use this once at the beginning to retrieve data,
13230: and then again once at the end to send only the new data back.
13231:
13232: The data is stored in the user's data directory on the user's
13233: homeserver under the ID of the course.
13234:
13235: The hash that is returned by restore will have all of the previous
13236: value for all of the elements of the hash.
13237:
13238: Example:
13239:
13240: #creating a hash
13241: my %hash;
13242: $hash{'foo'}='bar';
13243:
13244: #storing it
13245: &Apache::lonnet::cstore(\%hash);
13246:
13247: #changing a value
13248: $hash{'foo'}='notbar';
13249:
13250: #adding a new value
13251: $hash{'bar'}='foo';
13252: &Apache::lonnet::cstore(\%hash);
13253:
13254: #retrieving the hash
13255: my %history=&Apache::lonnet::restore();
13256:
13257: #print the hash
13258: foreach my $key (sort(keys(%history))) {
13259: print("\%history{$key} = $history{$key}");
13260: }
13261:
13262: Will print out:
1.191 harris41 13263:
1.394 bowersj2 13264: %history{1:foo} = bar
13265: %history{1:keys} = foo:timestamp
13266: %history{1:timestamp} = 990455579
13267: %history{2:bar} = foo
13268: %history{2:foo} = notbar
13269: %history{2:keys} = foo:bar:timestamp
13270: %history{2:timestamp} = 990455580
13271: %history{bar} = foo
13272: %history{foo} = notbar
13273: %history{timestamp} = 990455580
13274: %history{version} = 2
13275:
13276: Note that the special hash entries C<keys>, C<version> and
13277: C<timestamp> were added to the hash. C<version> will be equal to the
13278: total number of versions of the data that have been stored. The
13279: C<timestamp> attribute will be the UNIX time the hash was
13280: stored. C<keys> is available in every historical section to list which
13281: keys were added or changed at a specific historical revision of a
13282: hash.
13283:
13284: B<Warning>: do not store the hash that restore returns directly. This
13285: will cause a mess since it will restore the historical keys as if the
13286: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 13287:
1.394 bowersj2 13288: Calling convention:
1.191 harris41 13289:
1.1225 raeburn 13290: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1269 raeburn 13291: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191 harris41 13292:
1.394 bowersj2 13293: For more detailed information, see lonnet specific documentation.
1.191 harris41 13294:
1.394 bowersj2 13295: =head1 RETURN MESSAGES
1.191 harris41 13296:
1.394 bowersj2 13297: =over 4
1.191 harris41 13298:
1.394 bowersj2 13299: =item * B<con_lost>: unable to contact remote host
1.191 harris41 13300:
1.394 bowersj2 13301: =item * B<con_delayed>: unable to contact remote host, message will be delivered
13302: when the connection is brought back up
1.191 harris41 13303:
1.394 bowersj2 13304: =item * B<con_failed>: unable to contact remote host and unable to save message
13305: for later delivery
1.191 harris41 13306:
1.967 bisitz 13307: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 13308:
1.394 bowersj2 13309: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 13310: that was requested
1.191 harris41 13311:
1.243 albertel 13312: =back
1.191 harris41 13313:
1.243 albertel 13314: =head1 PUBLIC SUBROUTINES
1.191 harris41 13315:
1.243 albertel 13316: =head2 Session Environment Functions
1.191 harris41 13317:
1.243 albertel 13318: =over 4
1.191 harris41 13319:
1.394 bowersj2 13320: =item *
13321: X<appenv()>
1.949 raeburn 13322: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 13323: the user envirnoment file, and will be restored for each access this
1.620 albertel 13324: user makes during this session, also modifies the %env for the current
1.949 raeburn 13325: process. Optional rolesarrayref - if defined contains a reference to an array
13326: of roles which are exempt from the restriction on modifying user.role entries
13327: in the user's environment.db and in %env.
1.191 harris41 13328:
13329: =item *
1.394 bowersj2 13330: X<delenv()>
1.987 raeburn 13331: B<delenv($delthis,$regexp)>: removes all items from the session
13332: environment file that begin with $delthis. If the
13333: optional second arg - $regexp - is true, $delthis is treated as a
13334: regular expression, otherwise \Q$delthis\E is used.
13335: The values are also deleted from the current processes %env.
1.191 harris41 13336:
1.795 albertel 13337: =item * get_env_multiple($name)
13338:
13339: gets $name from the %env hash, it seemlessly handles the cases where multiple
13340: values may be defined and end up as an array ref.
13341:
13342: returns an array of values
13343:
1.243 albertel 13344: =back
13345:
13346: =head2 User Information
1.191 harris41 13347:
1.243 albertel 13348: =over 4
1.191 harris41 13349:
13350: =item *
1.394 bowersj2 13351: X<queryauthenticate()>
13352: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 13353: authentication scheme
13354:
13355: =item *
1.394 bowersj2 13356: X<authenticate()>
1.1073 raeburn 13357: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 13358: authenticate user from domain's lib servers (first use the current
13359: one). C<$upass> should be the users password.
1.1073 raeburn 13360: $checkdefauth is optional (value is 1 if a check should be made to
13361: authenticate user using default authentication method, and allow
13362: account creation if username does not have account in the domain).
13363: $clientcancheckhost is optional (value is 1 if checking whether the
13364: server can host will occur on the client side in lonauth.pm).
1.191 harris41 13365:
13366: =item *
1.394 bowersj2 13367: X<homeserver()>
13368: B<homeserver($uname,$udom)>: find the server which has
13369: the user's directory and files (there must be only one), this caches
13370: the answer, and also caches if there is a borken connection.
1.191 harris41 13371:
13372: =item *
1.394 bowersj2 13373: X<idget()>
1.1300 raeburn 13374: B<idget($udom,$idsref,$namespace)>: find the usernames behind either
13375: a list of student/employee IDs or clicker IDs
13376: (student/employee IDs are a unique resource in a domain, there must be
13377: only 1 ID per username, and only 1 username per ID in a specific domain).
13378: clickerIDs are not necessarily unique, as students might share clickers.
13379: (returns hash: id=>name,id=>name)
1.191 harris41 13380:
13381: =item *
1.394 bowersj2 13382: X<idrget()>
13383: B<idrget($udom,@unames)>: find the IDs behind a list of
13384: usernames (returns hash: name=>id,name=>id)
1.191 harris41 13385:
13386: =item *
1.394 bowersj2 13387: X<idput()>
1.1300 raeburn 13388: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of
13389: names and associated student/employee IDs or clicker IDs.
13390:
13391: =item *
13392: X<iddel()>
13393: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted
13394: student/employee ID or clicker ID username look-ups from domain.
13395: The homeserver ($uhome) and namespace ($namespace) are optional.
13396: If no $uhome is provided, it will be determined usig &homeserver()
13397: for each user. If no $namespace is provided, the default is ids.
13398:
13399: =item *
13400: X<updateclickers()>
13401: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update
13402: clicker ID-to-username look-ups in clickers.db on library server.
13403: Permitted actions are add or del (i.e., add or delete). The
13404: clickers.db contains clickerID as keys (escaped), and each corresponding
13405: value is an escaped comma-separated list of usernames (for whom the
13406: library server is the homeserver), who registered that particular ID.
13407: If $critical is true, the update will be sent via &critical, otherwise
13408: &reply() will be used.
1.191 harris41 13409:
13410: =item *
1.394 bowersj2 13411: X<rolesinit()>
1.1169 droeschl 13412: B<rolesinit($udom,$username)>: get user privileges.
13413: returns user role, first access and timer interval hashes
1.243 albertel 13414:
13415: =item *
1.1171 droeschl 13416: X<privileged()>
13417: B<privileged($username,$domain)>: returns a true if user has a
13418: privileged and active role (i.e. su or dc), false otherwise.
13419:
13420: =item *
1.551 albertel 13421: X<getsection()>
13422: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 13423: course $cname, return section name/number or '' for "not in course"
13424: and '-1' for "no section"
13425:
13426: =item *
1.394 bowersj2 13427: X<userenvironment()>
13428: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 13429: passed in @what from the requested user's environment, returns a hash
13430:
1.858 raeburn 13431: =item *
13432: X<userlog_query()>
1.859 albertel 13433: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
13434: activity.log file. %filters defines filters applied when parsing the
13435: log file. These can be start or end timestamps, or the type of action
13436: - log to look for Login or Logout events, check for Checkin or
13437: Checkout, role for role selection. The response is in the form
13438: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
13439: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 13440:
1.243 albertel 13441: =back
13442:
13443: =head2 User Roles
13444:
13445: =over 4
13446:
13447: =item *
13448:
1.1284 raeburn 13449: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege;
13450: returns codes for allowed actions.
13451:
13452: The first argument is required, all others are optional.
13453:
13454: $priv is the privilege being checked.
13455: $uri contains additional information about what is being checked for access (e.g.,
13456: URL, course ID etc.).
13457: $symb is the unique resource instance identifier in a course; if needed,
13458: but not provided, it will be retrieved via a call to &symbread().
13459: $role is the role for which a priv is being checked (only used if priv is evb).
13460: $clientip is the user's IP address (only used when checking for access to portfolio
13461: files).
13462: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
13463: prevents recursive calls to &allowed.
13464:
1.243 albertel 13465: F: full access
13466: U,I,K: authentication modes (cxx only)
13467: '': forbidden
13468: 1: user needs to choose course
13469: 2: browse allowed
1.766 albertel 13470: A: passphrase authentication needed
1.1284 raeburn 13471: B: access temporarily blocked because of a blocking event in a course.
1.243 albertel 13472:
13473: =item *
13474:
1.1192 raeburn 13475: constructaccess($url,$setpriv) : check for access to construction space URL
13476:
13477: See if the owner domain and name in the URL match those in the
13478: expected environment. If so, return three element list
13479: ($ownername,$ownerdomain,$ownerhome).
13480:
13481: Otherwise return the null string.
13482:
13483: If second argument 'setpriv' is true, it assigns the privileges,
13484: and returns the same three element list, unless the owner has
13485: blocked "ad hoc" Domain Coordinator access to the Author Space,
13486: in which case the null string is returned.
13487:
13488: =item *
13489:
1.243 albertel 13490: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
13491: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
13492: and course level
13493:
13494: =item *
13495:
1.988 raeburn 13496: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
13497: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 13498: $type is Course (default) or Community.
1.988 raeburn 13499: If $forcedefault evaluates to true, text returned will be default
13500: text for $type. Otherwise, if this is a course, the text returned
13501: will be a custom name for the role (if defined in the course's
13502: environment). If no custom name is defined the default is returned.
13503:
1.832 raeburn 13504: =item *
13505:
1.1219 raeburn 13506: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858 raeburn 13507: All arguments are optional. Returns a hash of a roles, either for
13508: co-author/assistant author roles for a user's Construction Space
1.906 albertel 13509: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 13510: In the hash, keys are set to colon-separated $uname,$udom,$role, and
13511: (optionally) if $withsec is true, a fourth colon-separated item - $section.
13512: For each key, value is set to colon-separated start and end times for
13513: the role. If no username and domain are specified, will default to
1.934 raeburn 13514: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 13515: of role statuses (active, future or previous), roles
13516: (e.g., cc,in, st etc.) and domains of the roles which can be used
13517: to restrict the list of roles reported. If no array ref is
13518: provided for types, will default to return only active roles.
1.834 albertel 13519:
1.1195 raeburn 13520: =item *
13521:
13522: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196 raeburn 13523: user: $uname:$udom has a role in the course: $cdom_$cnum.
13524:
13525: Additional optional arguments are: $type (if role checking is to be restricted
13526: to certain user status types -- previous (expired roles), active (currently
1.1195 raeburn 13527: available roles) or future (roles available in the future), and
13528: $hideprivileged -- if true will not report course roles for users who
1.1219 raeburn 13529: have active Domain Coordinator role in course's domain or in additional
13530: domains (specified in 'Domains to check for privileged users' in course
13531: environment -- set via: Course Settings -> Classlists and staff listing).
13532:
13533: =item *
13534:
13535: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
13536: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
13537: $possdomains and $possroles are optional array refs -- to domains to check and
13538: roles to check. If $possdomains is not specified, a dump will be done of the
13539: users' roles.db to check for a dc or su role in any domain. This can be
13540: time consuming if &privileged is called repeatedly (e.g., when displaying a
13541: classlist), so in such cases, supplying a $possdomains array is preferred, as
13542: this then allows &privileged_by_domain() to be used, which caches the identity
13543: of privileged users, eliminating the need for repeated calls to &dump().
13544:
13545: =item *
13546:
13547: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
13548: where the outer hash keys are domains specified in the $possdomains array ref,
13549: next inner hash keys are privileged roles specified in the $roles array ref,
13550: and the innermost hash contains key = value pairs for username:domain = end:start
13551: for active or future "privileged" users with that role in that domain. To avoid
13552: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
13553: innerhash are cached using priv_$role and $dom as the identifiers.
1.1195 raeburn 13554:
1.243 albertel 13555: =back
13556:
13557: =head2 User Modification
13558:
13559: =over 4
13560:
13561: =item *
13562:
1.957 raeburn 13563: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 13564: user for the level given by URL. Optional start and end dates (leave empty
13565: string or zero for "no date")
1.191 harris41 13566:
13567: =item *
13568:
1.243 albertel 13569: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
13570: change a users, password, possible return values are: ok,
13571: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
13572: refused
1.191 harris41 13573:
13574: =item *
13575:
1.243 albertel 13576: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 13577:
13578: =item *
13579:
1.1058 raeburn 13580: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
13581: $forceid,$desiredhome,$email,$inststatus,$candelete) :
13582:
13583: will update user information (firstname,middlename,lastname,generation,
13584: permanentemail), and if forceid is true, student/employee ID also.
13585: A user's institutional affiliation(s) can also be updated.
13586: User information fields will not be overwritten with empty entries
13587: unless the field is included in the $candelete array reference.
13588: This array is included when a single user is modified via "Manage Users",
13589: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 13590:
13591: =item *
13592:
1.286 matthew 13593: modifystudent
13594:
1.957 raeburn 13595: modify a student's enrollment and identification information.
1.1235 raeburn 13596: The course id is resolved based on the current user's environment.
13597: This means the invoking user must be a course coordinator or otherwise
1.286 matthew 13598: associated with a course.
13599:
1.297 matthew 13600: This call is essentially a wrapper for lonnet::modifyuser and
13601: lonnet::modify_student_enrollment
1.286 matthew 13602:
13603: Inputs:
13604:
13605: =over 4
13606:
1.957 raeburn 13607: =item B<$udom> Student's loncapa domain
1.286 matthew 13608:
1.957 raeburn 13609: =item B<$uname> Student's loncapa login name
1.286 matthew 13610:
1.964 bisitz 13611: =item B<$uid> Student/Employee ID
1.286 matthew 13612:
1.957 raeburn 13613: =item B<$umode> Student's authentication mode
1.286 matthew 13614:
1.957 raeburn 13615: =item B<$upass> Student's password
1.286 matthew 13616:
1.957 raeburn 13617: =item B<$first> Student's first name
1.286 matthew 13618:
1.957 raeburn 13619: =item B<$middle> Student's middle name
1.286 matthew 13620:
1.957 raeburn 13621: =item B<$last> Student's last name
1.286 matthew 13622:
1.957 raeburn 13623: =item B<$gene> Student's generation
1.286 matthew 13624:
1.957 raeburn 13625: =item B<$usec> Student's section in course
1.286 matthew 13626:
13627: =item B<$end> Unix time of the roles expiration
13628:
13629: =item B<$start> Unix time of the roles start date
13630:
13631: =item B<$forceid> If defined, allow $uid to be changed
13632:
13633: =item B<$desiredhome> server to use as home server for student
13634:
1.957 raeburn 13635: =item B<$email> Student's permanent e-mail address
13636:
13637: =item B<$type> Type of enrollment (auto or manual)
13638:
1.963 raeburn 13639: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
13640:
13641: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 13642:
1.963 raeburn 13643: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 13644:
1.963 raeburn 13645: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 13646:
1.1216 raeburn 13647: =item B<$inststatus> institutional status of user - : separated string of escaped status types
13648:
13649: =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 13650:
1.286 matthew 13651: =back
1.297 matthew 13652:
13653: =item *
13654:
13655: modify_student_enrollment
13656:
1.1235 raeburn 13657: Change a student's enrollment status in a class. The environment variable
1.297 matthew 13658: 'role.request.course' must be defined for this function to proceed.
13659:
13660: Inputs:
13661:
13662: =over 4
13663:
1.1235 raeburn 13664: =item $udom, student's domain
1.297 matthew 13665:
1.1235 raeburn 13666: =item $uname, student's name
1.297 matthew 13667:
1.1235 raeburn 13668: =item $uid, student's user id
1.297 matthew 13669:
1.1235 raeburn 13670: =item $first, student's first name
1.297 matthew 13671:
13672: =item $middle
13673:
13674: =item $last
13675:
13676: =item $gene
13677:
13678: =item $usec
13679:
13680: =item $end
13681:
13682: =item $start
13683:
1.957 raeburn 13684: =item $type
13685:
13686: =item $locktype
13687:
13688: =item $cid
13689:
13690: =item $selfenroll
13691:
13692: =item $context
13693:
1.1216 raeburn 13694: =item $credits, number of credits student will earn from this class
13695:
1.297 matthew 13696: =back
13697:
1.191 harris41 13698:
13699: =item *
13700:
1.243 albertel 13701: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
13702: custom role; give a custom role to a user for the level given by URL. Specify
13703: name and domain of role author, and role name
1.191 harris41 13704:
13705: =item *
13706:
1.243 albertel 13707: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 13708:
13709: =item *
13710:
1.243 albertel 13711: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
13712:
13713: =back
13714:
13715: =head2 Course Infomation
13716:
13717: =over 4
1.191 harris41 13718:
13719: =item *
13720:
1.1118 foxr 13721: coursedescription($courseid,$options) : returns a hash of information about the
1.631 albertel 13722: specified course id, including all environment settings for the
13723: course, the description of the course will be in the hash under the
13724: key 'description'
1.191 harris41 13725:
1.1118 foxr 13726: $options is an optional parameter that if supplied is a hash reference that controls
13727: what how this function works. It has the following key/values:
13728:
13729: =over 4
13730:
13731: =item freshen_cache
13732:
13733: If defined, and the environment cache for the course is valid, it is
13734: returned in the returned hash.
13735:
13736: =item one_time
13737:
13738: If defined, the last cache time is set to _now_
13739:
13740: =item user
13741:
13742: If defined, the supplied username is used instead of the current user.
13743:
13744:
13745: =back
13746:
1.191 harris41 13747: =item *
13748:
1.624 albertel 13749: resdata($name,$domain,$type,@which) : request for current parameter
13750: setting for a specific $type, where $type is either 'course' or 'user',
13751: @what should be a list of parameters to ask about. This routine caches
1.1235 raeburn 13752: answers for 10 minutes.
1.243 albertel 13753:
1.877 foxr 13754: =item *
13755:
13756: get_courseresdata($courseid, $domain) : dump the entire course resource
13757: data base, returning a hash that is keyed by the resource name and has
13758: values that are the resource value. I believe that the timestamps and
13759: versions are also returned.
13760:
1.1236 raeburn 13761: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
13762: supplemental content area. This routine caches the number of files for
13763: 10 minutes.
13764:
1.243 albertel 13765: =back
13766:
13767: =head2 Course Modification
13768:
13769: =over 4
1.191 harris41 13770:
13771: =item *
13772:
1.243 albertel 13773: writecoursepref($courseid,%prefs) : write preferences (environment
13774: database) for a course
1.191 harris41 13775:
13776: =item *
13777:
1.1011 raeburn 13778: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
13779:
13780: =item *
13781:
1.1038 raeburn 13782: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 13783:
1.1167 droeschl 13784: =item *
13785:
13786: is_course($courseid), is_course($cdom, $cnum)
13787:
13788: Accepts either a combined $courseid (in the form of domain_courseid) or the
13789: two component version $cdom, $cnum. It checks if the specified course exists.
13790:
13791: Returns:
13792: undef if the course doesn't exist, otherwise
13793: in scalar context the combined courseid.
13794: in list context the two components of the course identifier, domain and
13795: courseid.
13796:
1.243 albertel 13797: =back
13798:
13799: =head2 Resource Subroutines
13800:
13801: =over 4
1.191 harris41 13802:
13803: =item *
13804:
1.243 albertel 13805: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 13806:
13807: =item *
13808:
1.243 albertel 13809: repcopy($filename) : subscribes to the requested file, and attempts to
13810: replicate from the owning library server, Might return
1.607 raeburn 13811: 'unavailable', 'not_found', 'forbidden', 'ok', or
13812: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 13813: resource. Expects the local filesystem pathname
13814: (/home/httpd/html/res/....)
13815:
13816: =back
13817:
13818: =head2 Resource Information
13819:
13820: =over 4
1.191 harris41 13821:
13822: =item *
13823:
1.1228 raeburn 13824: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates
13825: and returns the value of a variety of different possible values,
13826: $varname should be a request string, and the other parameters can be
13827: used to specify who and what one is asking about. Ordinarily, $cid
13828: does not need to be specified, as it is retrived from
13829: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
13830: within lonuserstate::loadmap() when initializing a course, before
13831: $env{'request.course.id'} has been set, so it needs to be provided
13832: in that one case.
1.243 albertel 13833:
13834: Possible values for $varname are environment.lastname (or other item
13835: from the envirnment hash), user.name (or someother aspect about the
13836: user), resource.0.maxtries (or some other part and parameter of a
13837: resource)
1.204 albertel 13838:
13839: =item *
13840:
1.243 albertel 13841: directcondval($number) : get current value of a condition; reads from a state
13842: string
1.204 albertel 13843:
13844: =item *
13845:
1.243 albertel 13846: condval($condidx) : value of condition index based on state
1.204 albertel 13847:
13848: =item *
13849:
1.243 albertel 13850: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
13851: resource's metadata, $what should be either a specific key, or either
13852: 'keys' (to get a list of possible keys) or 'packages' to get a list of
13853: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
13854:
13855: this function automatically caches all requests
1.191 harris41 13856:
13857: =item *
13858:
1.243 albertel 13859: metadata_query($query,$custom,$customshow) : make a metadata query against the
13860: network of library servers; returns file handle of where SQL and regex results
13861: will be stored for query
1.191 harris41 13862:
13863: =item *
13864:
1.1282 raeburn 13865: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
13866: return symbolic list entry (all arguments optional).
13867:
13868: Args: filename is the filename (including path) for the file for which a symb
13869: is required; donotrecurse, if true will prevent calls to allowed() being made
13870: to check access status if more than one resource was found in the bighash
13871: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
13872: a randompick); ignorecachednull, if true will prevent a symb of '' being
13873: returned if $env{$cache_str} is defined as ''; checkforblock if true will
13874: cause possible symbs to be checked to determine if they are subject to content
13875: blocking, if so they will not be included as possible symbs; possibles is a
13876: ref to a hash, which, as a side effect, will be populated with all possible
13877: symbs (content blocking not tested).
13878:
1.243 albertel 13879: returns the data handle
1.191 harris41 13880:
13881: =item *
13882:
1.1190 raeburn 13883: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
13884: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582 albertel 13885: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190 raeburn 13886: on failure, user must be in a course, as it assumes the existence of
13887: the course initial hash, and uses $env('request.course.id'}. The third
13888: arg is an optional reference to a scalar. If this arg is passed in the
13889: call to symbverify, it will be set to 1 if the symb has been set to be
13890: encrypted; otherwise it will be null.
1.191 harris41 13891:
13892: =item *
13893:
1.243 albertel 13894: symbclean($symb) : removes versions numbers from a symb, returns the
13895: cleaned symb
1.191 harris41 13896:
13897: =item *
13898:
1.243 albertel 13899: is_on_map($uri) : checks if the $uri is somewhere on the current
13900: course map, user must be in a course for it to work.
1.191 harris41 13901:
13902: =item *
13903:
1.243 albertel 13904: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 13905:
13906: =item *
13907:
1.243 albertel 13908: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
13909: a random seed, all arguments are optional, if they aren't sent it uses the
13910: environment to derive them. Note: if symb isn't sent and it can't get one
13911: from &symbread it will use the current time as its return value
1.191 harris41 13912:
13913: =item *
13914:
1.243 albertel 13915: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
13916: unfakeable, receipt
1.191 harris41 13917:
13918: =item *
13919:
1.620 albertel 13920: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 13921:
13922: =item *
13923:
1.243 albertel 13924: countacc($url) : count the number of accesses to a given URL
1.191 harris41 13925:
13926: =item *
13927:
1.243 albertel 13928: 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 13929:
13930: =item *
13931:
1.243 albertel 13932: 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 13933:
13934: =item *
13935:
1.243 albertel 13936: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 13937:
13938: =item *
13939:
1.243 albertel 13940: devalidate($symb) : devalidate temporary spreadsheet calculations,
13941: forcing spreadsheet to reevaluate the resource scores next time.
13942:
1.1195 raeburn 13943: =item *
13944:
1.1196 raeburn 13945: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
13946: when viewing in course context.
1.1195 raeburn 13947:
1.1196 raeburn 13948: input: six args -- filename (decluttered), course number, course domain,
13949: url, symb (if registered) and group (if this is a
13950: group item -- e.g., bulletin board, group page etc.).
1.1195 raeburn 13951:
1.1196 raeburn 13952: output: array of five scalars --
1.1195 raeburn 13953: $cfile -- url for file editing if editable on current server
13954: $home -- homeserver of resource (i.e., for author if published,
13955: or course if uploaded.).
13956: $switchserver -- 1 if server switch will be needed.
1.1196 raeburn 13957: $forceedit -- 1 if icon/link should be to go to edit mode
13958: $forceview -- 1 if icon/link should be to go to view mode
1.1195 raeburn 13959:
13960: =item *
13961:
13962: is_course_upload($file,$cnum,$cdom)
13963:
13964: Used in course context to determine if current file was uploaded to
13965: the course (i.e., would be found in /userfiles/docs on the course's
13966: homeserver.
13967:
13968: input: 3 args -- filename (decluttered), course number and course domain.
13969: output: boolean -- 1 if file was uploaded.
13970:
1.243 albertel 13971: =back
13972:
13973: =head2 Storing/Retreiving Data
13974:
13975: =over 4
1.191 harris41 13976:
13977: =item *
13978:
1.1269 raeburn 13979: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
13980: permanently for this url; hashref needs to be given and should be a \%hashname;
13981: the remaining args aren't required and if they aren't passed or are '' they will
13982: be derived from the env (with the exception of $laststore, which is an
13983: optional arg used when a user's submission is stored in grading).
13984: $laststore is $version=$timestamp, where $version is the most recent version
13985: number retrieved for the corresponding $symb in the $namespace db file, and
13986: $timestamp is the timestamp for that transaction (UNIX time).
13987: $laststore is currently only passed when cstore() is called by
13988: structuretags::finalize_storage().
1.191 harris41 13989:
13990: =item *
13991:
1.1269 raeburn 13992: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
13993: but uses critical subroutine
1.191 harris41 13994:
13995: =item *
13996:
1.243 albertel 13997: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
13998: all args are optional
1.191 harris41 13999:
14000: =item *
14001:
1.717 albertel 14002: dumpstore($namespace,$udom,$uname,$regexp,$range) :
14003: dumps the complete (or key matching regexp) namespace into a hash
14004: ($udom, $uname, $regexp, $range are optional) for a namespace that is
14005: normally &store()ed into
14006:
14007: $range should be either an integer '100' (give me the first 100
14008: matching records)
14009: or be two integers sperated by a - with no spaces
14010: '30-50' (give me the 30th through the 50th matching
14011: records)
14012:
14013:
14014: =item *
14015:
1.1269 raeburn 14016: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717 albertel 14017: replaces a &store() version of data with a replacement set of data
14018: for a particular resource in a namespace passed in the $storehash hash
1.1269 raeburn 14019: reference. If $tolog is true, the transaction is logged in the courselog
14020: with an action=PUTSTORE.
1.717 albertel 14021:
14022: =item *
14023:
1.243 albertel 14024: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
14025: works very similar to store/cstore, but all data is stored in a
14026: temporary location and can be reset using tmpreset, $storehash should
14027: be a hash reference, returns nothing on success
1.191 harris41 14028:
14029: =item *
14030:
1.243 albertel 14031: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
14032: similar to restore, but all data is stored in a temporary location and
14033: can be reset using tmpreset. Returns a hash of values on success,
14034: error string otherwise.
1.191 harris41 14035:
14036: =item *
14037:
1.243 albertel 14038: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
14039: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 14040:
14041: =item *
14042:
1.243 albertel 14043: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
14044: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 14045:
14046: =item *
14047:
1.243 albertel 14048: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
14049: namesp ($udom and $uname are optional)
1.191 harris41 14050:
14051: =item *
14052:
1.702 albertel 14053: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 14054: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 14055: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 14056:
1.702 albertel 14057: $range should be either an integer '100' (give me the first 100
14058: matching records)
14059: or be two integers sperated by a - with no spaces
14060: '30-50' (give me the 30th through the 50th matching
14061: records)
1.449 matthew 14062: =item *
14063:
14064: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
14065: $store can be a scalar, an array reference, or if the amount to be
14066: incremented is > 1, a hash reference.
14067:
14068: ($udom and $uname are optional)
1.191 harris41 14069:
14070: =item *
14071:
1.243 albertel 14072: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
14073: ($udom and $uname are optional)
1.191 harris41 14074:
14075: =item *
14076:
1.243 albertel 14077: cput($namespace,$storehash,$udom,$uname) : critical put
14078: ($udom and $uname are optional)
1.191 harris41 14079:
14080: =item *
14081:
1.748 albertel 14082: newput($namespace,$storehash,$udom,$uname) :
14083:
14084: Attempts to store the items in the $storehash, but only if they don't
14085: currently exist, if this succeeds you can be certain that you have
14086: successfully created a new key value pair in the $namespace db.
14087:
14088:
14089: Args:
14090: $namespace: name of database to store values to
14091: $storehash: hashref to store to the db
14092: $udom: (optional) domain of user containing the db
14093: $uname: (optional) name of user caontaining the db
14094:
14095: Returns:
14096: 'ok' -> succeeded in storing all keys of $storehash
14097: 'key_exists: <key>' -> failed to anything out of $storehash, as at
14098: least <key> already existed in the db (other
14099: requested keys may also already exist)
1.967 bisitz 14100: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 14101: 'con_lost' -> unable to contact request server
14102: 'refused' -> action was not allowed by remote machine
14103:
14104:
14105: =item *
14106:
1.243 albertel 14107: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
14108: reference filled in from namesp (encrypts the return communication)
14109: ($udom and $uname are optional)
1.191 harris41 14110:
14111: =item *
14112:
1.243 albertel 14113: log($udom,$name,$home,$message) : write to permanent log for user; use
14114: critical subroutine
14115:
1.806 raeburn 14116: =item *
14117:
1.860 raeburn 14118: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
14119: array reference filled in from namespace found in domain level on either
14120: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 14121:
14122: =item *
14123:
1.860 raeburn 14124: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
14125: domain level either on specified domain server ($uhome) or primary domain
14126: server ($udom and $uhome are optional)
1.806 raeburn 14127:
1.943 raeburn 14128: =item *
14129:
1.1240 raeburn 14130: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
14131: for: authentication, language, quotas, timezone, date locale, and portal URL in
14132: the target domain.
14133:
14134: May also include additional key => value pairs for the following groups:
14135:
14136: =over
14137:
14138: =item
14139: disk quotas (MB allocated by default to portfolios and authoring spaces).
14140:
14141: =over
14142:
14143: =item defaultquota, authorquota
14144:
14145: =back
14146:
14147: =item
14148: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
14149: portfolio for users).
14150:
14151: =over
14152:
14153: =item
14154: aboutme, blog, webdav, portfolio
14155:
14156: =back
14157:
14158: =item
14159: requestcourses: ability to request courses, and how requests are processed.
14160:
14161: =over
14162:
14163: =item
1.1305 ! raeburn 14164: official, unofficial, community, textbook, placement
1.1240 raeburn 14165:
14166: =back
14167:
14168: =item
14169: inststatus: types of institutional affiliation, and order in which they are displayed.
14170:
14171: =over
14172:
14173: =item
1.1256 raeburn 14174: inststatustypes, inststatusorder, inststatusguest
1.1240 raeburn 14175:
14176: =back
14177:
14178: =item
14179: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
14180: for course's uploaded content.
14181:
14182: =over
14183:
14184: =item
1.1246 raeburn 14185: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
1.1305 ! raeburn 14186: communityquota, textbookquota, placementquota
1.1240 raeburn 14187:
14188: =back
14189:
14190: =item
14191: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
14192: on your servers.
14193:
14194: =over
14195:
14196: =item
14197: remotesessions, hostedsessions
14198:
14199: =back
14200:
14201: =back
14202:
14203: In cases where a domain coordinator has never used the "Set Domain Configuration"
14204: utility to create a configuration.db file on a domain's primary library server
14205: only the following domain defaults: auth_def, auth_arg_def, lang_def
14206: -- corresponding values are authentication type (internal, krb4, krb5,
14207: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
14208: will be available. Values are retrieved from cache (if current), unless the
14209: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
14210: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
14211:
14212: Typical usage:
1.943 raeburn 14213:
1.1240 raeburn 14214: %domdefaults = &get_domain_defaults($target_domain);
1.943 raeburn 14215:
1.243 albertel 14216: =back
14217:
14218: =head2 Network Status Functions
14219:
14220: =over 4
1.191 harris41 14221:
14222: =item *
14223:
1.1137 raeburn 14224: dirlist() : return directory list based on URI (first arg).
14225:
14226: Inputs: 1 required, 5 optional.
14227:
14228: =over
14229:
14230: =item
14231: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
14232:
14233: =item
14234: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
14235:
14236: =item
14237: $username - username of user/course to be listed. Extracted from $uri if absent.
14238:
14239: =item
14240: $getpropath - boolean: 1 if prepend path using &propath().
14241:
14242: =item
14243: $getuserdir - boolean: 1 if prepend path for "userfiles".
14244:
14245: =item
14246: $alternateRoot - path to prepend in place of path from $uri.
14247:
14248: =back
14249:
14250: Returns: Array of up to two items.
14251:
14252: =over
14253:
14254: a reference to an array of files/subdirectories
14255:
14256: =over
14257:
14258: Each element in the array of files/subdirectories is a & separated list of
14259: item name and the result of running stat on the item. If dirlist was requested
14260: for a file instead of a directory, the item name will be ''. For a directory
14261: listing, if the item is a metadata file, the element will end &N&M
14262: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
14263: default copyright set (1).
14264:
14265: =back
14266:
14267: a scalar containing error condition (if encountered).
14268:
14269: =over
14270:
14271: =item
14272: no_host (no homeserver identified for $username:$domain).
14273:
14274: =item
14275: no_such_host (server contacted for listing not identified as valid host).
14276:
14277: =item
14278: con_lost (connection to remote server failed).
14279:
14280: =item
14281: refused (invalid $username:$domain received on lond side).
14282:
14283: =item
14284: no_such_dir (directory at specified path on lond side does not exist).
14285:
14286: =item
14287: empty (directory at specified path on lond side is empty).
14288:
14289: =over
14290:
14291: This is currently not encountered because the &ls3, &ls2,
14292: &ls (_handler) routines on the lond side do not filter out
14293: . and .. from a directory listing.
14294:
14295: =back
14296:
14297: =back
14298:
14299: =back
1.191 harris41 14300:
14301: =item *
14302:
1.243 albertel 14303: spareserver() : find server with least workload from spare.tab
14304:
1.986 foxr 14305:
14306: =item *
14307:
14308: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
14309: if there is no corresponding loncapa host.
14310:
1.243 albertel 14311: =back
14312:
1.986 foxr 14313:
1.243 albertel 14314: =head2 Apache Request
14315:
14316: =over 4
1.191 harris41 14317:
14318: =item *
14319:
1.243 albertel 14320: ssi($url,%hash) : server side include, does a complete request cycle on url to
14321: localhost, posts hash
14322:
14323: =back
14324:
14325: =head2 Data to String to Data
14326:
14327: =over 4
1.191 harris41 14328:
14329: =item *
14330:
1.243 albertel 14331: hash2str(%hash) : convert a hash into a string complete with escaping and '='
14332: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 14333:
14334: =item *
14335:
1.243 albertel 14336: hashref2str($hashref) : convert a hashref into a string complete with
14337: escaping and '=' and '&' separators, supports elements that are
14338: arrayrefs and hashrefs
1.191 harris41 14339:
14340: =item *
14341:
1.243 albertel 14342: arrayref2str($arrayref) : convert an arrayref into a string complete
14343: with escaping and '&' separators, supports elements that are arrayrefs
14344: and hashrefs
1.191 harris41 14345:
14346: =item *
14347:
1.243 albertel 14348: str2hash($string) : convert string to hash using unescaping and
14349: splitting on '=' and '&', supports elements that are arrayrefs and
14350: hashrefs
1.191 harris41 14351:
14352: =item *
14353:
1.243 albertel 14354: str2array($string) : convert string to hash using unescaping and
14355: splitting on '&', supports elements that are arrayrefs and hashrefs
14356:
14357: =back
14358:
14359: =head2 Logging Routines
14360:
14361:
14362: These routines allow one to make log messages in the lonnet.log and
14363: lonnet.perm logfiles.
1.191 harris41 14364:
1.1119 foxr 14365: =over 4
14366:
1.191 harris41 14367: =item *
14368:
1.243 albertel 14369: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 14370:
14371: =item *
14372:
1.243 albertel 14373: logthis() : append message to the normal lonnet.log file, it gets
14374: preiodically rolled over and deleted.
1.191 harris41 14375:
14376: =item *
14377:
1.243 albertel 14378: logperm() : append a permanent message to lonnet.perm.log, this log
14379: file never gets deleted by any automated portion of the system, only
14380: messages of critical importance should go in here.
14381:
1.1119 foxr 14382:
1.243 albertel 14383: =back
14384:
14385: =head2 General File Helper Routines
14386:
14387: =over 4
1.191 harris41 14388:
14389: =item *
14390:
1.481 raeburn 14391: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
14392: (a) files in /uploaded
14393: (i) If a local copy of the file exists -
14394: compares modification date of local copy with last-modified date for
14395: definitive version stored on home server for course. If local copy is
14396: stale, requests a new version from the home server and stores it.
14397: If the original has been removed from the home server, then local copy
14398: is unlinked.
14399: (ii) If local copy does not exist -
14400: requests the file from the home server and stores it.
14401:
14402: If $caller is 'uploadrep':
14403: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
14404: for request for files originally uploaded via DOCS.
14405: - returns 'ok' if fresh local copy now available, -1 otherwise.
14406:
14407: Otherwise:
14408: This indicates a call from the content generation phase of the request.
14409: - returns the entire contents of the file or -1.
14410:
14411: (b) files in /res
14412: - returns the entire contents of a file or -1;
14413: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 14414:
1.712 albertel 14415:
14416: =item *
14417:
14418: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
14419: reference
14420:
14421: returns either a stat() list of data about the file or an empty list
14422: if the file doesn't exist or couldn't find out about it (connection
14423: problems or user unknown)
14424:
1.191 harris41 14425: =item *
14426:
1.243 albertel 14427: filelocation($dir,$file) : returns file system location of a file
14428: based on URI; meant to be "fairly clean" absolute reference, $dir is a
14429: directory that relative $file lookups are to looked in ($dir of /a/dir
14430: and a file of ../bob will become /a/bob)
1.191 harris41 14431:
14432: =item *
14433:
14434: hreflocation($dir,$file) : returns file system location or a URL; same as
14435: filelocation except for hrefs
14436:
14437: =item *
14438:
1.1261 raeburn 14439: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
14440: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191 harris41 14441:
1.243 albertel 14442: =back
14443:
1.608 albertel 14444: =head2 Usererfile file routines (/uploaded*)
14445:
14446: =over 4
14447:
14448: =item *
14449:
14450: userfileupload(): main rotine for putting a file in a user or course's
14451: filespace, arguments are,
14452:
1.620 albertel 14453: formname - required - this is the name of the element in $env where the
1.608 albertel 14454: filename, and the contents of the file to create/modifed exist
1.620 albertel 14455: the filename is in $env{'form.'.$formname.'.filename'} and the
14456: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 14457: context - if coursedoc, store the file in the course of the active role
14458: of the current user;
14459: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
14460: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 14461: subdir - required - subdirectory to put the file in under ../userfiles/
14462: if undefined, it will be placed in "unknown"
14463:
14464: (This routine calls clean_filename() to remove any dangerous
14465: characters from the filename, and then calls finuserfileupload() to
14466: complete the transaction)
14467:
14468: returns either the url of the uploaded file (/uploaded/....) if successful
14469: and /adm/notfound.html if unsuccessful
14470:
14471: =item *
14472:
14473: clean_filename(): routine for cleaing a filename up for storage in
14474: userfile space, argument is:
14475:
14476: filename - proposed filename
14477:
14478: returns: the new clean filename
14479:
14480: =item *
14481:
1.1090 raeburn 14482: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 14483: userspace, probably shouldn't be called directly
14484:
14485: docuname: username or courseid of destination for the file
14486: docudom: domain of user/course of destination for the file
14487: formname: same as for userfileupload()
1.1090 raeburn 14488: fname: filename (including subdirectories) for the file
14489: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
14490: allfiles: reference to hash used to store objects found by parser
14491: codebase: reference to hash used for codebases of java objects found by parser
14492: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
14493: thumbheight: height (pixels) of thumbnail to be created for uploaded image
14494: resizewidth: width to be used to resize image using resizeImage from ImageMagick
14495: resizeheight: height to be used to resize image using resizeImage from ImageMagick
14496: context: if 'overwrite', will move the uploaded file from its temporary location to
14497: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 14498: mimetype: reference to scalar to accommodate mime type determined
14499: from File::MMagic if $parser = parse.
1.608 albertel 14500:
14501: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 14502: and /adm/notfound.html if unsuccessful (or an error message if context
14503: was 'overwrite').
14504:
1.608 albertel 14505:
14506: =item *
14507:
14508: renameuserfile(): renames an existing userfile to a new name
14509:
14510: Args:
14511: docuname: username or courseid of destination for the file
14512: docudom: domain of user/course of destination for the file
14513: old: current file name (including any subdirs under userfiles)
14514: new: desired file name (including any subdirs under userfiles)
14515:
14516: =item *
14517:
14518: mkdiruserfile(): creates a directory is a userfiles dir
14519:
14520: Args:
14521: docuname: username or courseid of destination for the file
14522: docudom: domain of user/course of destination for the file
14523: dir: dir to create (including any subdirs under userfiles)
14524:
14525: =item *
14526:
14527: removeuserfile(): removes a file that exists in userfiles
14528:
14529: Args:
14530: docuname: username or courseid of destination for the file
14531: docudom: domain of user/course of destination for the file
14532: fname: filname to delete (including any subdirs under userfiles)
14533:
14534: =item *
14535:
14536: removeuploadedurl(): convience function for removeuserfile()
14537:
14538: Args:
14539: url: a full /uploaded/... url to delete
14540:
1.747 albertel 14541: =item *
14542:
14543: get_portfile_permissions():
14544: Args:
14545: domain: domain of user or course contain the portfolio files
14546: user: name of user or num of course contain the portfolio files
14547: Returns:
14548: hashref of a dump of the proper file_permissions.db
14549:
14550:
14551: =item *
14552:
14553: get_access_controls():
14554:
14555: Args:
14556: current_permissions: the hash ref returned from get_portfile_permissions()
14557: group: (optional) the group you want the files associated with
14558: file: (optional) the file you want access info on
14559:
14560: Returns:
1.749 raeburn 14561: a hash (keys are file names) of hashes containing
14562: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
14563: values are XML containing access control settings (see below)
1.747 albertel 14564:
14565: Internal notes:
14566:
1.749 raeburn 14567: access controls are stored in file_permissions.db as key=value pairs.
14568: key -> path to file/file_name\0uniqueID:scope_end_start
14569: where scope -> public,guest,course,group,domains or users.
14570: end -> UNIX time for end of access (0 -> no end date)
14571: start -> UNIX time for start of access
14572:
14573: value -> XML description of access control
14574: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
14575: <start></start>
14576: <end></end>
14577:
14578: <password></password> for scope type = guest
14579:
14580: <domain></domain> for scope type = course or group
14581: <number></number>
14582: <roles id="">
14583: <role></role>
14584: <access></access>
14585: <section></section>
14586: <group></group>
14587: </roles>
14588:
14589: <dom></dom> for scope type = domains
14590:
14591: <users> for scope type = users
14592: <user>
14593: <uname></uname>
14594: <udom></udom>
14595: </user>
14596: </users>
14597: </scope>
14598:
14599: Access data is also aggregated for each file in an additional key=value pair:
14600: key -> path to file/file_name\0accesscontrol
14601: value -> reference to hash
14602: hash contains key = value pairs
14603: where key = uniqueID:scope_end_start
14604: value = UNIX time record was last updated
14605:
14606: Used to improve speed of look-ups of access controls for each file.
14607:
14608: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
14609:
1.1198 raeburn 14610: =item *
14611:
1.749 raeburn 14612: modify_access_controls():
14613:
14614: Modifies access controls for a portfolio file
14615: Args
14616: 1. file name
14617: 2. reference to hash of required changes,
14618: 3. domain
14619: 4. username
14620: where domain,username are the domain of the portfolio owner
14621: (either a user or a course)
14622:
14623: Returns:
14624: 1. result of additions or updates ('ok' or 'error', with error message).
14625: 2. result of deletions ('ok' or 'error', with error message).
14626: 3. reference to hash of any new or updated access controls.
14627: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
14628: key = integer (inbound ID)
1.1198 raeburn 14629: value = uniqueID
14630:
14631: =item *
14632:
14633: get_timebased_id():
14634:
14635: Attempts to get a unique timestamp-based suffix for use with items added to a
14636: course via the Course Editor (e.g., folders, composite pages,
14637: group bulletin boards).
14638:
14639: Args: (first three required; six others optional)
14640:
14641: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
14642: docssequence, or name of group
14643:
14644: 2. keyid (alphanumeric): name of temporary locking key in hash,
14645: e.g., num, boardids
14646:
14647: 3. namespace: name of gdbm file used to store suffixes already assigned;
14648: file will be named nohist_namespace.db
14649:
14650: 4. cdom: domain of course; default is current course domain from %env
14651:
14652: 5. cnum: course number; default is current course number from %env
14653:
14654: 6. idtype: set to concat if an additional digit is to be appended to the
14655: unix timestamp to form the suffix, if the plain timestamp is already
14656: in use. Default is to not do this, but simply increment the unix
14657: timestamp by 1 until a unique key is obtained.
14658:
14659: 7. who: holder of locking key; defaults to user:domain for user.
14660:
14661: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
14662: retrying); default is 3.
14663:
14664: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
14665:
14666: Returns:
14667:
14668: 1. suffix obtained (numeric)
14669:
14670: 2. result of deleting locking key (ok if deleted, or lock never obtained)
14671:
14672: 3. error: contains (localized) error message if an error occurred.
14673:
1.747 albertel 14674:
1.608 albertel 14675: =back
14676:
1.243 albertel 14677: =head2 HTTP Helper Routines
14678:
14679: =over 4
14680:
1.191 harris41 14681: =item *
14682:
14683: escape() : unpack non-word characters into CGI-compatible hex codes
14684:
14685: =item *
14686:
14687: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
14688:
1.243 albertel 14689: =back
14690:
14691: =head1 PRIVATE SUBROUTINES
14692:
14693: =head2 Underlying communication routines (Shouldn't call)
14694:
14695: =over 4
14696:
14697: =item *
14698:
14699: subreply() : tries to pass a message to lonc, returns con_lost if incapable
14700:
14701: =item *
14702:
14703: reply() : uses subreply to send a message to remote machine, logs all failures
14704:
14705: =item *
14706:
14707: critical() : passes a critical message to another server; if cannot
14708: get through then place message in connection buffer directory and
14709: returns con_delayed, if incapable of saving message, returns
14710: con_failed
14711:
14712: =item *
14713:
14714: reconlonc() : tries to reconnect lonc client processes.
14715:
14716: =back
14717:
14718: =head2 Resource Access Logging
14719:
14720: =over 4
14721:
14722: =item *
14723:
14724: flushcourselogs() : flush (save) buffer logs and access logs
14725:
14726: =item *
14727:
14728: courselog($what) : save message for course in hash
14729:
14730: =item *
14731:
14732: courseacclog($what) : save message for course using &courselog(). Perform
14733: special processing for specific resource types (problems, exams, quizzes, etc).
14734:
1.191 harris41 14735: =item *
14736:
14737: goodbye() : flush course logs and log shutting down; it is called in srm.conf
14738: as a PerlChildExitHandler
1.243 albertel 14739:
14740: =back
14741:
14742: =head2 Other
14743:
14744: =over 4
14745:
14746: =item *
14747:
14748: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 14749:
14750: =back
14751:
14752: =cut
1.877 foxr 14753:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>