Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1317
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1317 ! raeburn 4: # $Id: lonnet.pm,v 1.1316 2016/08/01 18:05:22 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.1315 raeburn 232: sub get_servercerts_info {
233: my ($lonhost,$context) = @_;
234: my ($rep,$uselocal);
235: if (grep { $_ eq $lonhost } ¤t_machine_ids()) {
236: $uselocal = 1;
237: }
1.1316 raeburn 238: if (($context ne 'cgi') && ($uselocal)) {
1.1315 raeburn 239: my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
240: if ($distro =~ /^(?:centos|redhat|scientific)(\d+)$/) {
241: if ($1 < 6) {
242: $uselocal = 0;
243: }
244: }
245: }
246: if ($uselocal) {
247: $rep = LONCAPA::Lond::server_certs(\%perlvar);
248: } else {
249: $rep=&reply('servercerts',$lonhost);
250: }
251: my ($result,%returnhash);
252: if (defined($lonhost)) {
253: if (!defined(&hostname($lonhost))) {
254: return;
255: }
256: }
257: if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
258: ($rep eq 'unknown_cmd')) {
259: $result = $rep;
260: } else {
261: $result = 'ok';
262: my @pairs=split(/\&/,$rep);
263: foreach my $item (@pairs) {
264: my ($key,$value)=split(/=/,$item,2);
265: my $what = &unescape($key);
266: $returnhash{$what}=&thaw_unescape($value);
267: }
268: }
269: return ($result,\%returnhash);
270: }
271:
1.993 raeburn 272: sub get_server_loncaparev {
1.1073 raeburn 273: my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993 raeburn 274: if (defined($lonhost)) {
275: if (!defined(&hostname($lonhost))) {
276: undef($lonhost);
277: }
278: }
279: if (!defined($lonhost)) {
280: if (defined(&domain($dom,'primary'))) {
281: $lonhost=&domain($dom,'primary');
282: if ($lonhost eq 'no_host') {
283: undef($lonhost);
284: }
285: }
286: }
287: if (defined($lonhost)) {
1.1073 raeburn 288: my $cachetime = 12*3600;
289: if (!$ignore_cache) {
290: my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
291: if (defined($cached)) {
292: return $loncaparev;
293: }
294: }
295: my ($answer,$loncaparev);
296: my @ids=¤t_machine_ids();
297: if (grep(/^\Q$lonhost\E$/,@ids)) {
298: $answer = $perlvar{'lonVersion'};
1.1081 raeburn 299: if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 300: $loncaparev = $1;
301: }
302: } else {
303: $answer = &reply('serverloncaparev',$lonhost);
304: if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
305: if ($caller eq 'loncron') {
306: my $ua=new LWP::UserAgent;
1.1082 raeburn 307: $ua->timeout(4);
1.1073 raeburn 308: my $protocol = $protocol{$lonhost};
309: $protocol = 'http' if ($protocol ne 'https');
310: my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
311: my $request=new HTTP::Request('GET',$url);
312: my $response=$ua->request($request);
313: unless ($response->is_error()) {
314: my $content = $response->content;
1.1081 raeburn 315: if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073 raeburn 316: $loncaparev = $1;
317: }
318: }
319: } else {
320: $loncaparev = $loncaparevs{$lonhost};
321: }
1.1081 raeburn 322: } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 323: $loncaparev = $1;
324: }
1.993 raeburn 325: }
1.1073 raeburn 326: return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993 raeburn 327: }
328: }
329:
1.1074 raeburn 330: sub get_server_homeID {
331: my ($hostname,$ignore_cache,$caller) = @_;
332: unless ($ignore_cache) {
333: my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
334: if (defined($cached)) {
335: return $serverhomeID;
336: }
337: }
338: my $cachetime = 12*3600;
339: my $serverhomeID;
340: if ($caller eq 'loncron') {
341: my @machine_ids = &machine_ids($hostname);
342: foreach my $id (@machine_ids) {
343: my $response = &reply('serverhomeID',$id);
344: unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
345: $serverhomeID = $response;
346: last;
347: }
348: }
349: if ($serverhomeID eq '') {
350: $serverhomeID = $machine_ids[-1];
351: }
352: } else {
353: $serverhomeID = $serverhomeIDs{$hostname};
354: }
355: return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
356: }
357:
1.1121 raeburn 358: sub get_remote_globals {
359: my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125 raeburn 360: my ($result,%returnhash,%whatneeded);
361: if (ref($whathash) eq 'HASH') {
1.1121 raeburn 362: foreach my $what (sort(keys(%{$whathash}))) {
363: my $hashid = $lonhost.'-'.$what;
1.1125 raeburn 364: my ($response,$cached);
1.1121 raeburn 365: unless ($ignore_cache) {
1.1125 raeburn 366: ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121 raeburn 367: }
368: if (defined($cached)) {
1.1125 raeburn 369: $returnhash{$what} = $response;
1.1121 raeburn 370: } else {
1.1125 raeburn 371: $whatneeded{$what} = 1;
1.1121 raeburn 372: }
373: }
1.1125 raeburn 374: if (keys(%whatneeded) == 0) {
375: $result = 'ok';
376: } else {
1.1121 raeburn 377: my $requested = &freeze_escape(\%whatneeded);
378: my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125 raeburn 379: if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
380: ($rep eq 'unknown_cmd')) {
381: $result = $rep;
382: } else {
383: $result = 'ok';
1.1121 raeburn 384: my @pairs=split(/\&/,$rep);
1.1125 raeburn 385: foreach my $item (@pairs) {
386: my ($key,$value)=split(/=/,$item,2);
387: my $what = &unescape($key);
388: my $hashid = $lonhost.'-'.$what;
389: $returnhash{$what}=&thaw_unescape($value);
390: &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121 raeburn 391: }
392: }
393: }
394: }
1.1125 raeburn 395: return ($result,\%returnhash);
1.1121 raeburn 396: }
397:
1.1124 raeburn 398: sub remote_devalidate_cache {
1.1241 raeburn 399: my ($lonhost,$cachekeys) = @_;
400: my $items;
401: return unless (ref($cachekeys) eq 'ARRAY');
402: my $cachestr = join('&',@{$cachekeys});
403: my $response = &reply('devalidatecache:'.&escape($cachestr),$lonhost);
1.1124 raeburn 404: return $response;
405: }
406:
1.1 albertel 407: # -------------------------------------------------- Non-critical communication
408: sub subreply {
409: my ($cmd,$server)=@_;
1.838 albertel 410: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549 foxr 411: #
412: # With loncnew process trimming, there's a timing hole between lonc server
413: # process exit and the master server picking up the listen on the AF_UNIX
414: # socket. In that time interval, a lock file will exist:
415:
416: my $lockfile=$peerfile.".lock";
417: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
1.1289 damieng 418: sleep(0.1);
1.549 foxr 419: }
420: # At this point, either a loncnew parent is listening or an old lonc
1.550 foxr 421: # or loncnew child is listening so we can connect or everything's dead.
1.549 foxr 422: #
1.550 foxr 423: # We'll give the connection a few tries before abandoning it. If
424: # connection is not possible, we'll con_lost back to the client.
425: #
426: my $client;
427: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
428: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
429: Type => SOCK_STREAM,
430: Timeout => 10);
1.869 albertel 431: if ($client) {
1.550 foxr 432: last; # Connected!
1.850 albertel 433: } else {
1.853 albertel 434: &create_connection(&hostname($server),$server);
1.550 foxr 435: }
1.1289 damieng 436: sleep(0.1); # Try again later if failed connection.
1.550 foxr 437: }
438: my $answer;
439: if ($client) {
1.704 albertel 440: print $client "sethost:$server:$cmd\n";
1.550 foxr 441: $answer=<$client>;
442: if (!$answer) { $answer="con_lost"; }
443: chomp($answer);
444: } else {
445: $answer = 'con_lost'; # Failed connection.
446: }
1.1 albertel 447: return $answer;
448: }
449:
450: sub reply {
451: my ($cmd,$server)=@_;
1.838 albertel 452: unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1 albertel 453: my $answer=subreply($cmd,$server);
1.65 www 454: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672 albertel 455: &logthis("<font color=\"blue\">WARNING:".
1.12 www 456: " $cmd to $server returned $answer</font>");
457: }
1.1 albertel 458: return $answer;
459: }
460:
461: # ----------------------------------------------------------- Send USR1 to lonc
462:
463: sub reconlonc {
1.891 albertel 464: my ($lonid) = @_;
465: if ($lonid) {
1.1295 raeburn 466: my $hostname = &hostname($lonid);
1.891 albertel 467: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
468: if ($hostname && -e $peerfile) {
469: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
470: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
471: Type => SOCK_STREAM,
472: Timeout => 10);
473: if ($client) {
474: print $client ("reset_retries\n");
475: my $answer=<$client>;
476: #reset just this one.
477: }
478: }
479: return;
480: }
481:
1.836 www 482: &logthis("Trying to reconnect lonc");
1.1 albertel 483: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448 albertel 484: if (open(my $fh,"<$loncfile")) {
1.1 albertel 485: my $loncpid=<$fh>;
486: chomp($loncpid);
487: if (kill 0 => $loncpid) {
488: &logthis("lonc at pid $loncpid responding, sending USR1");
489: kill USR1 => $loncpid;
490: sleep 1;
1.1295 raeburn 491: } else {
1.12 www 492: &logthis(
1.672 albertel 493: "<font color=\"blue\">WARNING:".
1.12 www 494: " lonc at pid $loncpid not responding, giving up</font>");
1.1 albertel 495: }
496: } else {
1.836 www 497: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1 albertel 498: }
499: }
500:
501: # ------------------------------------------------------ Critical communication
1.12 www 502:
1.1 albertel 503: sub critical {
504: my ($cmd,$server)=@_;
1.838 albertel 505: unless (&hostname($server)) {
1.672 albertel 506: &logthis("<font color=\"blue\">WARNING:".
1.89 www 507: " Critical message to unknown server ($server)</font>");
508: return 'no_such_host';
509: }
1.1 albertel 510: my $answer=reply($cmd,$server);
511: if ($answer eq 'con_lost') {
1.1295 raeburn 512: &reconlonc($server);
1.589 albertel 513: my $answer=reply($cmd,$server);
1.1 albertel 514: if ($answer eq 'con_lost') {
515: my $now=time;
516: my $middlename=$cmd;
1.5 www 517: $middlename=substr($middlename,0,16);
1.1 albertel 518: $middlename=~s/\W//g;
519: my $dfilename=
1.305 www 520: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
521: $dumpcount++;
1.1 albertel 522: {
1.448 albertel 523: my $dfh;
524: if (open($dfh,">$dfilename")) {
525: print $dfh "$cmd\n";
526: close($dfh);
527: }
1.1 albertel 528: }
1.1288 damieng 529: sleep 1;
1.1 albertel 530: my $wcmd='';
531: {
1.448 albertel 532: my $dfh;
533: if (open($dfh,"<$dfilename")) {
534: $wcmd=<$dfh>;
535: close($dfh);
536: }
1.1 albertel 537: }
538: chomp($wcmd);
1.7 www 539: if ($wcmd eq $cmd) {
1.672 albertel 540: &logthis("<font color=\"blue\">WARNING: ".
1.12 www 541: "Connection buffer $dfilename: $cmd</font>");
1.1 albertel 542: &logperm("D:$server:$cmd");
543: return 'con_delayed';
544: } else {
1.672 albertel 545: &logthis("<font color=\"red\">CRITICAL:"
1.12 www 546: ." Critical connection failed: $server $cmd</font>");
1.1 albertel 547: &logperm("F:$server:$cmd");
548: return 'con_failed';
549: }
550: }
551: }
552: return $answer;
1.405 albertel 553: }
554:
1.755 albertel 555: # ------------------------------------------- check if return value is an error
556:
557: sub error {
558: my ($result) = @_;
1.756 albertel 559: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755 albertel 560: if ($2 == 2) { return undef; }
561: return $1;
562: }
563: return undef;
564: }
565:
1.783 albertel 566: sub convert_and_load_session_env {
567: my ($lonidsdir,$handle)=@_;
568: my @profile;
569: {
1.917 albertel 570: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
571: if (!$opened) {
1.915 albertel 572: return 0;
573: }
1.783 albertel 574: flock($idf,LOCK_SH);
575: @profile=<$idf>;
576: close($idf);
577: }
578: my %temp_env;
579: foreach my $line (@profile) {
1.786 albertel 580: if ($line !~ m/=/) {
581: return 0;
582: }
1.783 albertel 583: chomp($line);
584: my ($envname,$envvalue)=split(/=/,$line,2);
585: $temp_env{&unescape($envname)} = &unescape($envvalue);
586: }
587: unlink("$lonidsdir/$handle.id");
588: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
589: 0640)) {
590: %disk_env = %temp_env;
591: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
592: untie(%disk_env);
593: }
1.786 albertel 594: return 1;
1.783 albertel 595: }
596:
1.374 www 597: # ------------------------------------------- Transfer profile into environment
1.780 albertel 598: my $env_loaded;
599: sub transfer_profile_to_env {
1.788 albertel 600: my ($lonidsdir,$handle,$force_transfer) = @_;
601: if (!$force_transfer && $env_loaded) { return; }
1.374 www 602:
1.720 albertel 603: if (!defined($lonidsdir)) {
604: $lonidsdir = $perlvar{'lonIDsDir'};
605: }
606: if (!defined($handle)) {
607: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
608: }
609:
1.786 albertel 610: my $convert;
611: {
1.917 albertel 612: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
613: if (!$opened) {
1.915 albertel 614: return;
615: }
1.786 albertel 616: flock($idf,LOCK_SH);
617: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
618: &GDBM_READER(),0640)) {
619: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
620: untie(%disk_env);
621: } else {
622: $convert = 1;
623: }
624: }
625: if ($convert) {
626: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
627: &logthis("Failed to load session, or convert session.");
628: }
1.374 www 629: }
1.783 albertel 630:
1.786 albertel 631: my %remove;
1.783 albertel 632: while ( my $envname = each(%env) ) {
1.433 matthew 633: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
634: if ($time < time-300) {
1.783 albertel 635: $remove{$key}++;
1.433 matthew 636: }
637: }
638: }
1.783 albertel 639:
1.619 albertel 640: $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780 albertel 641: $env_loaded=1;
1.783 albertel 642: foreach my $expired_key (keys(%remove)) {
1.433 matthew 643: &delenv($expired_key);
1.374 www 644: }
1.1 albertel 645: }
646:
1.916 albertel 647: # ---------------------------------------------------- Check for valid session
648: sub check_for_valid_session {
1.1245 raeburn 649: my ($r,$name,$userhashref) = @_;
1.916 albertel 650: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1155 raeburn 651: if ($name eq '') {
652: $name = 'lonID';
653: }
654: my $lonid=$cookies{$name};
1.916 albertel 655: return undef if (!$lonid);
656:
657: my $handle=&LONCAPA::clean_handle($lonid->value);
1.1155 raeburn 658: my $lonidsdir;
659: if ($name eq 'lonDAV') {
660: $lonidsdir=$r->dir_config('lonDAVsessDir');
661: } else {
662: $lonidsdir=$r->dir_config('lonIDsDir');
663: }
1.916 albertel 664: return undef if (!-e "$lonidsdir/$handle.id");
665:
1.917 albertel 666: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
667: return undef if (!$opened);
1.916 albertel 668:
669: flock($idf,LOCK_SH);
670: my %disk_env;
671: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
672: &GDBM_READER(),0640)) {
673: return undef;
674: }
675:
676: if (!defined($disk_env{'user.name'})
677: || !defined($disk_env{'user.domain'})) {
678: return undef;
679: }
1.1245 raeburn 680:
681: if (ref($userhashref) eq 'HASH') {
682: $userhashref->{'name'} = $disk_env{'user.name'};
683: $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1212 raeburn 684: }
1.1245 raeburn 685:
1.916 albertel 686: return $handle;
687: }
688:
1.830 albertel 689: sub timed_flock {
690: my ($file,$lock_type) = @_;
691: my $failed=0;
692: eval {
693: local $SIG{__DIE__}='DEFAULT';
694: local $SIG{ALRM}=sub {
695: $failed=1;
696: die("failed lock");
697: };
698: alarm(13);
699: flock($file,$lock_type);
700: alarm(0);
701: };
702: if ($failed) {
703: return undef;
704: } else {
705: return 1;
706: }
707: }
708:
1.5 www 709: # ---------------------------------------------------------- Append Environment
710:
711: sub appenv {
1.949 raeburn 712: my ($newenv,$roles) = @_;
713: if (ref($newenv) eq 'HASH') {
714: foreach my $key (keys(%{$newenv})) {
715: my $refused = 0;
716: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
717: $refused = 1;
718: if (ref($roles) eq 'ARRAY') {
1.1250 raeburn 719: my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949 raeburn 720: if (grep(/^\Q$role\E$/,@{$roles})) {
721: $refused = 0;
722: }
723: }
724: }
725: if ($refused) {
726: &logthis("<font color=\"blue\">WARNING: ".
727: "Attempt to modify environment ".$key." to ".$newenv->{$key}
728: .'</font>');
729: delete($newenv->{$key});
730: } else {
731: $env{$key}=$newenv->{$key};
732: }
733: }
734: my $opened = open(my $env_file,'+<',$env{'user.environment'});
735: if ($opened
736: && &timed_flock($env_file,LOCK_EX)
737: &&
738: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
739: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
740: while (my ($key,$value) = each(%{$newenv})) {
741: $disk_env{$key} = $value;
742: }
743: untie(%disk_env);
1.35 www 744: }
1.191 harris41 745: }
1.56 www 746: return 'ok';
747: }
748: # ----------------------------------------------------- Delete from Environment
749:
750: sub delenv {
1.1104 raeburn 751: my ($delthis,$regexp,$roles) = @_;
752: if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
753: my $refused = 1;
754: if (ref($roles) eq 'ARRAY') {
755: my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
756: if (grep(/^\Q$role\E$/,@{$roles})) {
757: $refused = 0;
758: }
759: }
760: if ($refused) {
761: &logthis("<font color=\"blue\">WARNING: ".
762: "Attempt to delete from environment ".$delthis);
763: return 'error';
764: }
1.56 www 765: }
1.917 albertel 766: my $opened = open(my $env_file,'+<',$env{'user.environment'});
767: if ($opened
1.915 albertel 768: && &timed_flock($env_file,LOCK_EX)
1.830 albertel 769: &&
770: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
771: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 772: foreach my $key (keys(%disk_env)) {
1.987 raeburn 773: if ($regexp) {
774: if ($key=~/^$delthis/) {
775: delete($env{$key});
776: delete($disk_env{$key});
777: }
778: } else {
779: if ($key=~/^\Q$delthis\E/) {
780: delete($env{$key});
781: delete($disk_env{$key});
782: }
783: }
1.448 albertel 784: }
1.783 albertel 785: untie(%disk_env);
1.5 www 786: }
787: return 'ok';
1.369 albertel 788: }
789:
1.790 albertel 790: sub get_env_multiple {
791: my ($name) = @_;
792: my @values;
793: if (defined($env{$name})) {
794: # exists is it an array
795: if (ref($env{$name})) {
796: @values=@{ $env{$name} };
797: } else {
798: $values[0]=$env{$name};
799: }
800: }
801: return(@values);
802: }
803:
1.958 www 804: # ------------------------------------------------------------------- Locking
805:
806: sub set_lock {
807: my ($text)=@_;
808: $locknum++;
809: my $id=$$.'-'.$locknum;
810: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
811: 'session.lock.'.$id => $text});
812: return $id;
813: }
814:
815: sub get_locks {
816: my $num=0;
817: my %texts=();
818: foreach my $lock (split(/\,/,$env{'session.locks'})) {
819: if ($lock=~/\w/) {
820: $num++;
821: $texts{$lock}=$env{'session.lock.'.$lock};
822: }
823: }
824: return ($num,%texts);
825: }
826:
827: sub remove_lock {
828: my ($id)=@_;
829: my $newlocks='';
830: foreach my $lock (split(/\,/,$env{'session.locks'})) {
831: if (($lock=~/\w/) && ($lock ne $id)) {
832: $newlocks.=','.$lock;
833: }
834: }
835: &appenv({'session.locks' => $newlocks});
836: &delenv('session.lock.'.$id);
837: }
838:
839: sub remove_all_locks {
840: my $activelocks=$env{'session.locks'};
841: foreach my $lock (split(/\,/,$env{'session.locks'})) {
842: if ($lock=~/\w/) {
843: &remove_lock($lock);
844: }
845: }
846: }
847:
848:
1.369 albertel 849: # ------------------------------------------ Find out current server userload
850: sub userload {
851: my $numusers=0;
852: {
853: opendir(LONIDS,$perlvar{'lonIDsDir'});
854: my $filename;
855: my $curtime=time;
856: while ($filename=readdir(LONIDS)) {
1.925 albertel 857: next if ($filename eq '.' || $filename eq '..');
858: next if ($filename =~ /publicuser_\d+\.id/);
1.404 albertel 859: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437 albertel 860: if ($curtime-$mtime < 1800) { $numusers++; }
1.369 albertel 861: }
862: closedir(LONIDS);
863: }
864: my $userloadpercent=0;
865: my $maxuserload=$perlvar{'lonUserLoadLim'};
866: if ($maxuserload) {
1.371 albertel 867: $userloadpercent=100*$numusers/$maxuserload;
1.369 albertel 868: }
1.372 albertel 869: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369 albertel 870: return $userloadpercent;
1.283 www 871: }
872:
1.1 albertel 873: # ------------------------------ Find server with least workload from spare.tab
1.11 www 874:
1.1 albertel 875: sub spareserver {
1.1083 raeburn 876: my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784 albertel 877: my $spare_server;
1.370 albertel 878: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784 albertel 879: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
880: : $userloadpercent;
1.1083 raeburn 881: my ($uint_dom,$remotesessions);
882: if (($udom ne '') && (&domain($udom) ne '')) {
883: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
884: $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
885: my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
886: $remotesessions = $udomdefaults{'remotesessions'};
887: }
1.1123 raeburn 888: my $spareshash = &this_host_spares($udom);
889: if (ref($spareshash) eq 'HASH') {
890: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
891: foreach my $try_server (@{ $spareshash->{'primary'} }) {
1.1279 raeburn 892: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
893: $try_server));
1.1123 raeburn 894: ($spare_server, $lowest_load) =
895: &compare_server_load($try_server, $spare_server, $lowest_load);
896: }
1.1083 raeburn 897: }
1.784 albertel 898:
1.1123 raeburn 899: my $found_server = ($spare_server ne '' && $lowest_load < 100);
900:
901: if (!$found_server) {
902: if (ref($spareshash->{'default'}) eq 'ARRAY') {
903: foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1279 raeburn 904: next unless (&spare_can_host($udom,$uint_dom,
905: $remotesessions,$try_server));
1.1123 raeburn 906: ($spare_server, $lowest_load) =
907: &compare_server_load($try_server, $spare_server, $lowest_load);
908: }
909: }
910: }
1.784 albertel 911: }
912:
913: if (!$want_server_name) {
1.968 raeburn 914: my $protocol = 'http';
915: if ($protocol{$spare_server} eq 'https') {
916: $protocol = $protocol{$spare_server};
917: }
1.1001 raeburn 918: if (defined($spare_server)) {
919: my $hostname = &hostname($spare_server);
1.1083 raeburn 920: if (defined($hostname)) {
1.1001 raeburn 921: $spare_server = $protocol.'://'.$hostname;
922: }
923: }
1.784 albertel 924: }
925: return $spare_server;
926: }
927:
928: sub compare_server_load {
1.1253 raeburn 929: my ($try_server, $spare_server, $lowest_load, $required) = @_;
930:
931: if ($required) {
932: my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
933: my $remoterev = &get_server_loncaparev(undef,$try_server);
934: my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
935: if (($major eq '' && $minor eq '') ||
936: (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
937: return ($spare_server,$lowest_load);
938: }
939: }
1.784 albertel 940:
941: my $loadans = &reply('load', $try_server);
942: my $userloadans = &reply('userload',$try_server);
943:
944: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114 raeburn 945: return ($spare_server, $lowest_load); #didn't get a number from the server
1.784 albertel 946: }
947:
948: my $load;
949: if ($loadans =~ /\d/) {
950: if ($userloadans =~ /\d/) {
951: #both are numbers, pick the bigger one
952: $load = ($loadans > $userloadans) ? $loadans
953: : $userloadans;
1.411 albertel 954: } else {
1.784 albertel 955: $load = $loadans;
1.411 albertel 956: }
1.784 albertel 957: } else {
958: $load = $userloadans;
959: }
960:
961: if (($load =~ /\d/) && ($load < $lowest_load)) {
962: $spare_server = $try_server;
963: $lowest_load = $load;
1.370 albertel 964: }
1.784 albertel 965: return ($spare_server,$lowest_load);
1.202 matthew 966: }
1.914 albertel 967:
968: # --------------------------- ask offload servers if user already has a session
969: sub find_existing_session {
970: my ($udom,$uname) = @_;
1.1123 raeburn 971: my $spareshash = &this_host_spares($udom);
972: if (ref($spareshash) eq 'HASH') {
973: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
974: foreach my $try_server (@{ $spareshash->{'primary'} }) {
975: return $try_server if (&has_user_session($try_server, $udom, $uname));
976: }
977: }
978: if (ref($spareshash->{'default'}) eq 'ARRAY') {
979: foreach my $try_server (@{ $spareshash->{'default'} }) {
980: return $try_server if (&has_user_session($try_server, $udom, $uname));
981: }
982: }
1.914 albertel 983: }
984: return;
985: }
986:
987: # -------------------------------- ask if server already has a session for user
988: sub has_user_session {
989: my ($lonid,$udom,$uname) = @_;
990: my $result = &reply(join(':','userhassession',
991: map {&escape($_)} ($udom,$uname)),$lonid);
992: return 1 if ($result eq 'ok');
993:
994: return 0;
995: }
996:
1.1076 raeburn 997: # --------- determine least loaded server in a user's domain which allows login
998:
999: sub choose_server {
1.1259 raeburn 1000: my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076 raeburn 1001: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077 raeburn 1002: my %servers = &get_servers($udom);
1.1076 raeburn 1003: my $lowest_load = 30000;
1.1259 raeburn 1004: my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
1005: if ($skiploadbal) {
1006: ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
1007: unless (defined($cached)) {
1008: my $cachetime = 60*60*24;
1009: my %domconfig =
1010: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1011: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1012: $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
1013: $cachetime);
1014: }
1015: }
1016: }
1.1076 raeburn 1017: foreach my $lonhost (keys(%servers)) {
1.1259 raeburn 1018: if ($skiploadbal) {
1019: if (ref($balancers) eq 'HASH') {
1020: next if (exists($balancers->{$lonhost}));
1021: }
1022: }
1.1115 raeburn 1023: my $loginvia;
1024: if ($checkloginvia) {
1025: $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116 raeburn 1026: if ($loginvia) {
1027: my ($server,$path) = split(/:/,$loginvia);
1028: ($login_host, $lowest_load) =
1.1253 raeburn 1029: &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116 raeburn 1030: if ($login_host eq $server) {
1031: $portal_path = $path;
1.1151 raeburn 1032: $isredirect = 1;
1.1116 raeburn 1033: }
1034: } else {
1035: ($login_host, $lowest_load) =
1.1253 raeburn 1036: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116 raeburn 1037: if ($login_host eq $lonhost) {
1038: $portal_path = '';
1.1151 raeburn 1039: $isredirect = '';
1.1116 raeburn 1040: }
1041: }
1042: } else {
1.1076 raeburn 1043: ($login_host, $lowest_load) =
1.1253 raeburn 1044: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076 raeburn 1045: }
1046: }
1047: if ($login_host ne '') {
1.1116 raeburn 1048: $hostname = &hostname($login_host);
1.1076 raeburn 1049: }
1.1151 raeburn 1050: return ($login_host,$hostname,$portal_path,$isredirect);
1.1076 raeburn 1051: }
1052:
1.202 matthew 1053: # --------------------------------------------- Try to change a user's password
1054:
1055: sub changepass {
1.799 raeburn 1056: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 1057: $currentpass = &escape($currentpass);
1058: $newpass = &escape($newpass);
1.1030 raeburn 1059: my $lonhost = $perlvar{'lonHostID'};
1060: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202 matthew 1061: $server);
1062: if (! $answer) {
1063: &logthis("No reply on password change request to $server ".
1064: "by $uname in domain $udom.");
1065: } elsif ($answer =~ "^ok") {
1066: &logthis("$uname in $udom successfully changed their password ".
1067: "on $server.");
1068: } elsif ($answer =~ "^pwchange_failure") {
1069: &logthis("$uname in $udom was unable to change their password ".
1070: "on $server. The action was blocked by either lcpasswd ".
1071: "or pwchange");
1072: } elsif ($answer =~ "^non_authorized") {
1073: &logthis("$uname in $udom did not get their password correct when ".
1074: "attempting to change it on $server.");
1075: } elsif ($answer =~ "^auth_mode_error") {
1076: &logthis("$uname in $udom attempted to change their password despite ".
1077: "not being locally or internally authenticated on $server.");
1078: } elsif ($answer =~ "^unknown_user") {
1079: &logthis("$uname in $udom attempted to change their password ".
1080: "on $server but were unable to because $server is not ".
1081: "their home server.");
1082: } elsif ($answer =~ "^refused") {
1083: &logthis("$server refused to change $uname in $udom password because ".
1084: "it was sent an unencrypted request to change the password.");
1.1030 raeburn 1085: } elsif ($answer =~ "invalid_client") {
1086: &logthis("$server refused to change $uname in $udom password because ".
1087: "it was a reset by e-mail originating from an invalid server.");
1.202 matthew 1088: }
1089: return $answer;
1.1 albertel 1090: }
1091:
1.169 harris41 1092: # ----------------------- Try to determine user's current authentication scheme
1093:
1094: sub queryauthenticate {
1095: my ($uname,$udom)=@_;
1.456 albertel 1096: my $uhome=&homeserver($uname,$udom);
1097: if (!$uhome) {
1098: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
1099: return 'no_host';
1100: }
1101: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
1102: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
1103: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 1104: }
1.456 albertel 1105: return $answer;
1.169 harris41 1106: }
1107:
1.1 albertel 1108: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 1109:
1.1 albertel 1110: sub authenticate {
1.1073 raeburn 1111: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807 albertel 1112: $upass=&escape($upass);
1113: $uname= &LONCAPA::clean_username($uname);
1.836 www 1114: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 1115: my $newhome;
1.836 www 1116: if ((!$uhome) || ($uhome eq 'no_host')) {
1117: # Maybe the machine was offline and only re-appeared again recently?
1118: &reconlonc();
1119: # One more
1.952 raeburn 1120: $uhome=&homeserver($uname,$udom,1);
1121: if (($uhome eq 'no_host') && $checkdefauth) {
1122: if (defined(&domain($udom,'primary'))) {
1123: $newhome=&domain($udom,'primary');
1124: }
1125: if ($newhome ne '') {
1126: $uhome = $newhome;
1127: }
1128: }
1.836 www 1129: if ((!$uhome) || ($uhome eq 'no_host')) {
1130: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 1131: return 'no_host';
1132: }
1.1 albertel 1133: }
1.1073 raeburn 1134: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471 albertel 1135: if ($answer eq 'authorized') {
1.952 raeburn 1136: if ($newhome) {
1137: &logthis("User $uname at $udom authorized by $uhome, but needs account");
1138: return 'no_account_on_host';
1139: } else {
1140: &logthis("User $uname at $udom authorized by $uhome");
1141: return $uhome;
1142: }
1.471 albertel 1143: }
1144: if ($answer eq 'non_authorized') {
1145: &logthis("User $uname at $udom rejected by $uhome");
1146: return 'no_host';
1.9 www 1147: }
1.471 albertel 1148: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 1149: return 'no_host';
1150: }
1151:
1.1073 raeburn 1152: sub can_host_session {
1.1074 raeburn 1153: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073 raeburn 1154: my $canhost = 1;
1.1074 raeburn 1155: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073 raeburn 1156: if (ref($remotesessions) eq 'HASH') {
1157: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074 raeburn 1158: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073 raeburn 1159: $canhost = 0;
1160: } else {
1161: $canhost = 1;
1162: }
1163: }
1164: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074 raeburn 1165: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073 raeburn 1166: $canhost = 1;
1167: } else {
1168: $canhost = 0;
1169: }
1170: }
1171: if ($canhost) {
1172: if ($remotesessions->{'version'} ne '') {
1173: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1174: if ($reqmajor ne '' && $reqminor ne '') {
1175: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1176: my $major = $1;
1177: my $minor = $2;
1178: if (($major < $reqmajor ) ||
1179: (($major == $reqmajor) && ($minor < $reqminor))) {
1180: $canhost = 0;
1181: }
1182: } else {
1183: $canhost = 0;
1184: }
1185: }
1186: }
1187: }
1188: }
1189: if ($canhost) {
1190: if (ref($hostedsessions) eq 'HASH') {
1.1120 raeburn 1191: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1192: my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073 raeburn 1193: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120 raeburn 1194: if (($uint_dom ne '') &&
1195: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073 raeburn 1196: $canhost = 0;
1197: } else {
1198: $canhost = 1;
1199: }
1200: }
1201: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120 raeburn 1202: if (($uint_dom ne '') &&
1203: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073 raeburn 1204: $canhost = 1;
1205: } else {
1206: $canhost = 0;
1207: }
1208: }
1209: }
1210: }
1211: return $canhost;
1212: }
1213:
1.1083 raeburn 1214: sub spare_can_host {
1215: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1216: my $canhost=1;
1.1279 raeburn 1217: my $try_server_hostname = &hostname($try_server);
1218: my $serverhomeID = &get_server_homeID($try_server_hostname);
1219: my $serverhomedom = &host_domain($serverhomeID);
1220: my %defdomdefaults = &get_domain_defaults($serverhomedom);
1221: if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
1222: if ($defdomdefaults{'offloadnow'}{$try_server}) {
1223: $canhost = 0;
1224: }
1225: }
1226: if (($canhost) && ($uint_dom)) {
1227: my @intdoms;
1228: my $internet_names = &get_internet_names($try_server);
1229: if (ref($internet_names) eq 'ARRAY') {
1230: @intdoms = @{$internet_names};
1231: }
1232: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1233: my $remoterev = &get_server_loncaparev(undef,$try_server);
1234: $canhost = &can_host_session($udom,$try_server,$remoterev,
1235: $remotesessions,
1236: $defdomdefaults{'hostedsessions'});
1237: }
1.1083 raeburn 1238: }
1239: return $canhost;
1240: }
1241:
1.1123 raeburn 1242: sub this_host_spares {
1243: my ($dom) = @_;
1.1126 raeburn 1244: my ($dom_in_use,$lonhost_in_use,$result);
1.1123 raeburn 1245: my @hosts = ¤t_machine_ids();
1246: foreach my $lonhost (@hosts) {
1247: if (&host_domain($lonhost) eq $dom) {
1.1126 raeburn 1248: $dom_in_use = $dom;
1249: $lonhost_in_use = $lonhost;
1.1123 raeburn 1250: last;
1251: }
1252: }
1.1126 raeburn 1253: if ($dom_in_use ne '') {
1254: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1255: }
1256: if (ref($result) ne 'HASH') {
1257: $lonhost_in_use = $perlvar{'lonHostID'};
1258: $dom_in_use = &host_domain($lonhost_in_use);
1259: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1260: if (ref($result) ne 'HASH') {
1261: $result = \%spareid;
1262: }
1263: }
1264: return $result;
1265: }
1266:
1267: sub spares_for_offload {
1268: my ($dom_in_use,$lonhost_in_use) = @_;
1269: my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123 raeburn 1270: if (defined($cached)) {
1271: return $result;
1272: } else {
1.1126 raeburn 1273: my $cachetime = 60*60*24;
1274: my %domconfig =
1275: &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
1276: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1277: if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
1278: if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
1279: return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123 raeburn 1280: }
1281: }
1282: }
1283: }
1.1126 raeburn 1284: return;
1.1123 raeburn 1285: }
1286:
1.1129 raeburn 1287: sub get_lonbalancer_config {
1288: my ($servers) = @_;
1289: my ($currbalancer,$currtargets);
1290: if (ref($servers) eq 'HASH') {
1291: foreach my $server (keys(%{$servers})) {
1292: my %what = (
1293: spareid => 1,
1294: perlvar => 1,
1295: );
1296: my ($result,$returnhash) = &get_remote_globals($server,\%what);
1297: if ($result eq 'ok') {
1298: if (ref($returnhash) eq 'HASH') {
1299: if (ref($returnhash->{'perlvar'}) eq 'HASH') {
1300: if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
1301: $currbalancer = $server;
1302: $currtargets = {};
1303: if (ref($returnhash->{'spareid'}) eq 'HASH') {
1304: if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
1305: $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
1306: }
1307: if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
1308: $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
1309: }
1310: }
1311: last;
1312: }
1313: }
1314: }
1315: }
1316: }
1317: }
1318: return ($currbalancer,$currtargets);
1319: }
1320:
1321: sub check_loadbalancing {
1322: my ($uname,$udom) = @_;
1.1191 raeburn 1323: my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1324: $rule_in_effect,$offloadto,$otherserver);
1.1129 raeburn 1325: my $lonhost = $perlvar{'lonHostID'};
1.1175 raeburn 1326: my @hosts = ¤t_machine_ids();
1.1129 raeburn 1327: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1328: my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
1329: my $intdom = &Apache::lonnet::internet_dom($lonhost);
1330: my $serverhomedom = &host_domain($lonhost);
1.1307 raeburn 1331: my $domneedscache;
1.1129 raeburn 1332: my $cachetime = 60*60*24;
1333:
1334: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1335: $dom_in_use = $udom;
1336: $homeintdom = 1;
1337: } else {
1338: $dom_in_use = $serverhomedom;
1339: }
1340: my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
1341: unless (defined($cached)) {
1342: my %domconfig =
1343: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
1344: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1345: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1307 raeburn 1346: } else {
1347: $domneedscache = $dom_in_use;
1.1129 raeburn 1348: }
1349: }
1350: if (ref($result) eq 'HASH') {
1.1191 raeburn 1351: ($is_balancer,$currtargets,$currrules) =
1352: &check_balancer_result($result,@hosts);
1.1129 raeburn 1353: if ($is_balancer) {
1354: if (ref($currrules) eq 'HASH') {
1355: if ($homeintdom) {
1356: if ($uname ne '') {
1357: if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
1358: my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
1359: if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
1360: $rule_in_effect = $currrules->{'_LC_author'};
1361: } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
1362: $rule_in_effect = $currrules->{'_LC_adv'}
1363: }
1364: }
1365: if ($rule_in_effect eq '') {
1366: my %userenv = &userenvironment($udom,$uname,'inststatus');
1367: if ($userenv{'inststatus'} ne '') {
1368: my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
1369: my ($othertitle,$usertypes,$types) =
1370: &Apache::loncommon::sorted_inst_types($udom);
1371: if (ref($types) eq 'ARRAY') {
1372: foreach my $type (@{$types}) {
1373: if (grep(/^\Q$type\E$/,@statuses)) {
1374: if (exists($currrules->{$type})) {
1375: $rule_in_effect = $currrules->{$type};
1376: }
1377: }
1378: }
1379: }
1380: } else {
1381: if (exists($currrules->{'default'})) {
1382: $rule_in_effect = $currrules->{'default'};
1383: }
1384: }
1385: }
1386: } else {
1387: if (exists($currrules->{'default'})) {
1388: $rule_in_effect = $currrules->{'default'};
1389: }
1390: }
1391: } else {
1392: if ($currrules->{'_LC_external'} ne '') {
1393: $rule_in_effect = $currrules->{'_LC_external'};
1394: }
1395: }
1396: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1397: $uname,$udom);
1398: }
1399: }
1400: } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1239 raeburn 1401: ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129 raeburn 1402: unless (defined($cached)) {
1403: my %domconfig =
1404: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
1405: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1307 raeburn 1406: $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
1407: } else {
1408: $domneedscache = $serverhomedom;
1.1129 raeburn 1409: }
1410: }
1411: if (ref($result) eq 'HASH') {
1.1191 raeburn 1412: ($is_balancer,$currtargets,$currrules) =
1413: &check_balancer_result($result,@hosts);
1414: if ($is_balancer) {
1.1129 raeburn 1415: if (ref($currrules) eq 'HASH') {
1416: if ($currrules->{'_LC_internetdom'} ne '') {
1417: $rule_in_effect = $currrules->{'_LC_internetdom'};
1418: }
1419: }
1420: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1421: $uname,$udom);
1422: }
1423: } else {
1424: if ($perlvar{'lonBalancer'} eq 'yes') {
1425: $is_balancer = 1;
1426: $offloadto = &this_host_spares($dom_in_use);
1427: }
1.1307 raeburn 1428: unless (defined($cached)) {
1429: $domneedscache = $serverhomedom;
1430: }
1.1129 raeburn 1431: }
1432: } else {
1433: if ($perlvar{'lonBalancer'} eq 'yes') {
1434: $is_balancer = 1;
1435: $offloadto = &this_host_spares($dom_in_use);
1436: }
1.1307 raeburn 1437: unless (defined($cached)) {
1438: $domneedscache = $serverhomedom;
1439: }
1440: }
1441: if ($domneedscache) {
1442: &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129 raeburn 1443: }
1.1176 raeburn 1444: if ($is_balancer) {
1445: my $lowest_load = 30000;
1446: if (ref($offloadto) eq 'HASH') {
1447: if (ref($offloadto->{'primary'}) eq 'ARRAY') {
1448: foreach my $try_server (@{$offloadto->{'primary'}}) {
1449: ($otherserver,$lowest_load) =
1450: &compare_server_load($try_server,$otherserver,$lowest_load);
1451: }
1.1129 raeburn 1452: }
1.1176 raeburn 1453: my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129 raeburn 1454:
1.1176 raeburn 1455: if (!$found_server) {
1456: if (ref($offloadto->{'default'}) eq 'ARRAY') {
1457: foreach my $try_server (@{$offloadto->{'default'}}) {
1458: ($otherserver,$lowest_load) =
1459: &compare_server_load($try_server,$otherserver,$lowest_load);
1460: }
1461: }
1462: }
1463: } elsif (ref($offloadto) eq 'ARRAY') {
1464: if (@{$offloadto} == 1) {
1465: $otherserver = $offloadto->[0];
1466: } elsif (@{$offloadto} > 1) {
1467: foreach my $try_server (@{$offloadto}) {
1.1129 raeburn 1468: ($otherserver,$lowest_load) =
1469: &compare_server_load($try_server,$otherserver,$lowest_load);
1470: }
1471: }
1472: }
1.1176 raeburn 1473: if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
1474: $is_balancer = 0;
1475: if ($uname ne '' && $udom ne '') {
1476: if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1477:
1478: &appenv({'user.loadbalexempt' => $lonhost,
1479: 'user.loadbalcheck.time' => time});
1480: }
1.1129 raeburn 1481: }
1482: }
1483: }
1484: return ($is_balancer,$otherserver);
1485: }
1486:
1.1191 raeburn 1487: sub check_balancer_result {
1488: my ($result,@hosts) = @_;
1489: my ($is_balancer,$currtargets,$currrules);
1490: if (ref($result) eq 'HASH') {
1491: if ($result->{'lonhost'} ne '') {
1492: my $currbalancer = $result->{'lonhost'};
1493: if (grep(/^\Q$currbalancer\E$/,@hosts)) {
1494: $is_balancer = 1;
1495: $currtargets = $result->{'targets'};
1496: $currrules = $result->{'rules'};
1497: }
1498: } else {
1499: foreach my $key (keys(%{$result})) {
1500: if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
1501: (ref($result->{$key}) eq 'HASH')) {
1502: $is_balancer = 1;
1503: $currrules = $result->{$key}{'rules'};
1504: $currtargets = $result->{$key}{'targets'};
1505: last;
1506: }
1507: }
1508: }
1509: }
1510: return ($is_balancer,$currtargets,$currrules);
1511: }
1512:
1.1129 raeburn 1513: sub get_loadbalancer_targets {
1514: my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
1515: my $offloadto;
1.1175 raeburn 1516: if ($rule_in_effect eq 'none') {
1517: return [$perlvar{'lonHostID'}];
1518: } elsif ($rule_in_effect eq '') {
1.1129 raeburn 1519: $offloadto = $currtargets;
1520: } else {
1521: if ($rule_in_effect eq 'homeserver') {
1522: my $homeserver = &homeserver($uname,$udom);
1523: if ($homeserver ne 'no_host') {
1524: $offloadto = [$homeserver];
1525: }
1526: } elsif ($rule_in_effect eq 'externalbalancer') {
1527: my %domconfig =
1528: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1529: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1530: if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
1531: if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
1532: $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
1533: }
1534: }
1535: } else {
1.1178 raeburn 1536: my %servers = &internet_dom_servers($udom);
1.1129 raeburn 1537: my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
1538: if (&hostname($remotebalancer) ne '') {
1539: $offloadto = [$remotebalancer];
1540: }
1541: }
1542: } elsif (&hostname($rule_in_effect) ne '') {
1543: $offloadto = [$rule_in_effect];
1544: }
1545: }
1546: return $offloadto;
1547: }
1548:
1.1127 raeburn 1549: sub internet_dom_servers {
1550: my ($dom) = @_;
1551: my (%uniqservers,%servers);
1552: my $primaryserver = &hostname(&domain($dom,'primary'));
1553: my @machinedoms = &machine_domains($primaryserver);
1554: foreach my $mdom (@machinedoms) {
1555: my %currservers = %servers;
1556: my %server = &get_servers($mdom);
1557: %servers = (%currservers,%server);
1558: }
1559: my %by_hostname;
1560: foreach my $id (keys(%servers)) {
1561: push(@{$by_hostname{$servers{$id}}},$id);
1562: }
1563: foreach my $hostname (sort(keys(%by_hostname))) {
1564: if (@{$by_hostname{$hostname}} > 1) {
1565: my $match = 0;
1566: foreach my $id (@{$by_hostname{$hostname}}) {
1567: if (&host_domain($id) eq $dom) {
1568: $uniqservers{$id} = $hostname;
1569: $match = 1;
1570: }
1571: }
1572: unless ($match) {
1573: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1574: }
1575: } else {
1576: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1577: }
1578: }
1579: return %uniqservers;
1580: }
1581:
1.1 albertel 1582: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 1583:
1.599 albertel 1584: my %homecache;
1.1 albertel 1585: sub homeserver {
1.230 stredwic 1586: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 1587: my $index="$uname:$udom";
1.426 albertel 1588:
1.599 albertel 1589: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 1590:
1591: my %servers = &get_servers($udom,'library');
1592: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 1593: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 1594: exists($badServerCache{$tryserver}));
1.841 albertel 1595:
1596: my $answer=reply("home:$udom:$uname",$tryserver);
1597: if ($answer eq 'found') {
1598: delete($badServerCache{$tryserver});
1599: return $homecache{$index}=$tryserver;
1600: } elsif ($answer eq 'no_host') {
1601: $badServerCache{$tryserver}=1;
1602: }
1.1 albertel 1603: }
1604: return 'no_host';
1.70 www 1605: }
1606:
1.1300 raeburn 1607: # ----- Find the usernames behind a list of student/employee IDs or clicker IDs
1.70 www 1608:
1609: sub idget {
1.1300 raeburn 1610: my ($udom,$idsref,$namespace)=@_;
1.70 www 1611: my %returnhash=();
1.1300 raeburn 1612: my @ids=();
1613: if (ref($idsref) eq 'ARRAY') {
1614: @ids = @{$idsref};
1615: } else {
1616: return %returnhash;
1617: }
1618: if ($namespace eq '') {
1619: $namespace = 'ids';
1620: }
1.70 www 1621:
1.841 albertel 1622: my %servers = &get_servers($udom,'library');
1623: foreach my $tryserver (keys(%servers)) {
1.1299 raeburn 1624: my $idlist=join('&', map { &escape($_); } @ids);
1.1300 raeburn 1625: if ($namespace eq 'ids') {
1626: $idlist=~tr/A-Z/a-z/;
1627: }
1628: my $reply;
1629: if ($namespace eq 'ids') {
1630: $reply=&reply("idget:$udom:".$idlist,$tryserver);
1631: } else {
1632: $reply=&reply("getdom:$udom:$namespace:$idlist",$tryserver);
1633: }
1.841 albertel 1634: my @answer=();
1635: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1636: @answer=split(/\&/,$reply);
1637: } ;
1638: my $i;
1639: for ($i=0;$i<=$#ids;$i++) {
1640: if ($answer[$i]) {
1.1299 raeburn 1641: $returnhash{$ids[$i]}=&unescape($answer[$i]);
1.1300 raeburn 1642: }
1.841 albertel 1643: }
1.1300 raeburn 1644: }
1.70 www 1645: return %returnhash;
1646: }
1647:
1648: # ------------------------------------- Find the IDs behind a list of usernames
1649:
1650: sub idrget {
1651: my ($udom,@unames)=@_;
1652: my %returnhash=();
1.800 albertel 1653: foreach my $uname (@unames) {
1654: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 1655: }
1.70 www 1656: return %returnhash;
1657: }
1658:
1.1300 raeburn 1659: # Store away a list of names and associated student/employee IDs or clicker IDs
1.70 www 1660:
1661: sub idput {
1.1300 raeburn 1662: my ($udom,$idsref,$uhom,$namespace)=@_;
1.70 www 1663: my %servers=();
1.1300 raeburn 1664: my %ids=();
1665: my %byid = ();
1666: if (ref($idsref) eq 'HASH') {
1667: %ids=%{$idsref};
1668: }
1669: if ($namespace eq '') {
1670: $namespace = 'ids';
1671: }
1.800 albertel 1672: foreach my $uname (keys(%ids)) {
1673: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1.1300 raeburn 1674: if ($uhom eq '') {
1675: $uhom=&homeserver($uname,$udom);
1676: }
1.70 www 1677: if ($uhom ne 'no_host') {
1.800 albertel 1678: my $esc_unam=&escape($uname);
1.1300 raeburn 1679: if ($namespace eq 'ids') {
1680: my $id=&escape($ids{$uname});
1681: $id=~tr/A-Z/a-z/;
1682: my $esc_unam=&escape($uname);
1683: $servers{$uhom}.=$id.'='.$esc_unam.'&';
1.70 www 1684: } else {
1.1300 raeburn 1685: my @currids = split(/,/,$ids{$uname});
1686: foreach my $id (@currids) {
1687: $byid{$uhom}{$id} .= $uname.',';
1688: }
1689: }
1690: }
1691: }
1692: if ($namespace eq 'clickers') {
1693: foreach my $server (keys(%byid)) {
1694: if (ref($byid{$server}) eq 'HASH') {
1695: foreach my $id (keys(%{$byid{$server}})) {
1696: $byid{$server} =~ s/,$//;
1697: $servers{$uhom}.=&escape($id).'='.&escape($byid{$server}).'&';
1698: }
1.70 www 1699: }
1700: }
1.191 harris41 1701: }
1.800 albertel 1702: foreach my $server (keys(%servers)) {
1.1300 raeburn 1703: $servers{$server} =~ s/\&$//;
1704: if ($namespace eq 'ids') {
1705: &critical('idput:'.$udom.':'.$servers{$server},$server);
1706: } else {
1707: &critical('updateclickers:'.$udom.':add:'.$servers{$server},$server);
1708: }
1.191 harris41 1709: }
1.344 www 1710: }
1711:
1.1300 raeburn 1712: # ------------- Delete unwanted student/employee IDs or clicker IDs from domain
1.1231 raeburn 1713:
1714: sub iddel {
1.1300 raeburn 1715: my ($udom,$idshashref,$uhome,$namespace)=@_;
1.1231 raeburn 1716: my %result=();
1.1300 raeburn 1717: my %ids=();
1718: my %byid = ();
1719: if (ref($idshashref) eq 'HASH') {
1720: %ids=%{$idshashref};
1721: } else {
1.1231 raeburn 1722: return %result;
1723: }
1.1300 raeburn 1724: if ($namespace eq '') {
1725: $namespace = 'ids';
1726: }
1.1231 raeburn 1727: my %servers=();
1.1300 raeburn 1728: while (my ($id,$unamestr) = each(%ids)) {
1729: if ($namespace eq 'ids') {
1730: my $uhom = $uhome;
1731: if ($uhom eq '') {
1732: $uhom=&homeserver($unamestr,$udom);
1733: }
1734: if ($uhom ne 'no_host') {
1735: $servers{$uhom}.='&'.&escape($id);
1736: }
1737: } else {
1738: my @curritems = split(/,/,$ids{$id});
1739: foreach my $uname (@curritems) {
1740: my $uhom = $uhome;
1741: if ($uhom eq '') {
1742: $uhom=&homeserver($uname,$udom);
1743: }
1744: if ($uhom ne 'no_host') {
1745: $byid{$uhom}{$id} .= $uname.',';
1746: }
1747: }
1.1231 raeburn 1748: }
1.1300 raeburn 1749: }
1750: if ($namespace eq 'clickers') {
1751: foreach my $server (keys(%byid)) {
1752: if (ref($byid{$server}) eq 'HASH') {
1753: foreach my $id (keys(%{$byid{$server}})) {
1754: $byid{$server}{$id} =~ s/,$//;
1755: $servers{$server}.=&escape($id).'='.&escape($byid{$server}{$id}).'&';
1756: }
1.1231 raeburn 1757: }
1758: }
1759: }
1760: foreach my $server (keys(%servers)) {
1.1300 raeburn 1761: $servers{$server} =~ s/\&$//;
1762: if ($namespace eq 'ids') {
1763: $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
1764: } elsif ($namespace eq 'clickers') {
1765: $result{$server} = &critical('updateclickers:'.$udom.':del:'.$servers{$server},$server);
1766: }
1.1231 raeburn 1767: }
1768: return %result;
1769: }
1770:
1.1300 raeburn 1771: # ----- Update clicker ID-to-username look-ups in clickers.db on library server
1772:
1773: sub updateclickers {
1774: my ($udom,$action,$idshashref,$uhome,$critical) = @_;
1775: my %clickers;
1776: if (ref($idshashref) eq 'HASH') {
1777: %clickers=%{$idshashref};
1778: } else {
1779: return;
1780: }
1781: my $items='';
1782: foreach my $item (keys(%clickers)) {
1783: $items.=&escape($item).'='.&escape($clickers{$item}).'&';
1784: }
1785: $items=~s/\&$//;
1786: my $request = "updateclickers:$udom:$action:$items";
1787: if ($critical) {
1788: return &critical($request,$uhome);
1789: } else {
1790: return &reply($request,$uhome);
1791: }
1792: }
1793:
1.1023 raeburn 1794: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 1795: sub dump_dom {
1.1165 droeschl 1796: my ($namespace, $udom, $regexp) = @_;
1797:
1798: $udom ||= $env{'user.domain'};
1799:
1800: return () unless $udom;
1801:
1802: return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012 raeburn 1803: }
1804:
1.1023 raeburn 1805: # ------------------------------------------ get items from domain db files
1.806 raeburn 1806:
1807: sub get_dom {
1.860 raeburn 1808: my ($namespace,$storearr,$udom,$uhome)=@_;
1.1267 raeburn 1809: return if ($udom eq 'public');
1.806 raeburn 1810: my $items='';
1811: foreach my $item (@$storearr) {
1812: $items.=&escape($item).'&';
1813: }
1814: $items=~s/\&$//;
1.860 raeburn 1815: if (!$udom) {
1816: $udom=$env{'user.domain'};
1.1267 raeburn 1817: return if ($udom eq 'public');
1.860 raeburn 1818: if (defined(&domain($udom,'primary'))) {
1819: $uhome=&domain($udom,'primary');
1820: } else {
1.874 albertel 1821: undef($uhome);
1.860 raeburn 1822: }
1823: } else {
1824: if (!$uhome) {
1825: if (defined(&domain($udom,'primary'))) {
1826: $uhome=&domain($udom,'primary');
1827: }
1828: }
1829: }
1830: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1831: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866 raeburn 1832: my %returnhash;
1.875 albertel 1833: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 1834: return %returnhash;
1835: }
1.806 raeburn 1836: my @pairs=split(/\&/,$rep);
1837: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1838: return @pairs;
1839: }
1840: my $i=0;
1841: foreach my $item (@$storearr) {
1842: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1843: $i++;
1844: }
1845: return %returnhash;
1846: } else {
1.880 banghart 1847: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 1848: }
1849: }
1850:
1851: # -------------------------------------------- put items in domain db files
1852:
1853: sub put_dom {
1.860 raeburn 1854: my ($namespace,$storehash,$udom,$uhome)=@_;
1855: if (!$udom) {
1856: $udom=$env{'user.domain'};
1857: if (defined(&domain($udom,'primary'))) {
1858: $uhome=&domain($udom,'primary');
1859: } else {
1.874 albertel 1860: undef($uhome);
1.860 raeburn 1861: }
1862: } else {
1863: if (!$uhome) {
1864: if (defined(&domain($udom,'primary'))) {
1865: $uhome=&domain($udom,'primary');
1866: }
1867: }
1868: }
1869: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1870: my $items='';
1871: foreach my $item (keys(%$storehash)) {
1872: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1873: }
1874: $items=~s/\&$//;
1875: return &reply("putdom:$udom:$namespace:$items",$uhome);
1876: } else {
1.860 raeburn 1877: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 1878: }
1879: }
1880:
1.1023 raeburn 1881: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 1882: sub newput_dom {
1.1023 raeburn 1883: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 1884: my $result;
1885: if (!$udom) {
1886: $udom=$env{'user.domain'};
1887: }
1.1023 raeburn 1888: if ($udom) {
1889: my $uname = &get_domainconfiguser($udom);
1890: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 1891: }
1892: return $result;
1893: }
1894:
1.1023 raeburn 1895: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 1896: sub del_dom {
1.1023 raeburn 1897: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 1898: if (ref($storearr) eq 'ARRAY') {
1899: if (!$udom) {
1900: $udom=$env{'user.domain'};
1901: }
1.1023 raeburn 1902: if ($udom) {
1903: my $uname = &get_domainconfiguser($udom);
1904: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 1905: }
1906: }
1907: }
1908:
1.1023 raeburn 1909: # ----------------------------------construct domainconfig user for a domain
1910: sub get_domainconfiguser {
1911: my ($udom) = @_;
1912: return $udom.'-domainconfig';
1913: }
1914:
1.837 raeburn 1915: sub retrieve_inst_usertypes {
1916: my ($udom) = @_;
1917: my (%returnhash,@order);
1.989 raeburn 1918: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1919: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1920: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1256 raeburn 1921: return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989 raeburn 1922: } else {
1923: if (defined(&domain($udom,'primary'))) {
1924: my $uhome=&domain($udom,'primary');
1925: my $rep=&reply("inst_usertypes:$udom",$uhome);
1926: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1256 raeburn 1927: &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989 raeburn 1928: return (\%returnhash,\@order);
1929: }
1930: my ($hashitems,$orderitems) = split(/:/,$rep);
1931: my @pairs=split(/\&/,$hashitems);
1932: foreach my $item (@pairs) {
1933: my ($key,$value)=split(/=/,$item,2);
1934: $key = &unescape($key);
1935: next if ($key =~ /^error: 2 /);
1936: $returnhash{$key}=&thaw_unescape($value);
1937: }
1938: my @esc_order = split(/\&/,$orderitems);
1939: foreach my $item (@esc_order) {
1940: push(@order,&unescape($item));
1941: }
1942: } else {
1.1256 raeburn 1943: &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837 raeburn 1944: }
1.1256 raeburn 1945: return (\%returnhash,\@order);
1.837 raeburn 1946: }
1947: }
1948:
1.868 raeburn 1949: sub is_domainimage {
1950: my ($url) = @_;
1.1306 raeburn 1951: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
1.868 raeburn 1952: if (&domain($1) ne '') {
1953: return '1';
1954: }
1955: }
1956: return;
1957: }
1958:
1.899 raeburn 1959: sub inst_directory_query {
1960: my ($srch) = @_;
1961: my $udom = $srch->{'srchdomain'};
1962: my %results;
1963: my $homeserver = &domain($udom,'primary');
1.909 raeburn 1964: my $outcome;
1.899 raeburn 1965: if ($homeserver ne '') {
1.904 albertel 1966: my $queryid=&reply("querysend:instdirsearch:".
1967: &escape($srch->{'srchby'}).':'.
1968: &escape($srch->{'srchterm'}).':'.
1969: &escape($srch->{'srchtype'}),$homeserver);
1970: my $host=&hostname($homeserver);
1971: if ($queryid !~/^\Q$host\E\_/) {
1972: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1973: return;
1974: }
1975: my $response = &get_query_reply($queryid);
1976: my $maxtries = 5;
1977: my $tries = 1;
1978: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1979: $response = &get_query_reply($queryid);
1980: $tries ++;
1981: }
1982:
1983: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 1984: if ($response eq 'unavailable') {
1985: $outcome = $response;
1986: } else {
1987: $outcome = 'ok';
1988: my @matches = split(/\n/,$response);
1989: foreach my $match (@matches) {
1990: my ($key,$value) = split(/=/,$match);
1991: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1992: }
1.899 raeburn 1993: }
1994: }
1995: }
1.909 raeburn 1996: return ($outcome,%results);
1.899 raeburn 1997: }
1998:
1999: sub usersearch {
2000: my ($srch) = @_;
2001: my $dom = $srch->{'srchdomain'};
2002: my %results;
2003: my %libserv = &all_library();
2004: my $query = 'usersearch';
2005: foreach my $tryserver (keys(%libserv)) {
2006: if (&host_domain($tryserver) eq $dom) {
2007: my $host=&hostname($tryserver);
2008: my $queryid=
1.911 raeburn 2009: &reply("querysend:".&escape($query).':'.
2010: &escape($srch->{'srchby'}).':'.
1.899 raeburn 2011: &escape($srch->{'srchtype'}).':'.
2012: &escape($srch->{'srchterm'}),$tryserver);
2013: if ($queryid !~/^\Q$host\E\_/) {
2014: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 2015: next;
1.899 raeburn 2016: }
2017: my $reply = &get_query_reply($queryid);
2018: my $maxtries = 1;
2019: my $tries = 1;
2020: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
2021: $reply = &get_query_reply($queryid);
2022: $tries ++;
2023: }
2024: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
2025: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
2026: } else {
1.911 raeburn 2027: my @matches;
2028: if ($reply =~ /\n/) {
2029: @matches = split(/\n/,$reply);
2030: } else {
2031: @matches = split(/\&/,$reply);
2032: }
1.899 raeburn 2033: foreach my $match (@matches) {
2034: my ($uname,$udom,%userhash);
1.911 raeburn 2035: foreach my $entry (split(/:/,$match)) {
2036: my ($key,$value) =
2037: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 2038: $userhash{$key} = $value;
2039: if ($key eq 'username') {
2040: $uname = $value;
2041: } elsif ($key eq 'domain') {
2042: $udom = $value;
1.911 raeburn 2043: }
1.899 raeburn 2044: }
2045: $results{$uname.':'.$udom} = \%userhash;
2046: }
2047: }
2048: }
2049: }
2050: return %results;
2051: }
2052:
1.912 raeburn 2053: sub get_instuser {
2054: my ($udom,$uname,$id) = @_;
2055: my $homeserver = &domain($udom,'primary');
2056: my ($outcome,%results);
2057: if ($homeserver ne '') {
2058: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
2059: &escape($id).':'.&escape($udom),$homeserver);
2060: my $host=&hostname($homeserver);
2061: if ($queryid !~/^\Q$host\E\_/) {
2062: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
2063: return;
2064: }
2065: my $response = &get_query_reply($queryid);
2066: my $maxtries = 5;
2067: my $tries = 1;
2068: while (($response=~/^timeout/) && ($tries < $maxtries)) {
2069: $response = &get_query_reply($queryid);
2070: $tries ++;
2071: }
2072: if (!&error($response) && $response ne 'refused') {
2073: if ($response eq 'unavailable') {
2074: $outcome = $response;
2075: } else {
2076: $outcome = 'ok';
2077: my @matches = split(/\n/,$response);
2078: foreach my $match (@matches) {
2079: my ($key,$value) = split(/=/,$match);
2080: $results{&unescape($key)} = &thaw_unescape($value);
2081: }
2082: }
2083: }
2084: }
2085: my %userinfo;
2086: if (ref($results{$uname}) eq 'HASH') {
2087: %userinfo = %{$results{$uname}};
2088: }
2089: return ($outcome,%userinfo);
2090: }
2091:
1.1290 raeburn 2092: sub get_multiple_instusers {
2093: my ($udom,$users,$caller) = @_;
2094: my ($outcome,$results);
2095: if (ref($users) eq 'HASH') {
2096: my $count = keys(%{$users});
2097: my $requested = &freeze_escape($users);
2098: my $homeserver = &domain($udom,'primary');
2099: if ($homeserver ne '') {
2100: my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
2101: my $host=&hostname($homeserver);
2102: if ($queryid !~/^\Q$host\E\_/) {
2103: &logthis('get_multiple_instusers invalid queryid: '.$queryid.
2104: ' for host: '.$homeserver.'in domain '.$udom);
2105: return ($outcome,$results);
2106: }
2107: my $response = &get_query_reply($queryid);
2108: my $maxtries = 5;
2109: if ($count > 100) {
2110: $maxtries = 1+int($count/20);
2111: }
2112: my $tries = 1;
2113: while (($response=~/^timeout/) && ($tries <= $maxtries)) {
2114: $response = &get_query_reply($queryid);
2115: $tries ++;
2116: }
2117: if ($response eq '') {
2118: $results = {};
2119: foreach my $key (keys(%{$users})) {
2120: my ($uname,$id);
2121: if ($caller eq 'id') {
2122: $id = $key;
2123: } else {
2124: $uname = $key;
2125: }
2126: my ($resp,%info) = &get_instuser($udom,$uname,$id);
1.1291 raeburn 2127: $outcome = $resp;
1.1290 raeburn 2128: if ($resp eq 'ok') {
2129: %{$results} = (%{$results}, %info);
2130: } else {
2131: last;
2132: }
2133: }
2134: } elsif(!&error($response) && ($response ne 'refused')) {
2135: if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
2136: $outcome = $response;
2137: } else {
1.1291 raeburn 2138: ($outcome,my $userdata) = split(/=/,$response,2);
1.1290 raeburn 2139: if ($outcome eq 'ok') {
2140: $results = &thaw_unescape($userdata);
2141: }
2142: }
2143: }
2144: }
2145: }
2146: return ($outcome,$results);
2147: }
2148:
1.912 raeburn 2149: sub inst_rulecheck {
1.923 raeburn 2150: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 2151: my %returnhash;
2152: if ($udom ne '') {
2153: if (ref($rules) eq 'ARRAY') {
2154: @{$rules} = map {&escape($_);} (@{$rules});
2155: my $rulestr = join(':',@{$rules});
2156: my $homeserver=&domain($udom,'primary');
2157: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 2158: my $response;
2159: if ($item eq 'username') {
2160: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
2161: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 2162: $homeserver));
1.923 raeburn 2163: } elsif ($item eq 'id') {
2164: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
2165: ':'.&escape($id).':'.$rulestr,
2166: $homeserver));
1.945 raeburn 2167: } elsif ($item eq 'selfcreate') {
2168: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 2169: &escape($udom).':'.&escape($uname).
2170: ':'.$rulestr,$homeserver));
1.923 raeburn 2171: }
1.912 raeburn 2172: if ($response ne 'refused') {
2173: my @pairs=split(/\&/,$response);
2174: foreach my $item (@pairs) {
2175: my ($key,$value)=split(/=/,$item,2);
2176: $key = &unescape($key);
2177: next if ($key =~ /^error: 2 /);
2178: $returnhash{$key}=&thaw_unescape($value);
2179: }
2180: }
2181: }
2182: }
2183: }
2184: return %returnhash;
2185: }
2186:
2187: sub inst_userrules {
1.923 raeburn 2188: my ($udom,$check) = @_;
1.912 raeburn 2189: my (%ruleshash,@ruleorder);
2190: if ($udom ne '') {
2191: my $homeserver=&domain($udom,'primary');
2192: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 2193: my $response;
2194: if ($check eq 'id') {
2195: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 2196: $homeserver);
1.943 raeburn 2197: } elsif ($check eq 'email') {
2198: $response=&reply('instemailrules:'.&escape($udom),
2199: $homeserver);
1.923 raeburn 2200: } else {
2201: $response=&reply('instuserrules:'.&escape($udom),
2202: $homeserver);
2203: }
1.912 raeburn 2204: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 2205: ($response ne 'unknown_cmd') &&
1.912 raeburn 2206: ($response ne 'no_such_host')) {
2207: my ($hashitems,$orderitems) = split(/:/,$response);
2208: my @pairs=split(/\&/,$hashitems);
2209: foreach my $item (@pairs) {
2210: my ($key,$value)=split(/=/,$item,2);
2211: $key = &unescape($key);
2212: next if ($key =~ /^error: 2 /);
2213: $ruleshash{$key}=&thaw_unescape($value);
2214: }
2215: my @esc_order = split(/\&/,$orderitems);
2216: foreach my $item (@esc_order) {
2217: push(@ruleorder,&unescape($item));
2218: }
2219: }
2220: }
2221: }
2222: return (\%ruleshash,\@ruleorder);
2223: }
2224:
1.976 raeburn 2225: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 2226:
2227: sub get_domain_defaults {
1.1240 raeburn 2228: my ($domain,$ignore_cache) = @_;
1.1242 raeburn 2229: return if (($domain eq '') || ($domain eq 'public'));
1.943 raeburn 2230: my $cachetime = 60*60*24;
1.1240 raeburn 2231: unless ($ignore_cache) {
2232: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
2233: if (defined($cached)) {
2234: if (ref($result) eq 'HASH') {
2235: return %{$result};
2236: }
1.943 raeburn 2237: }
2238: }
2239: my %domdefaults;
2240: my %domconfig =
1.989 raeburn 2241: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 2242: 'requestcourses','inststatus',
1.1183 raeburn 2243: 'coursedefaults','usersessions',
1.1258 raeburn 2244: 'requestauthor','selfenrollment',
1.1315 raeburn 2245: 'coursecategories','ssl','autoenroll'],$domain);
1.1305 raeburn 2246: my @coursetypes = ('official','unofficial','community','textbook','placement');
1.943 raeburn 2247: if (ref($domconfig{'defaults'}) eq 'HASH') {
2248: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
2249: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
2250: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 2251: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 2252: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147 raeburn 2253: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943 raeburn 2254: } else {
2255: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
2256: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
2257: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
2258: }
1.976 raeburn 2259: if (ref($domconfig{'quotas'}) eq 'HASH') {
2260: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
2261: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
2262: } else {
2263: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1229 raeburn 2264: }
1.1177 raeburn 2265: my @usertools = ('aboutme','blog','webdav','portfolio');
1.976 raeburn 2266: foreach my $item (@usertools) {
2267: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
2268: $domdefaults{$item} = $domconfig{'quotas'}{$item};
2269: }
2270: }
1.1229 raeburn 2271: if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
2272: $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
2273: }
1.976 raeburn 2274: }
1.985 raeburn 2275: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1305 raeburn 2276: foreach my $item ('official','unofficial','community','textbook','placement') {
1.985 raeburn 2277: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
2278: }
2279: }
1.1183 raeburn 2280: if (ref($domconfig{'requestauthor'}) eq 'HASH') {
2281: $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
2282: }
1.989 raeburn 2283: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1256 raeburn 2284: foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989 raeburn 2285: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
2286: }
2287: }
1.1047 raeburn 2288: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1230 raeburn 2289: $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
1.1277 raeburn 2290: $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
2291: $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
2292: if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
2293: $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
2294: }
1.1254 raeburn 2295: foreach my $type (@coursetypes) {
2296: if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
2297: unless ($type eq 'community') {
2298: $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
2299: }
2300: }
2301: if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
2302: $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
2303: }
1.1277 raeburn 2304: if ($domdefaults{'postsubmit'} eq 'on') {
2305: if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
2306: $domdefaults{$type.'postsubtimeout'} =
2307: $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
2308: }
2309: }
1.1230 raeburn 2310: }
1.1286 raeburn 2311: if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
2312: if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
2313: my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
2314: if (@clonecodes) {
2315: $domdefaults{'canclone'} = join('+',@clonecodes);
2316: }
2317: }
2318: } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
2319: $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
2320: }
1.1047 raeburn 2321: }
1.1073 raeburn 2322: if (ref($domconfig{'usersessions'}) eq 'HASH') {
2323: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
2324: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
2325: }
2326: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
2327: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
2328: }
1.1279 raeburn 2329: if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
2330: $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
2331: }
1.1073 raeburn 2332: }
1.1254 raeburn 2333: if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
2334: if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
2335: my @settings = ('types','registered','enroll_dates','access_dates','section',
2336: 'approval','limit');
2337: foreach my $type (@coursetypes) {
2338: if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
2339: my @mgrdc = ();
2340: foreach my $item (@settings) {
2341: if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
2342: push(@mgrdc,$item);
2343: }
2344: }
2345: if (@mgrdc) {
2346: $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
2347: }
2348: }
2349: }
2350: }
2351: if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
2352: foreach my $type (@coursetypes) {
2353: if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
2354: foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
2355: $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
2356: }
2357: }
2358: }
2359: }
2360: }
1.1258 raeburn 2361: if (ref($domconfig{'coursecategories'}) eq 'HASH') {
2362: $domdefaults{'catauth'} = 'std';
2363: $domdefaults{'catunauth'} = 'std';
2364: if ($domconfig{'coursecategories'}{'auth'}) {
2365: $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
2366: }
2367: if ($domconfig{'coursecategories'}{'unauth'}) {
2368: $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
2369: }
2370: }
1.1315 raeburn 2371: if (ref($domconfig{'ssl'}) eq 'HASH') {
2372: if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
2373: $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
2374: }
2375: if (ref($domconfig{'ssl'}{'connect'}) eq 'HASH') {
2376: $domdefaults{'connect'} = $domconfig{'ssl'}{'connect'};
2377: }
2378: }
1.1314 raeburn 2379: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
2380: $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
2381: }
1.1219 raeburn 2382: &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943 raeburn 2383: return %domdefaults;
2384: }
2385:
1.1311 raeburn 2386: sub course_portal_url {
2387: my ($cnum,$cdom) = @_;
2388: my $chome = &homeserver($cnum,$cdom);
2389: my $hostname = &hostname($chome);
2390: my $protocol = $protocol{$chome};
2391: $protocol = 'http' if ($protocol ne 'https');
2392: my %domdefaults = &get_domain_defaults($cdom);
2393: my $firsturl;
2394: if ($domdefaults{'portal_def'}) {
2395: $firsturl = $domdefaults{'portal_def'};
2396: } else {
2397: $firsturl = $protocol.'://'.$hostname;
2398: }
2399: return $firsturl;
2400: }
2401:
1.344 www 2402: # --------------------------------------------------- Assign a key to a student
2403:
2404: sub assign_access_key {
1.364 www 2405: #
2406: # a valid key looks like uname:udom#comments
2407: # comments are being appended
2408: #
1.498 www 2409: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
2410: $kdom=
1.620 albertel 2411: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 2412: $knum=
1.620 albertel 2413: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 2414: $cdom=
1.620 albertel 2415: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2416: $cnum=
1.620 albertel 2417: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2418: $udom=$env{'user.name'} unless (defined($udom));
2419: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 2420: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 2421: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 2422: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 2423: # assigned to this person
2424: # - this should not happen,
1.345 www 2425: # unless something went wrong
2426: # the first time around
2427: # ready to assign
1.364 www 2428: $logentry=$1.'; '.$logentry;
1.496 www 2429: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 2430: $kdom,$knum) eq 'ok') {
1.345 www 2431: # key now belongs to user
1.346 www 2432: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 2433: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 2434: &appenv({'environment.'.$envkey => $ckey});
1.345 www 2435: return 'ok';
2436: } else {
2437: return
2438: 'error: Count not permanently assign key, will need to be re-entered later.';
2439: }
2440: } else {
2441: return 'error: Could not assign key, try again later.';
2442: }
1.364 www 2443: } elsif (!$existing{$ckey}) {
1.345 www 2444: # the key does not exist
2445: return 'error: The key does not exist';
2446: } else {
2447: # the key is somebody else's
2448: return 'error: The key is already in use';
2449: }
1.344 www 2450: }
2451:
1.364 www 2452: # ------------------------------------------ put an additional comment on a key
2453:
2454: sub comment_access_key {
2455: #
2456: # a valid key looks like uname:udom#comments
2457: # comments are being appended
2458: #
2459: my ($ckey,$cdom,$cnum,$logentry)=@_;
2460: $cdom=
1.620 albertel 2461: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 2462: $cnum=
1.620 albertel 2463: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 2464: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2465: if ($existing{$ckey}) {
2466: $existing{$ckey}.='; '.$logentry;
2467: # ready to assign
1.367 www 2468: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 2469: $cdom,$cnum) eq 'ok') {
2470: return 'ok';
2471: } else {
2472: return 'error: Count not store comment.';
2473: }
2474: } else {
2475: # the key does not exist
2476: return 'error: The key does not exist';
2477: }
2478: }
2479:
1.344 www 2480: # ------------------------------------------------------ Generate a set of keys
2481:
2482: sub generate_access_keys {
1.364 www 2483: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 2484: $cdom=
1.620 albertel 2485: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2486: $cnum=
1.620 albertel 2487: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 2488: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 2489: unless (($cdom) && ($cnum)) { return 0; }
2490: if ($number>10000) { return 0; }
2491: sleep(2); # make sure don't get same seed twice
2492: srand(time()^($$+($$<<15))); # from "Programming Perl"
2493: my $total=0;
2494: for (my $i=1;$i<=$number;$i++) {
2495: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
2496: sprintf("%lx",int(100000*rand)).'-'.
2497: sprintf("%lx",int(100000*rand));
2498: $newkey=~s/1/g/g; # folks mix up 1 and l
2499: $newkey=~s/0/h/g; # and also 0 and O
2500: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
2501: if ($existing{$newkey}) {
2502: $i--;
2503: } else {
1.364 www 2504: if (&put('accesskeys',
2505: { $newkey => '# generated '.localtime().
1.620 albertel 2506: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 2507: '; '.$logentry },
2508: $cdom,$cnum) eq 'ok') {
1.344 www 2509: $total++;
2510: }
2511: }
2512: }
1.620 albertel 2513: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 2514: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
2515: return $total;
2516: }
2517:
2518: # ------------------------------------------------------- Validate an accesskey
2519:
2520: sub validate_access_key {
2521: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
2522: $cdom=
1.620 albertel 2523: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2524: $cnum=
1.620 albertel 2525: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2526: $udom=$env{'user.domain'} unless (defined($udom));
2527: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 2528: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 2529: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 2530: }
2531:
2532: # ------------------------------------- Find the section of student in a course
1.652 albertel 2533: sub devalidate_getsection_cache {
2534: my ($udom,$unam,$courseid)=@_;
2535: my $hashid="$udom:$unam:$courseid";
2536: &devalidate_cache_new('getsection',$hashid);
2537: }
1.298 matthew 2538:
1.815 albertel 2539: sub courseid_to_courseurl {
2540: my ($courseid) = @_;
2541: #already url style courseid
2542: return $courseid if ($courseid =~ m{^/});
2543:
2544: if (exists($env{'course.'.$courseid.'.num'})) {
2545: my $cnum = $env{'course.'.$courseid.'.num'};
2546: my $cdom = $env{'course.'.$courseid.'.domain'};
2547: return "/$cdom/$cnum";
2548: }
2549:
2550: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
2551: if (exists($courseinfo{'num'})) {
2552: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
2553: }
2554:
2555: return undef;
2556: }
2557:
1.298 matthew 2558: sub getsection {
2559: my ($udom,$unam,$courseid)=@_;
1.599 albertel 2560: my $cachetime=1800;
1.551 albertel 2561:
2562: my $hashid="$udom:$unam:$courseid";
1.599 albertel 2563: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 2564: if (defined($cached)) { return $result; }
2565:
1.298 matthew 2566: my %Pending;
2567: my %Expired;
2568: #
2569: # Each role can either have not started yet (pending), be active,
2570: # or have expired.
2571: #
2572: # If there is an active role, we are done.
2573: #
2574: # If there is more than one role which has not started yet,
2575: # choose the one which will start sooner
2576: # If there is one role which has not started yet, return it.
2577: #
2578: # If there is more than one expired role, choose the one which ended last.
2579: # If there is a role which has expired, return it.
2580: #
1.815 albertel 2581: $courseid = &courseid_to_courseurl($courseid);
1.1166 raeburn 2582: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817 raeburn 2583: foreach my $key (keys(%roleshash)) {
1.479 albertel 2584: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 2585: my $section=$1;
2586: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 2587: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 2588: my $now=time;
1.548 albertel 2589: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 2590: $Expired{$end}=$section;
2591: next;
2592: }
1.548 albertel 2593: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 2594: $Pending{$start}=$section;
2595: next;
2596: }
1.599 albertel 2597: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 2598: }
2599: #
2600: # Presumedly there will be few matching roles from the above
2601: # loop and the sorting time will be negligible.
2602: if (scalar(keys(%Pending))) {
2603: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 2604: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 2605: }
2606: if (scalar(keys(%Expired))) {
2607: my @sorted = sort {$a <=> $b} keys(%Expired);
2608: my $time = pop(@sorted);
1.599 albertel 2609: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 2610: }
1.599 albertel 2611: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 2612: }
1.70 www 2613:
1.599 albertel 2614: sub save_cache {
2615: &purge_remembered();
1.722 albertel 2616: #&Apache::loncommon::validate_page();
1.620 albertel 2617: undef(%env);
1.780 albertel 2618: undef($env_loaded);
1.599 albertel 2619: }
1.452 albertel 2620:
1.599 albertel 2621: my $to_remember=-1;
2622: my %remembered;
2623: my %accessed;
2624: my $kicks=0;
2625: my $hits=0;
1.849 albertel 2626: sub make_key {
2627: my ($name,$id) = @_;
1.872 albertel 2628: if (length($id) > 65
2629: && length(&escape($id)) > 200) {
2630: $id=length($id).':'.&Digest::MD5::md5_hex($id);
2631: }
1.849 albertel 2632: return &escape($name.':'.$id);
2633: }
2634:
1.599 albertel 2635: sub devalidate_cache_new {
2636: my ($name,$id,$debug) = @_;
2637: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849 albertel 2638: $id=&make_key($name,$id);
1.599 albertel 2639: $memcache->delete($id);
2640: delete($remembered{$id});
2641: delete($accessed{$id});
2642: }
2643:
2644: sub is_cached_new {
2645: my ($name,$id,$debug) = @_;
1.849 albertel 2646: $id=&make_key($name,$id);
1.599 albertel 2647: if (exists($remembered{$id})) {
1.1133 foxr 2648: if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
1.599 albertel 2649: $accessed{$id}=[&gettimeofday()];
2650: $hits++;
2651: return ($remembered{$id},1);
2652: }
2653: my $value = $memcache->get($id);
2654: if (!(defined($value))) {
2655: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 2656: return (undef,undef);
1.416 albertel 2657: }
1.599 albertel 2658: if ($value eq '__undef__') {
2659: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
2660: $value=undef;
2661: }
2662: &make_room($id,$value,$debug);
2663: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
2664: return ($value,1);
2665: }
2666:
2667: sub do_cache_new {
2668: my ($name,$id,$value,$time,$debug) = @_;
1.849 albertel 2669: $id=&make_key($name,$id);
1.599 albertel 2670: my $setvalue=$value;
2671: if (!defined($setvalue)) {
2672: $setvalue='__undef__';
2673: }
1.623 albertel 2674: if (!defined($time) ) {
2675: $time=600;
2676: }
1.599 albertel 2677: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 2678: my $result = $memcache->set($id,$setvalue,$time);
2679: if (! $result) {
1.872 albertel 2680: &logthis("caching of id -> $id failed");
1.910 albertel 2681: $memcache->disconnect_all();
1.872 albertel 2682: }
1.600 albertel 2683: # need to make a copy of $value
1.919 albertel 2684: &make_room($id,$value,$debug);
1.599 albertel 2685: return $value;
2686: }
2687:
2688: sub make_room {
2689: my ($id,$value,$debug)=@_;
1.919 albertel 2690:
2691: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
2692: : $value;
1.599 albertel 2693: if ($to_remember<0) { return; }
2694: $accessed{$id}=[&gettimeofday()];
2695: if (scalar(keys(%remembered)) <= $to_remember) { return; }
2696: my $to_kick;
2697: my $max_time=0;
2698: foreach my $other (keys(%accessed)) {
2699: if (&tv_interval($accessed{$other}) > $max_time) {
2700: $to_kick=$other;
2701: $max_time=&tv_interval($accessed{$other});
2702: }
2703: }
2704: delete($remembered{$to_kick});
2705: delete($accessed{$to_kick});
2706: $kicks++;
2707: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 2708: return;
2709: }
2710:
1.599 albertel 2711: sub purge_remembered {
1.604 albertel 2712: #&logthis("Tossing ".scalar(keys(%remembered)));
2713: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 2714: undef(%remembered);
2715: undef(%accessed);
1.428 albertel 2716: }
1.70 www 2717: # ------------------------------------- Read an entry from a user's environment
2718:
2719: sub userenvironment {
2720: my ($udom,$unam,@what)=@_;
1.976 raeburn 2721: my $items;
2722: foreach my $item (@what) {
2723: $items.=&escape($item).'&';
2724: }
2725: $items=~s/\&$//;
1.70 www 2726: my %returnhash=();
1.1009 raeburn 2727: my $uhome = &homeserver($unam,$udom);
2728: unless ($uhome eq 'no_host') {
2729: my @answer=split(/\&/,
2730: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 2731: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
2732: return %returnhash;
2733: }
1.1009 raeburn 2734: my $i;
2735: for ($i=0;$i<=$#what;$i++) {
2736: $returnhash{$what[$i]}=&unescape($answer[$i]);
2737: }
1.70 www 2738: }
2739: return %returnhash;
1.1 albertel 2740: }
2741:
1.617 albertel 2742: # ---------------------------------------------------------- Get a studentphoto
2743: sub studentphoto {
2744: my ($udom,$unam,$ext) = @_;
2745: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 2746: if (defined($env{'request.course.id'})) {
1.708 raeburn 2747: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 2748: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
2749: return(&retrievestudentphoto($udom,$unam,$ext));
2750: } else {
2751: my ($result,$perm_reqd)=
1.707 albertel 2752: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2753: if ($result eq 'ok') {
2754: if (!($perm_reqd eq 'yes')) {
2755: return(&retrievestudentphoto($udom,$unam,$ext));
2756: }
2757: }
2758: }
2759: }
2760: } else {
2761: my ($result,$perm_reqd) =
1.707 albertel 2762: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2763: if ($result eq 'ok') {
2764: if (!($perm_reqd eq 'yes')) {
2765: return(&retrievestudentphoto($udom,$unam,$ext));
2766: }
2767: }
2768: }
2769: return '/adm/lonKaputt/lonlogo_broken.gif';
2770: }
2771:
2772: sub retrievestudentphoto {
2773: my ($udom,$unam,$ext,$type) = @_;
2774: my $home=&Apache::lonnet::homeserver($unam,$udom);
2775: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
2776: if ($ret eq 'ok') {
2777: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
2778: if ($type eq 'thumbnail') {
2779: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
2780: }
2781: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
2782: return $tokenurl;
2783: } else {
2784: if ($type eq 'thumbnail') {
2785: return '/adm/lonKaputt/genericstudent_tn.gif';
2786: } else {
2787: return '/adm/lonKaputt/lonlogo_broken.gif';
2788: }
1.617 albertel 2789: }
2790: }
2791:
1.263 www 2792: # -------------------------------------------------------------------- New chat
2793:
2794: sub chatsend {
1.724 raeburn 2795: my ($newentry,$anon,$group)=@_;
1.620 albertel 2796: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
2797: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2798: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 2799: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 2800: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 2801: &escape($newentry)).':'.$group,$chome);
1.292 www 2802: }
2803:
2804: # ------------------------------------------ Find current version of a resource
2805:
2806: sub getversion {
2807: my $fname=&clutter(shift);
1.1189 raeburn 2808: unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292 www 2809: return ¤tversion(&filelocation('',$fname));
2810: }
2811:
2812: sub currentversion {
2813: my $fname=shift;
2814: my $author=$fname;
2815: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2816: my ($udom,$uname)=split(/\//,$author);
1.1112 www 2817: my $home=&homeserver($uname,$udom);
1.292 www 2818: if ($home eq 'no_host') {
2819: return -1;
2820: }
1.1112 www 2821: my $answer=&reply("currentversion:$fname",$home);
1.292 www 2822: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2823: return -1;
2824: }
1.1112 www 2825: return $answer;
1.263 www 2826: }
2827:
1.1111 www 2828: #
2829: # Return special version number of resource if set by override, empty otherwise
2830: #
2831: sub usedversion {
2832: my $fname=shift;
2833: unless ($fname) { $fname=$env{'request.uri'}; }
2834: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
2835: if ($urlversion) { return $urlversion; }
2836: return '';
2837: }
2838:
1.1 albertel 2839: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 2840:
1.1 albertel 2841: sub subscribe {
2842: my $fname=shift;
1.761 raeburn 2843: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 2844: $fname=~s/[\n\r]//g;
1.1 albertel 2845: my $author=$fname;
2846: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2847: my ($udom,$uname)=split(/\//,$author);
2848: my $home=homeserver($uname,$udom);
1.335 albertel 2849: if ($home eq 'no_host') {
2850: return 'not_found';
1.1 albertel 2851: }
2852: my $answer=reply("sub:$fname",$home);
1.64 www 2853: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2854: $answer.=' by '.$home;
2855: }
1.1 albertel 2856: return $answer;
2857: }
2858:
1.8 www 2859: # -------------------------------------------------------------- Replicate file
2860:
2861: sub repcopy {
2862: my $filename=shift;
1.23 www 2863: $filename=~s/\/+/\//g;
1.1142 raeburn 2864: my $londocroot = $perlvar{'lonDocRoot'};
2865: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164 raeburn 2866: if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142 raeburn 2867: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
2868: $filename=~m{^/*(uploaded|editupload)/}) {
1.538 albertel 2869: return &repcopy_userfile($filename);
2870: }
1.532 albertel 2871: $filename=~s/[\n\r]//g;
1.8 www 2872: my $transname="$filename.in.transfer";
1.828 www 2873: # FIXME: this should flock
1.607 raeburn 2874: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 2875: my $remoteurl=subscribe($filename);
1.64 www 2876: if ($remoteurl =~ /^con_lost by/) {
2877: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2878: return 'unavailable';
1.8 www 2879: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 2880: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 2881: return 'not_found';
1.64 www 2882: } elsif ($remoteurl =~ /^rejected by/) {
2883: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2884: return 'forbidden';
1.20 www 2885: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 2886: return 'ok';
1.8 www 2887: } else {
1.290 www 2888: my $author=$filename;
2889: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2890: my ($udom,$uname)=split(/\//,$author);
2891: my $home=homeserver($uname,$udom);
2892: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 2893: my @parts=split(/\//,$filename);
2894: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142 raeburn 2895: if ($path ne "$londocroot/res") {
1.8 www 2896: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 2897: return 'bad_request';
1.8 www 2898: }
2899: my $count;
2900: for ($count=5;$count<$#parts;$count++) {
2901: $path.="/$parts[$count]";
2902: if ((-e $path)!=1) {
2903: mkdir($path,0777);
2904: }
2905: }
2906: my $ua=new LWP::UserAgent;
2907: my $request=new HTTP::Request('GET',"$remoteurl");
2908: my $response=$ua->request($request,$transname);
2909: if ($response->is_error()) {
2910: unlink($transname);
2911: my $message=$response->status_line;
1.672 albertel 2912: &logthis("<font color=\"blue\">WARNING:"
1.12 www 2913: ." LWP get: $message: $filename</font>");
1.607 raeburn 2914: return 'unavailable';
1.8 www 2915: } else {
1.16 www 2916: if ($remoteurl!~/\.meta$/) {
2917: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2918: my $mresponse=$ua->request($mrequest,$filename.'.meta');
2919: if ($mresponse->is_error()) {
2920: unlink($filename.'.meta');
2921: &logthis(
1.672 albertel 2922: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 2923: }
2924: }
1.8 www 2925: rename($transname,$filename);
1.607 raeburn 2926: return 'ok';
1.8 www 2927: }
1.290 www 2928: }
1.8 www 2929: }
1.330 www 2930: }
2931:
2932: # ------------------------------------------------ Get server side include body
2933: sub ssi_body {
1.381 albertel 2934: my ($filelink,%form)=@_;
1.606 matthew 2935: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
2936: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
2937: }
1.953 www 2938: my $output='';
2939: my $response;
1.980 raeburn 2940: if ($filelink=~/^https?\:/) {
1.954 raeburn 2941: ($output,$response)=&externalssi($filelink);
1.953 www 2942: } else {
1.1004 droeschl 2943: $filelink .= $filelink=~/\?/ ? '&' : '?';
2944: $filelink .= 'inhibitmenu=yes';
1.953 www 2945: ($output,$response)=&ssi($filelink,%form);
2946: }
1.778 albertel 2947: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 2948: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 2949: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 2950: if (wantarray) {
2951: return ($output, $response);
2952: } else {
2953: return $output;
2954: }
1.8 www 2955: }
2956:
1.15 www 2957: # --------------------------------------------------------- Server Side Include
2958:
1.782 albertel 2959: sub absolute_url {
2960: my ($host_name) = @_;
2961: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
2962: if ($host_name eq '') {
2963: $host_name = $ENV{'SERVER_NAME'};
2964: }
2965: return $protocol.$host_name;
2966: }
2967:
1.942 foxr 2968: #
2969: # Server side include.
2970: # Parameters:
2971: # fn Possibly encrypted resource name/id.
2972: # form Hash that describes how the rendering should be done
2973: # and other things.
1.944 foxr 2974: # Returns:
1.950 raeburn 2975: # Scalar context: The content of the response.
2976: # Array context: 2 element list of the content and the full response object.
1.942 foxr 2977: #
1.15 www 2978: sub ssi {
2979:
1.944 foxr 2980: my ($fn,%form)=@_;
1.15 www 2981: my $ua=new LWP::UserAgent;
1.23 www 2982: my $request;
1.711 albertel 2983:
2984: $form{'no_update_last_known'}=1;
1.895 albertel 2985: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 2986: if (%form) {
1.782 albertel 2987: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1272 droeschl 2988: $request->content(join('&',map {
2989: my $name = escape($_);
2990: "$name=" . ( ref($form{$_}) eq 'ARRAY'
2991: ? join("&$name=", map {escape($_) } @{$form{$_}})
2992: : &escape($form{$_}) );
2993: } keys(%form)));
1.23 www 2994: } else {
1.782 albertel 2995: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 2996: }
2997:
1.15 www 2998: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1173 foxr 2999: my $response= $ua->request($request);
1.1182 foxr 3000: my $content = $response->content;
3001:
3002:
1.944 foxr 3003: if (wantarray) {
1.1173 foxr 3004: return ($content, $response);
1.944 foxr 3005: } else {
1.1173 foxr 3006: return $content;
1.942 foxr 3007: }
1.324 www 3008: }
3009:
3010: sub externalssi {
3011: my ($url)=@_;
3012: my $ua=new LWP::UserAgent;
3013: my $request=new HTTP::Request('GET',$url);
3014: my $response=$ua->request($request);
1.954 raeburn 3015: if (wantarray) {
3016: return ($response->content, $response);
3017: } else {
3018: return $response->content;
3019: }
1.15 www 3020: }
1.254 www 3021:
1.492 albertel 3022: # -------------------------------- Allow a /uploaded/ URI to be vouched for
3023:
3024: sub allowuploaded {
3025: my ($srcurl,$url)=@_;
3026: $url=&clutter(&declutter($url));
3027: my $dir=$url;
3028: $dir=~s/\/[^\/]+$//;
3029: my %httpref=();
3030: my $httpurl=&hreflocation('',$url);
3031: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 3032: &Apache::lonnet::appenv(\%httpref);
1.254 www 3033: }
1.477 raeburn 3034:
1.1193 raeburn 3035: #
3036: # Determine if the current user should be able to edit a particular resource,
3037: # when viewing in course context.
3038: # (a) When viewing resource used to determine if "Edit" item is included in
3039: # Functions.
3040: # (b) When displaying folder contents in course editor, used to determine if
3041: # "Edit" link will be displayed alongside resource.
3042: #
1.1196 raeburn 3043: # input: six args -- filename (decluttered), course number, course domain,
3044: # url, symb (if registered) and group (if this is a group
3045: # item -- e.g., bulletin board, group page etc.).
3046: # output: array of five scalars --
1.1193 raeburn 3047: # $cfile -- url for file editing if editable on current server
3048: # $home -- homeserver of resource (i.e., for author if published,
3049: # or course if uploaded.).
3050: # $switchserver -- 1 if server switch will be needed.
1.1196 raeburn 3051: # $forceedit -- 1 if icon/link should be to go to edit mode
3052: # $forceview -- 1 if icon/link should be to go to view mode
1.1193 raeburn 3053: #
3054:
3055: sub can_edit_resource {
1.1194 raeburn 3056: my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
3057: my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
3058: #
3059: # For aboutme pages user can only edit his/her own.
3060: #
1.1199 raeburn 3061: if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
1.1194 raeburn 3062: my ($sdom,$sname) = ($1,$2);
3063: if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
3064: $home = $env{'user.home'};
3065: $cfile = $resurl;
3066: if ($env{'form.forceedit'}) {
3067: $forceview = 1;
3068: } else {
3069: $forceedit = 1;
3070: }
3071: return ($cfile,$home,$switchserver,$forceedit,$forceview);
3072: } else {
3073: return;
3074: }
3075: }
3076:
3077: if ($env{'request.course.id'}) {
3078: my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
3079: if ($group ne '') {
3080: # if this is a group homepage or group bulletin board, check group privs
3081: my $allowed = 0;
1.1197 raeburn 3082: if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
3083: if ((&allowed('mdg',$env{'request.course.id'}.
1.1198 raeburn 3084: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
1.1194 raeburn 3085: (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
3086: $allowed = 1;
3087: }
1.1197 raeburn 3088: } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
3089: if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
3090: (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
1.1194 raeburn 3091: $allowed = 1;
3092: }
3093: }
3094: if ($allowed) {
3095: $home=&homeserver($cnum,$cdom);
3096: if ($env{'form.forceedit'}) {
3097: $forceview = 1;
3098: } else {
3099: $forceedit = 1;
3100: }
3101: $cfile = $resurl;
3102: } else {
3103: return;
3104: }
3105: } else {
1.1208 raeburn 3106: if ($resurl =~ m{^/?adm/viewclasslist$}) {
3107: unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
3108: return;
3109: }
3110: } elsif (!$crsedit) {
1.1194 raeburn 3111: #
3112: # No edit allowed where CC has switched to student role.
3113: #
3114: return;
3115: }
3116: }
3117: }
3118:
1.1193 raeburn 3119: if ($file ne '') {
3120: if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
1.1194 raeburn 3121: if (&is_course_upload($file,$cnum,$cdom)) {
3122: $uploaded = 1;
3123: $incourse = 1;
1.1193 raeburn 3124: if ($file =~/\.(htm|html|css|js|txt)$/) {
3125: $cfile = &hreflocation('',$file);
1.1201 raeburn 3126: if ($env{'form.forceedit'}) {
3127: $forceview = 1;
3128: } else {
3129: $forceedit = 1;
3130: }
1.1194 raeburn 3131: }
3132: } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
3133: $incourse = 1;
3134: if ($env{'form.forceedit'}) {
3135: $forceview = 1;
3136: } else {
3137: $forceedit = 1;
3138: }
3139: $cfile = $resurl;
3140: } elsif (($resurl ne '') && (&is_on_map($resurl))) {
3141: if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
3142: $incourse = 1;
3143: if ($env{'form.forceedit'}) {
3144: $forceview = 1;
3145: } else {
3146: $forceedit = 1;
3147: }
3148: $cfile = $resurl;
1.1199 raeburn 3149: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
1.1194 raeburn 3150: $incourse = 1;
3151: $cfile = $resurl.'/smpedit';
1.1199 raeburn 3152: } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
1.1194 raeburn 3153: $incourse = 1;
1.1199 raeburn 3154: if ($env{'form.forceedit'}) {
3155: $forceview = 1;
3156: } else {
3157: $forceedit = 1;
3158: }
3159: $cfile = $resurl;
1.1298 raeburn 3160: } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/exttools?$}) {
3161: $incourse = 1;
3162: if ($env{'form.forceedit'}) {
3163: $forceview = 1;
3164: } else {
3165: $forceedit = 1;
3166: }
3167: $cfile = $resurl;
1.1208 raeburn 3168: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3169: $incourse = 1;
3170: if ($env{'form.forceedit'}) {
3171: $forceview = 1;
3172: } else {
3173: $forceedit = 1;
3174: }
3175: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1194 raeburn 3176: }
3177: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
3178: my $template = '/res/lib/templates/simpleproblem.problem';
3179: if (&is_on_map($template)) {
3180: $incourse = 1;
3181: $forceview = 1;
3182: $cfile = $template;
1.1193 raeburn 3183: }
1.1199 raeburn 3184: } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
3185: $incourse = 1;
3186: if ($env{'form.forceedit'}) {
3187: $forceview = 1;
3188: } else {
3189: $forceedit = 1;
3190: }
3191: $cfile = $resurl;
1.1298 raeburn 3192: } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/exttools?$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
3193: $incourse = 1;
3194: if ($env{'form.forceedit'}) {
3195: $forceview = 1;
3196: } else {
3197: $forceedit = 1;
3198: }
3199: $cfile = $resurl;
1.1199 raeburn 3200: } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
3201: $incourse = 1;
3202: $forceview = 1;
3203: if ($symb) {
3204: my ($map,$id,$res)=&decode_symb($symb);
3205: $env{'request.symb'} = $symb;
3206: $cfile = &clutter($res);
3207: } else {
3208: $cfile = $env{'form.suppurl'};
1.1298 raeburn 3209: my $escfile = &unescape($cfile);
3210: if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/exttools?$}) {
3211: $cfile = '/adm/wrapper'.$escfile;
3212: } else {
3213: $escfile =~ s{^http://}{};
3214: $cfile = &escape("/adm/wrapper/ext/$escfile");
3215: }
1.1199 raeburn 3216: }
1.1234 raeburn 3217: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3218: if ($env{'form.forceedit'}) {
3219: $forceview = 1;
3220: } else {
3221: $forceedit = 1;
3222: }
3223: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1193 raeburn 3224: }
3225: }
1.1194 raeburn 3226: if ($uploaded || $incourse) {
3227: $home=&homeserver($cnum,$cdom);
1.1207 raeburn 3228: } elsif ($file !~ m{/$}) {
1.1193 raeburn 3229: $file=~s{^(priv/$match_domain/$match_username)}{/$1};
3230: $file=~s{^($match_domain/$match_username)}{/priv/$1};
3231: # Check that the user has permission to edit this resource
3232: my $setpriv = 1;
3233: my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
3234: if (defined($cfudom)) {
3235: $home=&homeserver($cfuname,$cfudom);
3236: $cfile=$file;
3237: }
3238: }
1.1194 raeburn 3239: if (($cfile ne '') && (!$incourse || $uploaded) &&
3240: (($home ne '') && ($home ne 'no_host'))) {
1.1193 raeburn 3241: my @ids=¤t_machine_ids();
3242: unless (grep(/^\Q$home\E$/,@ids)) {
3243: $switchserver=1;
3244: }
3245: }
3246: }
1.1194 raeburn 3247: return ($cfile,$home,$switchserver,$forceedit,$forceview);
1.1193 raeburn 3248: }
3249:
3250: sub is_course_upload {
3251: my ($file,$cnum,$cdom) = @_;
3252: my $uploadpath = &LONCAPA::propath($cdom,$cnum);
3253: $uploadpath =~ s{^\/}{};
1.1201 raeburn 3254: if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
3255: ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
1.1193 raeburn 3256: return 1;
3257: }
3258: return;
3259: }
3260:
1.1194 raeburn 3261: sub in_course {
1.1195 raeburn 3262: my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
3263: if ($hideprivileged) {
3264: my $skipuser;
1.1219 raeburn 3265: my %coursehash = &coursedescription($cdom.'_'.$cnum);
3266: my @possdoms = ($cdom);
3267: if ($coursehash{'checkforpriv'}) {
3268: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
3269: }
3270: if (&privileged($uname,$udom,\@possdoms)) {
1.1195 raeburn 3271: $skipuser = 1;
3272: if ($coursehash{'nothideprivileged'}) {
3273: foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3274: my $user;
3275: if ($item =~ /:/) {
3276: $user = $item;
3277: } else {
3278: $user = join(':',split(/[\@]/,$item));
3279: }
3280: if ($user eq $uname.':'.$udom) {
3281: undef($skipuser);
3282: last;
3283: }
3284: }
3285: }
3286: if ($skipuser) {
3287: return 0;
3288: }
3289: }
3290: }
1.1194 raeburn 3291: $type ||= 'any';
3292: if (!defined($cdom) || !defined($cnum)) {
3293: my $cid = $env{'request.course.id'};
3294: $cdom = $env{'course.'.$cid.'.domain'};
3295: $cnum = $env{'course.'.$cid.'.num'};
3296: }
3297: my $typesref;
1.1195 raeburn 3298: if (($type eq 'any') || ($type eq 'all')) {
1.1194 raeburn 3299: $typesref = ['active','previous','future'];
3300: } elsif ($type eq 'previous' || $type eq 'future') {
3301: $typesref = [$type];
3302: }
3303: my %roles = &get_my_roles($uname,$udom,'userroles',
3304: $typesref,undef,[$cdom]);
3305: my ($tmp) = keys(%roles);
3306: return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
3307: my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
3308: if (@course_roles > 0) {
3309: return 1;
3310: }
3311: return 0;
3312: }
3313:
1.478 albertel 3314: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 3315: # input: action, courseID, current domain, intended
1.637 raeburn 3316: # path to file, source of file, instruction to parse file for objects,
3317: # ref to hash for embedded objects,
3318: # ref to hash for codebase of java objects.
1.1095 raeburn 3319: # reference to scalar to accommodate mime type determined
3320: # from File::MMagic if $parser = parse.
1.637 raeburn 3321: #
1.485 raeburn 3322: # output: url to file (if action was uploaddoc),
3323: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 3324: #
1.478 albertel 3325: # Allows directory structure to be used within lonUsers/../userfiles/ for a
3326: # course.
1.477 raeburn 3327: #
1.478 albertel 3328: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3329: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
3330: # course's home server.
1.477 raeburn 3331: #
1.478 albertel 3332: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
3333: # be copied from $source (current location) to
3334: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3335: # and will then be copied to
3336: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
3337: # course's home server.
1.485 raeburn 3338: #
1.481 raeburn 3339: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 3340: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 3341: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3342: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
3343: # in course's home server.
1.637 raeburn 3344: #
1.477 raeburn 3345:
3346: sub process_coursefile {
1.1095 raeburn 3347: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
3348: $mimetype)=@_;
1.477 raeburn 3349: my $fetchresult;
1.638 albertel 3350: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 3351: if ($action eq 'propagate') {
1.638 albertel 3352: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
3353: $home);
1.481 raeburn 3354: } else {
1.477 raeburn 3355: my $fpath = '';
3356: my $fname = $file;
1.478 albertel 3357: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 3358: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 3359: my $filepath = &build_filepath($fpath);
1.481 raeburn 3360: if ($action eq 'copy') {
3361: if ($source eq '') {
3362: $fetchresult = 'no source file';
3363: return $fetchresult;
3364: } else {
3365: my $destination = $filepath.'/'.$fname;
3366: rename($source,$destination);
3367: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3368: $home);
1.481 raeburn 3369: }
3370: } elsif ($action eq 'uploaddoc') {
3371: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 3372: print $fh $env{'form.'.$source};
1.481 raeburn 3373: close($fh);
1.637 raeburn 3374: if ($parser eq 'parse') {
1.1024 raeburn 3375: my $mm = new File::MMagic;
1.1095 raeburn 3376: my $type = $mm->checktype_filename($filepath.'/'.$fname);
3377: if ($type eq 'text/html') {
1.1024 raeburn 3378: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
3379: unless ($parse_result eq 'ok') {
3380: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
3381: }
1.637 raeburn 3382: }
1.1095 raeburn 3383: if (ref($mimetype)) {
3384: $$mimetype = $type;
3385: }
1.637 raeburn 3386: }
1.477 raeburn 3387: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3388: $home);
1.481 raeburn 3389: if ($fetchresult eq 'ok') {
3390: return '/uploaded/'.$fpath.'/'.$fname;
3391: } else {
3392: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3393: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 3394: return '/adm/notfound.html';
3395: }
1.477 raeburn 3396: }
3397: }
1.485 raeburn 3398: unless ( $fetchresult eq 'ok') {
1.477 raeburn 3399: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3400: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 3401: }
3402: return $fetchresult;
3403: }
3404:
1.637 raeburn 3405: sub build_filepath {
3406: my ($fpath) = @_;
3407: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
3408: unless ($fpath eq '') {
3409: my @parts=split('/',$fpath);
3410: foreach my $part (@parts) {
3411: $filepath.= '/'.$part;
3412: if ((-e $filepath)!=1) {
3413: mkdir($filepath,0777);
3414: }
3415: }
3416: }
3417: return $filepath;
3418: }
3419:
3420: sub store_edited_file {
1.638 albertel 3421: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 3422: my $file = $primary_url;
3423: $file =~ s#^/uploaded/$docudom/$docuname/##;
3424: my $fpath = '';
3425: my $fname = $file;
3426: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
3427: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
3428: my $filepath = &build_filepath($fpath);
3429: open(my $fh,'>'.$filepath.'/'.$fname);
3430: print $fh $content;
3431: close($fh);
1.638 albertel 3432: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 3433: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3434: $home);
1.637 raeburn 3435: if ($$fetchresult eq 'ok') {
3436: return '/uploaded/'.$fpath.'/'.$fname;
3437: } else {
1.638 albertel 3438: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
3439: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 3440: return '/adm/notfound.html';
3441: }
3442: }
3443:
1.531 albertel 3444: sub clean_filename {
1.831 albertel 3445: my ($fname,$args)=@_;
1.315 www 3446: # Replace Windows backslashes by forward slashes
1.257 www 3447: $fname=~s/\\/\//g;
1.831 albertel 3448: if (!$args->{'keep_path'}) {
3449: # Get rid of everything but the actual filename
3450: $fname=~s/^.*\/([^\/]+)$/$1/;
3451: }
1.315 www 3452: # Replace spaces by underscores
3453: $fname=~s/\s+/\_/g;
3454: # Replace all other weird characters by nothing
1.831 albertel 3455: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 3456: # Replace all .\d. sequences with _\d. so they no longer look like version
3457: # numbers
3458: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 3459: return $fname;
3460: }
1.1051 raeburn 3461: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
3462: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
3463: # image with the same aspect ratio as the original, but with dimensions which do
3464: # not exceed $resizewidth and $resizeheight.
3465:
1.984 neumanie 3466: sub resizeImage {
1.1051 raeburn 3467: my ($img_path,$resizewidth,$resizeheight) = @_;
3468: my $ima = Image::Magick->new;
3469: my $resized;
3470: if (-e $img_path) {
3471: $ima->Read($img_path);
3472: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
3473: my $width = $ima->Get('width');
3474: my $height = $ima->Get('height');
3475: if ($width > $resizewidth) {
3476: my $factor = $width/$resizewidth;
3477: my $newheight = $height/$factor;
3478: $ima->Scale(width=>$resizewidth,height=>$newheight);
3479: $resized = 1;
3480: }
3481: }
3482: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
3483: my $width = $ima->Get('width');
3484: my $height = $ima->Get('height');
3485: if ($height > $resizeheight) {
3486: my $factor = $height/$resizeheight;
3487: my $newwidth = $width/$factor;
3488: $ima->Scale(width=>$newwidth,height=>$resizeheight);
3489: $resized = 1;
3490: }
3491: }
3492: if ($resized) {
3493: $ima->Write($img_path);
3494: }
3495: }
3496: return;
1.977 amueller 3497: }
3498:
1.608 albertel 3499: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 3500: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093 raeburn 3501: # the desired filename is in $env{"form.$formname.filename"}
1.1090 raeburn 3502: # $context - possible values: coursedoc, existingfile, overwrite,
3503: # canceloverwrite, or ''.
3504: # if 'coursedoc': upload to the current course
3505: # if 'existingfile': write file to tmp/overwrites directory
3506: # if 'canceloverwrite': delete file written to tmp/overwrites directory
3507: # $context is passed as argument to &finishuserfileupload
1.686 albertel 3508: # $subdir - directory in userfile to store the file into
1.858 raeburn 3509: # $parser - instruction to parse file for objects ($parser = parse)
3510: # $allfiles - reference to hash for embedded objects
3511: # $codebase - reference to hash for codebase of java objects
3512: # $desuname - username for permanent storage of uploaded file
3513: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 3514: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
3515: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 3516: # $resizewidth - width (pixels) to which to resize uploaded image
3517: # $resizeheight - height (pixels) to which to resize uploaded image
1.1095 raeburn 3518: # $mimetype - reference to scalar to accommodate mime type determined
1.1152 raeburn 3519: # from File::MMagic.
1.858 raeburn 3520: #
1.686 albertel 3521: # output: url of file in userspace, or error: <message>
3522: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 3523:
1.531 albertel 3524: sub userfileupload {
1.1090 raeburn 3525: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095 raeburn 3526: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531 albertel 3527: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 3528: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 3529: $fname=&clean_filename($fname);
1.1090 raeburn 3530: # See if there is anything left
1.257 www 3531: unless ($fname) { return 'error: no uploaded file'; }
1.1090 raeburn 3532: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
3533: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
3534: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
3535: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523 raeburn 3536: my $now = time;
1.1090 raeburn 3537: my $filepath;
1.1095 raeburn 3538: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090 raeburn 3539: $filepath = 'tmp/helprequests/'.$now;
3540: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
3541: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
3542: '_'.$env{'user.domain'}.'/pending';
3543: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
3544: my ($docuname,$docudom);
3545: if ($destudom) {
3546: $docudom = $destudom;
3547: } else {
3548: $docudom = $env{'user.domain'};
3549: }
3550: if ($destuname) {
3551: $docuname = $destuname;
3552: } else {
3553: $docuname = $env{'user.name'};
3554: }
3555: if (exists($env{'form.group'})) {
3556: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3557: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3558: }
3559: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
3560: if ($context eq 'canceloverwrite') {
3561: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
3562: if (-e $tempfile) {
3563: my @info = stat($tempfile);
3564: if ($info[9] eq $env{'form.timestamp'}) {
3565: unlink($tempfile);
3566: }
3567: }
3568: return;
1.523 raeburn 3569: }
3570: }
1.1090 raeburn 3571: # Create the directory if not present
1.741 raeburn 3572: my @parts=split(/\//,$filepath);
3573: my $fullpath = $perlvar{'lonDaemons'};
3574: for (my $i=0;$i<@parts;$i++) {
3575: $fullpath .= '/'.$parts[$i];
3576: if ((-e $fullpath)!=1) {
3577: mkdir($fullpath,0777);
3578: }
3579: }
3580: open(my $fh,'>'.$fullpath.'/'.$fname);
3581: print $fh $env{'form.'.$formname};
3582: close($fh);
1.1090 raeburn 3583: if ($context eq 'existingfile') {
3584: my @info = stat($fullpath.'/'.$fname);
3585: return ($fullpath.'/'.$fname,$info[9]);
3586: } else {
3587: return $fullpath.'/'.$fname;
3588: }
1.523 raeburn 3589: }
1.995 raeburn 3590: if ($subdir eq 'scantron') {
3591: $fname = 'scantron_orig_'.$fname;
1.1093 raeburn 3592: } else {
1.995 raeburn 3593: $fname="$subdir/$fname";
3594: }
1.1090 raeburn 3595: if ($context eq 'coursedoc') {
1.638 albertel 3596: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3597: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 3598: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 3599: return &finishuserfileupload($docuname,$docudom,
3600: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 3601: $codebase,$thumbwidth,$thumbheight,
1.1095 raeburn 3602: $resizewidth,$resizeheight,$context,$mimetype);
1.481 raeburn 3603: } else {
1.1218 raeburn 3604: if ($env{'form.folder'}) {
3605: $fname=$env{'form.folder'}.'/'.$fname;
3606: }
1.638 albertel 3607: return &process_coursefile('uploaddoc',$docuname,$docudom,
3608: $fname,$formname,$parser,
1.1095 raeburn 3609: $allfiles,$codebase,$mimetype);
1.481 raeburn 3610: }
1.719 banghart 3611: } elsif (defined($destuname)) {
3612: my $docuname=$destuname;
3613: my $docudom=$destudom;
1.860 raeburn 3614: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3615: $parser,$allfiles,$codebase,
1.1051 raeburn 3616: $thumbwidth,$thumbheight,
1.1095 raeburn 3617: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3618: } else {
1.638 albertel 3619: my $docuname=$env{'user.name'};
3620: my $docudom=$env{'user.domain'};
1.1220 raeburn 3621: if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714 raeburn 3622: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3623: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3624: }
1.860 raeburn 3625: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3626: $parser,$allfiles,$codebase,
1.1051 raeburn 3627: $thumbwidth,$thumbheight,
1.1095 raeburn 3628: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3629: }
1.271 www 3630: }
3631:
3632: sub finishuserfileupload {
1.860 raeburn 3633: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095 raeburn 3634: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477 raeburn 3635: my $path=$docudom.'/'.$docuname.'/';
1.258 www 3636: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 3637:
1.860 raeburn 3638: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 3639: $file=$fname;
3640: if ($fname=~m|/|) {
3641: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
3642: $path.=$fnamepath.'/';
3643: }
1.259 www 3644: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 3645: my $count;
3646: for ($count=4;$count<=$#parts;$count++) {
3647: $filepath.="/$parts[$count]";
3648: if ((-e $filepath)!=1) {
3649: mkdir($filepath,0777);
3650: }
3651: }
1.984 neumanie 3652:
1.258 www 3653: # Save the file
3654: {
1.701 albertel 3655: if (!open(FH,'>'.$filepath.'/'.$file)) {
3656: &logthis('Failed to create '.$filepath.'/'.$file);
3657: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
3658: return '/adm/notfound.html';
3659: }
1.1090 raeburn 3660: if ($context eq 'overwrite') {
1.1117 foxr 3661: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090 raeburn 3662: my $target = $filepath.'/'.$file;
3663: if (-e $source) {
3664: my @info = stat($source);
3665: if ($info[9] eq $env{'form.timestamp'}) {
3666: unless (&File::Copy::move($source,$target)) {
3667: &logthis('Failed to overwrite '.$filepath.'/'.$file);
3668: return "Moving from $source failed";
3669: }
3670: } else {
3671: return "Temporary file: $source had unexpected date/time for last modification";
3672: }
3673: } else {
3674: return "Temporary file: $source missing";
3675: }
3676: } elsif (!print FH ($env{'form.'.$formname})) {
1.701 albertel 3677: &logthis('Failed to write to '.$filepath.'/'.$file);
3678: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
3679: return '/adm/notfound.html';
3680: }
1.570 albertel 3681: close(FH);
1.1051 raeburn 3682: if ($resizewidth && $resizeheight) {
3683: my $mm = new File::MMagic;
3684: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
3685: if ($mime_type =~ m{^image/}) {
3686: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
3687: }
1.977 amueller 3688: }
1.258 www 3689: }
1.1152 raeburn 3690: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
3691: if (ref($mimetype)) {
3692: if ($$mimetype eq '') {
3693: my $mm = new File::MMagic;
3694: my $type = $mm->checktype_filename($filepath.'/'.$file);
3695: $$mimetype = $type;
3696: }
3697: }
3698: }
1.637 raeburn 3699: if ($parser eq 'parse') {
1.1152 raeburn 3700: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024 raeburn 3701: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
3702: $allfiles,$codebase);
3703: unless ($parse_result eq 'ok') {
3704: &logthis('Failed to parse '.$filepath.$file.
3705: ' for embedded media: '.$parse_result);
3706: }
1.637 raeburn 3707: }
3708: }
1.860 raeburn 3709: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
3710: my $input = $filepath.'/'.$file;
3711: my $output = $filepath.'/'.'tn-'.$file;
3712: my $thumbsize = $thumbwidth.'x'.$thumbheight;
3713: system("convert -sample $thumbsize $input $output");
3714: if (-e $filepath.'/'.'tn-'.$file) {
3715: $fetchthumb = 1;
3716: }
3717: }
1.858 raeburn 3718:
1.259 www 3719: # Notify homeserver to grep it
3720: #
1.984 neumanie 3721: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 3722: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 3723: if ($fetchresult eq 'ok') {
1.860 raeburn 3724: if ($fetchthumb) {
3725: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
3726: if ($thumbresult ne 'ok') {
3727: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
3728: $docuhome.': '.$thumbresult);
3729: }
3730: }
1.259 www 3731: #
1.258 www 3732: # Return the URL to it
1.494 albertel 3733: return '/uploaded/'.$path.$file;
1.263 www 3734: } else {
1.494 albertel 3735: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
3736: ': '.$fetchresult);
1.263 www 3737: return '/adm/notfound.html';
1.858 raeburn 3738: }
1.493 albertel 3739: }
3740:
1.637 raeburn 3741: sub extract_embedded_items {
1.961 raeburn 3742: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 3743: my @state = ();
1.1164 raeburn 3744: my (%lastids,%related,%shockwave,%flashvars);
1.637 raeburn 3745: my %javafiles = (
3746: codebase => '',
3747: code => '',
3748: archive => ''
3749: );
3750: my %mediafiles = (
3751: src => '',
3752: movie => '',
3753: );
1.648 raeburn 3754: my $p;
3755: if ($content) {
3756: $p = HTML::LCParser->new($content);
3757: } else {
1.961 raeburn 3758: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 3759: }
1.641 albertel 3760: while (my $t=$p->get_token()) {
1.640 albertel 3761: if ($t->[0] eq 'S') {
3762: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 3763: push(@state, $tagname);
1.648 raeburn 3764: if (lc($tagname) eq 'allow') {
3765: &add_filetype($allfiles,$attr->{'src'},'src');
3766: }
1.640 albertel 3767: if (lc($tagname) eq 'img') {
3768: &add_filetype($allfiles,$attr->{'src'},'src');
3769: }
1.886 albertel 3770: if (lc($tagname) eq 'a') {
1.1222 raeburn 3771: unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
1.1221 raeburn 3772: &add_filetype($allfiles,$attr->{'href'},'href');
3773: }
1.886 albertel 3774: }
1.645 raeburn 3775: if (lc($tagname) eq 'script') {
1.1164 raeburn 3776: my $src;
1.645 raeburn 3777: if ($attr->{'archive'} =~ /\.jar$/i) {
3778: &add_filetype($allfiles,$attr->{'archive'},'archive');
3779: } else {
1.1164 raeburn 3780: if ($attr->{'src'} ne '') {
3781: $src = $attr->{'src'};
3782: &add_filetype($allfiles,$src,'src');
3783: }
3784: }
3785: my $text = $p->get_trimmed_text();
3786: if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
3787: my @swfargs = split(/,/,$1);
3788: foreach my $item (@swfargs) {
3789: $item =~ s/["']//g;
3790: $item =~ s/^\s+//;
3791: $item =~ s/\s+$//;
3792: }
3793: if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
3794: if (ref($related{$swfargs[0]}) eq 'ARRAY') {
3795: push(@{$related{$swfargs[0]}},$swfargs[2]);
3796: } else {
3797: $related{$swfargs[0]} = [$swfargs[2]];
3798: }
3799: }
1.645 raeburn 3800: }
3801: }
3802: if (lc($tagname) eq 'link') {
3803: if (lc($attr->{'rel'}) eq 'stylesheet') {
3804: &add_filetype($allfiles,$attr->{'href'},'href');
3805: }
3806: }
1.640 albertel 3807: if (lc($tagname) eq 'object' ||
3808: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
3809: foreach my $item (keys(%javafiles)) {
3810: $javafiles{$item} = '';
3811: }
1.1164 raeburn 3812: if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
3813: $lastids{lc($tagname)} = $attr->{'id'};
3814: }
1.640 albertel 3815: }
3816: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
3817: my $name = lc($attr->{'name'});
3818: foreach my $item (keys(%javafiles)) {
3819: if ($name eq $item) {
3820: $javafiles{$item} = $attr->{'value'};
3821: last;
3822: }
3823: }
1.1164 raeburn 3824: my $pathfrom;
1.640 albertel 3825: foreach my $item (keys(%mediafiles)) {
3826: if ($name eq $item) {
1.1164 raeburn 3827: $pathfrom = $attr->{'value'};
3828: $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
3829: &add_filetype($allfiles,$pathfrom,$name);
1.640 albertel 3830: last;
3831: }
3832: }
1.1164 raeburn 3833: if ($name eq 'flashvars') {
3834: $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
3835: }
3836: if ($pathfrom ne '') {
3837: &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
3838: $pathfrom);
3839: }
1.640 albertel 3840: }
3841: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
3842: foreach my $item (keys(%javafiles)) {
3843: if ($attr->{$item}) {
3844: $javafiles{$item} = $attr->{$item};
3845: last;
3846: }
3847: }
3848: foreach my $item (keys(%mediafiles)) {
3849: if ($attr->{$item}) {
3850: &add_filetype($allfiles,$attr->{$item},$item);
3851: last;
3852: }
3853: }
1.1164 raeburn 3854: if (lc($tagname) eq 'embed') {
3855: if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
3856: &embedded_dependency($allfiles,\%related,$attr->{'name'},
3857: $attr->{'src'});
3858: }
3859: }
1.640 albertel 3860: }
1.1243 raeburn 3861: if (lc($tagname) eq 'iframe') {
3862: my $src = $attr->{'src'} ;
3863: if (($src ne '') && ($src !~ m{^(/|https?://)})) {
3864: &add_filetype($allfiles,$src,'src');
3865: } elsif ($src =~ m{^/}) {
3866: if ($env{'request.course.id'}) {
3867: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
3868: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
3869: my $url = &hreflocation('',$fullpath);
3870: if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
3871: my $relpath = $1;
3872: if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
3873: &add_filetype($allfiles,$1,'src');
3874: }
3875: }
3876: }
3877: }
3878: }
1.1164 raeburn 3879: if ($t->[4] =~ m{/>$}) {
1.1243 raeburn 3880: pop(@state);
1.1164 raeburn 3881: }
1.640 albertel 3882: } elsif ($t->[0] eq 'E') {
3883: my ($tagname) = ($t->[1]);
3884: if ($javafiles{'codebase'} ne '') {
3885: $javafiles{'codebase'} .= '/';
3886: }
3887: if (lc($tagname) eq 'applet' ||
3888: lc($tagname) eq 'object' ||
3889: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
3890: ) {
3891: foreach my $item (keys(%javafiles)) {
3892: if ($item ne 'codebase' && $javafiles{$item} ne '') {
3893: my $file=$javafiles{'codebase'}.$javafiles{$item};
3894: &add_filetype($allfiles,$file,$item);
3895: }
3896: }
3897: }
3898: pop @state;
3899: }
3900: }
1.1164 raeburn 3901: foreach my $id (sort(keys(%flashvars))) {
3902: if ($shockwave{$id} ne '') {
3903: my @pairs = split(/\&/,$flashvars{$id});
3904: foreach my $pair (@pairs) {
3905: my ($key,$value) = split(/\=/,$pair);
3906: if ($key eq 'thumb') {
3907: &add_filetype($allfiles,$value,$key);
3908: } elsif ($key eq 'content') {
3909: my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
3910: my ($ext) = ($value =~ /\.([^.]+)$/);
3911: if ($ext ne '') {
3912: &add_filetype($allfiles,$path.$value,$ext);
3913: }
3914: }
3915: }
3916: }
3917: }
1.637 raeburn 3918: return 'ok';
3919: }
3920:
1.639 albertel 3921: sub add_filetype {
3922: my ($allfiles,$file,$type)=@_;
3923: if (exists($allfiles->{$file})) {
3924: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
3925: push(@{$allfiles->{$file}}, &escape($type));
3926: }
3927: } else {
3928: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 3929: }
3930: }
3931:
1.1164 raeburn 3932: sub embedded_dependency {
3933: my ($allfiles,$related,$identifier,$pathfrom) = @_;
3934: if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
3935: if (($identifier ne '') &&
3936: (ref($related->{$identifier}) eq 'ARRAY') &&
3937: ($pathfrom ne '')) {
3938: my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
3939: foreach my $dep (@{$related->{$identifier}}) {
3940: &add_filetype($allfiles,$path.$dep,'object');
3941: }
3942: }
3943: }
3944: return;
3945: }
3946:
1.493 albertel 3947: sub removeuploadedurl {
1.984 neumanie 3948: my ($url)=@_;
3949: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 3950: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 3951: }
3952:
3953: sub removeuserfile {
3954: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 3955: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3956: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 3957: if ($result eq 'ok') {
1.798 raeburn 3958: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
3959: my $metafile = $fname.'.meta';
3960: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 3961: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 3962: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3963: my $sqlresult =
1.823 albertel 3964: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3965: 'portfolio_metadata',$group,
3966: 'delete');
1.798 raeburn 3967: }
3968: }
3969: return $result;
1.257 www 3970: }
1.15 www 3971:
1.530 albertel 3972: sub mkdiruserfile {
3973: my ($docuname,$docudom,$dir)=@_;
3974: my $home=&homeserver($docuname,$docudom);
3975: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
3976: }
3977:
1.531 albertel 3978: sub renameuserfile {
3979: my ($docuname,$docudom,$old,$new)=@_;
3980: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3981: my $result = &reply("renameuserfile:$docudom:$docuname:".
3982: &escape("$old").':'.&escape("$new"),$home);
3983: if ($result eq 'ok') {
3984: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
3985: my $oldmeta = $old.'.meta';
3986: my $newmeta = $new.'.meta';
3987: my $metaresult =
3988: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 3989: my $url = "/uploaded/$docudom/$docuname/$old";
3990: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3991: my $sqlresult =
1.823 albertel 3992: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3993: 'portfolio_metadata',$group,
3994: 'delete');
1.798 raeburn 3995: }
3996: }
3997: return $result;
1.531 albertel 3998: }
3999:
1.14 www 4000: # ------------------------------------------------------------------------- Log
4001:
4002: sub log {
4003: my ($dom,$nam,$hom,$what)=@_;
1.47 www 4004: return critical("log:$dom:$nam:$what",$hom);
1.157 www 4005: }
4006:
4007: # ------------------------------------------------------------------ Course Log
1.352 www 4008: #
4009: # This routine flushes several buffers of non-mission-critical nature
4010: #
1.157 www 4011:
4012: sub flushcourselogs {
1.352 www 4013: &logthis('Flushing log buffers');
4014: #
4015: # course logs
4016: # This is a log of all transactions in a course, which can be used
4017: # for data mining purposes
4018: #
4019: # It also collects the courseid database, which lists last transaction
4020: # times and course titles for all courseids
4021: #
4022: my %courseidbuffer=();
1.921 raeburn 4023: foreach my $crsid (keys(%courselogs)) {
1.352 www 4024: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 4025: &escape($courselogs{$crsid}),
4026: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 4027: delete $courselogs{$crsid};
4028: } else {
4029: &logthis('Failed to flush log buffer for '.$crsid);
4030: if (length($courselogs{$crsid})>40000) {
1.672 albertel 4031: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 4032: " exceeded maximum size, deleting.</font>");
4033: delete $courselogs{$crsid};
4034: }
1.352 www 4035: }
1.920 raeburn 4036: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 4037: 'description' => $coursedescrbuf{$crsid},
4038: 'inst_code' => $courseinstcodebuf{$crsid},
4039: 'type' => $coursetypebuf{$crsid},
4040: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 4041: };
1.191 harris41 4042: }
1.352 www 4043: #
4044: # Write course id database (reverse lookup) to homeserver of courses
4045: # Is used in pickcourse
4046: #
1.840 albertel 4047: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 4048: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 4049: $courseidbuffer{$crs_home},
4050: $crs_home,'timeonly');
1.352 www 4051: }
4052: #
4053: # File accesses
4054: # Writes to the dynamic metadata of resources to get hit counts, etc.
4055: #
1.449 matthew 4056: foreach my $entry (keys(%accesshash)) {
1.458 matthew 4057: if ($entry =~ /___count$/) {
4058: my ($dom,$name);
1.807 albertel 4059: ($dom,$name,undef)=
1.811 albertel 4060: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 4061: if (! defined($dom) || $dom eq '' ||
4062: ! defined($name) || $name eq '') {
1.620 albertel 4063: my $cid = $env{'request.course.id'};
4064: $dom = $env{'request.'.$cid.'.domain'};
4065: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 4066: }
1.450 matthew 4067: my $value = $accesshash{$entry};
4068: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
4069: my %temphash=($url => $value);
1.449 matthew 4070: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
4071: if ($result eq 'ok') {
4072: delete $accesshash{$entry};
4073: }
4074: } else {
1.811 albertel 4075: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159 www 4076: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450 matthew 4077: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 4078: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
4079: delete $accesshash{$entry};
4080: }
1.185 www 4081: }
1.191 harris41 4082: }
1.352 www 4083: #
4084: # Roles
4085: # Reverse lookup of user roles for course faculty/staff and co-authorship
4086: #
1.800 albertel 4087: foreach my $entry (keys(%userrolehash)) {
1.351 www 4088: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 4089: split(/\:/,$entry);
4090: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 4091: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 4092: $rudom,$runame) eq 'ok') {
4093: delete $userrolehash{$entry};
4094: }
4095: }
1.662 raeburn 4096: #
4097: # Reverse lookup of domain roles (dc, ad, li, sc, au)
4098: #
4099: my %domrolebuffer = ();
1.1000 raeburn 4100: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 4101: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 4102: if ($domrolebuffer{$rudom}) {
4103: $domrolebuffer{$rudom}.='&'.&escape($entry).
4104: '='.&escape($domainrolehash{$entry});
4105: } else {
4106: $domrolebuffer{$rudom}.=&escape($entry).
4107: '='.&escape($domainrolehash{$entry});
4108: }
4109: delete $domainrolehash{$entry};
4110: }
4111: foreach my $dom (keys(%domrolebuffer)) {
1.841 albertel 4112: my %servers = &get_servers($dom,'library');
4113: foreach my $tryserver (keys(%servers)) {
4114: unless (&reply('domroleput:'.$dom.':'.
4115: $domrolebuffer{$dom},$tryserver) eq 'ok') {
4116: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
4117: }
1.662 raeburn 4118: }
4119: }
1.186 www 4120: $dumpcount++;
1.157 www 4121: }
4122:
4123: sub courselog {
4124: my $what=shift;
1.158 www 4125: $what=time.':'.$what;
1.620 albertel 4126: unless ($env{'request.course.id'}) { return ''; }
4127: $coursedombuf{$env{'request.course.id'}}=
4128: $env{'course.'.$env{'request.course.id'}.'.domain'};
4129: $coursenumbuf{$env{'request.course.id'}}=
4130: $env{'course.'.$env{'request.course.id'}.'.num'};
4131: $coursehombuf{$env{'request.course.id'}}=
4132: $env{'course.'.$env{'request.course.id'}.'.home'};
4133: $coursedescrbuf{$env{'request.course.id'}}=
4134: $env{'course.'.$env{'request.course.id'}.'.description'};
4135: $courseinstcodebuf{$env{'request.course.id'}}=
4136: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
4137: $courseownerbuf{$env{'request.course.id'}}=
4138: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 4139: $coursetypebuf{$env{'request.course.id'}}=
4140: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 4141: if (defined $courselogs{$env{'request.course.id'}}) {
4142: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 4143: } else {
1.620 albertel 4144: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 4145: }
1.620 albertel 4146: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 4147: &flushcourselogs();
4148: }
1.158 www 4149: }
4150:
4151: sub courseacclog {
4152: my $fnsymb=shift;
1.620 albertel 4153: unless ($env{'request.course.id'}) { return ''; }
4154: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144 www 4155: if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187 www 4156: $what.=':POST';
1.583 matthew 4157: # FIXME: Probably ought to escape things....
1.800 albertel 4158: foreach my $key (keys(%env)) {
4159: if ($key=~/^form\.(.*)/) {
1.975 raeburn 4160: my $formitem = $1;
4161: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
4162: $what.=':'.$formitem.'='.$env{$key};
4163: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
4164: $what.=':'.$formitem.'='.$env{$key};
4165: }
1.158 www 4166: }
1.191 harris41 4167: }
1.583 matthew 4168: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
4169: # FIXME: We should not be depending on a form parameter that someone
4170: # editing lonsearchcat.pm might change in the future.
1.620 albertel 4171: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 4172: $what.= ':POST';
4173: # FIXME: Probably ought to escape things....
4174: foreach my $element ('courseexp','crsfulltext','crsrelated',
4175: 'crsdiscuss') {
1.620 albertel 4176: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 4177: }
4178: }
1.158 www 4179: }
4180: &courselog($what);
1.149 www 4181: }
4182:
1.185 www 4183: sub countacc {
4184: my $url=&declutter(shift);
1.458 matthew 4185: return if (! defined($url) || $url eq '');
1.620 albertel 4186: unless ($env{'request.course.id'}) { return ''; }
1.1158 www 4187: #
4188: # Mark that this url was used in this course
4189: #
1.620 albertel 4190: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158 www 4191: #
4192: # Increase the access count for this resource in this child process
4193: #
1.281 www 4194: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 4195: $accesshash{$key}++;
1.185 www 4196: }
1.349 www 4197:
1.361 www 4198: sub linklog {
4199: my ($from,$to)=@_;
4200: $from=&declutter($from);
4201: $to=&declutter($to);
4202: $accesshash{$from.'___'.$to.'___comefrom'}=1;
4203: $accesshash{$to.'___'.$from.'___goto'}=1;
4204: }
1.1160 www 4205:
4206: sub statslog {
4207: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
4208: if ($users<2) { return; }
4209: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
4210: 'course' => $env{'request.course.id'},
4211: 'sections' => '"all"',
4212: 'num_students' => $users,
4213: 'part' => $part,
4214: 'symb' => $symb,
4215: 'mean_tries' => $av_attempts,
4216: 'deg_of_diff' => $degdiff});
4217: foreach my $key (keys(%dynstore)) {
4218: $accesshash{$key}=$dynstore{$key};
4219: }
4220: }
1.361 www 4221:
1.349 www 4222: sub userrolelog {
4223: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169 droeschl 4224: if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350 www 4225: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
4226: $userrolehash
4227: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 4228: =$tend.':'.$tstart;
1.662 raeburn 4229: }
1.1169 droeschl 4230: if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898 albertel 4231: $userrolehash
4232: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
4233: =$tend.':'.$tstart;
4234: }
1.1169 droeschl 4235: if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
1.662 raeburn 4236: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
4237: $domainrolehash
4238: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
4239: = $tend.':'.$tstart;
4240: }
1.351 www 4241: }
4242:
1.957 raeburn 4243: sub courserolelog {
4244: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1184 raeburn 4245: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
4246: my $cdom = $1;
4247: my $cnum = $2;
4248: my $sec = $3;
4249: my $namespace = 'rolelog';
4250: my %storehash = (
4251: role => $trole,
4252: start => $tstart,
4253: end => $tend,
4254: selfenroll => $selfenroll,
4255: context => $context,
4256: );
4257: if ($trole eq 'gr') {
4258: $namespace = 'groupslog';
4259: $storehash{'group'} = $sec;
4260: } else {
4261: $storehash{'section'} = $sec;
4262: }
1.1188 raeburn 4263: &write_log('course',$namespace,\%storehash,$delflag,$username,
4264: $domain,$cnum,$cdom);
1.1184 raeburn 4265: if (($trole ne 'st') || ($sec ne '')) {
4266: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957 raeburn 4267: }
4268: }
4269: return;
4270: }
4271:
1.1184 raeburn 4272: sub domainrolelog {
4273: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4274: if ($area =~ m{^/($match_domain)/$}) {
4275: my $cdom = $1;
4276: my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
4277: my $namespace = 'rolelog';
4278: my %storehash = (
4279: role => $trole,
4280: start => $tstart,
4281: end => $tend,
4282: context => $context,
4283: );
1.1188 raeburn 4284: &write_log('domain',$namespace,\%storehash,$delflag,$username,
4285: $domain,$domconfiguser,$cdom);
1.1184 raeburn 4286: }
4287: return;
4288:
4289: }
4290:
4291: sub coauthorrolelog {
4292: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4293: if ($area =~ m{^/($match_domain)/($match_username)$}) {
4294: my $audom = $1;
4295: my $auname = $2;
4296: my $namespace = 'rolelog';
4297: my %storehash = (
4298: role => $trole,
4299: start => $tstart,
4300: end => $tend,
4301: context => $context,
4302: );
1.1188 raeburn 4303: &write_log('author',$namespace,\%storehash,$delflag,$username,
4304: $domain,$auname,$audom);
1.1184 raeburn 4305: }
4306: return;
4307: }
4308:
1.351 www 4309: sub get_course_adv_roles {
1.948 raeburn 4310: my ($cid,$codes) = @_;
1.620 albertel 4311: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 4312: my %coursehash=&coursedescription($cid);
1.988 raeburn 4313: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 4314: my %nothide=();
1.800 albertel 4315: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 4316: if ($user !~ /:/) {
4317: $nothide{join(':',split(/[\@]/,$user))}=1;
4318: } else {
4319: $nothide{$user}=1;
4320: }
1.470 www 4321: }
1.1219 raeburn 4322: my @possdoms = ($coursehash{'domain'});
4323: if ($coursehash{'checkforpriv'}) {
4324: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
4325: }
1.351 www 4326: my %returnhash=();
4327: my %dumphash=
4328: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
4329: my $now=time;
1.997 raeburn 4330: my %privileged;
1.1000 raeburn 4331: foreach my $entry (keys(%dumphash)) {
1.800 albertel 4332: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 4333: if (($tstart) && ($tstart<0)) { next; }
4334: if (($tend) && ($tend<$now)) { next; }
4335: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 4336: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 4337: if ($username eq '' || $domain eq '') { next; }
1.1219 raeburn 4338: if ((&privileged($username,$domain,\@possdoms)) &&
1.997 raeburn 4339: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 4340: if ($role eq 'cr') { next; }
1.948 raeburn 4341: if ($codes) {
4342: if ($section) { $role .= ':'.$section; }
4343: if ($returnhash{$role}) {
4344: $returnhash{$role}.=','.$username.':'.$domain;
4345: } else {
4346: $returnhash{$role}=$username.':'.$domain;
4347: }
1.351 www 4348: } else {
1.988 raeburn 4349: my $key=&plaintext($role,$crstype);
1.973 bisitz 4350: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 4351: if ($returnhash{$key}) {
4352: $returnhash{$key}.=','.$username.':'.$domain;
4353: } else {
4354: $returnhash{$key}=$username.':'.$domain;
4355: }
1.351 www 4356: }
1.948 raeburn 4357: }
1.400 www 4358: return %returnhash;
4359: }
4360:
4361: sub get_my_roles {
1.937 raeburn 4362: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 4363: unless (defined($uname)) { $uname=$env{'user.name'}; }
4364: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 4365: my (%dumphash,%nothide);
1.1086 raeburn 4366: if ($context eq 'userroles') {
1.1166 raeburn 4367: %dumphash = &dump('roles',$udom,$uname);
1.858 raeburn 4368: } else {
1.1219 raeburn 4369: %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 4370: if ($hidepriv) {
4371: my %coursehash=&coursedescription($udom.'_'.$uname);
4372: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
4373: if ($user !~ /:/) {
4374: $nothide{join(':',split(/[\@]/,$user))} = 1;
4375: } else {
4376: $nothide{$user} = 1;
4377: }
4378: }
4379: }
1.858 raeburn 4380: }
1.400 www 4381: my %returnhash=();
4382: my $now=time;
1.999 raeburn 4383: my %privileged;
1.800 albertel 4384: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 4385: my ($role,$tend,$tstart);
4386: if ($context eq 'userroles') {
1.1149 raeburn 4387: next if ($entry =~ /^rolesdef/);
1.867 raeburn 4388: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
4389: } else {
4390: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
4391: }
1.400 www 4392: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 4393: my $status = 'active';
1.939 raeburn 4394: if (($tend) && ($tend<=$now)) {
1.832 raeburn 4395: $status = 'previous';
4396: }
4397: if (($tstart) && ($now<$tstart)) {
4398: $status = 'future';
4399: }
4400: if (ref($types) eq 'ARRAY') {
4401: if (!grep(/^\Q$status\E$/,@{$types})) {
4402: next;
4403: }
4404: } else {
4405: if ($status ne 'active') {
4406: next;
4407: }
4408: }
1.867 raeburn 4409: my ($rolecode,$username,$domain,$section,$area);
4410: if ($context eq 'userroles') {
1.1186 raeburn 4411: ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867 raeburn 4412: (undef,$domain,$username,$section) = split(/\//,$area);
4413: } else {
4414: ($role,$username,$domain,$section) = split(/\:/,$entry);
4415: }
1.832 raeburn 4416: if (ref($roledoms) eq 'ARRAY') {
4417: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
4418: next;
4419: }
4420: }
4421: if (ref($roles) eq 'ARRAY') {
4422: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 4423: if ($role =~ /^cr\//) {
4424: if (!grep(/^cr$/,@{$roles})) {
4425: next;
4426: }
1.1104 raeburn 4427: } elsif ($role =~ /^gr\//) {
4428: if (!grep(/^gr$/,@{$roles})) {
4429: next;
4430: }
1.922 raeburn 4431: } else {
4432: next;
4433: }
1.832 raeburn 4434: }
1.867 raeburn 4435: }
1.937 raeburn 4436: if ($hidepriv) {
1.1219 raeburn 4437: my @privroles = ('dc','su');
1.999 raeburn 4438: if ($context eq 'userroles') {
1.1219 raeburn 4439: next if (grep(/^\Q$role\E$/,@privroles));
1.999 raeburn 4440: } else {
1.1219 raeburn 4441: my $possdoms = [$domain];
4442: if (ref($roledoms) eq 'ARRAY') {
4443: push(@{$possdoms},@{$roledoms});
1.999 raeburn 4444: }
1.1219 raeburn 4445: if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999 raeburn 4446: if (!$nothide{$username.':'.$domain}) {
4447: next;
4448: }
4449: }
1.937 raeburn 4450: }
4451: }
1.933 raeburn 4452: if ($withsec) {
4453: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
4454: $tstart.':'.$tend;
4455: } else {
4456: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
4457: }
1.832 raeburn 4458: }
1.373 www 4459: return %returnhash;
1.399 www 4460: }
4461:
4462: # ----------------------------------------------------- Frontpage Announcements
4463: #
4464: #
4465:
4466: sub postannounce {
4467: my ($server,$text)=@_;
1.844 albertel 4468: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 4469: unless ($text=~/\w/) { $text=''; }
4470: return &reply('setannounce:'.&escape($text),$server);
4471: }
4472:
4473: sub getannounce {
1.448 albertel 4474:
4475: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 4476: my $announcement='';
1.800 albertel 4477: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 4478: close($fh);
1.399 www 4479: if ($announcement=~/\w/) {
4480: return
4481: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 4482: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 4483: } else {
4484: return '';
4485: }
4486: } else {
4487: return '';
4488: }
1.351 www 4489: }
1.353 www 4490:
4491: # ---------------------------------------------------------- Course ID routines
4492: # Deal with domain's nohist_courseid.db files
4493: #
4494:
4495: sub courseidput {
1.921 raeburn 4496: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 4497: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 4498: my $outcome;
4499: if ($caller eq 'timeonly') {
4500: my $cids = '';
4501: foreach my $item (keys(%$storehash)) {
4502: $cids.=&escape($item).'&';
4503: }
4504: $cids=~s/\&$//;
4505: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
4506: $coursehome);
4507: } else {
4508: my $items = '';
4509: foreach my $item (keys(%$storehash)) {
4510: $items.= &escape($item).'='.
4511: &freeze_escape($$storehash{$item}).'&';
4512: }
4513: $items=~s/\&$//;
4514: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
4515: $coursehome);
1.918 raeburn 4516: }
4517: if ($outcome eq 'unknown_cmd') {
4518: my $what;
4519: foreach my $cid (keys(%$storehash)) {
4520: $what .= &escape($cid).'=';
1.921 raeburn 4521: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 4522: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 4523: }
4524: $what =~ s/\:$/&/;
4525: }
4526: $what =~ s/\&$//;
4527: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
4528: } else {
4529: return $outcome;
4530: }
1.353 www 4531: }
4532:
4533: sub courseiddump {
1.921 raeburn 4534: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 4535: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 4536: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1247 raeburn 4537: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1287 raeburn 4538: $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918 raeburn 4539: my $as_hash = 1;
4540: my %returnhash;
4541: if (!$domfilter) { $domfilter=''; }
1.845 albertel 4542: my %libserv = &all_library();
4543: foreach my $tryserver (keys(%libserv)) {
4544: if ( ( $hostidflag == 1
4545: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
4546: || (!defined($hostidflag)) ) {
4547:
1.918 raeburn 4548: if (($domfilter eq '') ||
4549: (&host_domain($tryserver) eq $domfilter)) {
1.1180 droeschl 4550: my $rep;
4551: if (grep { $_ eq $tryserver } current_machine_ids()) {
4552: $rep = LONCAPA::Lond::dump_course_id_handler(
4553: join(":", (&host_domain($tryserver), $sincefilter,
4554: &escape($descfilter), &escape($instcodefilter),
4555: &escape($ownerfilter), &escape($coursefilter),
4556: &escape($typefilter), &escape($regexp_ok),
4557: $as_hash, &escape($selfenrollonly),
4558: &escape($catfilter), $showhidden, $caller,
4559: &escape($cloner), &escape($cc_clone), $cloneonly,
4560: &escape($createdbefore), &escape($createdafter),
1.1287 raeburn 4561: &escape($creationcontext),$domcloner,$hasuniquecode,
4562: $reqcrsdom,&escape($reqinstcode))));
1.1180 droeschl 4563: } else {
4564: $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
4565: $sincefilter.':'.&escape($descfilter).':'.
4566: &escape($instcodefilter).':'.&escape($ownerfilter).
4567: ':'.&escape($coursefilter).':'.&escape($typefilter).
4568: ':'.&escape($regexp_ok).':'.$as_hash.':'.
4569: &escape($selfenrollonly).':'.&escape($catfilter).':'.
4570: $showhidden.':'.$caller.':'.&escape($cloner).':'.
4571: &escape($cc_clone).':'.$cloneonly.':'.
4572: &escape($createdbefore).':'.&escape($createdafter).':'.
1.1287 raeburn 4573: &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
4574: ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1180 droeschl 4575: }
4576:
1.918 raeburn 4577: my @pairs=split(/\&/,$rep);
4578: foreach my $item (@pairs) {
4579: my ($key,$value)=split(/\=/,$item,2);
4580: $key = &unescape($key);
4581: next if ($key =~ /^error: 2 /);
4582: my $result = &thaw_unescape($value);
4583: if (ref($result) eq 'HASH') {
4584: $returnhash{$key}=$result;
4585: } else {
1.921 raeburn 4586: my @responses = split(/:/,$value);
4587: my @items = ('description','inst_code','owner','type');
1.918 raeburn 4588: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 4589: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 4590: }
1.1008 raeburn 4591: }
1.353 www 4592: }
4593: }
4594: }
4595: }
4596: return %returnhash;
4597: }
4598:
1.1055 raeburn 4599: sub courselastaccess {
4600: my ($cdom,$cnum,$hostidref) = @_;
4601: my %returnhash;
4602: if ($cdom && $cnum) {
4603: my $chome = &homeserver($cnum,$cdom);
4604: if ($chome ne 'no_host') {
4605: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
4606: &extract_lastaccess(\%returnhash,$rep);
4607: }
4608: } else {
4609: if (!$cdom) { $cdom=''; }
4610: my %libserv = &all_library();
4611: foreach my $tryserver (keys(%libserv)) {
4612: if (ref($hostidref) eq 'ARRAY') {
4613: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
4614: }
4615: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
4616: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
4617: &extract_lastaccess(\%returnhash,$rep);
4618: }
4619: }
4620: }
4621: return %returnhash;
4622: }
4623:
4624: sub extract_lastaccess {
4625: my ($returnhash,$rep) = @_;
4626: if (ref($returnhash) eq 'HASH') {
4627: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
4628: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
4629: $rep eq '') {
4630: my @pairs=split(/\&/,$rep);
4631: foreach my $item (@pairs) {
4632: my ($key,$value)=split(/\=/,$item,2);
4633: $key = &unescape($key);
4634: next if ($key =~ /^error: 2 /);
4635: $returnhash->{$key} = &thaw_unescape($value);
4636: }
4637: }
4638: }
4639: return;
4640: }
4641:
1.658 raeburn 4642: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 4643:
4644: sub dcmailput {
1.685 raeburn 4645: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 4646: my $status = &Apache::lonnet::critical(
1.740 www 4647: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
4648: &escape($message),$server);
1.662 raeburn 4649: return $status;
4650: }
4651:
1.658 raeburn 4652: sub dcmaildump {
4653: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 4654: my %returnhash=();
1.846 albertel 4655:
4656: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 4657: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
4658: &escape($enddate).':';
4659: my @esc_senders=map { &escape($_)} @$senders;
4660: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 4661: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 4662: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 4663: if (($key) && ($value)) {
4664: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 4665: }
4666: }
4667: }
4668: return %returnhash;
4669: }
1.662 raeburn 4670: # ---------------------------------------------------------- Domain roles
4671:
4672: sub get_domain_roles {
4673: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 4674: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 4675: $startdate = '.';
4676: }
1.1018 raeburn 4677: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 4678: $enddate = '.';
4679: }
1.922 raeburn 4680: my $rolelist;
4681: if (ref($roles) eq 'ARRAY') {
1.1219 raeburn 4682: $rolelist = join('&',@{$roles});
1.922 raeburn 4683: }
1.662 raeburn 4684: my %personnel = ();
1.841 albertel 4685:
4686: my %servers = &get_servers($dom,'library');
4687: foreach my $tryserver (keys(%servers)) {
4688: %{$personnel{$tryserver}}=();
4689: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
4690: &escape($startdate).':'.
4691: &escape($enddate).':'.
4692: &escape($rolelist), $tryserver))) {
4693: my ($key,$value) = split(/\=/,$line,2);
4694: if (($key) && ($value)) {
4695: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
4696: }
4697: }
1.662 raeburn 4698: }
4699: return %personnel;
4700: }
1.658 raeburn 4701:
1.1057 www 4702: # ----------------------------------------------------------- Interval timing
1.149 www 4703:
1.1153 www 4704: {
4705: # Caches needed for speedup of navmaps
4706: # We don't want to cache this for very long at all (5 seconds at most)
4707: #
4708: # The user for whom we cache
4709: my $cachedkey='';
4710: # The cached times for this user
4711: my %cachedtimes=();
4712: # When this was last done
1.1282 raeburn 4713: my $cachedtime='';
1.1153 www 4714:
4715: sub load_all_first_access {
1.1308 raeburn 4716: my ($uname,$udom,$ignorecache)=@_;
1.1156 www 4717: if (($cachedkey eq $uname.':'.$udom) &&
1.1308 raeburn 4718: (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
4719: (!$ignorecache)) {
1.1154 raeburn 4720: return;
4721: }
4722: $cachedtime=time;
4723: $cachedkey=$uname.':'.$udom;
4724: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153 www 4725: }
4726:
1.504 albertel 4727: sub get_first_access {
1.1308 raeburn 4728: my ($type,$argsymb,$argmap,$ignorecache)=@_;
1.790 albertel 4729: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4730: if ($argsymb) { $symb=$argsymb; }
4731: my ($map,$id,$res)=&decode_symb($symb);
1.1162 raeburn 4732: if ($argmap) { $map = $argmap; }
1.926 albertel 4733: if ($type eq 'course') {
4734: $res='course';
4735: } elsif ($type eq 'map') {
1.588 albertel 4736: $res=&symbread($map);
4737: } else {
4738: $res=$symb;
4739: }
1.1308 raeburn 4740: &load_all_first_access($uname,$udom,$ignorecache);
1.1153 www 4741: return $cachedtimes{"$courseid\0$res"};
1.504 albertel 4742: }
4743:
4744: sub set_first_access {
1.1162 raeburn 4745: my ($type,$interval)=@_;
1.790 albertel 4746: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4747: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 4748: if ($type eq 'course') {
4749: $res='course';
4750: } elsif ($type eq 'map') {
1.588 albertel 4751: $res=&symbread($map);
4752: } else {
4753: $res=$symb;
4754: }
1.1153 www 4755: $cachedkey='';
1.1162 raeburn 4756: my $firstaccess=&get_first_access($type,$symb,$map);
1.505 albertel 4757: if (!$firstaccess) {
1.1162 raeburn 4758: my $start = time;
4759: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
4760: $udom,$uname);
4761: if ($putres eq 'ok') {
4762: &put('timerinterval',{"$courseid\0$res"=>$interval},
4763: $udom,$uname);
4764: &appenv(
4765: {
4766: 'course.'.$courseid.'.firstaccess.'.$res => $start,
4767: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
4768: }
4769: );
4770: }
4771: return $putres;
1.505 albertel 4772: }
4773: return 'already_set';
1.504 albertel 4774: }
1.1153 www 4775: }
1.1282 raeburn 4776:
1.110 www 4777: # --------------------------------------------- Set Expire Date for Spreadsheet
4778:
4779: sub expirespread {
4780: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 4781: my $cid=$env{'request.course.id'};
1.110 www 4782: if ($cid) {
4783: my $now=time;
4784: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 4785: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
4786: $env{'course.'.$cid.'.num'}.
1.110 www 4787: ':nohist_expirationdates:'.
4788: &escape($key).'='.$now,
1.620 albertel 4789: $env{'course.'.$cid.'.home'})
1.110 www 4790: }
4791: return 'ok';
1.14 www 4792: }
4793:
1.109 www 4794: # ----------------------------------------------------- Devalidate Spreadsheets
4795:
4796: sub devalidate {
1.325 www 4797: my ($symb,$uname,$udom)=@_;
1.620 albertel 4798: my $cid=$env{'request.course.id'};
1.109 www 4799: if ($cid) {
1.391 matthew 4800: # delete the stored spreadsheets for
4801: # - the student level sheet of this user in course's homespace
4802: # - the assessment level sheet for this resource
4803: # for this user in user's homespace
1.553 albertel 4804: # - current conditional state info
1.325 www 4805: my $key=$uname.':'.$udom.':';
1.109 www 4806: my $status=
1.299 matthew 4807: &del('nohist_calculatedsheets',
1.391 matthew 4808: [$key.'studentcalc:'],
1.620 albertel 4809: $env{'course.'.$cid.'.domain'},
4810: $env{'course.'.$cid.'.num'})
1.133 albertel 4811: .' '.
4812: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 4813: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 4814: unless ($status eq 'ok ok') {
4815: &logthis('Could not devalidate spreadsheet '.
1.325 www 4816: $uname.' at '.$udom.' for '.
1.109 www 4817: $symb.': '.$status);
1.133 albertel 4818: }
1.553 albertel 4819: &delenv('user.state.'.$cid);
1.109 www 4820: }
4821: }
4822:
1.265 albertel 4823: sub get_scalar {
4824: my ($string,$end) = @_;
4825: my $value;
4826: if ($$string =~ s/^([^&]*?)($end)/$2/) {
4827: $value = $1;
4828: } elsif ($$string =~ s/^([^&]*?)&//) {
4829: $value = $1;
4830: }
4831: return &unescape($value);
4832: }
4833:
4834: sub array2str {
4835: my (@array) = @_;
4836: my $result=&arrayref2str(\@array);
4837: $result=~s/^__ARRAY_REF__//;
4838: $result=~s/__END_ARRAY_REF__$//;
4839: return $result;
4840: }
4841:
1.204 albertel 4842: sub arrayref2str {
4843: my ($arrayref) = @_;
1.265 albertel 4844: my $result='__ARRAY_REF__';
1.204 albertel 4845: foreach my $elem (@$arrayref) {
1.265 albertel 4846: if(ref($elem) eq 'ARRAY') {
4847: $result.=&arrayref2str($elem).'&';
4848: } elsif(ref($elem) eq 'HASH') {
4849: $result.=&hashref2str($elem).'&';
4850: } elsif(ref($elem)) {
4851: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 4852: } else {
4853: $result.=&escape($elem).'&';
4854: }
4855: }
4856: $result=~s/\&$//;
1.265 albertel 4857: $result .= '__END_ARRAY_REF__';
1.204 albertel 4858: return $result;
4859: }
4860:
1.168 albertel 4861: sub hash2str {
1.204 albertel 4862: my (%hash) = @_;
4863: my $result=&hashref2str(\%hash);
1.265 albertel 4864: $result=~s/^__HASH_REF__//;
4865: $result=~s/__END_HASH_REF__$//;
1.204 albertel 4866: return $result;
4867: }
4868:
4869: sub hashref2str {
4870: my ($hashref)=@_;
1.265 albertel 4871: my $result='__HASH_REF__';
1.800 albertel 4872: foreach my $key (sort(keys(%$hashref))) {
4873: if (ref($key) eq 'ARRAY') {
4874: $result.=&arrayref2str($key).'=';
4875: } elsif (ref($key) eq 'HASH') {
4876: $result.=&hashref2str($key).'=';
4877: } elsif (ref($key)) {
1.265 albertel 4878: $result.='=';
1.800 albertel 4879: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 4880: } else {
1.1132 raeburn 4881: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 4882: }
4883:
1.800 albertel 4884: if(ref($hashref->{$key}) eq 'ARRAY') {
4885: $result.=&arrayref2str($hashref->{$key}).'&';
4886: } elsif(ref($hashref->{$key}) eq 'HASH') {
4887: $result.=&hashref2str($hashref->{$key}).'&';
4888: } elsif(ref($hashref->{$key})) {
1.265 albertel 4889: $result.='&';
1.800 albertel 4890: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 4891: } else {
1.800 albertel 4892: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 4893: }
4894: }
1.168 albertel 4895: $result=~s/\&$//;
1.265 albertel 4896: $result .= '__END_HASH_REF__';
1.168 albertel 4897: return $result;
4898: }
4899:
4900: sub str2hash {
1.265 albertel 4901: my ($string)=@_;
4902: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
4903: return %$hash;
4904: }
4905:
4906: sub str2hashref {
1.168 albertel 4907: my ($string) = @_;
1.265 albertel 4908:
4909: my %hash;
4910:
4911: if($string !~ /^__HASH_REF__/) {
4912: if (! ($string eq '' || !defined($string))) {
4913: $hash{'error'}='Not hash reference';
4914: }
4915: return (\%hash, $string);
4916: }
4917:
4918: $string =~ s/^__HASH_REF__//;
4919:
4920: while($string !~ /^__END_HASH_REF__/) {
4921: #key
4922: my $key='';
4923: if($string =~ /^__HASH_REF__/) {
4924: ($key, $string)=&str2hashref($string);
4925: if(defined($key->{'error'})) {
4926: $hash{'error'}='Bad data';
4927: return (\%hash, $string);
4928: }
4929: } elsif($string =~ /^__ARRAY_REF__/) {
4930: ($key, $string)=&str2arrayref($string);
4931: if($key->[0] eq 'Array reference error') {
4932: $hash{'error'}='Bad data';
4933: return (\%hash, $string);
4934: }
4935: } else {
4936: $string =~ s/^(.*?)=//;
1.267 albertel 4937: $key=&unescape($1);
1.265 albertel 4938: }
4939: $string =~ s/^=//;
4940:
4941: #value
4942: my $value='';
4943: if($string =~ /^__HASH_REF__/) {
4944: ($value, $string)=&str2hashref($string);
4945: if(defined($value->{'error'})) {
4946: $hash{'error'}='Bad data';
4947: return (\%hash, $string);
4948: }
4949: } elsif($string =~ /^__ARRAY_REF__/) {
4950: ($value, $string)=&str2arrayref($string);
4951: if($value->[0] eq 'Array reference error') {
4952: $hash{'error'}='Bad data';
4953: return (\%hash, $string);
4954: }
4955: } else {
4956: $value=&get_scalar(\$string,'__END_HASH_REF__');
4957: }
4958: $string =~ s/^&//;
4959:
4960: $hash{$key}=$value;
1.204 albertel 4961: }
1.265 albertel 4962:
4963: $string =~ s/^__END_HASH_REF__//;
4964:
4965: return (\%hash, $string);
1.204 albertel 4966: }
4967:
4968: sub str2array {
1.265 albertel 4969: my ($string)=@_;
4970: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
4971: return @$array;
4972: }
4973:
4974: sub str2arrayref {
1.204 albertel 4975: my ($string) = @_;
1.265 albertel 4976: my @array;
4977:
4978: if($string !~ /^__ARRAY_REF__/) {
4979: if (! ($string eq '' || !defined($string))) {
4980: $array[0]='Array reference error';
4981: }
4982: return (\@array, $string);
4983: }
4984:
4985: $string =~ s/^__ARRAY_REF__//;
4986:
4987: while($string !~ /^__END_ARRAY_REF__/) {
4988: my $value='';
4989: if($string =~ /^__HASH_REF__/) {
4990: ($value, $string)=&str2hashref($string);
4991: if(defined($value->{'error'})) {
4992: $array[0] ='Array reference error';
4993: return (\@array, $string);
4994: }
4995: } elsif($string =~ /^__ARRAY_REF__/) {
4996: ($value, $string)=&str2arrayref($string);
4997: if($value->[0] eq 'Array reference error') {
4998: $array[0] ='Array reference error';
4999: return (\@array, $string);
5000: }
5001: } else {
5002: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
5003: }
5004: $string =~ s/^&//;
5005:
5006: push(@array, $value);
1.191 harris41 5007: }
1.265 albertel 5008:
5009: $string =~ s/^__END_ARRAY_REF__//;
5010:
5011: return (\@array, $string);
1.168 albertel 5012: }
5013:
1.167 albertel 5014: # -------------------------------------------------------------------Temp Store
5015:
1.168 albertel 5016: sub tmpreset {
5017: my ($symb,$namespace,$domain,$stuname) = @_;
5018: if (!$symb) {
5019: $symb=&symbread();
1.620 albertel 5020: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 5021: }
5022: $symb=escape($symb);
5023:
1.620 albertel 5024: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 5025: $namespace=~s/\//\_/g;
5026: $namespace=~s/\W//g;
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.1117 foxr 5033: my $path=LONCAPA::tempdir();
1.168 albertel 5034: my %hash;
5035: if (tie(%hash,'GDBM_File',
5036: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 5037: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 5038: foreach my $key (keys(%hash)) {
1.180 albertel 5039: if ($key=~ /:$symb/) {
1.168 albertel 5040: delete($hash{$key});
5041: }
5042: }
5043: }
5044: }
5045:
1.167 albertel 5046: sub tmpstore {
1.168 albertel 5047: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
5048:
5049: if (!$symb) {
5050: $symb=&symbread();
1.620 albertel 5051: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 5052: }
5053: $symb=escape($symb);
5054:
5055: if (!$namespace) {
5056: # I don't think we would ever want to store this for a course.
5057: # it seems this will only be used if we don't have a course.
1.620 albertel 5058: #$namespace=$env{'request.course.id'};
1.168 albertel 5059: #if (!$namespace) {
1.620 albertel 5060: $namespace=$env{'request.state'};
1.168 albertel 5061: #}
5062: }
5063: $namespace=~s/\//\_/g;
5064: $namespace=~s/\W//g;
1.620 albertel 5065: if (!$domain) { $domain=$env{'user.domain'}; }
5066: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 5067: if ($domain eq 'public' && $stuname eq 'public') {
5068: $stuname=$ENV{'REMOTE_ADDR'};
5069: }
1.168 albertel 5070: my $now=time;
5071: my %hash;
1.1117 foxr 5072: my $path=LONCAPA::tempdir();
1.168 albertel 5073: if (tie(%hash,'GDBM_File',
5074: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 5075: &GDBM_WRCREAT(),0640)) {
1.168 albertel 5076: $hash{"version:$symb"}++;
5077: my $version=$hash{"version:$symb"};
5078: my $allkeys='';
5079: foreach my $key (keys(%$storehash)) {
5080: $allkeys.=$key.':';
1.591 albertel 5081: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 5082: }
5083: $hash{"$version:$symb:timestamp"}=$now;
5084: $allkeys.='timestamp';
5085: $hash{"$version:keys:$symb"}=$allkeys;
5086: if (untie(%hash)) {
5087: return 'ok';
5088: } else {
5089: return "error:$!";
5090: }
5091: } else {
5092: return "error:$!";
5093: }
5094: }
1.167 albertel 5095:
1.168 albertel 5096: # -----------------------------------------------------------------Temp Restore
1.167 albertel 5097:
1.168 albertel 5098: sub tmprestore {
5099: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 5100:
1.168 albertel 5101: if (!$symb) {
5102: $symb=&symbread();
1.620 albertel 5103: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 5104: }
5105: $symb=escape($symb);
5106:
1.620 albertel 5107: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 5108:
1.620 albertel 5109: if (!$domain) { $domain=$env{'user.domain'}; }
5110: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 5111: if ($domain eq 'public' && $stuname eq 'public') {
5112: $stuname=$ENV{'REMOTE_ADDR'};
5113: }
1.168 albertel 5114: my %returnhash;
5115: $namespace=~s/\//\_/g;
5116: $namespace=~s/\W//g;
5117: my %hash;
1.1117 foxr 5118: my $path=LONCAPA::tempdir();
1.168 albertel 5119: if (tie(%hash,'GDBM_File',
5120: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 5121: &GDBM_READER(),0640)) {
1.168 albertel 5122: my $version=$hash{"version:$symb"};
5123: $returnhash{'version'}=$version;
5124: my $scope;
5125: for ($scope=1;$scope<=$version;$scope++) {
5126: my $vkeys=$hash{"$scope:keys:$symb"};
5127: my @keys=split(/:/,$vkeys);
5128: my $key;
5129: $returnhash{"$scope:keys"}=$vkeys;
5130: foreach $key (@keys) {
1.591 albertel 5131: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
5132: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 5133: }
5134: }
1.168 albertel 5135: if (!(untie(%hash))) {
5136: return "error:$!";
5137: }
5138: } else {
5139: return "error:$!";
5140: }
5141: return %returnhash;
1.167 albertel 5142: }
5143:
1.9 www 5144: # ----------------------------------------------------------------------- Store
5145:
5146: sub store {
1.1269 raeburn 5147: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 5148: my $home='';
5149:
1.168 albertel 5150: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 5151:
1.213 www 5152: $symb=&symbclean($symb);
1.122 albertel 5153: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 5154:
1.620 albertel 5155: if (!$domain) { $domain=$env{'user.domain'}; }
5156: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 5157:
5158: &devalidate($symb,$stuname,$domain);
1.109 www 5159:
5160: $symb=escape($symb);
1.187 www 5161: if (!$namespace) {
1.620 albertel 5162: unless ($namespace=$env{'request.course.id'}) {
1.187 www 5163: return '';
5164: }
5165: }
1.620 albertel 5166: if (!$home) { $home=$env{'user.home'}; }
1.447 www 5167:
5168: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
5169: $$storehash{'host'}=$perlvar{'lonHostID'};
5170:
1.12 www 5171: my $namevalue='';
1.800 albertel 5172: foreach my $key (keys(%$storehash)) {
5173: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 5174: }
1.12 www 5175: $namevalue=~s/\&$//;
1.187 www 5176: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1269 raeburn 5177: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9 www 5178: }
5179:
1.47 www 5180: # -------------------------------------------------------------- Critical Store
5181:
5182: sub cstore {
1.1269 raeburn 5183: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 5184: my $home='';
5185:
1.168 albertel 5186: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 5187:
1.213 www 5188: $symb=&symbclean($symb);
1.122 albertel 5189: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 5190:
1.620 albertel 5191: if (!$domain) { $domain=$env{'user.domain'}; }
5192: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 5193:
5194: &devalidate($symb,$stuname,$domain);
1.109 www 5195:
5196: $symb=escape($symb);
1.187 www 5197: if (!$namespace) {
1.620 albertel 5198: unless ($namespace=$env{'request.course.id'}) {
1.187 www 5199: return '';
5200: }
5201: }
1.620 albertel 5202: if (!$home) { $home=$env{'user.home'}; }
1.447 www 5203:
5204: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
5205: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 5206:
1.47 www 5207: my $namevalue='';
1.800 albertel 5208: foreach my $key (keys(%$storehash)) {
5209: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 5210: }
1.47 www 5211: $namevalue=~s/\&$//;
1.187 www 5212: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 5213: return critical
1.1269 raeburn 5214: ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47 www 5215: }
5216:
1.9 www 5217: # --------------------------------------------------------------------- Restore
5218:
5219: sub restore {
1.124 www 5220: my ($symb,$namespace,$domain,$stuname) = @_;
5221: my $home='';
5222:
1.168 albertel 5223: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 5224:
1.122 albertel 5225: if (!$symb) {
1.1224 raeburn 5226: return if ($namespace eq 'courserequests');
5227: unless ($symb=escape(&symbread())) { return ''; }
1.122 albertel 5228: } else {
1.1224 raeburn 5229: unless ($namespace eq 'courserequests') {
5230: $symb=&escape(&symbclean($symb));
5231: }
1.122 albertel 5232: }
1.188 www 5233: if (!$namespace) {
1.620 albertel 5234: unless ($namespace=$env{'request.course.id'}) {
1.188 www 5235: return '';
5236: }
5237: }
1.620 albertel 5238: if (!$domain) { $domain=$env{'user.domain'}; }
5239: if (!$stuname) { $stuname=$env{'user.name'}; }
5240: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 5241: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
5242:
1.12 www 5243: my %returnhash=();
1.800 albertel 5244: foreach my $line (split(/\&/,$answer)) {
5245: my ($name,$value)=split(/\=/,$line);
1.591 albertel 5246: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 5247: }
1.75 www 5248: my $version;
5249: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 5250: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
5251: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 5252: }
1.75 www 5253: }
1.13 www 5254: return %returnhash;
1.34 www 5255: }
5256:
5257: # ---------------------------------------------------------- Course Description
1.1118 foxr 5258: #
5259: #
1.34 www 5260:
5261: sub coursedescription {
1.731 albertel 5262: my ($courseid,$args)=@_;
1.34 www 5263: $courseid=~s/^\///;
1.49 www 5264: $courseid=~s/\_/\//g;
1.34 www 5265: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 5266: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 5267: my $normalid=$cdomain.'_'.$cnum;
5268: # need to always cache even if we get errors otherwise we keep
5269: # trying and trying and trying to get the course description.
5270: my %envhash=();
5271: my %returnhash=();
1.731 albertel 5272:
5273: my $expiretime=600;
5274: if ($env{'request.course.id'} eq $normalid) {
5275: $expiretime=120;
5276: }
5277:
5278: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
5279: if (!$args->{'freshen_cache'}
5280: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
5281: foreach my $key (keys(%env)) {
5282: next if ($key !~ /^\Q$prefix\E(.*)/);
5283: my ($setting) = $1;
5284: $returnhash{$setting} = $env{$key};
5285: }
5286: return %returnhash;
5287: }
5288:
1.1118 foxr 5289: # get the data again
5290:
1.731 albertel 5291: if (!$args->{'one_time'}) {
5292: $envhash{'course.'.$normalid.'.last_cache'}=time;
5293: }
1.811 albertel 5294:
1.34 www 5295: if ($chome ne 'no_host') {
1.302 albertel 5296: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 5297: if (!exists($returnhash{'con_lost'})) {
1.1118 foxr 5298: my $username = $env{'user.name'}; # Defult username
5299: if(defined $args->{'user'}) {
5300: $username = $args->{'user'};
5301: }
1.129 albertel 5302: $returnhash{'home'}= $chome;
5303: $returnhash{'domain'} = $cdomain;
5304: $returnhash{'num'} = $cnum;
1.741 raeburn 5305: if (!defined($returnhash{'type'})) {
5306: $returnhash{'type'} = 'Course';
5307: }
1.130 albertel 5308: while (my ($name,$value) = each %returnhash) {
1.53 www 5309: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 5310: }
1.270 www 5311: $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117 foxr 5312: $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118 foxr 5313: $username.'_'.$cdomain.'_'.$cnum;
1.60 www 5314: $envhash{'course.'.$normalid.'.home'}=$chome;
5315: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
5316: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 5317: }
5318: }
1.731 albertel 5319: if (!$args->{'one_time'}) {
1.949 raeburn 5320: &appenv(\%envhash);
1.731 albertel 5321: }
1.302 albertel 5322: return %returnhash;
1.461 www 5323: }
5324:
1.1080 raeburn 5325: sub update_released_required {
5326: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
5327: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
5328: $cid = $env{'request.course.id'};
5329: $cdom = $env{'course.'.$cid.'.domain'};
5330: $cnum = $env{'course.'.$cid.'.num'};
5331: $chome = $env{'course.'.$cid.'.home'};
5332: }
5333: if ($needsrelease) {
5334: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
5335: my $needsupdate;
5336: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
5337: $needsupdate = 1;
5338: } else {
5339: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
5340: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
5341: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
5342: $needsupdate = 1;
5343: }
5344: }
5345: if ($needsupdate) {
5346: my %needshash = (
5347: 'internal.releaserequired' => $needsrelease,
5348: );
5349: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
5350: if ($putresult eq 'ok') {
5351: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
5352: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
5353: if (ref($crsinfo{$cid}) eq 'HASH') {
5354: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
5355: &courseidput($cdom,\%crsinfo,$chome,'notime');
5356: }
5357: }
5358: }
5359: }
5360: return;
5361: }
5362:
1.461 www 5363: # -------------------------------------------------See if a user is privileged
5364:
5365: sub privileged {
1.1219 raeburn 5366: my ($username,$domain,$possdomains,$possroles)=@_;
1.1170 droeschl 5367: my $now = time;
1.1219 raeburn 5368: my $roles;
5369: if (ref($possroles) eq 'ARRAY') {
5370: $roles = $possroles;
5371: } else {
5372: $roles = ['dc','su'];
5373: }
5374: if (ref($possdomains) eq 'ARRAY') {
5375: my %privileged = &privileged_by_domain($possdomains,$roles);
5376: foreach my $dom (@{$possdomains}) {
5377: if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
5378: (ref($privileged{$dom}) eq 'HASH')) {
5379: foreach my $role (@{$roles}) {
5380: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5381: if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
5382: my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
5383: return 1 unless (($end && $end < $now) ||
5384: ($start && $start > $now));
5385: }
5386: }
5387: }
5388: }
5389: }
5390: } else {
5391: my %rolesdump = &dump("roles", $domain, $username) or return 0;
5392: my $now = time;
1.1170 droeschl 5393:
1.1275 musolffc 5394: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170 droeschl 5395: my ($trole, $tend, $tstart) = split(/_/, $role);
1.1219 raeburn 5396: if (grep(/^\Q$trole\E$/,@{$roles})) {
1.1170 droeschl 5397: return 1 unless ($tend && $tend < $now)
1.1219 raeburn 5398: or ($tstart && $tstart > $now);
1.1170 droeschl 5399: }
1.1219 raeburn 5400: }
5401: }
5402: return 0;
5403: }
1.1170 droeschl 5404:
1.1219 raeburn 5405: sub privileged_by_domain {
5406: my ($domains,$roles) = @_;
5407: my %privileged = ();
5408: my $cachetime = 60*60*24;
5409: my $now = time;
5410: unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
5411: return %privileged;
5412: }
5413: foreach my $dom (@{$domains}) {
5414: next if (ref($privileged{$dom}) eq 'HASH');
5415: my $needroles;
5416: foreach my $role (@{$roles}) {
5417: my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
5418: if (defined($cached)) {
5419: if (ref($result) eq 'HASH') {
5420: $privileged{$dom}{$role} = $result;
5421: }
5422: } else {
5423: $needroles = 1;
5424: }
5425: }
5426: if ($needroles) {
5427: my %dompersonnel = &get_domain_roles($dom,$roles);
5428: $privileged{$dom} = {};
5429: foreach my $server (keys(%dompersonnel)) {
5430: if (ref($dompersonnel{$server}) eq 'HASH') {
5431: foreach my $item (keys(%{$dompersonnel{$server}})) {
5432: my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
5433: my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
5434: next if ($end && $end < $now);
5435: $privileged{$dom}{$trole}{$uname.':'.$udom} =
5436: $dompersonnel{$server}{$item};
5437: }
5438: }
5439: }
5440: if (ref($privileged{$dom}) eq 'HASH') {
5441: foreach my $role (@{$roles}) {
5442: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5443: &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
5444: } else {
5445: my %hash = ();
5446: &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
5447: }
5448: }
5449: }
5450: }
5451: }
5452: return %privileged;
1.9 www 5453: }
1.1 albertel 5454:
1.103 harris41 5455: # -------------------------------------------------------- Get user privileges
1.11 www 5456:
5457: sub rolesinit {
1.1169 droeschl 5458: my ($domain, $username) = @_;
5459: my %userroles = ('user.login.time' => time);
5460: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
5461:
5462: # firstaccess and timerinterval are related to timed maps/resources.
5463: # also, blocking can be triggered by an activating timer
5464: # it's saved in the user's %env.
5465: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
5466: my %timerinterval = &dump('timerinterval', $domain, $username);
5467: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
5468: %timerintchk, %timerintenv);
5469:
1.1162 raeburn 5470: foreach my $key (keys(%firstaccess)) {
1.1169 droeschl 5471: my ($cid, $rest) = split(/\0/, $key);
1.1162 raeburn 5472: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
5473: }
1.1169 droeschl 5474:
1.1162 raeburn 5475: foreach my $key (keys(%timerinterval)) {
5476: my ($cid,$rest) = split(/\0/,$key);
5477: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
5478: }
1.1169 droeschl 5479:
1.11 www 5480: my %allroles=();
1.1162 raeburn 5481: my %allgroups=();
1.11 www 5482:
1.1274 raeburn 5483: for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169 droeschl 5484: my $role = $rolesdump{$area};
5485: $area =~ s/\_\w\w$//;
5486:
5487: my ($trole, $tend, $tstart, $group_privs);
5488:
5489: if ($role =~ /^cr/) {
5490: # Custom role, defined by a user
5491: # e.g., user.role.cr/msu/smith/mynewrole
5492: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
5493: $trole = $1;
5494: ($tend, $tstart) = split('_', $2);
5495: } else {
5496: $trole = $role;
5497: }
5498: } elsif ($role =~ m|^gr/|) {
5499: # Role of member in a group, defined within a course/community
5500: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
5501: ($trole, $tend, $tstart) = split(/_/, $role);
5502: next if $tstart eq '-1';
5503: ($trole, $group_privs) = split(/\//, $trole);
5504: $group_privs = &unescape($group_privs);
5505: } else {
5506: # Just a normal role, defined in roles.tab
5507: ($trole, $tend, $tstart) = split(/_/,$role);
5508: }
5509:
5510: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
5511: $username);
5512: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
5513:
5514: # role expired or not available yet?
5515: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
5516: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
5517:
5518: next if $area eq '' or $trole eq '';
5519:
5520: my $spec = "$trole.$area";
5521: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
5522:
5523: if ($trole =~ /^cr\//) {
5524: # Custom role, defined by a user
5525: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5526: } elsif ($trole eq 'gr') {
5527: # Role of a member in a group, defined within a course/community
5528: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
5529: next;
5530: } else {
5531: # Normal role, defined in roles.tab
5532: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5533: }
5534:
5535: my $cid = $tdomain.'_'.$trest;
5536: unless ($firstaccchk{$cid}) {
5537: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
5538: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
5539: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
5540: $coursetimerstarts{$cid}{$item};
5541: }
5542: }
5543: $firstaccchk{$cid} = 1;
5544: }
5545: unless ($timerintchk{$cid}) {
5546: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
5547: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
5548: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
5549: $coursetimerintervals{$cid}{$item};
1.1162 raeburn 5550: }
1.12 www 5551: }
1.1169 droeschl 5552: $timerintchk{$cid} = 1;
1.191 harris41 5553: }
1.11 www 5554: }
1.1169 droeschl 5555:
5556: @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
5557: \%allroles, \%allgroups);
5558: $env{'user.adv'} = $userroles{'user.adv'};
5559:
1.1162 raeburn 5560: return (\%userroles,\%firstaccenv,\%timerintenv);
1.11 www 5561: }
5562:
1.567 raeburn 5563: sub set_arearole {
1.1215 raeburn 5564: my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
5565: unless ($nolog) {
1.567 raeburn 5566: # log the associated role with the area
1.1215 raeburn 5567: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
5568: }
1.743 albertel 5569: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 5570: }
5571:
5572: sub custom_roleprivs {
5573: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
5574: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1250 raeburn 5575: my $homsvr = &homeserver($rauthor,$rdomain);
1.838 albertel 5576: if (&hostname($homsvr) ne '') {
1.567 raeburn 5577: my ($rdummy,$roledef)=
5578: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
5579: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
5580: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
5581: if (defined($syspriv)) {
1.1043 raeburn 5582: if ($trest =~ /^$match_community$/) {
5583: $syspriv =~ s/bre\&S//;
5584: }
1.567 raeburn 5585: $$allroles{'cm./'}.=':'.$syspriv;
5586: $$allroles{$spec.'./'}.=':'.$syspriv;
5587: }
5588: if ($tdomain ne '') {
5589: if (defined($dompriv)) {
5590: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
5591: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
5592: }
5593: if (($trest ne '') && (defined($coursepriv))) {
5594: $$allroles{'cm.'.$area}.=':'.$coursepriv;
5595: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
5596: }
5597: }
5598: }
5599: }
5600: }
5601:
1.678 raeburn 5602: sub group_roleprivs {
5603: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
5604: my $access = 1;
5605: my $now = time;
5606: if (($tend!=0) && ($tend<$now)) { $access = 0; }
5607: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
5608: if ($access) {
1.811 albertel 5609: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 5610: $$allgroups{$course}{$group} .=':'.$group_privs;
5611: }
5612: }
1.567 raeburn 5613:
5614: sub standard_roleprivs {
5615: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
5616: if (defined($pr{$trole.':s'})) {
5617: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
5618: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
5619: }
5620: if ($tdomain ne '') {
5621: if (defined($pr{$trole.':d'})) {
5622: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5623: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5624: }
5625: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
5626: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
5627: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
5628: }
5629: }
5630: }
5631:
5632: sub set_userprivs {
1.1064 raeburn 5633: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 5634: my $author=0;
5635: my $adv=0;
1.678 raeburn 5636: my %grouproles = ();
5637: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 5638: my @groupkeys;
1.1000 raeburn 5639: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 5640: push(@groupkeys,$role);
5641: }
5642: if (ref($groups_roles) eq 'HASH') {
5643: foreach my $key (keys(%{$groups_roles})) {
5644: unless (grep(/^\Q$key\E$/,@groupkeys)) {
5645: push(@groupkeys,$key);
5646: }
5647: }
5648: }
5649: if (@groupkeys > 0) {
5650: foreach my $role (@groupkeys) {
5651: my ($trole,$area,$sec,$extendedarea);
5652: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
5653: $trole = $1;
5654: $area = $2;
5655: $sec = $3;
5656: $extendedarea = $area.$sec;
5657: if (exists($$allgroups{$area})) {
5658: foreach my $group (keys(%{$$allgroups{$area}})) {
5659: my $spec = $trole.'.'.$extendedarea;
5660: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 5661: $$allgroups{$area}{$group};
1.1064 raeburn 5662: }
1.678 raeburn 5663: }
5664: }
5665: }
5666: }
5667: }
1.800 albertel 5668: foreach my $group (keys(%grouproles)) {
5669: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 5670: }
1.800 albertel 5671: foreach my $role (keys(%{$allroles})) {
5672: my %thesepriv;
1.941 raeburn 5673: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 5674: foreach my $item (split(/:/,$$allroles{$role})) {
5675: if ($item ne '') {
5676: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 5677: if ($restrictions eq '') {
5678: $thesepriv{$privilege}='F';
5679: } elsif ($thesepriv{$privilege} ne 'F') {
5680: $thesepriv{$privilege}.=$restrictions;
5681: }
5682: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
5683: }
5684: }
5685: my $thesestr='';
1.1104 raeburn 5686: foreach my $priv (sort(keys(%thesepriv))) {
1.800 albertel 5687: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
5688: }
5689: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 5690: }
5691: return ($author,$adv);
5692: }
5693:
1.994 raeburn 5694: sub role_status {
1.1104 raeburn 5695: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 5696: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1250 raeburn 5697: my ($one,$two) = split(m{\./},$rolekey,2);
5698: (undef,undef,$$role) = split(/\./,$one,3);
1.994 raeburn 5699: unless (!defined($$role) || $$role eq '') {
1.1251 raeburn 5700: $$where = '/'.$two;
1.994 raeburn 5701: $$trolecode=$$role.'.'.$$where;
5702: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
5703: $$tstatus='is';
1.1104 raeburn 5704: if ($$tstart && $$tstart>$update) {
1.994 raeburn 5705: $$tstatus='future';
1.1034 raeburn 5706: if ($$tstart<$now) {
5707: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 5708: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 5709: my (%allroles,%allgroups,$group_privs,
5710: %groups_roles,@rolecodes);
1.1002 raeburn 5711: my %userroles = (
5712: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
5713: );
1.1064 raeburn 5714: @rolecodes = ('cm');
1.1002 raeburn 5715: my $spec=$$role.'.'.$$where;
5716: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
5717: if ($$role =~ /^cr\//) {
5718: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 5719: push(@rolecodes,'cr');
1.1002 raeburn 5720: } elsif ($$role eq 'gr') {
1.1064 raeburn 5721: push(@rolecodes,$$role);
1.1002 raeburn 5722: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
5723: $env{'user.name'});
1.1064 raeburn 5724: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 5725: (undef,my $group_privs) = split(/\//,$trole);
5726: $group_privs = &unescape($group_privs);
5727: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 5728: 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 5729: &get_groups_roles($tdomain,$trest,
5730: \%course_roles,\@rolecodes,
5731: \%groups_roles);
1.1002 raeburn 5732: } else {
1.1064 raeburn 5733: push(@rolecodes,$$role);
1.1002 raeburn 5734: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
5735: }
1.1064 raeburn 5736: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
5737: &appenv(\%userroles,\@rolecodes);
1.1002 raeburn 5738: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
5739: }
5740: }
1.1034 raeburn 5741: $$tstatus = 'is';
1.1002 raeburn 5742: }
1.994 raeburn 5743: }
5744: if ($$tend) {
1.1104 raeburn 5745: if ($$tend<$update) {
1.994 raeburn 5746: $$tstatus='expired';
5747: } elsif ($$tend<$now) {
5748: $$tstatus='will_not';
5749: }
5750: }
5751: }
5752: }
5753: }
5754:
1.1104 raeburn 5755: sub get_groups_roles {
5756: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
5757: return unless((ref($cdom_courseroles) eq 'HASH') &&
5758: (ref($rolecodes) eq 'ARRAY') &&
5759: (ref($groups_roles) eq 'HASH'));
5760: if (keys(%{$cdom_courseroles}) > 0) {
5761: my ($cnum) = ($rest =~ /^($match_courseid)/);
5762: if ($cdom ne '' && $cnum ne '') {
5763: foreach my $key (keys(%{$cdom_courseroles})) {
5764: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
5765: my $crsrole = $1;
5766: my $crssec = $2;
5767: if ($crsrole =~ /^cr/) {
5768: unless (grep(/^cr$/,@{$rolecodes})) {
5769: push(@{$rolecodes},'cr');
5770: }
5771: } else {
5772: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
5773: push(@{$rolecodes},$crsrole);
5774: }
5775: }
5776: my $rolekey = "$crsrole./$cdom/$cnum";
5777: if ($crssec ne '') {
5778: $rolekey .= "/$crssec";
5779: }
5780: $rolekey .= './';
5781: $groups_roles->{$rolekey} = $rolecodes;
5782: }
5783: }
5784: }
5785: }
5786: return;
5787: }
5788:
5789: sub delete_env_groupprivs {
5790: my ($where,$courseroles,$possroles) = @_;
5791: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
5792: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
5793: unless (ref($courseroles->{$udom}) eq 'HASH') {
5794: %{$courseroles->{$udom}} =
5795: &get_my_roles('','','userroles',['active'],
5796: $possroles,[$udom],1);
5797: }
5798: if (ref($courseroles->{$udom}) eq 'HASH') {
5799: foreach my $item (keys(%{$courseroles->{$udom}})) {
5800: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
5801: my $area = '/'.$cdom.'/'.$cnum;
5802: my $privkey = "user.priv.$crsrole.$area";
5803: if ($crssec ne '') {
5804: $privkey .= '/'.$crssec;
5805: }
5806: $privkey .= ".$area/$group";
5807: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
5808: }
5809: }
5810: return;
5811: }
5812:
1.994 raeburn 5813: sub check_adhoc_privs {
1.1104 raeburn 5814: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994 raeburn 5815: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1185 raeburn 5816: my $setprivs;
1.994 raeburn 5817: if ($env{$cckey}) {
5818: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104 raeburn 5819: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 5820: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088 raeburn 5821: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185 raeburn 5822: $setprivs = 1;
1.994 raeburn 5823: }
5824: } else {
1.1088 raeburn 5825: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185 raeburn 5826: $setprivs = 1;
1.994 raeburn 5827: }
1.1185 raeburn 5828: return $setprivs;
1.994 raeburn 5829: }
5830:
5831: sub set_adhoc_privileges {
5832: # role can be cc or ca
1.1088 raeburn 5833: my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994 raeburn 5834: my $area = '/'.$dcdom.'/'.$pickedcourse;
5835: my $spec = $role.'.'.$area;
5836: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1215 raeburn 5837: $env{'user.name'},1);
1.994 raeburn 5838: my %ccrole = ();
5839: &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
5840: my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
5841: &appenv(\%userroles,[$role,'cm']);
5842: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088 raeburn 5843: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
5844: &appenv( {'request.role' => $spec,
5845: 'request.role.domain' => $dcdom,
5846: 'request.course.sec' => ''
5847: }
5848: );
5849: my $tadv=0;
5850: if (&allowed('adv') eq 'F') { $tadv=1; }
5851: &appenv({'request.role.adv' => $tadv});
5852: }
1.994 raeburn 5853: }
5854:
1.12 www 5855: # --------------------------------------------------------------- get interface
5856:
5857: sub get {
1.131 albertel 5858: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 5859: my $items='';
1.800 albertel 5860: foreach my $item (@$storearr) {
5861: $items.=&escape($item).'&';
1.191 harris41 5862: }
1.12 www 5863: $items=~s/\&$//;
1.620 albertel 5864: if (!$udomain) { $udomain=$env{'user.domain'}; }
5865: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 5866: my $uhome=&homeserver($uname,$udomain);
5867:
1.133 albertel 5868: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 5869: my @pairs=split(/\&/,$rep);
1.273 albertel 5870: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
5871: return @pairs;
5872: }
1.15 www 5873: my %returnhash=();
1.42 www 5874: my $i=0;
1.800 albertel 5875: foreach my $item (@$storearr) {
5876: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 5877: $i++;
1.191 harris41 5878: }
1.15 www 5879: return %returnhash;
1.27 www 5880: }
5881:
5882: # --------------------------------------------------------------- del interface
5883:
5884: sub del {
1.133 albertel 5885: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 5886: my $items='';
1.800 albertel 5887: foreach my $item (@$storearr) {
5888: $items.=&escape($item).'&';
1.191 harris41 5889: }
1.984 neumanie 5890:
1.27 www 5891: $items=~s/\&$//;
1.620 albertel 5892: if (!$udomain) { $udomain=$env{'user.domain'}; }
5893: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 5894: my $uhome=&homeserver($uname,$udomain);
5895: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 5896: }
5897:
5898: # -------------------------------------------------------------- dump interface
5899:
1.1180 droeschl 5900: sub unserialize {
5901: my ($rep, $escapedkeys) = @_;
5902:
5903: return {} if $rep =~ /^error/;
5904:
5905: my %returnhash=();
1.1252 raeburn 5906: foreach my $item (split(/\&/,$rep)) {
1.1180 droeschl 5907: my ($key, $value) = split(/=/, $item, 2);
5908: $key = unescape($key) unless $escapedkeys;
5909: next if $key =~ /^error: 2 /;
1.1252 raeburn 5910: $returnhash{$key} = &thaw_unescape($value);
1.1180 droeschl 5911: }
5912: #return %returnhash;
5913: return \%returnhash;
5914: }
5915:
5916: # see Lond::dump_with_regexp
5917: # if $escapedkeys hash keys won't get unescaped.
1.15 www 5918: sub dump {
1.1180 droeschl 5919: my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755 albertel 5920: if (!$udomain) { $udomain=$env{'user.domain'}; }
5921: if (!$uname) { $uname=$env{'user.name'}; }
5922: my $uhome=&homeserver($uname,$udomain);
1.1167 droeschl 5923:
1.1266 raeburn 5924: if ($regexp) {
5925: $regexp=&escape($regexp);
5926: } else {
5927: $regexp='.';
5928: }
1.1180 droeschl 5929: if (grep { $_ eq $uhome } current_machine_ids()) {
5930: # user is hosted on this machine
1.1266 raeburn 5931: my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
1.1226 raeburn 5932: $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1180 droeschl 5933: return %{unserialize($reply, $escapedkeys)};
5934: }
1.1166 raeburn 5935: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755 albertel 5936: my @pairs=split(/\&/,$rep);
5937: my %returnhash=();
1.1098 foxr 5938: if (!($rep =~ /^error/ )) {
5939: foreach my $item (@pairs) {
5940: my ($key,$value)=split(/=/,$item,2);
1.1180 droeschl 5941: $key = unescape($key) unless $escapedkeys;
5942: #$key = &unescape($key);
1.1098 foxr 5943: next if ($key =~ /^error: 2 /);
5944: $returnhash{$key}=&thaw_unescape($value);
5945: }
1.755 albertel 5946: }
5947: return %returnhash;
1.407 www 5948: }
5949:
1.1098 foxr 5950:
1.717 albertel 5951: # --------------------------------------------------------- dumpstore interface
5952:
5953: sub dumpstore {
5954: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180 droeschl 5955: # same as dump but keys must be escaped. They may contain colon separated
5956: # lists of values that may themself contain colons (e.g. symbs).
5957: return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717 albertel 5958: }
5959:
1.407 www 5960: # -------------------------------------------------------------- keys interface
5961:
5962: sub getkeys {
5963: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 5964: if (!$udomain) { $udomain=$env{'user.domain'}; }
5965: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 5966: my $uhome=&homeserver($uname,$udomain);
5967: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
5968: my @keyarray=();
1.800 albertel 5969: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 5970: next if ($key =~ /^error: 2 /);
1.800 albertel 5971: push(@keyarray,&unescape($key));
1.407 www 5972: }
5973: return @keyarray;
1.318 matthew 5974: }
5975:
1.319 matthew 5976: # --------------------------------------------------------------- currentdump
5977: sub currentdump {
1.328 matthew 5978: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 5979: $courseid = $env{'request.course.id'} if (! defined($courseid));
5980: $sdom = $env{'user.domain'} if (! defined($sdom));
5981: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 5982: my $uhome = &homeserver($sname,$sdom);
1.1180 droeschl 5983: my $rep;
5984:
5985: if (grep { $_ eq $uhome } current_machine_ids()) {
5986: $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
5987: $courseid)));
5988: } else {
5989: $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
5990: }
5991:
1.318 matthew 5992: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 5993: #
1.318 matthew 5994: my %returnhash=();
1.319 matthew 5995: #
5996: if ($rep eq "unknown_cmd") {
5997: # an old lond will not know currentdump
5998: # Do a dump and make it look like a currentdump
1.822 albertel 5999: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 6000: return if ($tmp[0] =~ /^(error:|no_such_host)/);
6001: my %hash = @tmp;
6002: @tmp=();
1.424 matthew 6003: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 6004: } else {
6005: my @pairs=split(/\&/,$rep);
1.800 albertel 6006: foreach my $pair (@pairs) {
6007: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 6008: my ($symb,$param) = split(/:/,$key);
6009: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 6010: &thaw_unescape($value);
1.319 matthew 6011: }
1.191 harris41 6012: }
1.12 www 6013: return %returnhash;
1.424 matthew 6014: }
6015:
6016: sub convert_dump_to_currentdump{
6017: my %hash = %{shift()};
6018: my %returnhash;
6019: # Code ripped from lond, essentially. The only difference
6020: # here is the unescaping done by lonnet::dump(). Conceivably
6021: # we might run in to problems with parameter names =~ /^v\./
6022: while (my ($key,$value) = each(%hash)) {
6023: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 6024: $symb = &unescape($symb);
6025: $param = &unescape($param);
1.424 matthew 6026: next if ($v eq 'version' || $symb eq 'keys');
6027: next if (exists($returnhash{$symb}) &&
6028: exists($returnhash{$symb}->{$param}) &&
6029: $returnhash{$symb}->{'v.'.$param} > $v);
6030: $returnhash{$symb}->{$param}=$value;
6031: $returnhash{$symb}->{'v.'.$param}=$v;
6032: }
6033: #
6034: # Remove all of the keys in the hashes which keep track of
6035: # the version of the parameter.
6036: while (my ($symb,$param_hash) = each(%returnhash)) {
6037: # use a foreach because we are going to delete from the hash.
6038: foreach my $key (keys(%$param_hash)) {
6039: delete($param_hash->{$key}) if ($key =~ /^v\./);
6040: }
6041: }
6042: return \%returnhash;
1.12 www 6043: }
6044:
1.627 albertel 6045: # ------------------------------------------------------ critical inc interface
6046:
6047: sub cinc {
6048: return &inc(@_,'critical');
6049: }
6050:
1.449 matthew 6051: # --------------------------------------------------------------- inc interface
6052:
6053: sub inc {
1.627 albertel 6054: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 6055: if (!$udomain) { $udomain=$env{'user.domain'}; }
6056: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 6057: my $uhome=&homeserver($uname,$udomain);
6058: my $items='';
6059: if (! ref($store)) {
6060: # got a single value, so use that instead
6061: $items = &escape($store).'=&';
6062: } elsif (ref($store) eq 'SCALAR') {
6063: $items = &escape($$store).'=&';
6064: } elsif (ref($store) eq 'ARRAY') {
6065: $items = join('=&',map {&escape($_);} @{$store});
6066: } elsif (ref($store) eq 'HASH') {
6067: while (my($key,$value) = each(%{$store})) {
6068: $items.= &escape($key).'='.&escape($value).'&';
6069: }
6070: }
6071: $items=~s/\&$//;
1.627 albertel 6072: if ($critical) {
6073: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
6074: } else {
6075: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
6076: }
1.449 matthew 6077: }
6078:
1.12 www 6079: # --------------------------------------------------------------- put interface
6080:
6081: sub put {
1.134 albertel 6082: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 6083: if (!$udomain) { $udomain=$env{'user.domain'}; }
6084: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 6085: my $uhome=&homeserver($uname,$udomain);
1.12 www 6086: my $items='';
1.800 albertel 6087: foreach my $item (keys(%$storehash)) {
6088: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 6089: }
1.12 www 6090: $items=~s/\&$//;
1.134 albertel 6091: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 6092: }
6093:
1.631 albertel 6094: # ------------------------------------------------------------ newput interface
6095:
6096: sub newput {
6097: my ($namespace,$storehash,$udomain,$uname)=@_;
6098: if (!$udomain) { $udomain=$env{'user.domain'}; }
6099: if (!$uname) { $uname=$env{'user.name'}; }
6100: my $uhome=&homeserver($uname,$udomain);
6101: my $items='';
6102: foreach my $key (keys(%$storehash)) {
6103: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
6104: }
6105: $items=~s/\&$//;
6106: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
6107: }
6108:
6109: # --------------------------------------------------------- putstore interface
6110:
1.524 raeburn 6111: sub putstore {
1.1269 raeburn 6112: my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620 albertel 6113: if (!$udomain) { $udomain=$env{'user.domain'}; }
6114: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 6115: my $uhome=&homeserver($uname,$udomain);
6116: my $items='';
1.715 albertel 6117: foreach my $key (keys(%$storehash)) {
6118: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 6119: }
1.715 albertel 6120: $items=~s/\&$//;
1.716 albertel 6121: my $esc_symb=&escape($symb);
6122: my $esc_v=&escape($version);
1.715 albertel 6123: my $reply =
1.716 albertel 6124: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 6125: $uhome);
1.1269 raeburn 6126: if (($tolog) && ($reply eq 'ok')) {
6127: my $namevalue='';
6128: foreach my $key (keys(%{$storehash})) {
6129: $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
6130: }
6131: $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
6132: '&host='.&escape($perlvar{'lonHostID'}).
6133: '&version='.$esc_v.
6134: '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
6135: &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
6136: }
1.715 albertel 6137: if ($reply eq 'unknown_cmd') {
1.716 albertel 6138: # gfall back to way things use to be done
1.715 albertel 6139: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
6140: $uname);
1.524 raeburn 6141: }
1.715 albertel 6142: return $reply;
6143: }
6144:
6145: sub old_putstore {
1.716 albertel 6146: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
6147: if (!$udomain) { $udomain=$env{'user.domain'}; }
6148: if (!$uname) { $uname=$env{'user.name'}; }
6149: my $uhome=&homeserver($uname,$udomain);
6150: my %newstorehash;
1.800 albertel 6151: foreach my $item (keys(%$storehash)) {
6152: my $key = $version.':'.&escape($symb).':'.$item;
6153: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 6154: }
6155: my $items='';
6156: my %allitems = ();
1.800 albertel 6157: foreach my $item (keys(%newstorehash)) {
6158: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 6159: my $key = $1.':keys:'.$2;
6160: $allitems{$key} .= $3.':';
6161: }
1.800 albertel 6162: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 6163: }
1.800 albertel 6164: foreach my $item (keys(%allitems)) {
6165: $allitems{$item} =~ s/\:$//;
6166: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 6167: }
6168: $items=~s/\&$//;
6169: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 6170: }
6171:
1.47 www 6172: # ------------------------------------------------------ critical put interface
6173:
6174: sub cput {
1.134 albertel 6175: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 6176: if (!$udomain) { $udomain=$env{'user.domain'}; }
6177: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 6178: my $uhome=&homeserver($uname,$udomain);
1.47 www 6179: my $items='';
1.800 albertel 6180: foreach my $item (keys(%$storehash)) {
6181: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 6182: }
1.47 www 6183: $items=~s/\&$//;
1.134 albertel 6184: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 6185: }
6186:
6187: # -------------------------------------------------------------- eget interface
6188:
6189: sub eget {
1.133 albertel 6190: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 6191: my $items='';
1.800 albertel 6192: foreach my $item (@$storearr) {
6193: $items.=&escape($item).'&';
1.191 harris41 6194: }
1.12 www 6195: $items=~s/\&$//;
1.620 albertel 6196: if (!$udomain) { $udomain=$env{'user.domain'}; }
6197: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 6198: my $uhome=&homeserver($uname,$udomain);
6199: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 6200: my @pairs=split(/\&/,$rep);
6201: my %returnhash=();
1.42 www 6202: my $i=0;
1.800 albertel 6203: foreach my $item (@$storearr) {
6204: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 6205: $i++;
1.191 harris41 6206: }
1.12 www 6207: return %returnhash;
6208: }
6209:
1.667 albertel 6210: # ------------------------------------------------------------ tmpput interface
6211: sub tmpput {
1.802 raeburn 6212: my ($storehash,$server,$context)=@_;
1.667 albertel 6213: my $items='';
1.800 albertel 6214: foreach my $item (keys(%$storehash)) {
6215: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 6216: }
6217: $items=~s/\&$//;
1.802 raeburn 6218: if (defined($context)) {
6219: $items .= ':'.&escape($context);
6220: }
1.667 albertel 6221: return &reply("tmpput:$items",$server);
6222: }
6223:
6224: # ------------------------------------------------------------ tmpget interface
6225: sub tmpget {
1.688 albertel 6226: my ($token,$server)=@_;
6227: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
6228: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 6229: my %returnhash;
6230: foreach my $item (split(/\&/,$rep)) {
6231: my ($key,$value)=split(/=/,$item);
1.951 raeburn 6232: next if ($key =~ /^error: 2 /);
1.667 albertel 6233: $returnhash{&unescape($key)}=&thaw_unescape($value);
6234: }
6235: return %returnhash;
6236: }
6237:
1.1113 raeburn 6238: # ------------------------------------------------------------ tmpdel interface
1.688 albertel 6239: sub tmpdel {
6240: my ($token,$server)=@_;
6241: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
6242: return &reply("tmpdel:$token",$server);
6243: }
6244:
1.1198 raeburn 6245: # ------------------------------------------------------------ get_timebased_id
6246:
6247: sub get_timebased_id {
6248: my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
6249: $maxtries) = @_;
6250: my ($newid,$error,$dellock);
6251: unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
6252: return ('','ok','invalid call to get suffix');
6253: }
6254:
6255: # set defaults for any optional args for which values were not supplied
6256: if ($who eq '') {
6257: $who = $env{'user.name'}.':'.$env{'user.domain'};
6258: }
6259: if (!$locktries) {
6260: $locktries = 3;
6261: }
6262: if (!$maxtries) {
6263: $maxtries = 10;
6264: }
6265:
6266: if (($cdom eq '') || ($cnum eq '')) {
6267: if ($env{'request.course.id'}) {
6268: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6269: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6270: }
6271: if (($cdom eq '') || ($cnum eq '')) {
6272: return ('','ok','call to get suffix not in course context');
6273: }
6274: }
6275:
6276: # construct locking item
6277: my $lockhash = {
6278: $prefix."\0".'locked_'.$keyid => $who,
6279: };
6280: my $tries = 0;
6281:
6282: # attempt to get lock on nohist_$namespace file
6283: my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
6284: while (($gotlock ne 'ok') && $tries <$locktries) {
6285: $tries ++;
6286: sleep 1;
6287: $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
6288: }
6289:
6290: # attempt to get unique identifier, based on current timestamp
6291: if ($gotlock eq 'ok') {
6292: my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
6293: my $id = time;
6294: $newid = $id;
1.1268 raeburn 6295: if ($idtype eq 'addcode') {
6296: $newid .= &sixnum_code();
6297: }
1.1198 raeburn 6298: my $idtries = 0;
6299: while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
6300: if ($idtype eq 'concat') {
6301: $newid = $id.$idtries;
1.1268 raeburn 6302: } elsif ($idtype eq 'addcode') {
6303: $newid = $newid.&sixnum_code();
1.1198 raeburn 6304: } else {
6305: $newid ++;
6306: }
6307: $idtries ++;
6308: }
6309: if (!exists($inuse{$prefix."\0".$newid})) {
6310: my %new_item = (
6311: $prefix."\0".$newid => $who,
6312: );
6313: my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
6314: $cdom,$cnum);
6315: if ($putresult ne 'ok') {
6316: undef($newid);
6317: $error = 'error saving new item: '.$putresult;
6318: }
6319: } else {
1.1268 raeburn 6320: undef($newid);
1.1198 raeburn 6321: $error = ('error: no unique suffix available for the new item ');
6322: }
6323: # remove lock
6324: my @del_lock = ($prefix."\0".'locked_'.$keyid);
6325: $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
6326: } else {
6327: $error = "error: could not obtain lockfile\n";
6328: $dellock = 'ok';
1.1276 raeburn 6329: if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
6330: $dellock = 'nolock';
6331: }
1.1198 raeburn 6332: }
6333: return ($newid,$dellock,$error);
6334: }
6335:
1.1268 raeburn 6336: sub sixnum_code {
6337: my $code;
6338: for (0..6) {
6339: $code .= int( rand(9) );
6340: }
6341: return $code;
6342: }
6343:
1.765 albertel 6344: # -------------------------------------------------- portfolio access checking
6345:
6346: sub portfolio_access {
1.1270 raeburn 6347: my ($requrl,$clientip) = @_;
1.765 albertel 6348: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1270 raeburn 6349: my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814 raeburn 6350: if ($result) {
6351: my %setters;
6352: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6353: my ($startblock,$endblock) =
6354: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
6355: if ($startblock && $endblock) {
6356: return 'B';
6357: }
6358: } else {
6359: my ($startblock,$endblock) =
6360: &Apache::loncommon::blockcheck(\%setters,'port');
6361: if ($startblock && $endblock) {
6362: return 'B';
6363: }
6364: }
6365: }
1.765 albertel 6366: if ($result eq 'ok') {
1.766 albertel 6367: return 'F';
1.765 albertel 6368: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 6369: return 'A';
1.765 albertel 6370: }
1.766 albertel 6371: return '';
1.765 albertel 6372: }
6373:
6374: sub get_portfolio_access {
1.1270 raeburn 6375: my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767 albertel 6376:
6377: if (!ref($access_hash)) {
6378: my $current_perms = &get_portfile_permissions($udom,$unum);
6379: my %access_controls = &get_access_controls($current_perms,$group,
6380: $file_name);
6381: $access_hash = $access_controls{$file_name};
6382: }
6383:
1.1270 raeburn 6384: my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765 albertel 6385: my $now = time;
6386: if (ref($access_hash) eq 'HASH') {
6387: foreach my $key (keys(%{$access_hash})) {
6388: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
6389: if ($start > $now) {
6390: next;
6391: }
6392: if ($end && $end<$now) {
6393: next;
6394: }
6395: if ($scope eq 'public') {
6396: $public = $key;
6397: last;
6398: } elsif ($scope eq 'guest') {
6399: $guest = $key;
6400: } elsif ($scope eq 'domains') {
6401: push(@domains,$key);
6402: } elsif ($scope eq 'users') {
6403: push(@users,$key);
6404: } elsif ($scope eq 'course') {
6405: push(@courses,$key);
6406: } elsif ($scope eq 'group') {
6407: push(@groups,$key);
1.1270 raeburn 6408: } elsif ($scope eq 'ip') {
6409: push(@ips,$key);
1.765 albertel 6410: }
6411: }
6412: if ($public) {
6413: return 'ok';
1.1270 raeburn 6414: } elsif (@ips > 0) {
6415: my $allowed;
6416: foreach my $ipkey (@ips) {
6417: if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
6418: if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
6419: $allowed = 1;
6420: last;
6421: }
6422: }
6423: }
6424: if ($allowed) {
6425: return 'ok';
6426: }
1.765 albertel 6427: }
6428: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6429: if ($guest) {
6430: return $guest;
6431: }
6432: } else {
6433: if (@domains > 0) {
6434: foreach my $domkey (@domains) {
6435: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
6436: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
6437: return 'ok';
6438: }
6439: }
6440: }
6441: }
6442: if (@users > 0) {
6443: foreach my $userkey (@users) {
1.865 raeburn 6444: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
6445: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
6446: if (ref($item) eq 'HASH') {
6447: if (($item->{'uname'} eq $env{'user.name'}) &&
6448: ($item->{'udom'} eq $env{'user.domain'})) {
6449: return 'ok';
6450: }
6451: }
6452: }
6453: }
1.765 albertel 6454: }
6455: }
6456: my %roleshash;
6457: my @courses_and_groups = @courses;
6458: push(@courses_and_groups,@groups);
6459: if (@courses_and_groups > 0) {
6460: my (%allgroups,%allroles);
6461: my ($start,$end,$role,$sec,$group);
6462: foreach my $envkey (%env) {
1.1060 raeburn 6463: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6464: my $cid = $2.'_'.$3;
6465: if ($1 eq 'gr') {
6466: $group = $4;
6467: $allgroups{$cid}{$group} = $env{$envkey};
6468: } else {
6469: if ($4 eq '') {
6470: $sec = 'none';
6471: } else {
6472: $sec = $4;
6473: }
6474: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6475: }
1.811 albertel 6476: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6477: my $cid = $2.'_'.$3;
6478: if ($4 eq '') {
6479: $sec = 'none';
6480: } else {
6481: $sec = $4;
6482: }
6483: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6484: }
6485: }
6486: if (keys(%allroles) == 0) {
6487: return;
6488: }
6489: foreach my $key (@courses_and_groups) {
6490: my %content = %{$$access_hash{$key}};
6491: my $cnum = $content{'number'};
6492: my $cdom = $content{'domain'};
6493: my $cid = $cdom.'_'.$cnum;
6494: if (!exists($allroles{$cid})) {
6495: next;
6496: }
6497: foreach my $role_id (keys(%{$content{'roles'}})) {
6498: my @sections = @{$content{'roles'}{$role_id}{'section'}};
6499: my @groups = @{$content{'roles'}{$role_id}{'group'}};
6500: my @status = @{$content{'roles'}{$role_id}{'access'}};
6501: my @roles = @{$content{'roles'}{$role_id}{'role'}};
6502: foreach my $role (keys(%{$allroles{$cid}})) {
6503: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
6504: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
6505: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
6506: if (grep/^all$/,@sections) {
6507: return 'ok';
6508: } else {
6509: if (grep/^$sec$/,@sections) {
6510: return 'ok';
6511: }
6512: }
6513: }
6514: }
6515: if (keys(%{$allgroups{$cid}}) == 0) {
6516: if (grep/^none$/,@groups) {
6517: return 'ok';
6518: }
6519: } else {
6520: if (grep/^all$/,@groups) {
6521: return 'ok';
6522: }
6523: foreach my $group (keys(%{$allgroups{$cid}})) {
6524: if (grep/^$group$/,@groups) {
6525: return 'ok';
6526: }
6527: }
6528: }
6529: }
6530: }
6531: }
6532: }
6533: }
6534: if ($guest) {
6535: return $guest;
6536: }
6537: }
6538: }
6539: return;
6540: }
6541:
6542: sub course_group_datechecker {
6543: my ($dates,$now,$status) = @_;
6544: my ($start,$end) = split(/\./,$dates);
6545: if (!$start && !$end) {
6546: return 'ok';
6547: }
6548: if (grep/^active$/,@{$status}) {
6549: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
6550: return 'ok';
6551: }
6552: }
6553: if (grep/^previous$/,@{$status}) {
6554: if ($end > $now ) {
6555: return 'ok';
6556: }
6557: }
6558: if (grep/^future$/,@{$status}) {
6559: if ($start > $now) {
6560: return 'ok';
6561: }
6562: }
6563: return;
6564: }
6565:
6566: sub parse_portfolio_url {
6567: my ($url) = @_;
6568:
6569: my ($type,$udom,$unum,$group,$file_name);
6570:
1.823 albertel 6571: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 6572: $type = 1;
6573: $udom = $1;
6574: $unum = $2;
6575: $file_name = $3;
1.823 albertel 6576: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 6577: $type = 2;
6578: $udom = $1;
6579: $unum = $2;
6580: $group = $3;
6581: $file_name = $3.'/'.$4;
6582: }
6583: if (wantarray) {
6584: return ($type,$udom,$unum,$file_name,$group);
6585: }
6586: return $type;
6587: }
6588:
6589: sub is_portfolio_url {
6590: my ($url) = @_;
6591: return scalar(&parse_portfolio_url($url));
6592: }
6593:
1.798 raeburn 6594: sub is_portfolio_file {
6595: my ($file) = @_;
1.820 raeburn 6596: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 6597: return 1;
6598: }
6599: return;
6600: }
6601:
1.976 raeburn 6602: sub usertools_access {
1.1084 raeburn 6603: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 6604: my ($access,%tools);
6605: if ($context eq '') {
6606: $context = 'tools';
6607: }
6608: if ($context eq 'requestcourses') {
6609: %tools = (
6610: official => 1,
6611: unofficial => 1,
1.1006 raeburn 6612: community => 1,
1.1246 raeburn 6613: textbook => 1,
1.1305 raeburn 6614: placement => 1,
1.985 raeburn 6615: );
1.1183 raeburn 6616: } elsif ($context eq 'requestauthor') {
6617: %tools = (
6618: requestauthor => 1,
6619: );
1.985 raeburn 6620: } else {
6621: %tools = (
6622: aboutme => 1,
6623: blog => 1,
1.1177 raeburn 6624: webdav => 1,
1.985 raeburn 6625: portfolio => 1,
6626: );
6627: }
1.976 raeburn 6628: return if (!defined($tools{$tool}));
6629:
1.1242 raeburn 6630: if (($udom eq '') || ($uname eq '')) {
1.976 raeburn 6631: $udom = $env{'user.domain'};
6632: $uname = $env{'user.name'};
6633: }
6634:
1.978 raeburn 6635: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
6636: if ($action ne 'reload') {
1.985 raeburn 6637: if ($context eq 'requestcourses') {
6638: return $env{'environment.canrequest.'.$tool};
1.1183 raeburn 6639: } elsif ($context eq 'requestauthor') {
6640: return $env{'environment.canrequest.author'};
1.985 raeburn 6641: } else {
6642: return $env{'environment.availabletools.'.$tool};
6643: }
6644: }
1.976 raeburn 6645: }
6646:
1.1183 raeburn 6647: my ($toolstatus,$inststatus,$envkey);
6648: if ($context eq 'requestauthor') {
6649: $envkey = $context;
6650: } else {
6651: $envkey = $context.'.'.$tool;
6652: }
1.976 raeburn 6653:
1.985 raeburn 6654: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
6655: ($action ne 'reload')) {
1.1183 raeburn 6656: $toolstatus = $env{'environment.'.$envkey};
1.976 raeburn 6657: $inststatus = $env{'environment.inststatus'};
6658: } else {
1.1084 raeburn 6659: if (ref($userenvref) eq 'HASH') {
1.1183 raeburn 6660: $toolstatus = $userenvref->{$envkey};
1.1084 raeburn 6661: $inststatus = $userenvref->{'inststatus'};
6662: } else {
1.1183 raeburn 6663: my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
6664: $toolstatus = $userenv{$envkey};
1.1084 raeburn 6665: $inststatus = $userenv{'inststatus'};
6666: }
1.976 raeburn 6667: }
6668:
6669: if ($toolstatus ne '') {
6670: if ($toolstatus) {
6671: $access = 1;
6672: } else {
6673: $access = 0;
6674: }
6675: return $access;
6676: }
6677:
1.1084 raeburn 6678: my ($is_adv,%domdef);
6679: if (ref($is_advref) eq 'HASH') {
6680: $is_adv = $is_advref->{'is_adv'};
6681: } else {
6682: $is_adv = &is_advanced_user($udom,$uname);
6683: }
6684: if (ref($domdefref) eq 'HASH') {
6685: %domdef = %{$domdefref};
6686: } else {
6687: %domdef = &get_domain_defaults($udom);
6688: }
1.976 raeburn 6689: if (ref($domdef{$tool}) eq 'HASH') {
6690: if ($is_adv) {
6691: if ($domdef{$tool}{'_LC_adv'} ne '') {
6692: if ($domdef{$tool}{'_LC_adv'}) {
6693: $access = 1;
6694: } else {
6695: $access = 0;
6696: }
6697: return $access;
6698: }
6699: }
6700: if ($inststatus ne '') {
6701: my ($hasaccess,$hasnoaccess);
6702: foreach my $affiliation (split(/:/,$inststatus)) {
6703: if ($domdef{$tool}{$affiliation} ne '') {
6704: if ($domdef{$tool}{$affiliation}) {
6705: $hasaccess = 1;
6706: } else {
6707: $hasnoaccess = 1;
6708: }
6709: }
6710: }
6711: if ($hasaccess || $hasnoaccess) {
6712: if ($hasaccess) {
6713: $access = 1;
6714: } elsif ($hasnoaccess) {
6715: $access = 0;
6716: }
6717: return $access;
6718: }
6719: } else {
6720: if ($domdef{$tool}{'default'} ne '') {
6721: if ($domdef{$tool}{'default'}) {
6722: $access = 1;
6723: } elsif ($domdef{$tool}{'default'} == 0) {
6724: $access = 0;
6725: }
6726: return $access;
6727: }
6728: }
6729: } else {
1.1177 raeburn 6730: if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985 raeburn 6731: $access = 1;
6732: } else {
6733: $access = 0;
6734: }
1.976 raeburn 6735: return $access;
6736: }
6737: }
6738:
1.1050 raeburn 6739: sub is_course_owner {
6740: my ($cdom,$cnum,$udom,$uname) = @_;
6741: if (($udom eq '') || ($uname eq '')) {
6742: $udom = $env{'user.domain'};
6743: $uname = $env{'user.name'};
6744: }
6745: unless (($udom eq '') || ($uname eq '')) {
6746: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
6747: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
6748: return 1;
6749: } else {
6750: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
6751: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
6752: return 1;
6753: }
6754: }
6755: }
6756: }
6757: return;
6758: }
6759:
1.976 raeburn 6760: sub is_advanced_user {
6761: my ($udom,$uname) = @_;
1.1085 raeburn 6762: if ($udom ne '' && $uname ne '') {
6763: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128 raeburn 6764: if (wantarray) {
6765: return ($env{'user.adv'},$env{'user.author'});
6766: } else {
6767: return $env{'user.adv'};
6768: }
1.1085 raeburn 6769: }
6770: }
1.976 raeburn 6771: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
6772: my %allroles;
1.1128 raeburn 6773: my ($is_adv,$is_author);
1.976 raeburn 6774: foreach my $role (keys(%roleshash)) {
6775: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
6776: my $area = '/'.$tdomain.'/'.$trest;
6777: if ($sec ne '') {
6778: $area .= '/'.$sec;
6779: }
6780: if (($area ne '') && ($trole ne '')) {
6781: my $spec=$trole.'.'.$area;
6782: if ($trole =~ /^cr\//) {
6783: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
6784: } elsif ($trole ne 'gr') {
6785: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
6786: }
1.1128 raeburn 6787: if ($trole eq 'au') {
6788: $is_author = 1;
6789: }
1.976 raeburn 6790: }
6791: }
6792: foreach my $role (keys(%allroles)) {
6793: last if ($is_adv);
6794: foreach my $item (split(/:/,$allroles{$role})) {
6795: if ($item ne '') {
6796: my ($privilege,$restrictions)=split(/&/,$item);
6797: if ($privilege eq 'adv') {
6798: $is_adv = 1;
6799: last;
6800: }
6801: }
6802: }
6803: }
1.1128 raeburn 6804: if (wantarray) {
6805: return ($is_adv,$is_author);
6806: }
1.976 raeburn 6807: return $is_adv;
6808: }
1.798 raeburn 6809:
1.1035 raeburn 6810: sub check_can_request {
1.1036 raeburn 6811: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 6812: my $canreq = 0;
6813: my ($types,$typename) = &Apache::loncommon::course_types();
6814: my @options = ('approval','validate','autolimit');
6815: my $optregex = join('|',@options);
6816: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
6817: foreach my $type (@{$types}) {
6818: if (&usertools_access($env{'user.name'},
6819: $env{'user.domain'},
6820: $type,undef,'requestcourses')) {
6821: $canreq ++;
1.1036 raeburn 6822: if (ref($request_domains) eq 'HASH') {
6823: push(@{$request_domains->{$type}},$env{'user.domain'});
6824: }
1.1035 raeburn 6825: if ($dom eq $env{'user.domain'}) {
6826: $can_request->{$type} = 1;
6827: }
6828: }
6829: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
6830: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
6831: if (@curr > 0) {
1.1036 raeburn 6832: foreach my $item (@curr) {
6833: if (ref($request_domains) eq 'HASH') {
6834: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
6835: if ($otherdom ne '') {
6836: if (ref($request_domains->{$type}) eq 'ARRAY') {
6837: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
6838: push(@{$request_domains->{$type}},$otherdom);
6839: }
6840: } else {
6841: push(@{$request_domains->{$type}},$otherdom);
6842: }
6843: }
6844: }
6845: }
6846: unless($dom eq $env{'user.domain'}) {
6847: $canreq ++;
1.1035 raeburn 6848: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
6849: $can_request->{$type} = 1;
6850: }
6851: }
6852: }
6853: }
6854: }
6855: }
6856: return $canreq;
6857: }
6858:
1.341 www 6859: # ---------------------------------------------- Custom access rule evaluation
6860:
6861: sub customaccess {
6862: my ($priv,$uri)=@_;
1.807 albertel 6863: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 6864: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 6865: $udom = &LONCAPA::clean_domain($udom);
6866: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 6867: my $access=0;
1.800 albertel 6868: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 6869: my ($effect,$realm,$role,$type)=split(/\:/,$right);
6870: if ($type eq 'user') {
6871: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 6872: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 6873: if ($tdom) {
6874: if ($tdom ne $env{'user.domain'}) { next; }
6875: }
1.896 albertel 6876: if ($tuname) {
6877: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 6878: }
6879: $access=($effect eq 'allow');
6880: last;
6881: }
6882: } else {
6883: if ($role) {
6884: if ($role ne $urole) { next; }
6885: }
6886: foreach my $scope (split(/\s*\,\s*/,$realm)) {
6887: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
6888: if ($tdom) {
6889: if ($tdom ne $udom) { next; }
6890: }
6891: if ($tcrs) {
6892: if ($tcrs ne $ucrs) { next; }
6893: }
6894: if ($tsec) {
6895: if ($tsec ne $usec) { next; }
6896: }
6897: $access=($effect eq 'allow');
6898: last;
6899: }
6900: if ($realm eq '' && $role eq '') {
6901: $access=($effect eq 'allow');
6902: }
1.402 bowersj2 6903: }
1.341 www 6904: }
6905: return $access;
6906: }
6907:
1.103 harris41 6908: # ------------------------------------------------- Check for a user privilege
1.12 www 6909:
6910: sub allowed {
1.1281 raeburn 6911: my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
1.705 albertel 6912: my $ver_orguri=$uri;
1.439 www 6913: $uri=&deversion($uri);
1.152 www 6914: my $orguri=$uri;
1.52 www 6915: $uri=&declutter($uri);
1.809 raeburn 6916:
1.810 raeburn 6917: if ($priv eq 'evb') {
6918: # Evade communication block restrictions for specified role in a course
6919: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
6920: return $1;
6921: } else {
6922: return;
6923: }
6924: }
6925:
1.620 albertel 6926: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 6927: # Free bre access to adm and meta resources
1.775 albertel 6928: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 6929: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
6930: && ($priv eq 'bre')) {
1.14 www 6931: return 'F';
1.159 www 6932: }
6933:
1.545 banghart 6934: # Free bre access to user's own portfolio contents
1.714 raeburn 6935: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 6936: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 6937: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 6938: my %setters;
6939: my ($startblock,$endblock) =
6940: &Apache::loncommon::blockcheck(\%setters,'port');
6941: if ($startblock && $endblock) {
6942: return 'B';
6943: } else {
6944: return 'F';
6945: }
1.545 banghart 6946: }
6947:
1.762 raeburn 6948: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 6949: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
6950: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
6951: if (exists($env{'request.course.id'})) {
6952: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6953: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6954: if (($domain eq $cdom) && ($name eq $cnum)) {
6955: my $courseprivid=$env{'request.course.id'};
6956: $courseprivid=~s/\_/\//;
6957: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
6958: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
6959: return $1;
1.762 raeburn 6960: } else {
6961: if ($env{'request.course.sec'}) {
6962: $courseprivid.='/'.$env{'request.course.sec'};
6963: }
6964: if ($env{'user.priv.'.$env{'request.role'}.'./'.
6965: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
6966: return $2;
6967: }
1.714 raeburn 6968: }
6969: }
6970: }
6971: }
6972:
1.159 www 6973: # Free bre to public access
6974:
6975: if ($priv eq 'bre') {
1.238 www 6976: my $copyright=&metadata($uri,'copyright');
1.620 albertel 6977: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 6978: return 'F';
6979: }
1.238 www 6980: if ($copyright eq 'priv') {
6981: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 6982: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 6983: return '';
6984: }
6985: }
6986: if ($copyright eq 'domain') {
6987: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 6988: unless (($env{'user.domain'} eq $1) ||
6989: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 6990: return '';
6991: }
1.262 matthew 6992: }
1.620 albertel 6993: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 6994: # Library role, so allow browsing of resources in this domain.
6995: return 'F';
1.238 www 6996: }
1.341 www 6997: if ($copyright eq 'custom') {
6998: unless (&customaccess($priv,$uri)) { return ''; }
6999: }
1.14 www 7000: }
1.264 matthew 7001: # Domain coordinator is trying to create a course
1.620 albertel 7002: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 7003: # uri is the requested domain in this case.
7004: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 7005: # a role of dc for the domain in question.
1.620 albertel 7006: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 7007: }
1.29 www 7008:
1.52 www 7009: my $thisallowed='';
7010: my $statecond=0;
7011: my $courseprivid='';
7012:
1.1039 raeburn 7013: my $ownaccess;
1.1043 raeburn 7014: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 7015: if (($priv eq 'bro') && ($env{'user.author'})) {
7016: if ($uri eq '') {
7017: $ownaccess = 1;
7018: } else {
7019: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
7020: my $udom = $env{'user.domain'};
7021: my $uname = $env{'user.name'};
7022: if ($uri =~ m{^\Q$udom\E/?$}) {
7023: $ownaccess = 1;
1.1040 raeburn 7024: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 7025: unless ($uri =~ m{\.\./}) {
7026: $ownaccess = 1;
7027: }
7028: } elsif (($udom ne 'public') && ($uname ne 'public')) {
7029: my $now = time;
7030: if ($uri =~ m{^([^/]+)/?$}) {
7031: my $adom = $1;
7032: foreach my $key (keys(%env)) {
1.1042 raeburn 7033: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 7034: my ($start,$end) = split('.',$env{$key});
7035: if (($now >= $start) && (!$end || $end < $now)) {
7036: $ownaccess = 1;
7037: last;
7038: }
7039: }
7040: }
7041: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
7042: my $adom = $1;
7043: my $aname = $2;
1.1042 raeburn 7044: foreach my $role ('ca','aa') {
7045: if ($env{"user.role.$role./$adom/$aname"}) {
7046: my ($start,$end) =
7047: split('.',$env{"user.role.$role./$adom/$aname"});
7048: if (($now >= $start) && (!$end || $end < $now)) {
7049: $ownaccess = 1;
7050: last;
7051: }
1.1039 raeburn 7052: }
7053: }
7054: }
7055: }
7056: }
7057: }
7058: }
7059:
1.52 www 7060: # Course
7061:
1.620 albertel 7062: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 7063: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 7064: $thisallowed.=$1;
7065: }
1.52 www 7066: }
1.29 www 7067:
1.52 www 7068: # Domain
7069:
1.620 albertel 7070: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 7071: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 7072: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 7073: $thisallowed.=$1;
7074: }
1.12 www 7075: }
1.52 www 7076:
1.1141 raeburn 7077: # User who is not author or co-author might still be able to edit
7078: # resource of an author in the domain (e.g., if Domain Coordinator).
7079: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
7080: (&allowed('mdc',$env{'request.course.id'}))) {
7081: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
7082: $thisallowed.=$1;
7083: }
7084: }
7085:
1.52 www 7086: # Course: uri itself is a course
1.66 www 7087: my $courseuri=$uri;
7088: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 7089: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 7090:
1.620 albertel 7091: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 7092: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 7093: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 7094: $thisallowed.=$1;
7095: }
1.12 www 7096: }
1.29 www 7097:
1.665 albertel 7098: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 7099: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 7100: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 7101: $thisallowed='';
1.671 raeburn 7102: my ($match)=&is_on_map($uri);
7103: if ($match) {
7104: if ($env{'user.priv.'.$env{'request.role'}.'./'}
7105: =~/\Q$priv\E\&([^\:]*)/) {
1.1281 raeburn 7106: my $value = $1;
7107: if ($noblockcheck) {
7108: $thisallowed.=$value;
1.1162 raeburn 7109: } else {
1.1281 raeburn 7110: my @blockers = &has_comm_blocking($priv,$symb,$uri);
7111: if (@blockers > 0) {
7112: $thisallowed = 'B';
7113: } else {
7114: $thisallowed.=$value;
7115: }
1.1162 raeburn 7116: }
1.671 raeburn 7117: }
7118: } else {
1.705 albertel 7119: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 7120: if ($refuri) {
7121: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 7122: $thisallowed='F';
1.671 raeburn 7123: } else {
7124: $refuri=&declutter($refuri);
7125: my ($match) = &is_on_map($refuri);
7126: if ($match) {
1.1281 raeburn 7127: if ($noblockcheck) {
7128: $thisallowed='F';
1.1162 raeburn 7129: } else {
1.1281 raeburn 7130: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
7131: if (@blockers > 0) {
7132: $thisallowed = 'B';
7133: } else {
7134: $thisallowed='F';
7135: }
1.1162 raeburn 7136: }
1.671 raeburn 7137: }
1.669 raeburn 7138: }
1.671 raeburn 7139: }
7140: }
1.314 www 7141: }
1.492 albertel 7142:
1.766 albertel 7143: if ($priv eq 'bre'
7144: && $thisallowed ne 'F'
7145: && $thisallowed ne '2'
7146: && &is_portfolio_url($uri)) {
1.1270 raeburn 7147: $thisallowed = &portfolio_access($uri,$clientip);
1.766 albertel 7148: }
1.1250 raeburn 7149:
1.52 www 7150: # Full access at system, domain or course-wide level? Exit.
1.29 www 7151: if ($thisallowed=~/F/) {
7152: return 'F';
7153: }
7154:
1.52 www 7155: # If this is generating or modifying users, exit with special codes
1.29 www 7156:
1.643 www 7157: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
7158: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 7159: my ($audom,$auname)=split('/',$uri);
1.643 www 7160: # no author name given, so this just checks on the general right to make a co-author in this domain
7161: unless ($auname) { return $thisallowed; }
7162: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 7163: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
7164: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
7165: ($audom ne $env{'request.role.domain'}))) { return ''; }
7166: }
1.52 www 7167: return $thisallowed;
7168: }
7169: #
1.103 harris41 7170: # Gathered so far: system, domain and course wide privileges
1.52 www 7171: #
7172: # Course: See if uri or referer is an individual resource that is part of
7173: # the course
7174:
1.620 albertel 7175: if ($env{'request.course.id'}) {
1.232 www 7176:
1.620 albertel 7177: $courseprivid=$env{'request.course.id'};
7178: if ($env{'request.course.sec'}) {
7179: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 7180: }
7181: $courseprivid=~s/\_/\//;
7182: my $checkreferer=1;
1.232 www 7183: my ($match,$cond)=&is_on_map($uri);
7184: if ($match) {
7185: $statecond=$cond;
1.620 albertel 7186: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 7187: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 7188: my $value = $1;
7189: if ($priv eq 'bre') {
1.1281 raeburn 7190: if ($noblockcheck) {
7191: $thisallowed.=$value;
1.1162 raeburn 7192: } else {
1.1281 raeburn 7193: my @blockers = &has_comm_blocking($priv,$symb,$uri);
7194: if (@blockers > 0) {
7195: $thisallowed = 'B';
7196: } else {
7197: $thisallowed.=$value;
7198: }
1.1162 raeburn 7199: }
7200: } else {
7201: $thisallowed.=$value;
7202: }
1.52 www 7203: $checkreferer=0;
7204: }
1.29 www 7205: }
1.83 www 7206:
1.148 www 7207: if ($checkreferer) {
1.620 albertel 7208: my $refuri=$env{'httpref.'.$orguri};
1.148 www 7209: unless ($refuri) {
1.800 albertel 7210: foreach my $key (keys(%env)) {
7211: if ($key=~/^httpref\..*\*/) {
7212: my $pattern=$key;
1.156 www 7213: $pattern=~s/^httpref\.\/res\///;
1.148 www 7214: $pattern=~s/\*/\[\^\/\]\+/g;
7215: $pattern=~s/\//\\\//g;
1.152 www 7216: if ($orguri=~/$pattern/) {
1.800 albertel 7217: $refuri=$env{$key};
1.148 www 7218: }
7219: }
1.191 harris41 7220: }
1.148 www 7221: }
1.232 www 7222:
1.148 www 7223: if ($refuri) {
1.152 www 7224: $refuri=&declutter($refuri);
1.232 www 7225: my ($match,$cond)=&is_on_map($refuri);
7226: if ($match) {
7227: my $refstatecond=$cond;
1.620 albertel 7228: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 7229: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 7230: my $value = $1;
7231: if ($priv eq 'bre') {
1.1281 raeburn 7232: if ($noblockcheck) {
7233: $thisallowed.=$value;
1.1162 raeburn 7234: } else {
1.1281 raeburn 7235: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
7236: if (@blockers > 0) {
7237: $thisallowed = 'B';
7238: } else {
7239: $thisallowed.=$value;
7240: }
1.1162 raeburn 7241: }
7242: } else {
7243: $thisallowed.=$value;
7244: }
1.53 www 7245: $uri=$refuri;
7246: $statecond=$refstatecond;
1.52 www 7247: }
7248: }
1.148 www 7249: }
1.29 www 7250: }
1.52 www 7251: }
1.29 www 7252:
1.52 www 7253: #
1.103 harris41 7254: # Gathered now: all privileges that could apply, and condition number
1.52 www 7255: #
7256: #
7257: # Full or no access?
7258: #
1.29 www 7259:
1.52 www 7260: if ($thisallowed=~/F/) {
7261: return 'F';
7262: }
1.29 www 7263:
1.52 www 7264: unless ($thisallowed) {
7265: return '';
7266: }
1.29 www 7267:
1.52 www 7268: # Restrictions exist, deal with them
7269: #
7270: # C:according to course preferences
7271: # R:according to resource settings
7272: # L:unless locked
7273: # X:according to user session state
7274: #
7275:
7276: # Possibly locked functionality, check all courses
1.54 www 7277: # Locks might take effect only after 10 minutes cache expiration for other
7278: # courses, and 2 minutes for current course
1.52 www 7279:
7280: my $envkey;
7281: if ($thisallowed=~/L/) {
1.1000 raeburn 7282: foreach $envkey (keys(%env)) {
1.54 www 7283: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
7284: my $courseid=$2;
7285: my $roleid=$1.'.'.$2;
1.92 www 7286: $courseid=~s/^\///;
1.54 www 7287: my $expiretime=600;
1.620 albertel 7288: if ($env{'request.role'} eq $roleid) {
1.54 www 7289: $expiretime=120;
7290: }
7291: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
7292: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 7293: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 7294: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 7295: }
1.620 albertel 7296: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
7297: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
7298: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
7299: &log($env{'user.domain'},$env{'user.name'},
7300: $env{'user.home'},
1.57 www 7301: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 7302: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 7303: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 7304: return '';
7305: }
7306: }
1.620 albertel 7307: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
7308: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
7309: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
7310: &log($env{'user.domain'},$env{'user.name'},
7311: $env{'user.home'},
1.57 www 7312: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 7313: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 7314: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 7315: return '';
7316: }
7317: }
7318: }
1.29 www 7319: }
1.52 www 7320: }
7321:
7322: #
7323: # Rest of the restrictions depend on selected course
7324: #
7325:
1.620 albertel 7326: unless ($env{'request.course.id'}) {
1.766 albertel 7327: if ($thisallowed eq 'A') {
7328: return 'A';
1.814 raeburn 7329: } elsif ($thisallowed eq 'B') {
7330: return 'B';
1.766 albertel 7331: } else {
7332: return '1';
7333: }
1.52 www 7334: }
1.29 www 7335:
1.52 www 7336: #
7337: # Now user is definitely in a course
7338: #
1.53 www 7339:
7340:
7341: # Course preferences
7342:
7343: if ($thisallowed=~/C/) {
1.620 albertel 7344: my $rolecode=(split(/\./,$env{'request.role'}))[0];
7345: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
7346: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 7347: =~/\Q$rolecode\E/) {
1.1304 raeburn 7348: if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689 albertel 7349: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
7350: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
7351: $env{'request.course.id'});
7352: }
1.237 www 7353: return '';
7354: }
7355:
1.620 albertel 7356: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 7357: =~/\Q$unamedom\E/) {
1.1304 raeburn 7358: if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689 albertel 7359: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
7360: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
7361: $env{'request.course.id'});
7362: }
1.54 www 7363: return '';
7364: }
1.53 www 7365: }
7366:
7367: # Resource preferences
7368:
7369: if ($thisallowed=~/R/) {
1.620 albertel 7370: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 7371: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103 raeburn 7372: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7373: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
7374: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
7375: }
7376: return '';
1.54 www 7377: }
1.53 www 7378: }
1.30 www 7379:
1.246 www 7380: # Restricted by state or randomout?
1.30 www 7381:
1.52 www 7382: if ($thisallowed=~/X/) {
1.620 albertel 7383: if ($env{'acc.randomout'}) {
1.579 albertel 7384: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 7385: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 7386: return '';
7387: }
1.247 www 7388: }
7389: if (&condval($statecond)) {
1.52 www 7390: return '2';
7391: } else {
7392: return '';
7393: }
7394: }
1.30 www 7395:
1.766 albertel 7396: if ($thisallowed eq 'A') {
7397: return 'A';
1.814 raeburn 7398: } elsif ($thisallowed eq 'B') {
7399: return 'B';
1.766 albertel 7400: }
1.52 www 7401: return 'F';
1.232 www 7402: }
1.1162 raeburn 7403:
1.1192 raeburn 7404: # ------------------------------------------- Check construction space access
7405:
7406: sub constructaccess {
7407: my ($url,$setpriv)=@_;
7408:
7409: # We do not allow editing of previous versions of files
7410: if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
7411:
7412: # Get username and domain from URL
7413: my ($ownername,$ownerdomain,$ownerhome);
7414:
7415: ($ownerdomain,$ownername) =
1.1297 damieng 7416: ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)/});
1.1192 raeburn 7417:
7418: # The URL does not really point to any authorspace, forget it
7419: unless (($ownername) && ($ownerdomain)) { return ''; }
7420:
7421: # Now we need to see if the user has access to the authorspace of
7422: # $ownername at $ownerdomain
7423:
7424: if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
7425: # Real author for this?
7426: $ownerhome = $env{'user.home'};
7427: if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
7428: return ($ownername,$ownerdomain,$ownerhome);
7429: }
7430: } else {
7431: # Co-author for this?
7432: if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
7433: exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
7434: $ownerhome = &homeserver($ownername,$ownerdomain);
7435: return ($ownername,$ownerdomain,$ownerhome);
7436: }
1.1312 raeburn 7437: if ($env{'request.course.id'}) {
7438: if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
7439: ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
7440: if (&allowed('mdc',$env{'request.course.id'})) {
7441: $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
7442: return ($ownername,$ownerdomain,$ownerhome);
7443: }
7444: }
7445: }
1.1192 raeburn 7446: }
7447:
7448: # We don't have any access right now. If we are not possibly going to do anything about this,
7449: # we might as well leave
7450: unless ($setpriv) { return ''; }
7451:
7452: # Backdoor access?
7453: my $allowed=&allowed('eco',$ownerdomain);
7454: # Nope
7455: unless ($allowed) { return ''; }
7456: # Looks like we may have access, but could be locked by the owner of the construction space
7457: if ($allowed eq 'U') {
7458: my %blocked=&get('environment',['domcoord.author'],
7459: $ownerdomain,$ownername);
7460: # Is blocked by owner
7461: if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
7462: }
7463: if (($allowed eq 'F') || ($allowed eq 'U')) {
7464: # Grant temporary access
7465: my $then=$env{'user.login.time'};
1.1209 raeburn 7466: my $update=$env{'user.update.time'};
1.1192 raeburn 7467: if (!$update) { $update = $then; }
7468: my $refresh=$env{'user.refresh.time'};
7469: if (!$refresh) { $refresh = $update; }
7470: my $now = time;
7471: &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
7472: $now,'ca','constructaccess');
7473: $ownerhome = &homeserver($ownername,$ownerdomain);
7474: return($ownername,$ownerdomain,$ownerhome);
7475: }
7476: # No business here
7477: return '';
7478: }
7479:
1.1282 raeburn 7480: # ----------------------------------------------------------- Content Blocking
7481:
7482: {
7483: # Caches for faster Course Contents display where content blocking
7484: # is in operation (i.e., interval param set) for timed quiz.
7485: #
7486: # User for whom data are being temporarily cached.
7487: my $cacheduser='';
7488: # Cached blockers for this user (a hash of blocking items).
7489: my %cachedblockers=();
7490: # When the data were last cached.
7491: my $cachedlast='';
7492:
7493: sub load_all_blockers {
7494: my ($uname,$udom,$blocks)=@_;
7495: if (($uname ne '') && ($udom ne '')) {
7496: if (($cacheduser eq $uname.':'.$udom) &&
7497: (abs($cachedlast-time)<5)) {
7498: return;
7499: }
7500: }
7501: $cachedlast=time;
7502: $cacheduser=$uname.':'.$udom;
7503: %cachedblockers = &get_commblock_resources($blocks);
7504: }
7505:
1.1162 raeburn 7506: sub get_comm_blocks {
7507: my ($cdom,$cnum) = @_;
7508: if ($cdom eq '' || $cnum eq '') {
7509: return unless ($env{'request.course.id'});
7510: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7511: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7512: }
7513: my %commblocks;
7514: my $hashid=$cdom.'_'.$cnum;
7515: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
7516: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
7517: %commblocks = %{$blocksref};
7518: } else {
7519: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
7520: my $cachetime = 600;
7521: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
7522: }
7523: return %commblocks;
7524: }
7525:
1.1282 raeburn 7526: sub get_commblock_resources {
7527: my ($blocks) = @_;
7528: my %blockers = ();
7529: return %blockers unless ($env{'request.course.id'});
7530: return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162 raeburn 7531: my %commblocks;
7532: if (ref($blocks) eq 'HASH') {
7533: %commblocks = %{$blocks};
7534: } else {
7535: %commblocks = &get_comm_blocks();
7536: }
1.1282 raeburn 7537: return %blockers unless (keys(%commblocks) > 0);
7538: my $navmap = Apache::lonnavmaps::navmap->new();
7539: return %blockers unless (ref($navmap));
1.1162 raeburn 7540: my $now = time;
7541: foreach my $block (keys(%commblocks)) {
7542: if ($block =~ /^(\d+)____(\d+)$/) {
7543: my ($start,$end) = ($1,$2);
7544: if ($start <= $now && $end >= $now) {
7545: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7546: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
7547: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1282 raeburn 7548: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
7549: $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162 raeburn 7550: }
7551: }
7552: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1282 raeburn 7553: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
7554: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162 raeburn 7555: }
7556: }
7557: }
7558: }
7559: }
7560: } elsif ($block =~ /^firstaccess____(.+)$/) {
7561: my $item = $1;
1.1163 raeburn 7562: my @to_test;
1.1162 raeburn 7563: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7564: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1282 raeburn 7565: my @interval;
7566: my $type = 'map';
7567: if ($item eq 'course') {
7568: $type = 'course';
7569: @interval=&EXT("resource.0.interval");
7570: } else {
7571: if ($item =~ /___\d+___/) {
7572: $type = 'resource';
7573: @interval=&EXT("resource.0.interval",$item);
7574: if (ref($navmap)) {
7575: my $res = $navmap->getBySymb($item);
7576: push(@to_test,$res);
7577: }
1.1162 raeburn 7578: } else {
1.1282 raeburn 7579: my $mapsymb = &symbread($item,1);
7580: if ($mapsymb) {
7581: if (ref($navmap)) {
7582: my $mapres = $navmap->getBySymb($mapsymb);
7583: @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
7584: foreach my $res (@to_test) {
7585: my $symb = $res->symb();
7586: next if ($symb eq $mapsymb);
7587: if ($symb ne '') {
7588: @interval=&EXT("resource.0.interval",$symb);
7589: if ($interval[1] eq 'map') {
7590: last;
1.1162 raeburn 7591: }
7592: }
7593: }
7594: }
7595: }
7596: }
1.1282 raeburn 7597: }
1.1310 raeburn 7598: if ($interval[0] =~ /^(\d+)/) {
1.1308 raeburn 7599: my $timelimit = $1;
1.1282 raeburn 7600: my $first_access;
7601: if ($type eq 'resource') {
7602: $first_access=&get_first_access($interval[1],$item);
7603: } elsif ($type eq 'map') {
7604: $first_access=&get_first_access($interval[1],undef,$item);
7605: } else {
7606: $first_access=&get_first_access($interval[1]);
7607: }
7608: if ($first_access) {
1.1292 raeburn 7609: my $timesup = $first_access+$timelimit;
1.1282 raeburn 7610: if ($timesup > $now) {
7611: my $activeblock;
7612: foreach my $res (@to_test) {
1.1283 raeburn 7613: if ($res->answerable()) {
1.1282 raeburn 7614: $activeblock = 1;
7615: last;
7616: }
7617: }
7618: if ($activeblock) {
7619: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
7620: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
7621: $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
7622: }
7623: }
7624: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
7625: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
7626: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163 raeburn 7627: }
1.1162 raeburn 7628: }
7629: }
7630: }
7631: }
7632: }
7633: }
7634: }
7635: }
7636: }
1.1282 raeburn 7637: return %blockers;
1.1162 raeburn 7638: }
7639:
1.1282 raeburn 7640: sub has_comm_blocking {
7641: my ($priv,$symb,$uri,$blocks) = @_;
7642: my @blockers;
7643: return unless ($env{'request.course.id'});
7644: return unless ($priv eq 'bre');
7645: return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
7646: return if ($env{'request.state'} eq 'construct');
7647: &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
7648: return unless (keys(%cachedblockers) > 0);
7649: my (%possibles,@symbs);
7650: if (!$symb) {
7651: $symb = &symbread($uri,1,1,1,\%possibles);
1.1162 raeburn 7652: }
1.1282 raeburn 7653: if ($symb) {
7654: @symbs = ($symb);
7655: } elsif (keys(%possibles)) {
7656: @symbs = keys(%possibles);
7657: }
7658: my $noblock;
7659: foreach my $symb (@symbs) {
7660: last if ($noblock);
7661: my ($map,$resid,$resurl)=&decode_symb($symb);
7662: foreach my $block (keys(%cachedblockers)) {
7663: if ($block =~ /^firstaccess____(.+)$/) {
7664: my $item = $1;
7665: if (($item eq $map) || ($item eq $symb)) {
7666: $noblock = 1;
7667: last;
7668: }
7669: }
7670: if (ref($cachedblockers{$block}) eq 'HASH') {
7671: if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
7672: if ($cachedblockers{$block}{'resources'}{$symb}) {
7673: unless (grep(/^\Q$block\E$/,@blockers)) {
7674: push(@blockers,$block);
7675: }
7676: }
7677: }
1.1162 raeburn 7678: }
1.1282 raeburn 7679: if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
7680: if ($cachedblockers{$block}{'maps'}{$map}) {
7681: unless (grep(/^\Q$block\E$/,@blockers)) {
7682: push(@blockers,$block);
7683: }
7684: }
1.1162 raeburn 7685: }
7686: }
7687: }
1.1282 raeburn 7688: return if ($noblock);
7689: return @blockers;
7690: }
1.1162 raeburn 7691: }
7692:
1.1282 raeburn 7693: # -------------------------------- Deversion and split uri into path an filename
7694:
1.1133 foxr 7695: #
1.1282 raeburn 7696: # Removes the version from a URI and
1.1133 foxr 7697: # splits it in to its filename and path to the filename.
7698: # Seems like File::Basename could have done this more clearly.
7699: # Parameters:
7700: # $uri - input URI
7701: # Returns:
7702: # Two element list consisting of
7703: # $pathname - the URI up to and excluding the trailing /
7704: # $filename - The part of the URI following the last /
7705: # NOTE:
7706: # Another realization of this is simply:
7707: # use File::Basename;
7708: # ...
7709: # $uri = shift;
7710: # $filename = basename($uri);
7711: # $path = dirname($uri);
7712: # return ($filename, $path);
7713: #
7714: # The implementation below is probably faster however.
7715: #
1.710 albertel 7716: sub split_uri_for_cond {
7717: my $uri=&deversion(&declutter(shift));
7718: my @uriparts=split(/\//,$uri);
7719: my $filename=pop(@uriparts);
7720: my $pathname=join('/',@uriparts);
7721: return ($pathname,$filename);
7722: }
1.232 www 7723: # --------------------------------------------------- Is a resource on the map?
7724:
7725: sub is_on_map {
1.710 albertel 7726: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 7727: #Trying to find the conditional for the file
1.620 albertel 7728: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 7729: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 7730: if ($match) {
1.289 bowersj2 7731: return (1,$1);
7732: } else {
1.434 www 7733: return (0,0);
1.289 bowersj2 7734: }
1.12 www 7735: }
7736:
1.427 www 7737: # --------------------------------------------------------- Get symb from alias
7738:
7739: sub get_symb_from_alias {
7740: my $symb=shift;
7741: my ($map,$resid,$url)=&decode_symb($symb);
7742: # Already is a symb
7743: if ($url) { return $symb; }
7744: # Must be an alias
7745: my $aliassymb='';
7746: my %bighash;
1.620 albertel 7747: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 7748: &GDBM_READER(),0640)) {
7749: my $rid=$bighash{'mapalias_'.$symb};
7750: if ($rid) {
7751: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 7752: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
7753: $resid,$bighash{'src_'.$rid});
1.427 www 7754: }
7755: untie %bighash;
7756: }
7757: return $aliassymb;
7758: }
7759:
1.12 www 7760: # ----------------------------------------------------------------- Define Role
7761:
7762: sub definerole {
7763: if (allowed('mcr','/')) {
7764: my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800 albertel 7765: foreach my $role (split(':',$sysrole)) {
7766: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7767: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
7768: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
7769: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 7770: return "refused:s:$crole&$cqual";
7771: }
7772: }
1.191 harris41 7773: }
1.800 albertel 7774: foreach my $role (split(':',$domrole)) {
7775: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7776: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
7777: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
7778: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 7779: return "refused:d:$crole&$cqual";
7780: }
7781: }
1.191 harris41 7782: }
1.800 albertel 7783: foreach my $role (split(':',$courole)) {
7784: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7785: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
7786: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
7787: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 7788: return "refused:c:$crole&$cqual";
7789: }
7790: }
1.191 harris41 7791: }
1.620 albertel 7792: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
7793: "$env{'user.domain'}:$env{'user.name'}:".
1.21 www 7794: "rolesdef_$rolename=".
7795: escape($sysrole.'_'.$domrole.'_'.$courole);
1.620 albertel 7796: return reply($command,$env{'user.home'});
1.12 www 7797: } else {
7798: return 'refused';
7799: }
1.105 harris41 7800: }
7801:
7802: # ---------------- Make a metadata query against the network of library servers
7803:
7804: sub metadata_query {
1.1237 raeburn 7805: my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120 harris41 7806: my %rhash;
1.845 albertel 7807: my %libserv = &all_library();
1.244 matthew 7808: my @server_list = (defined($server_array) ? @$server_array
7809: : keys(%libserv) );
7810: for my $server (@server_list) {
1.1237 raeburn 7811: my $domains = '';
7812: if (ref($domains_hash) eq 'HASH') {
7813: $domains = $domains_hash->{$server};
7814: }
1.118 harris41 7815: unless ($custom or $customshow) {
1.1237 raeburn 7816: my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118 harris41 7817: $rhash{$server}=$reply;
7818: }
7819: else {
7820: my $reply=&reply("querysend:".&escape($query).':'.
1.1237 raeburn 7821: &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118 harris41 7822: $server);
7823: $rhash{$server}=$reply;
7824: }
1.112 harris41 7825: }
1.118 harris41 7826: return \%rhash;
1.240 www 7827: }
7828:
7829: # ----------------------------------------- Send log queries and wait for reply
7830:
7831: sub log_query {
7832: my ($uname,$udom,$query,%filters)=@_;
7833: my $uhome=&homeserver($uname,$udom);
7834: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 7835: my $uhost=&hostname($uhome);
1.800 albertel 7836: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 7837: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
7838: $uhome);
1.479 albertel 7839: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 7840: return get_query_reply($queryid);
7841: }
7842:
1.818 raeburn 7843: # -------------------------- Update MySQL table for portfolio file
7844:
7845: sub update_portfolio_table {
1.821 raeburn 7846: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 7847: if ($group ne '') {
7848: $file_name =~s /^\Q$group\E//;
7849: }
1.818 raeburn 7850: my $homeserver = &homeserver($uname,$udom);
7851: my $queryid=
1.821 raeburn 7852: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
7853: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 7854: my $reply = &get_query_reply($queryid);
7855: return $reply;
7856: }
7857:
1.899 raeburn 7858: # -------------------------- Update MySQL allusers table
7859:
7860: sub update_allusers_table {
7861: my ($uname,$udom,$names) = @_;
7862: my $homeserver = &homeserver($uname,$udom);
7863: my $queryid=
7864: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
7865: 'lastname='.&escape($names->{'lastname'}).'%%'.
7866: 'firstname='.&escape($names->{'firstname'}).'%%'.
7867: 'middlename='.&escape($names->{'middlename'}).'%%'.
7868: 'generation='.&escape($names->{'generation'}).'%%'.
7869: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
7870: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 7871: return;
1.899 raeburn 7872: }
7873:
1.508 raeburn 7874: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 7875:
7876: sub fetch_enrollment_query {
1.511 raeburn 7877: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1317 ! raeburn 7878: my ($homeserver,$sleep,$loopmax);
1.547 raeburn 7879: my $maxtries = 1;
1.508 raeburn 7880: if ($context eq 'automated') {
7881: $homeserver = $perlvar{'lonHostID'};
1.1317 ! raeburn 7882: $sleep = 2;
! 7883: $loopmax = 100;
1.547 raeburn 7884: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 7885: } else {
7886: $homeserver = &homeserver($cnum,$dom);
7887: }
1.838 albertel 7888: my $host=&hostname($homeserver);
1.506 raeburn 7889: my $cmd = '';
1.1000 raeburn 7890: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 7891: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 7892: }
7893: $cmd =~ s/%%$//;
7894: $cmd = &escape($cmd);
7895: my $query = 'fetchenrollment';
1.620 albertel 7896: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 7897: unless ($queryid=~/^\Q$host\E\_/) {
7898: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
7899: return 'error: '.$queryid;
7900: }
1.1317 ! raeburn 7901: my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547 raeburn 7902: my $tries = 1;
7903: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1317 ! raeburn 7904: $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547 raeburn 7905: $tries ++;
7906: }
1.526 raeburn 7907: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 7908: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 7909: } else {
1.901 albertel 7910: my @responses = split(/:/,$reply);
1.515 raeburn 7911: if ($homeserver eq $perlvar{'lonHostID'}) {
1.800 albertel 7912: foreach my $line (@responses) {
7913: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 7914: $$replyref{$key} = $value;
7915: }
7916: } else {
1.1117 foxr 7917: my $pathname = LONCAPA::tempdir();
1.800 albertel 7918: foreach my $line (@responses) {
7919: my ($key,$value) = split(/=/,$line);
1.506 raeburn 7920: $$replyref{$key} = $value;
7921: if ($value > 0) {
1.800 albertel 7922: foreach my $item (@{$$affiliatesref{$key}}) {
7923: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 7924: my $destname = $pathname.'/'.$filename;
7925: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 7926: if ($xml_classlist =~ /^error/) {
7927: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
7928: } else {
1.506 raeburn 7929: if ( open(FILE,">$destname") ) {
7930: print FILE &unescape($xml_classlist);
7931: close(FILE);
1.526 raeburn 7932: } else {
7933: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 7934: }
7935: }
7936: }
7937: }
7938: }
7939: }
7940: return 'ok';
7941: }
7942: return 'error';
7943: }
7944:
1.242 www 7945: sub get_query_reply {
1.1317 ! raeburn 7946: my ($queryid,$sleep,$loopmax) = @_;;
! 7947: if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
! 7948: $sleep = 0.2;
! 7949: }
! 7950: if (($loopmax eq '') || ($loopmax =~ /\D/)) {
! 7951: $loopmax = 100;
! 7952: }
1.1117 foxr 7953: my $replyfile=LONCAPA::tempdir().$queryid;
1.240 www 7954: my $reply='';
1.1317 ! raeburn 7955: for (1..$loopmax) {
! 7956: sleep($sleep);
1.240 www 7957: if (-e $replyfile.'.end') {
1.448 albertel 7958: if (open(my $fh,$replyfile)) {
1.904 albertel 7959: $reply = join('',<$fh>);
7960: close($fh);
1.240 www 7961: } else { return 'error: reply_file_error'; }
1.242 www 7962: return &unescape($reply);
7963: }
1.240 www 7964: }
1.242 www 7965: return 'timeout:'.$queryid;
1.240 www 7966: }
7967:
7968: sub courselog_query {
1.241 www 7969: #
7970: # possible filters:
7971: # url: url or symb
7972: # username
7973: # domain
7974: # action: view, submit, grade
7975: # start: timestamp
7976: # end: timestamp
7977: #
1.240 www 7978: my (%filters)=@_;
1.620 albertel 7979: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 7980: if ($filters{'url'}) {
7981: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
7982: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
7983: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
7984: }
1.620 albertel 7985: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
7986: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 7987: return &log_query($cname,$cdom,'courselog',%filters);
7988: }
7989:
7990: sub userlog_query {
1.858 raeburn 7991: #
7992: # possible filters:
7993: # action: log check role
7994: # start: timestamp
7995: # end: timestamp
7996: #
1.240 www 7997: my ($uname,$udom,%filters)=@_;
7998: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 7999: }
8000:
1.506 raeburn 8001: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
8002:
8003: sub auto_run {
1.508 raeburn 8004: my ($cnum,$cdom) = @_;
1.876 raeburn 8005: my $response = 0;
8006: my $settings;
8007: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
8008: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
8009: $settings = $domconfig{'autoenroll'};
8010: if ($settings->{'run'} eq '1') {
8011: $response = 1;
8012: }
8013: } else {
1.934 raeburn 8014: my $homeserver;
8015: if (&is_course($cdom,$cnum)) {
8016: $homeserver = &homeserver($cnum,$cdom);
8017: } else {
8018: $homeserver = &domain($cdom,'primary');
8019: }
8020: if ($homeserver ne 'no_host') {
8021: $response = &reply('autorun:'.$cdom,$homeserver);
8022: }
1.876 raeburn 8023: }
1.506 raeburn 8024: return $response;
8025: }
1.776 albertel 8026:
1.506 raeburn 8027: sub auto_get_sections {
1.508 raeburn 8028: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 8029: my $homeserver;
8030: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
8031: $homeserver = &homeserver($cnum,$cdom);
8032: }
8033: if (!defined($homeserver)) {
8034: if ($cdom =~ /^$match_domain$/) {
8035: $homeserver = &domain($cdom,'primary');
8036: }
8037: }
8038: my @secs;
8039: if (defined($homeserver)) {
8040: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
8041: unless ($response eq 'refused') {
8042: @secs = split(/:/,$response);
8043: }
1.506 raeburn 8044: }
8045: return @secs;
8046: }
1.776 albertel 8047:
1.506 raeburn 8048: sub auto_new_course {
1.1099 raeburn 8049: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 8050: my $homeserver = &homeserver($cnum,$cdom);
1.1099 raeburn 8051: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 8052: return $response;
8053: }
1.776 albertel 8054:
1.506 raeburn 8055: sub auto_validate_courseID {
1.508 raeburn 8056: my ($cnum,$cdom,$inst_course_id) = @_;
8057: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 8058: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 8059: return $response;
8060: }
1.776 albertel 8061:
1.1007 raeburn 8062: sub auto_validate_instcode {
1.1020 raeburn 8063: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 8064: my ($homeserver,$response);
8065: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
8066: $homeserver = &homeserver($cnum,$cdom);
8067: }
8068: if (!defined($homeserver)) {
8069: if ($cdom =~ /^$match_domain$/) {
8070: $homeserver = &domain($cdom,'primary');
8071: }
8072: }
1.1065 raeburn 8073: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
8074: &escape($instcode).':'.&escape($owner),$homeserver));
1.1216 raeburn 8075: my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
8076: return ($outcome,$description,$defaultcredits);
1.1007 raeburn 8077: }
8078:
1.506 raeburn 8079: sub auto_create_password {
1.873 raeburn 8080: my ($cnum,$cdom,$authparam,$udom) = @_;
8081: my ($homeserver,$response);
1.506 raeburn 8082: my $create_passwd = 0;
8083: my $authchk = '';
1.873 raeburn 8084: if ($udom =~ /^$match_domain$/) {
8085: $homeserver = &domain($udom,'primary');
8086: }
8087: if ($homeserver eq '') {
8088: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
8089: $homeserver = &homeserver($cnum,$cdom);
8090: }
8091: }
8092: if ($homeserver eq '') {
8093: $authchk = 'nodomain';
1.506 raeburn 8094: } else {
1.873 raeburn 8095: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
8096: if ($response eq 'refused') {
8097: $authchk = 'refused';
8098: } else {
1.901 albertel 8099: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 8100: }
1.506 raeburn 8101: }
8102: return ($authparam,$create_passwd,$authchk);
8103: }
8104:
1.706 raeburn 8105: sub auto_photo_permission {
8106: my ($cnum,$cdom,$students) = @_;
8107: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 8108: my ($outcome,$perm_reqd,$conditions) =
8109: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 8110: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
8111: return (undef,undef);
8112: }
1.706 raeburn 8113: return ($outcome,$perm_reqd,$conditions);
8114: }
8115:
8116: sub auto_checkphotos {
8117: my ($uname,$udom,$pid) = @_;
8118: my $homeserver = &homeserver($uname,$udom);
8119: my ($result,$resulttype);
8120: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 8121: &escape($uname).':'.&escape($pid),
8122: $homeserver));
1.709 albertel 8123: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
8124: return (undef,undef);
8125: }
1.706 raeburn 8126: if ($outcome) {
8127: ($result,$resulttype) = split(/:/,$outcome);
8128: }
8129: return ($result,$resulttype);
8130: }
8131:
8132: sub auto_photochoice {
8133: my ($cnum,$cdom) = @_;
8134: my $homeserver = &homeserver($cnum,$cdom);
8135: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 8136: &escape($cdom),
8137: $homeserver)));
1.709 albertel 8138: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
8139: return (undef,undef);
8140: }
1.706 raeburn 8141: return ($update,$comment);
8142: }
8143:
8144: sub auto_photoupdate {
8145: my ($affiliatesref,$dom,$cnum,$photo) = @_;
8146: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 8147: my $host=&hostname($homeserver);
1.706 raeburn 8148: my $cmd = '';
8149: my $maxtries = 1;
1.800 albertel 8150: foreach my $affiliate (keys(%{$affiliatesref})) {
8151: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 8152: }
8153: $cmd =~ s/%%$//;
8154: $cmd = &escape($cmd);
8155: my $query = 'institutionalphotos';
8156: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
8157: unless ($queryid=~/^\Q$host\E\_/) {
8158: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
8159: return 'error: '.$queryid;
8160: }
8161: my $reply = &get_query_reply($queryid);
8162: my $tries = 1;
8163: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
8164: $reply = &get_query_reply($queryid);
8165: $tries ++;
8166: }
8167: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
8168: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
8169: } else {
8170: my @responses = split(/:/,$reply);
8171: my $outcome = shift(@responses);
8172: foreach my $item (@responses) {
8173: my ($key,$value) = split(/=/,$item);
8174: $$photo{$key} = $value;
8175: }
8176: return $outcome;
8177: }
8178: return 'error';
8179: }
8180:
1.521 raeburn 8181: sub auto_instcode_format {
1.793 albertel 8182: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
8183: $cat_order) = @_;
1.521 raeburn 8184: my $courses = '';
1.772 raeburn 8185: my @homeservers;
1.521 raeburn 8186: if ($caller eq 'global') {
1.841 albertel 8187: my %servers = &get_servers($codedom,'library');
8188: foreach my $tryserver (keys(%servers)) {
8189: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
8190: push(@homeservers,$tryserver);
8191: }
1.584 raeburn 8192: }
1.1022 raeburn 8193: } elsif ($caller eq 'requests') {
8194: if ($codedom =~ /^$match_domain$/) {
8195: my $chome = &domain($codedom,'primary');
8196: unless ($chome eq 'no_host') {
8197: push(@homeservers,$chome);
8198: }
8199: }
1.521 raeburn 8200: } else {
1.772 raeburn 8201: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 8202: }
1.793 albertel 8203: foreach my $code (keys(%{$instcodes})) {
8204: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 8205: }
8206: chop($courses);
1.772 raeburn 8207: my $ok_response = 0;
8208: my $response;
8209: while (@homeservers > 0 && $ok_response == 0) {
8210: my $server = shift(@homeservers);
8211: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
8212: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
8213: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 8214: split(/:/,$response);
1.772 raeburn 8215: %{$codes} = (%{$codes},&str2hash($codes_str));
8216: push(@{$codetitles},&str2array($codetitles_str));
8217: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
8218: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
8219: $ok_response = 1;
8220: }
8221: }
8222: if ($ok_response) {
1.521 raeburn 8223: return 'ok';
1.772 raeburn 8224: } else {
8225: return $response;
1.521 raeburn 8226: }
8227: }
8228:
1.792 raeburn 8229: sub auto_instcode_defaults {
8230: my ($domain,$returnhash,$code_order) = @_;
8231: my @homeservers;
1.841 albertel 8232:
8233: my %servers = &get_servers($domain,'library');
8234: foreach my $tryserver (keys(%servers)) {
8235: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
8236: push(@homeservers,$tryserver);
8237: }
1.792 raeburn 8238: }
1.841 albertel 8239:
1.792 raeburn 8240: my $response;
1.841 albertel 8241: foreach my $server (@homeservers) {
1.792 raeburn 8242: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 8243: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
8244:
8245: foreach my $pair (split(/\&/,$response)) {
8246: my ($name,$value)=split(/\=/,$pair);
8247: if ($name eq 'code_order') {
8248: @{$code_order} = split(/\&/,&unescape($value));
8249: } else {
8250: $returnhash->{&unescape($name)}=&unescape($value);
8251: }
8252: }
8253: return 'ok';
1.792 raeburn 8254: }
1.841 albertel 8255:
8256: return $response;
1.1003 raeburn 8257: }
8258:
8259: sub auto_possible_instcodes {
1.1007 raeburn 8260: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
8261: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
8262: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
8263: return;
8264: }
1.1003 raeburn 8265: my (@homeservers,$uhome);
8266: if (defined(&domain($domain,'primary'))) {
8267: $uhome=&domain($domain,'primary');
8268: push(@homeservers,&domain($domain,'primary'));
8269: } else {
8270: my %servers = &get_servers($domain,'library');
8271: foreach my $tryserver (keys(%servers)) {
8272: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
8273: push(@homeservers,$tryserver);
8274: }
8275: }
8276: }
8277: my $response;
8278: foreach my $server (@homeservers) {
8279: $response=&reply('autopossibleinstcodes:'.$domain,$server);
8280: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 8281: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
8282: split(':',$response);
8283: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
8284: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 8285: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 8286: my ($name,$value)=split('=',$item);
8287: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 8288: }
8289: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 8290: my ($name,$value)=split('=',$item);
8291: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 8292: }
8293: return 'ok';
8294: }
8295: return $response;
8296: }
1.792 raeburn 8297:
1.1010 raeburn 8298: sub auto_courserequest_checks {
8299: my ($dom) = @_;
1.1020 raeburn 8300: my ($homeserver,%validations);
8301: if ($dom =~ /^$match_domain$/) {
8302: $homeserver = &domain($dom,'primary');
8303: }
8304: unless ($homeserver eq 'no_host') {
8305: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
8306: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
8307: my @items = split(/&/,$response);
8308: foreach my $item (@items) {
8309: my ($key,$value) = split('=',$item);
8310: $validations{&unescape($key)} = &thaw_unescape($value);
8311: }
8312: }
8313: }
1.1010 raeburn 8314: return %validations;
8315: }
8316:
1.1020 raeburn 8317: sub auto_courserequest_validation {
1.1255 raeburn 8318: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020 raeburn 8319: my ($homeserver,$response);
8320: if ($dom =~ /^$match_domain$/) {
8321: $homeserver = &domain($dom,'primary');
8322: }
1.1255 raeburn 8323: unless ($homeserver eq 'no_host') {
8324: my $customdata;
8325: if (ref($custominfo) eq 'HASH') {
8326: $customdata = &freeze_escape($custominfo);
8327: }
1.1020 raeburn 8328: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 8329: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1255 raeburn 8330: ':'.&escape($instcode).':'.&escape($instseclist).':'.
8331: $customdata,$homeserver));
1.1020 raeburn 8332: }
8333: return $response;
8334: }
8335:
1.777 albertel 8336: sub auto_validate_class_sec {
1.918 raeburn 8337: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 8338: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 8339: my $ownerlist;
8340: if (ref($owners) eq 'ARRAY') {
8341: $ownerlist = join(',',@{$owners});
8342: } else {
8343: $ownerlist = $owners;
8344: }
1.773 raeburn 8345: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 8346: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 8347: return $response;
8348: }
8349:
1.1248 raeburn 8350: sub auto_crsreq_update {
8351: my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1257 raeburn 8352: $code,$accessstart,$accessend,$inbound) = @_;
1.1248 raeburn 8353: my ($homeserver,%crsreqresponse);
8354: if ($cdom =~ /^$match_domain$/) {
8355: $homeserver = &domain($cdom,'primary');
8356: }
8357: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
8358: my $info;
8359: if (ref($inbound) eq 'HASH') {
8360: $info = &freeze_escape($inbound);
8361: }
8362: my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
8363: ':'.&escape($action).':'.&escape($ownername).':'.
8364: &escape($ownerdomain).':'.&escape($fullname).':'.
1.1257 raeburn 8365: &escape($title).':'.&escape($code).':'.
8366: &escape($accessstart).':'.&escape($accessend).':'.$info,
8367: $homeserver);
1.1248 raeburn 8368: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
8369: my @items = split(/&/,$response);
8370: foreach my $item (@items) {
8371: my ($key,$value) = split('=',$item);
8372: $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
8373: }
8374: }
8375: }
8376: return \%crsreqresponse;
8377: }
8378:
1.1305 raeburn 8379: sub auto_export_grades {
1.1309 raeburn 8380: my ($cdom,$cnum,$inforef,$gradesref) = @_;
8381: my ($homeserver,%exportresponse);
8382: if ($cdom =~ /^$match_domain$/) {
8383: $homeserver = &domain($cdom,'primary');
8384: }
8385: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
8386: my $info;
8387: if (ref($inforef) eq 'HASH') {
8388: $info = &freeze_escape($inforef);
8389: }
8390: if (ref($gradesref) eq 'HASH') {
8391: my $grades = &freeze_escape($gradesref);
8392: my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
8393: $info.':'.$grades,$homeserver);
8394: unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
8395: my @items = split(/&/,$response);
8396: foreach my $item (@items) {
8397: my ($key,$value) = split('=',$item);
8398: $exportresponse{&unescape($key)} = &thaw_unescape($value);
8399: }
8400: }
8401: }
8402: }
8403: return \%exportresponse;
1.1305 raeburn 8404: }
8405:
1.1287 raeburn 8406: sub check_instcode_cloning {
8407: my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
8408: unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
8409: return;
8410: }
8411: my $canclone;
8412: if (@{$code_order} > 0) {
8413: my $instcoderegexp ='^';
8414: my @clonecodes = split(/\&/,$cloner);
8415: foreach my $item (@{$code_order}) {
8416: if (grep(/^\Q$item\E=/,@clonecodes)) {
8417: foreach my $pair (@clonecodes) {
8418: my ($key,$val) = split(/\=/,$pair,2);
8419: $val = &unescape($val);
8420: if ($key eq $item) {
8421: $instcoderegexp .= '('.$val.')';
8422: last;
8423: }
8424: }
8425: } else {
8426: $instcoderegexp .= $codedefaults->{$item};
8427: }
8428: }
8429: $instcoderegexp .= '$';
8430: my (@from,@to);
8431: eval {
8432: (@from) = ($clonefromcode =~ /$instcoderegexp/);
8433: (@to) = ($clonetocode =~ /$instcoderegexp/);
8434: };
8435: if ((@from > 0) && (@to > 0)) {
8436: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
8437: if (!@diffs) {
8438: $canclone = 1;
8439: }
8440: }
8441: }
8442: return $canclone;
8443: }
8444:
8445: sub default_instcode_cloning {
8446: my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
8447: my (%codedefaults,@code_order,$canclone);
8448: if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
8449: %codedefaults = %{$codedefaultsref};
8450: @code_order = @{$codeorderref};
8451: } elsif ($clonedom) {
8452: &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
8453: }
8454: if (($domdefclone) && (@code_order)) {
8455: my @clonecodes = split(/\+/,$domdefclone);
8456: my $instcoderegexp ='^';
8457: foreach my $item (@code_order) {
8458: if (grep(/^\Q$item\E$/,@clonecodes)) {
8459: $instcoderegexp .= '('.$codedefaults{$item}.')';
8460: } else {
8461: $instcoderegexp .= $codedefaults{$item};
8462: }
8463: }
8464: $instcoderegexp .= '$';
8465: my (@from,@to);
8466: eval {
8467: (@from) = ($clonefromcode =~ /$instcoderegexp/);
8468: (@to) = ($clonetocode =~ /$instcoderegexp/);
8469: };
8470: if ((@from > 0) && (@to > 0)) {
8471: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
8472: if (!@diffs) {
8473: $canclone = 1;
8474: }
8475: }
8476: }
8477: return $canclone;
8478: }
8479:
1.679 raeburn 8480: # ------------------------------------------------------- Course Group routines
8481:
8482: sub get_coursegroups {
1.809 raeburn 8483: my ($cdom,$cnum,$group,$namespace) = @_;
8484: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 8485: }
8486:
1.679 raeburn 8487: sub modify_coursegroup {
8488: my ($cdom,$cnum,$groupsettings) = @_;
8489: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
8490: }
8491:
1.809 raeburn 8492: sub toggle_coursegroup_status {
8493: my ($cdom,$cnum,$group,$action) = @_;
8494: my ($from_namespace,$to_namespace);
8495: if ($action eq 'delete') {
8496: $from_namespace = 'coursegroups';
8497: $to_namespace = 'deleted_groups';
8498: } else {
8499: $from_namespace = 'deleted_groups';
8500: $to_namespace = 'coursegroups';
8501: }
8502: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 8503: if (my $tmp = &error(%curr_group)) {
8504: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
8505: return ('read error',$tmp);
8506: } else {
8507: my %savedsettings = %curr_group;
1.809 raeburn 8508: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 8509: my $deloutcome;
8510: if ($result eq 'ok') {
1.809 raeburn 8511: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 8512: } else {
8513: return ('write error',$result);
8514: }
8515: if ($deloutcome eq 'ok') {
8516: return 'ok';
8517: } else {
8518: return ('delete error',$deloutcome);
8519: }
8520: }
8521: }
8522:
1.679 raeburn 8523: sub modify_group_roles {
1.957 raeburn 8524: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 8525: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
8526: my $role = 'gr/'.&escape($userprivs);
8527: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 8528: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 8529: if ($result eq 'ok') {
8530: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
8531: }
1.679 raeburn 8532: return $result;
8533: }
8534:
8535: sub modify_coursegroup_membership {
8536: my ($cdom,$cnum,$membership) = @_;
8537: my $result = &put('groupmembership',$membership,$cdom,$cnum);
8538: return $result;
8539: }
8540:
1.682 raeburn 8541: sub get_active_groups {
8542: my ($udom,$uname,$cdom,$cnum) = @_;
8543: my $now = time;
8544: my %groups = ();
8545: foreach my $key (keys(%env)) {
1.811 albertel 8546: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 8547: my ($start,$end) = split(/\./,$env{$key});
8548: if (($end!=0) && ($end<$now)) { next; }
8549: if (($start!=0) && ($start>$now)) { next; }
8550: if ($1 eq $cdom && $2 eq $cnum) {
8551: $groups{$3} = $env{$key} ;
8552: }
8553: }
8554: }
8555: return %groups;
8556: }
8557:
1.683 raeburn 8558: sub get_group_membership {
8559: my ($cdom,$cnum,$group) = @_;
8560: return(&dump('groupmembership',$cdom,$cnum,$group));
8561: }
8562:
8563: sub get_users_groups {
8564: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 8565: my @usersgroups;
1.683 raeburn 8566: my $cachetime=1800;
8567:
8568: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 8569: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
8570: if (defined($cached)) {
1.734 albertel 8571: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 8572: } else {
8573: $grouplist = '';
1.816 raeburn 8574: my $courseurl = &courseid_to_courseurl($courseid);
1.1166 raeburn 8575: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 8576: my $access_end = $env{'course.'.$courseid.
8577: '.default_enrollment_end_date'};
8578: my $now = time;
8579: foreach my $key (keys(%roleshash)) {
8580: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
8581: my $group = $1;
8582: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
8583: my $start = $2;
8584: my $end = $1;
8585: if ($start == -1) { next; } # deleted from group
8586: if (($start!=0) && ($start>$now)) { next; }
8587: if (($end!=0) && ($end<$now)) {
8588: if ($access_end && $access_end < $now) {
8589: if ($access_end - $end < 86400) {
8590: push(@usersgroups,$group);
1.733 raeburn 8591: }
8592: }
1.817 raeburn 8593: next;
1.733 raeburn 8594: }
1.817 raeburn 8595: push(@usersgroups,$group);
1.683 raeburn 8596: }
8597: }
8598: }
1.817 raeburn 8599: @usersgroups = &sort_course_groups($courseid,@usersgroups);
8600: $grouplist = join(':',@usersgroups);
8601: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 8602: }
1.733 raeburn 8603: return @usersgroups;
1.683 raeburn 8604: }
8605:
8606: sub devalidate_getgroups_cache {
8607: my ($udom,$uname,$cdom,$cnum)=@_;
8608: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 8609:
1.683 raeburn 8610: my $hashid="$udom:$uname:$courseid";
8611: &devalidate_cache_new('getgroups',$hashid);
8612: }
8613:
1.12 www 8614: # ------------------------------------------------------------------ Plain Text
8615:
8616: sub plaintext {
1.988 raeburn 8617: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 8618: if ($short =~ m{^cr/}) {
1.758 albertel 8619: return (split('/',$short))[-1];
8620: }
1.742 raeburn 8621: if (!defined($cid)) {
8622: $cid = $env{'request.course.id'};
8623: }
8624: my %rolenames = (
1.1008 raeburn 8625: Course => 'std',
8626: Community => 'alt1',
1.1305 raeburn 8627: Placement => 'std',
1.742 raeburn 8628: );
1.1037 raeburn 8629: if ($cid ne '') {
8630: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
8631: unless ($forcedefault) {
8632: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
8633: &Apache::lonlocal::mt_escape(\$roletext);
8634: return &Apache::lonlocal::mt($roletext);
8635: }
8636: }
8637: }
8638: if ((defined($type)) && (defined($rolenames{$type})) &&
8639: (defined($rolenames{$type})) &&
8640: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 8641: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 8642: } elsif ($cid ne '') {
8643: my $crstype = $env{'course.'.$cid.'.type'};
8644: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
8645: (defined($prp{$short}{$rolenames{$crstype}}))) {
8646: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
8647: }
1.742 raeburn 8648: }
1.1037 raeburn 8649: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 8650: }
8651:
8652: # ----------------------------------------------------------------- Assign Role
8653:
8654: sub assignrole {
1.957 raeburn 8655: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
8656: $context)=@_;
1.21 www 8657: my $mrole;
8658: if ($role =~ /^cr\//) {
1.393 www 8659: my $cwosec=$url;
1.811 albertel 8660: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 8661: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 8662: my $refused = 1;
8663: if ($context eq 'requestcourses') {
8664: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
8665: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
8666: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
8667: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8668: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8669: if ($crsenv{'internal.courseowner'} eq
8670: $env{'user.name'}.':'.$env{'user.domain'}) {
8671: $refused = '';
8672: }
8673: }
8674: }
8675: }
8676: }
8677: if ($refused) {
8678: &logthis('Refused custom assignrole: '.
8679: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
8680: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
8681: return 'refused';
8682: }
1.104 www 8683: }
1.21 www 8684: $mrole='cr';
1.678 raeburn 8685: } elsif ($role =~ /^gr\//) {
8686: my $cwogrp=$url;
1.811 albertel 8687: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 8688: unless (&allowed('mdg',$cwogrp)) {
8689: &logthis('Refused group assignrole: '.
8690: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
8691: $env{'user.name'}.' at '.$env{'user.domain'});
8692: return 'refused';
8693: }
8694: $mrole='gr';
1.21 www 8695: } else {
1.82 www 8696: my $cwosec=$url;
1.811 albertel 8697: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 8698: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
8699: my $refused;
8700: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
8701: if (!(&allowed('c'.$role,$url))) {
8702: $refused = 1;
8703: }
8704: } else {
8705: $refused = 1;
8706: }
1.947 raeburn 8707: if ($refused) {
1.1045 raeburn 8708: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8709: if (!$selfenroll && $context eq 'course') {
8710: my %crsenv;
8711: if ($role eq 'cc' || $role eq 'co') {
8712: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8713: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
8714: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
8715: if ($crsenv{'internal.courseowner'} eq
8716: $env{'user.name'}.':'.$env{'user.domain'}) {
8717: $refused = '';
8718: }
8719: }
8720: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
8721: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
8722: if ($crsenv{'internal.courseowner'} eq
8723: $env{'user.name'}.':'.$env{'user.domain'}) {
8724: $refused = '';
8725: }
8726: }
8727: }
8728: }
8729: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 8730: $refused = '';
1.1017 raeburn 8731: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 8732: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 8733: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 8734: my $wrongcc;
8735: if ($cnum =~ /^$match_community$/) {
8736: $wrongcc = 1 if ($role eq 'cc');
8737: } else {
8738: $wrongcc = 1 if ($role eq 'co');
8739: }
8740: unless ($wrongcc) {
8741: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8742: if ($crsenv{'internal.courseowner'} eq
8743: $env{'user.name'}.':'.$env{'user.domain'}) {
8744: $refused = '';
8745: }
1.1017 raeburn 8746: }
8747: }
1.1183 raeburn 8748: } elsif ($context eq 'requestauthor') {
8749: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
8750: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
8751: if ($env{'environment.requestauthor'} eq 'automatic') {
8752: $refused = '';
8753: } else {
8754: my %domdefaults = &get_domain_defaults($udom);
8755: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
8756: my $checkbystatus;
8757: if ($env{'user.adv'}) {
8758: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
8759: if ($disposition eq 'automatic') {
8760: $refused = '';
8761: } elsif ($disposition eq '') {
8762: $checkbystatus = 1;
8763: }
8764: } else {
8765: $checkbystatus = 1;
8766: }
8767: if ($checkbystatus) {
8768: if ($env{'environment.inststatus'}) {
8769: my @inststatuses = split(/,/,$env{'environment.inststatus'});
8770: foreach my $type (@inststatuses) {
8771: if (($type ne '') &&
8772: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
8773: $refused = '';
8774: }
8775: }
8776: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
8777: $refused = '';
8778: }
8779: }
8780: }
8781: }
8782: }
1.1017 raeburn 8783: }
8784: if ($refused) {
1.947 raeburn 8785: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
8786: ' '.$role.' '.$end.' '.$start.' by '.
8787: $env{'user.name'}.' at '.$env{'user.domain'});
8788: return 'refused';
8789: }
1.932 raeburn 8790: }
1.1131 raeburn 8791: } elsif ($role eq 'au') {
8792: if ($url ne '/'.$udom.'/') {
8793: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
8794: ' to assign author role for '.$uname.':'.$udom.
8795: ' in domain: '.$url.' refused (wrong domain).');
8796: return 'refused';
8797: }
1.104 www 8798: }
1.21 www 8799: $mrole=$role;
8800: }
1.620 albertel 8801: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 8802: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 8803: if ($end) { $command.='_'.$end; }
1.21 www 8804: if ($start) {
8805: if ($end) {
1.81 www 8806: $command.='_'.$start;
1.21 www 8807: } else {
1.81 www 8808: $command.='_0_'.$start;
1.21 www 8809: }
8810: }
1.739 raeburn 8811: my $origstart = $start;
8812: my $origend = $end;
1.957 raeburn 8813: my $delflag;
1.357 www 8814: # actually delete
8815: if ($deleteflag) {
1.373 www 8816: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 8817: # modify command to delete the role
1.620 albertel 8818: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 8819: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 8820: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 8821: # set start and finish to negative values for userrolelog
8822: $start=-1;
8823: $end=-1;
1.957 raeburn 8824: $delflag = 1;
1.357 www 8825: }
8826: }
8827: # send command
1.349 www 8828: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 8829: # log new user role if status is ok
1.349 www 8830: if ($answer eq 'ok') {
1.663 raeburn 8831: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.1184 raeburn 8832: if (($role eq 'cc') || ($role eq 'in') ||
8833: ($role eq 'ep') || ($role eq 'ad') ||
8834: ($role eq 'ta') || ($role eq 'st') ||
8835: ($role=~/^cr/) || ($role eq 'gr') ||
8836: ($role eq 'co')) {
1.1200 raeburn 8837: # for course roles, perform group memberships changes triggered by role change.
8838: unless ($role =~ /^gr/) {
8839: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
8840: $origstart,$selfenroll,$context);
8841: }
1.1184 raeburn 8842: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8843: $selfenroll,$context);
8844: } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
8845: ($role eq 'au') || ($role eq 'dc')) {
8846: &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8847: $context);
8848: } elsif (($role eq 'ca') || ($role eq 'aa')) {
8849: &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8850: $context);
8851: }
1.1053 raeburn 8852: if ($role eq 'cc') {
8853: &autoupdate_coowners($url,$end,$start,$uname,$udom);
8854: }
1.349 www 8855: }
8856: return $answer;
1.169 harris41 8857: }
8858:
1.1053 raeburn 8859: sub autoupdate_coowners {
8860: my ($url,$end,$start,$uname,$udom) = @_;
8861: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
8862: if (($cdom ne '') && ($cnum ne '')) {
8863: my $now = time;
8864: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
8865: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
8866: my %coursehash = &coursedescription($cdom.'_'.$cnum);
8867: my $instcode = $coursehash{'internal.coursecode'};
8868: if ($instcode ne '') {
1.1056 raeburn 8869: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
8870: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 8871: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 8872: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
8873: if ($result eq 'valid') {
8874: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 8875: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
8876: push(@newcoowners,$coowner);
8877: }
8878: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
8879: push(@newcoowners,$uname.':'.$udom);
8880: }
8881: @newcoowners = sort(@newcoowners);
8882: } else {
8883: push(@newcoowners,$uname.':'.$udom);
8884: }
8885: } else {
8886: if ($coursehash{'internal.co-owners'}) {
8887: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
8888: unless ($coowner eq $uname.':'.$udom) {
8889: push(@newcoowners,$coowner);
8890: }
8891: }
8892: unless (@newcoowners > 0) {
8893: $delcoowners = 1;
8894: $coowners = '';
8895: }
8896: }
8897: }
8898: if (@newcoowners || $delcoowners) {
8899: &store_coowners($cdom,$cnum,$coursehash{'home'},
8900: $delcoowners,@newcoowners);
8901: }
8902: }
8903: }
8904: }
8905: }
8906: }
8907: }
8908:
8909: sub store_coowners {
8910: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
8911: my $cid = $cdom.'_'.$cnum;
8912: my ($coowners,$delresult,$putresult);
8913: if (@newcoowners) {
8914: $coowners = join(',',@newcoowners);
8915: my %coownershash = (
8916: 'internal.co-owners' => $coowners,
8917: );
8918: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
8919: if ($putresult eq 'ok') {
8920: if ($env{'course.'.$cid.'.num'} eq $cnum) {
8921: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
8922: }
8923: }
8924: }
8925: if ($delcoowners) {
8926: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
8927: if ($delresult eq 'ok') {
8928: if ($env{'course.'.$cid.'.internal.co-owners'}) {
8929: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
8930: }
8931: }
8932: }
8933: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
8934: my %crsinfo =
8935: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
8936: if (ref($crsinfo{$cid}) eq 'HASH') {
8937: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
8938: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
8939: }
8940: }
8941: }
8942:
1.169 harris41 8943: # -------------------------------------------------- Modify user authentication
1.197 www 8944: # Overrides without validation
8945:
1.169 harris41 8946: sub modifyuserauth {
8947: my ($udom,$uname,$umode,$upass)=@_;
8948: my $uhome=&homeserver($uname,$udom);
1.197 www 8949: unless (&allowed('mau',$udom)) { return 'refused'; }
8950: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 8951: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
8952: ' in domain '.$env{'request.role.domain'});
1.169 harris41 8953: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
8954: &escape($upass),$uhome);
1.620 albertel 8955: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 8956: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
8957: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
8958: &log($udom,,$uname,$uhome,
1.620 albertel 8959: 'Authentication changed by '.$env{'user.domain'}.', '.
8960: $env{'user.name'}.', '.$umode.
1.197 www 8961: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 8962: unless ($reply eq 'ok') {
1.197 www 8963: &logthis('Authentication mode error: '.$reply);
1.169 harris41 8964: return 'error: '.$reply;
8965: }
1.170 harris41 8966: return 'ok';
1.80 www 8967: }
8968:
1.81 www 8969: # --------------------------------------------------------------- Modify a user
1.80 www 8970:
1.81 www 8971: sub modifyuser {
1.206 matthew 8972: my ($udom, $uname, $uid,
8973: $umode, $upass, $first,
8974: $middle, $last, $gene,
1.1058 raeburn 8975: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 8976: $udom= &LONCAPA::clean_domain($udom);
8977: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 8978: my $showcandelete = 'none';
8979: if (ref($candelete) eq 'ARRAY') {
8980: if (@{$candelete} > 0) {
8981: $showcandelete = join(', ',@{$candelete});
8982: }
8983: }
1.81 www 8984: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 8985: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 8986: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 8987: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
8988: ' desiredhome not specified').
1.620 albertel 8989: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
8990: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 8991: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 8992: my $newuser;
8993: if ($uhome eq 'no_host') {
8994: $newuser = 1;
8995: }
1.80 www 8996: # ----------------------------------------------------------------- Create User
1.406 albertel 8997: if (($uhome eq 'no_host') &&
8998: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 8999: my $unhome='';
1.844 albertel 9000: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 9001: $unhome = $desiredhome;
1.620 albertel 9002: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
9003: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 9004: } else { # load balancing routine for determining $unhome
1.81 www 9005: my $loadm=10000000;
1.841 albertel 9006: my %servers = &get_servers($udom,'library');
9007: foreach my $tryserver (keys(%servers)) {
9008: my $answer=reply('load',$tryserver);
9009: if (($answer=~/\d+/) && ($answer<$loadm)) {
9010: $loadm=$answer;
9011: $unhome=$tryserver;
9012: }
1.80 www 9013: }
9014: }
9015: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 9016: return 'error: unable to find a home server for '.$uname.
9017: ' in domain '.$udom;
1.80 www 9018: }
9019: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
9020: &escape($upass),$unhome);
9021: unless ($reply eq 'ok') {
9022: return 'error: '.$reply;
9023: }
1.230 stredwic 9024: $uhome=&homeserver($uname,$udom,'true');
1.80 www 9025: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 9026: return 'error: unable verify users home machine.';
1.80 www 9027: }
1.209 matthew 9028: } # End of creation of new user
1.80 www 9029: # ---------------------------------------------------------------------- Add ID
9030: if ($uid) {
9031: $uid=~tr/A-Z/a-z/;
9032: my %uidhash=&idrget($udom,$uname);
1.196 www 9033: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
9034: && (!$forceid)) {
1.80 www 9035: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 9036: return 'error: user id "'.$uid.'" does not match '.
9037: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 9038: }
9039: } else {
1.1300 raeburn 9040: &idput($udom,{$uname => $uid},$uhome,'ids');
1.80 www 9041: }
9042: }
9043: # -------------------------------------------------------------- Add names, etc
1.313 matthew 9044: my @tmp=&get('environment',
1.899 raeburn 9045: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 9046: 'permanentemail','inststatus'],
1.134 albertel 9047: $udom,$uname);
1.1075 raeburn 9048: my (%names,%oldnames);
1.313 matthew 9049: if ($tmp[0] =~ m/^error:.*/) {
9050: %names=();
9051: } else {
9052: %names = @tmp;
1.1075 raeburn 9053: %oldnames = %names;
1.313 matthew 9054: }
1.388 www 9055: #
1.1058 raeburn 9056: # If name, email and/or uid are blank (e.g., because an uploaded file
9057: # of users did not contain them), do not overwrite existing values
9058: # unless field is in $candelete array ref.
9059: #
9060:
9061: my @fields = ('firstname','middlename','lastname','generation',
9062: 'permanentemail','id');
9063: my %newvalues;
9064: if (ref($candelete) eq 'ARRAY') {
9065: foreach my $field (@fields) {
9066: if (grep(/^\Q$field\E$/,@{$candelete})) {
9067: if ($field eq 'firstname') {
9068: $names{$field} = $first;
9069: } elsif ($field eq 'middlename') {
9070: $names{$field} = $middle;
9071: } elsif ($field eq 'lastname') {
9072: $names{$field} = $last;
9073: } elsif ($field eq 'generation') {
9074: $names{$field} = $gene;
9075: } elsif ($field eq 'permanentemail') {
9076: $names{$field} = $email;
9077: } elsif ($field eq 'id') {
9078: $names{$field} = $uid;
9079: }
9080: }
9081: }
9082: }
1.388 www 9083: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 9084: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 9085: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 9086: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 9087: if ($email) {
9088: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 9089: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 9090: }
1.899 raeburn 9091: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 9092: if (defined($inststatus)) {
9093: $names{'inststatus'} = '';
9094: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
9095: if (ref($usertypes) eq 'HASH') {
9096: my @okstatuses;
9097: foreach my $item (split(/:/,$inststatus)) {
9098: if (defined($usertypes->{$item})) {
9099: push(@okstatuses,$item);
9100: }
9101: }
9102: if (@okstatuses) {
9103: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
9104: }
9105: }
9106: }
1.1075 raeburn 9107: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 9108: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 9109: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 9110: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
9111: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
9112: } else {
9113: $logmsg .= ' during self creation';
9114: }
1.1075 raeburn 9115: my $changed;
9116: if ($newuser) {
9117: $changed = 1;
9118: } else {
9119: foreach my $field (@fields) {
9120: if ($names{$field} ne $oldnames{$field}) {
9121: $changed = 1;
9122: last;
9123: }
9124: }
9125: }
9126: unless ($changed) {
9127: $logmsg = 'No changes in user information needed for: '.$logmsg;
9128: &logthis($logmsg);
9129: return 'ok';
9130: }
9131: my $reply = &put('environment', \%names, $udom,$uname);
9132: if ($reply ne 'ok') {
9133: return 'error: '.$reply;
9134: }
1.1087 raeburn 9135: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
9136: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
9137: }
1.1075 raeburn 9138: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
9139: &devalidate_cache_new('namescache',$uname.':'.$udom);
9140: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 9141: &logthis($logmsg);
1.134 albertel 9142: return 'ok';
1.80 www 9143: }
9144:
1.81 www 9145: # -------------------------------------------------------------- Modify student
1.80 www 9146:
1.81 www 9147: sub modifystudent {
9148: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 9149: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1314 raeburn 9150: $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455 albertel 9151: if (!$cid) {
1.620 albertel 9152: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 9153: return 'not_in_class';
9154: }
1.80 www 9155: }
9156: # --------------------------------------------------------------- Make the user
1.81 www 9157: my $reply=&modifyuser
1.209 matthew 9158: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 9159: $desiredhome,$email,$inststatus);
1.80 www 9160: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 9161: # This will cause &modify_student_enrollment to get the uid from the
1.1235 raeburn 9162: # student's environment
1.297 matthew 9163: $uid = undef if (!$forceid);
1.455 albertel 9164: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1216 raeburn 9165: $gene,$usec,$end,$start,$type,$locktype,
1.1314 raeburn 9166: $cid,$selfenroll,$context,$credits,$instsec);
1.297 matthew 9167: return $reply;
9168: }
9169:
9170: sub modify_student_enrollment {
1.1216 raeburn 9171: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1314 raeburn 9172: $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455 albertel 9173: my ($cdom,$cnum,$chome);
9174: if (!$cid) {
1.620 albertel 9175: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 9176: return 'not_in_class';
9177: }
1.620 albertel 9178: $cdom=$env{'course.'.$cid.'.domain'};
9179: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 9180: } else {
9181: ($cdom,$cnum)=split(/_/,$cid);
9182: }
1.620 albertel 9183: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 9184: if (!$chome) {
1.457 raeburn 9185: $chome=&homeserver($cnum,$cdom);
1.297 matthew 9186: }
1.455 albertel 9187: if (!$chome) { return 'unknown_course'; }
1.297 matthew 9188: # Make sure the user exists
1.81 www 9189: my $uhome=&homeserver($uname,$udom);
9190: if (($uhome eq '') || ($uhome eq 'no_host')) {
9191: return 'error: no such user';
9192: }
1.297 matthew 9193: # Get student data if we were not given enough information
9194: if (!defined($first) || $first eq '' ||
9195: !defined($last) || $last eq '' ||
9196: !defined($uid) || $uid eq '' ||
9197: !defined($middle) || $middle eq '' ||
9198: !defined($gene) || $gene eq '') {
1.294 matthew 9199: # They did not supply us with enough data to enroll the student, so
9200: # we need to pick up more information.
1.297 matthew 9201: my %tmp = &get('environment',
1.294 matthew 9202: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 9203: ,$udom,$uname);
9204:
1.800 albertel 9205: #foreach my $key (keys(%tmp)) {
9206: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 9207: #}
1.294 matthew 9208: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
9209: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
9210: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 9211: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 9212: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
9213: }
1.556 albertel 9214: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148 raeburn 9215: my $user = "$uname:$udom";
9216: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487 albertel 9217: my $reply=cput('classlist',
1.1148 raeburn 9218: {$user =>
1.1314 raeburn 9219: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487 albertel 9220: $cdom,$cnum);
1.1148 raeburn 9221: if (($reply eq 'ok') || ($reply eq 'delayed')) {
9222: &devalidate_getsection_cache($udom,$uname,$cid);
9223: } else {
1.81 www 9224: return 'error: '.$reply;
9225: }
1.297 matthew 9226: # Add student role to user
1.83 www 9227: my $uurl='/'.$cid;
1.81 www 9228: $uurl=~s/\_/\//g;
9229: if ($usec) {
9230: $uurl.='/'.$usec;
9231: }
1.1148 raeburn 9232: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
9233: $selfenroll,$context);
9234: if ($result ne 'ok') {
9235: if ($old_entry{$user} ne '') {
9236: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
9237: } else {
9238: $reply = &del('classlist',[$user],$cdom,$cnum);
9239: }
9240: }
9241: return $result;
1.21 www 9242: }
9243:
1.556 albertel 9244: sub format_name {
9245: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
9246: my $name;
9247: if ($first ne 'lastname') {
9248: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
9249: } else {
9250: if ($lastname=~/\S/) {
9251: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
9252: $name=~s/\s+,/,/;
9253: } else {
9254: $name.= $firstname.' '.$middlename.' '.$generation;
9255: }
9256: }
9257: $name=~s/^\s+//;
9258: $name=~s/\s+$//;
9259: $name=~s/\s+/ /g;
9260: return $name;
9261: }
9262:
1.84 www 9263: # ------------------------------------------------- Write to course preferences
9264:
9265: sub writecoursepref {
9266: my ($courseid,%prefs)=@_;
9267: $courseid=~s/^\///;
9268: $courseid=~s/\_/\//g;
9269: my ($cdomain,$cnum)=split(/\//,$courseid);
9270: my $chome=homeserver($cnum,$cdomain);
9271: if (($chome eq '') || ($chome eq 'no_host')) {
9272: return 'error: no such course';
9273: }
9274: my $cstring='';
1.800 albertel 9275: foreach my $pref (keys(%prefs)) {
9276: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 9277: }
1.84 www 9278: $cstring=~s/\&$//;
9279: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
9280: }
9281:
9282: # ---------------------------------------------------------- Make/modify course
9283:
9284: sub createcourse {
1.741 raeburn 9285: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 9286: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 9287: $url=&declutter($url);
9288: my $cid='';
1.1028 raeburn 9289: if ($context eq 'requestcourses') {
9290: my $can_create = 0;
9291: my ($ownername,$ownerdom) = split(':',$course_owner);
9292: if ($udom eq $ownerdom) {
9293: if (&usertools_access($ownername,$ownerdom,$category,undef,
9294: $context)) {
9295: $can_create = 1;
9296: }
9297: } else {
9298: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
9299: $category);
9300: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
9301: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
9302: if (@curr > 0) {
9303: my @options = qw(approval validate autolimit);
9304: my $optregex = join('|',@options);
9305: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
9306: $can_create = 1;
9307: }
9308: }
9309: }
9310: }
9311: if ($can_create) {
9312: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
9313: unless (&allowed('ccc',$udom)) {
9314: return 'refused';
9315: }
1.1017 raeburn 9316: }
9317: } else {
9318: return 'refused';
9319: }
1.1028 raeburn 9320: } elsif (!&allowed('ccc',$udom)) {
9321: return 'refused';
1.84 www 9322: }
1.1011 raeburn 9323: # --------------------------------------------------------------- Get Unique ID
9324: my $uname;
9325: if ($cnum =~ /^$match_courseid$/) {
9326: my $chome=&homeserver($cnum,$udom,'true');
9327: if (($chome eq '') || ($chome eq 'no_host')) {
9328: $uname = $cnum;
9329: } else {
1.1038 raeburn 9330: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 9331: }
9332: } else {
1.1038 raeburn 9333: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 9334: }
9335: return $uname if ($uname =~ /^error/);
9336: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 9337: if (!defined($course_server)) {
9338: if (defined(&domain($udom,'primary'))) {
9339: $course_server = &domain($udom,'primary');
9340: } else {
9341: $course_server = $env{'user.home'};
9342: }
9343: }
9344: my %host_servers =
9345: &Apache::lonnet::get_servers($udom,'library');
9346: unless ($host_servers{$course_server}) {
9347: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 9348: }
1.84 www 9349: # ------------------------------------------------------------- Make the course
9350: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 9351: $course_server);
1.84 www 9352: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 9353: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 9354: if (($uhome eq '') || ($uhome eq 'no_host')) {
9355: return 'error: no such course';
9356: }
1.271 www 9357: # ----------------------------------------------------------------- Course made
1.516 raeburn 9358: # log existence
1.1029 raeburn 9359: my $now = time;
1.918 raeburn 9360: my $newcourse = {
9361: $udom.'_'.$uname => {
1.921 raeburn 9362: description => $description,
9363: inst_code => $inst_code,
9364: owner => $course_owner,
9365: type => $crstype,
1.1029 raeburn 9366: creator => $env{'user.name'}.':'.
9367: $env{'user.domain'},
9368: created => $now,
9369: context => $context,
1.918 raeburn 9370: },
9371: };
1.921 raeburn 9372: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 9373: # set toplevel url
1.271 www 9374: my $topurl=$url;
9375: unless ($nonstandard) {
9376: # ------------------------------------------ For standard courses, make top url
9377: my $mapurl=&clutter($url);
1.278 www 9378: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 9379: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 9380: <map>
9381: <resource id="1" type="start"></resource>
9382: <resource id="2" src="$mapurl"></resource>
9383: <resource id="3" type="finish"></resource>
9384: <link index="1" from="1" to="2"></link>
9385: <link index="2" from="2" to="3"></link>
9386: </map>
9387: ENDINITMAP
9388: $topurl=&declutter(
1.638 albertel 9389: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 9390: );
9391: }
9392: # ----------------------------------------------------------- Write preferences
1.84 www 9393: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 9394: ('description' => $description,
9395: 'url' => $topurl,
9396: 'internal.creator' => $env{'user.name'}.':'.
9397: $env{'user.domain'},
9398: 'internal.created' => $now,
9399: 'internal.creationcontext' => $context)
9400: );
1.84 www 9401: return '/'.$udom.'/'.$uname;
9402: }
9403:
1.1011 raeburn 9404: # ------------------------------------------------------------------- Create ID
9405: sub generate_coursenum {
1.1038 raeburn 9406: my ($udom,$crstype) = @_;
1.1011 raeburn 9407: my $domdesc = &domain($udom);
9408: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 9409: my $first;
9410: if ($crstype eq 'Community') {
9411: $first = '0';
9412: } else {
9413: $first = int(1+rand(9));
9414: }
9415: my $uname=$first.
1.1011 raeburn 9416: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
9417: substr($$.time,0,5).unpack("H8",pack("I32",time)).
9418: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
9419: # ----------------------------------------------- Make sure that does not exist
9420: my $uhome=&homeserver($uname,$udom,'true');
9421: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 9422: if ($crstype eq 'Community') {
9423: $first = '0';
9424: } else {
9425: $first = int(1+rand(9));
9426: }
9427: $uname=$first.
1.1011 raeburn 9428: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
9429: substr($$.time,0,5).unpack("H8",pack("I32",time)).
9430: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
9431: $uhome=&homeserver($uname,$udom,'true');
9432: unless (($uhome eq '') || ($uhome eq 'no_host')) {
9433: return 'error: unable to generate unique course-ID';
9434: }
9435: }
9436: return $uname;
9437: }
9438:
1.813 albertel 9439: sub is_course {
1.1167 droeschl 9440: my ($cdom, $cnum) = scalar(@_) == 1 ?
9441: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
9442:
9443: return unless $cdom and $cnum;
9444:
9445: my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
9446: '.');
9447:
1.1219 raeburn 9448: return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167 droeschl 9449: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813 albertel 9450: }
9451:
1.1015 raeburn 9452: sub store_userdata {
9453: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 9454: my $result;
1.1016 raeburn 9455: if ($datakey ne '') {
1.1013 raeburn 9456: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 9457: if ($udom eq '' || $uname eq '') {
9458: $udom = $env{'user.domain'};
9459: $uname = $env{'user.name'};
9460: }
9461: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 9462: if (($uhome eq '') || ($uhome eq 'no_host')) {
9463: $result = 'error: no_host';
9464: } else {
9465: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
9466: $storehash->{'host'} = $perlvar{'lonHostID'};
9467:
9468: my $namevalue='';
9469: foreach my $key (keys(%{$storehash})) {
9470: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
9471: }
9472: $namevalue=~s/\&$//;
1.1224 raeburn 9473: unless ($namespace eq 'courserequests') {
9474: $datakey = &escape($datakey);
9475: }
1.1105 raeburn 9476: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
9477: $namevalue,$uhome);
1.1013 raeburn 9478: }
9479: } else {
9480: $result = 'error: data to store was not a hash reference';
9481: }
9482: } else {
9483: $result= 'error: invalid requestkey';
9484: }
9485: return $result;
9486: }
9487:
1.21 www 9488: # ---------------------------------------------------------- Assign Custom Role
9489:
9490: sub assigncustomrole {
1.957 raeburn 9491: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9492: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 9493: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 9494: }
9495:
9496: # ----------------------------------------------------------------- Revoke Role
9497:
9498: sub revokerole {
1.957 raeburn 9499: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9500: my $now=time;
1.965 raeburn 9501: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 9502: }
9503:
9504: # ---------------------------------------------------------- Revoke Custom Role
9505:
9506: sub revokecustomrole {
1.957 raeburn 9507: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9508: my $now=time;
1.357 www 9509: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 9510: $deleteflag,$selfenroll,$context);
1.17 www 9511: }
9512:
1.533 banghart 9513: # ------------------------------------------------------------ Disk usage
1.535 albertel 9514: sub diskusage {
1.955 raeburn 9515: my ($udom,$uname,$directorypath,$getpropath)=@_;
9516: $directorypath =~ s/\/$//;
9517: my $listing=&reply('du2:'.&escape($directorypath).':'
9518: .&escape($getpropath).':'.&escape($uname).':'
9519: .&escape($udom),homeserver($uname,$udom));
9520: if ($listing eq 'unknown_cmd') {
9521: if ($getpropath) {
9522: $directorypath = &propath($udom,$uname).'/'.$directorypath;
9523: }
9524: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
9525: }
1.514 albertel 9526: return $listing;
1.512 banghart 9527: }
9528:
1.566 banghart 9529: sub is_locked {
1.1096 raeburn 9530: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 9531: my @check;
9532: my $is_locked;
1.1093 raeburn 9533: push (@check,$file_name);
1.613 albertel 9534: my %locked = &get('file_permissions',\@check,
1.620 albertel 9535: $env{'user.domain'},$env{'user.name'});
1.615 albertel 9536: my ($tmp)=keys(%locked);
9537: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 9538:
1.566 banghart 9539: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 9540: $is_locked = 'false';
9541: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 9542: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 9543: $is_locked = 'true';
1.1096 raeburn 9544: if (ref($which) eq 'ARRAY') {
9545: push(@{$which},$entry);
9546: } else {
9547: last;
9548: }
1.745 raeburn 9549: }
9550: }
1.566 banghart 9551: } else {
9552: $is_locked = 'false';
9553: }
1.1093 raeburn 9554: return $is_locked;
1.566 banghart 9555: }
9556:
1.759 albertel 9557: sub declutter_portfile {
9558: my ($file) = @_;
1.833 albertel 9559: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 9560: return $file;
9561: }
9562:
1.559 banghart 9563: # ------------------------------------------------------------- Mark as Read Only
9564:
9565: sub mark_as_readonly {
9566: my ($domain,$user,$files,$what) = @_;
1.613 albertel 9567: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 9568: my ($tmp)=keys(%current_permissions);
9569: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 9570: foreach my $file (@{$files}) {
1.759 albertel 9571: $file = &declutter_portfile($file);
1.561 banghart 9572: push(@{$current_permissions{$file}},$what);
1.559 banghart 9573: }
1.613 albertel 9574: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 9575: return;
9576: }
9577:
1.572 banghart 9578: # ------------------------------------------------------------Save Selected Files
9579:
9580: sub save_selected_files {
9581: my ($user, $path, @files) = @_;
9582: my $filename = $user."savedfiles";
1.573 banghart 9583: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 9584: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 9585: foreach my $file (@files) {
1.620 albertel 9586: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 9587: }
9588: foreach my $file (@other_files) {
1.574 banghart 9589: print (OUT $file."\n");
1.572 banghart 9590: }
1.574 banghart 9591: close (OUT);
1.572 banghart 9592: return 'ok';
9593: }
9594:
1.574 banghart 9595: sub clear_selected_files {
9596: my ($user) = @_;
9597: my $filename = $user."savedfiles";
1.1117 foxr 9598: open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574 banghart 9599: print (OUT undef);
9600: close (OUT);
9601: return ("ok");
9602: }
9603:
1.572 banghart 9604: sub files_in_path {
9605: my ($user, $path) = @_;
9606: my $filename = $user."savedfiles";
9607: my %return_files;
1.1117 foxr 9608: open (IN, '<'.LONCAPA::tempdir().$filename);
1.573 banghart 9609: while (my $line_in = <IN>) {
1.574 banghart 9610: chomp ($line_in);
9611: my @paths_and_file = split (m!/!, $line_in);
9612: my $file_part = pop (@paths_and_file);
9613: my $path_part = join ('/', @paths_and_file);
1.573 banghart 9614: $path_part.='/';
9615: my $path_and_file = $path_part.$file_part;
9616: if ($path_part eq $path) {
9617: $return_files{$file_part}= 'selected';
9618: }
9619: }
1.574 banghart 9620: close (IN);
9621: return (\%return_files);
1.572 banghart 9622: }
9623:
9624: # called in portfolio select mode, to show files selected NOT in current directory
9625: sub files_not_in_path {
9626: my ($user, $path) = @_;
9627: my $filename = $user."savedfiles";
9628: my @return_files;
9629: my $path_part;
1.1117 foxr 9630: open(IN, '<'.LONCAPA::.$filename);
1.800 albertel 9631: while (my $line = <IN>) {
1.572 banghart 9632: #ok, I know it's clunky, but I want it to work
1.800 albertel 9633: my @paths_and_file = split(m|/|, $line);
9634: my $file_part = pop(@paths_and_file);
9635: chomp($file_part);
9636: my $path_part = join('/', @paths_and_file);
1.572 banghart 9637: $path_part .= '/';
9638: my $path_and_file = $path_part.$file_part;
9639: if ($path_part ne $path) {
1.800 albertel 9640: push(@return_files, ($path_and_file));
1.572 banghart 9641: }
9642: }
1.800 albertel 9643: close(OUT);
1.574 banghart 9644: return (@return_files);
1.572 banghart 9645: }
9646:
1.1273 raeburn 9647: #------------------------------Submitted/Handedback Portfolio Files Versioning
9648:
9649: sub portfiles_versioning {
9650: my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
9651: my $portfolio_root = '/userfiles/portfolio';
9652: return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
9653: foreach my $file (@{$portfiles}) {
9654: &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
9655: my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
9656: my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
9657: my $getpropath = 1;
9658: my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
9659: $stu_name,$getpropath);
9660: my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
9661: my $new_answer =
9662: &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
9663: if ($new_answer ne 'problem getting file') {
9664: push(@{$versioned_portfiles}, $directory.$new_answer);
9665: &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
9666: [$symb,$env{'request.course.id'},'graded']);
9667: }
9668: }
9669: }
9670:
9671: sub get_next_version {
9672: my ($answer_name, $answer_ext, $dir_list) = @_;
9673: my $version;
9674: if (ref($dir_list) eq 'ARRAY') {
9675: foreach my $row (@{$dir_list}) {
9676: my ($file) = split(/\&/,$row,2);
9677: my ($file_name,$file_version,$file_ext) =
9678: &file_name_version_ext($file);
9679: if (($file_name eq $answer_name) &&
9680: ($file_ext eq $answer_ext)) {
9681: # gets here if filename and extension match,
9682: # regardless of version
9683: if ($file_version ne '') {
9684: # a versioned file is found so save it for later
9685: if ($file_version > $version) {
9686: $version = $file_version;
9687: }
9688: }
9689: }
9690: }
9691: }
9692: $version ++;
9693: return($version);
9694: }
9695:
9696: sub version_selected_portfile {
9697: my ($domain,$stu_name,$directory,$file_name,$version) = @_;
9698: my ($answer_name,$answer_ver,$answer_ext) =
9699: &file_name_version_ext($file_name);
9700: my $new_answer;
9701: $env{'form.copy'} =
9702: &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
9703: if($env{'form.copy'} eq '-1') {
9704: $new_answer = 'problem getting file';
9705: } else {
9706: $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
9707: my $copy_result =
9708: &finishuserfileupload($stu_name,$domain,'copy',
9709: '/portfolio'.$directory.$new_answer);
9710: }
9711: undef($env{'form.copy'});
9712: return ($new_answer);
9713: }
9714:
9715: sub file_name_version_ext {
9716: my ($file)=@_;
9717: my @file_parts = split(/\./, $file);
9718: my ($name,$version,$ext);
9719: if (@file_parts > 1) {
9720: $ext=pop(@file_parts);
9721: if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
9722: $version=pop(@file_parts);
9723: }
9724: $name=join('.',@file_parts);
9725: } else {
9726: $name=join('.',@file_parts);
9727: }
9728: return($name,$version,$ext);
9729: }
9730:
1.745 raeburn 9731: #----------------------------------------------Get portfolio file permissions
1.629 banghart 9732:
1.745 raeburn 9733: sub get_portfile_permissions {
9734: my ($domain,$user) = @_;
1.613 albertel 9735: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 9736: my ($tmp)=keys(%current_permissions);
9737: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 9738: return \%current_permissions;
9739: }
9740:
9741: #---------------------------------------------Get portfolio file access controls
9742:
1.749 raeburn 9743: sub get_access_controls {
1.745 raeburn 9744: my ($current_permissions,$group,$file) = @_;
1.769 albertel 9745: my %access;
9746: my $real_file = $file;
9747: $file =~ s/\.meta$//;
1.745 raeburn 9748: if (defined($file)) {
1.749 raeburn 9749: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
9750: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 9751: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 9752: }
9753: }
1.745 raeburn 9754: } else {
1.749 raeburn 9755: foreach my $key (keys(%{$current_permissions})) {
9756: if ($key =~ /\0accesscontrol$/) {
9757: if (defined($group)) {
9758: if ($key !~ m-^\Q$group\E/-) {
9759: next;
9760: }
9761: }
9762: my ($fullpath) = split(/\0/,$key);
9763: if (ref($$current_permissions{$key}) eq 'HASH') {
9764: foreach my $control (keys(%{$$current_permissions{$key}})) {
9765: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
9766: }
9767: }
9768: }
9769: }
9770: }
9771: return %access;
9772: }
9773:
9774: sub modify_access_controls {
9775: my ($file_name,$changes,$domain,$user)=@_;
9776: my ($outcome,$deloutcome);
9777: my %store_permissions;
9778: my %new_values;
9779: my %new_control;
9780: my %translation;
9781: my @deletions = ();
9782: my $now = time;
9783: if (exists($$changes{'activate'})) {
9784: if (ref($$changes{'activate'}) eq 'HASH') {
9785: my @newitems = sort(keys(%{$$changes{'activate'}}));
9786: my $numnew = scalar(@newitems);
9787: for (my $i=0; $i<$numnew; $i++) {
9788: my $newkey = $newitems[$i];
9789: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 9790: if ($newkey =~ /^\d+:/) {
9791: $newkey =~ s/^(\d+)/$newid/;
9792: $translation{$1} = $newid;
9793: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
9794: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
9795: $translation{$1} = $newid;
9796: }
1.749 raeburn 9797: $new_values{$file_name."\0".$newkey} =
9798: $$changes{'activate'}{$newitems[$i]};
9799: $new_control{$newkey} = $now;
9800: }
9801: }
9802: }
9803: my %todelete;
9804: my %changed_items;
9805: foreach my $action ('delete','update') {
9806: if (exists($$changes{$action})) {
9807: if (ref($$changes{$action}) eq 'HASH') {
9808: foreach my $key (keys(%{$$changes{$action}})) {
9809: my ($itemnum) = ($key =~ /^([^:]+):/);
9810: if ($action eq 'delete') {
9811: $todelete{$itemnum} = 1;
9812: } else {
9813: $changed_items{$itemnum} = $key;
9814: }
9815: }
1.745 raeburn 9816: }
9817: }
1.749 raeburn 9818: }
9819: # get lock on access controls for file.
9820: my $lockhash = {
9821: $file_name."\0".'locked_access_records' => $env{'user.name'}.
9822: ':'.$env{'user.domain'},
9823: };
9824: my $tries = 0;
9825: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9826:
1.1288 damieng 9827: while (($gotlock ne 'ok') && $tries < 10) {
1.749 raeburn 9828: $tries ++;
1.1289 damieng 9829: sleep(0.1);
1.749 raeburn 9830: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9831: }
9832: if ($gotlock eq 'ok') {
9833: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
9834: my ($tmp)=keys(%curr_permissions);
9835: if ($tmp=~/^error:/) { undef(%curr_permissions); }
9836: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
9837: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
9838: if (ref($curr_controls) eq 'HASH') {
9839: foreach my $control_item (keys(%{$curr_controls})) {
9840: my ($itemnum) = ($control_item =~ /^([^:]+):/);
9841: if (defined($todelete{$itemnum})) {
9842: push(@deletions,$file_name."\0".$control_item);
9843: } else {
9844: if (defined($changed_items{$itemnum})) {
9845: $new_control{$changed_items{$itemnum}} = $now;
9846: push(@deletions,$file_name."\0".$control_item);
9847: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
9848: } else {
9849: $new_control{$control_item} = $$curr_controls{$control_item};
9850: }
9851: }
1.745 raeburn 9852: }
9853: }
9854: }
1.970 raeburn 9855: my ($group);
9856: if (&is_course($domain,$user)) {
9857: ($group,my $file) = split(/\//,$file_name,2);
9858: }
1.749 raeburn 9859: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
9860: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
9861: $outcome = &put('file_permissions',\%new_values,$domain,$user);
9862: # remove lock
9863: my @del_lock = ($file_name."\0".'locked_access_records');
9864: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 9865: my $sqlresult =
1.970 raeburn 9866: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 9867: $group);
1.749 raeburn 9868: } else {
9869: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 9870: }
1.749 raeburn 9871: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 9872: }
9873:
1.827 raeburn 9874: sub make_public_indefinitely {
1.1271 raeburn 9875: my (@requrl) = @_;
9876: return &automated_portfile_access('public',\@requrl);
9877: }
9878:
9879: sub automated_portfile_access {
9880: my ($accesstype,$addsref,$delsref,$info) = @_;
1.1273 raeburn 9881: unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
9882: return 'invalid';
9883: }
1.1271 raeburn 9884: my %urls;
9885: if (ref($addsref) eq 'ARRAY') {
9886: foreach my $requrl (@{$addsref}) {
9887: if (&is_portfolio_url($requrl)) {
9888: unless (exists($urls{$requrl})) {
9889: $urls{$requrl} = 'add';
9890: }
9891: }
9892: }
9893: }
9894: if (ref($delsref) eq 'ARRAY') {
9895: foreach my $requrl (@{$delsref}) {
9896: if (&is_portfolio_url($requrl)) {
9897: unless (exists($urls{$requrl})) {
9898: $urls{$requrl} = 'delete';
9899: }
9900: }
9901: }
9902: }
9903: unless (keys(%urls)) {
9904: return 'invalid';
9905: }
9906: my $ip;
9907: if ($accesstype eq 'ip') {
9908: if (ref($info) eq 'HASH') {
9909: if ($info->{'ip'} ne '') {
9910: $ip = $info->{'ip'};
9911: }
9912: }
9913: if ($ip eq '') {
9914: return 'invalid';
9915: }
9916: }
9917: my $errors;
1.827 raeburn 9918: my $now = time;
1.1271 raeburn 9919: my %current_perms;
9920: foreach my $requrl (sort(keys(%urls))) {
9921: my $action;
9922: if ($urls{$requrl} eq 'add') {
9923: $action = 'activate';
9924: } else {
9925: $action = 'none';
9926: }
9927: my $aclnum = 0;
1.827 raeburn 9928: my (undef,$udom,$unum,$file_name,$group) =
9929: &parse_portfolio_url($requrl);
1.1271 raeburn 9930: unless (exists($current_perms{$unum.':'.$udom})) {
9931: $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
9932: }
9933: my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
1.827 raeburn 9934: $group,$file_name);
9935: foreach my $key (keys(%{$access_controls{$file_name}})) {
9936: my ($num,$scope,$end,$start) =
9937: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
1.1271 raeburn 9938: if ($scope eq $accesstype) {
9939: if (($start <= $now) && ($end == 0)) {
9940: if ($accesstype eq 'ip') {
9941: if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
9942: if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
9943: if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
9944: if ($urls{$requrl} eq 'add') {
9945: $action = 'none';
9946: last;
9947: } else {
9948: $action = 'delete';
9949: $aclnum = $num;
9950: last;
9951: }
9952: }
9953: }
9954: }
9955: } elsif ($accesstype eq 'public') {
9956: if ($urls{$requrl} eq 'add') {
9957: $action = 'none';
9958: last;
9959: } else {
9960: $action = 'delete';
9961: $aclnum = $num;
9962: last;
9963: }
9964: }
9965: } elsif ($accesstype eq 'public') {
1.827 raeburn 9966: $action = 'update';
9967: $aclnum = $num;
1.1271 raeburn 9968: last;
1.827 raeburn 9969: }
9970: }
9971: }
9972: if ($action eq 'none') {
1.1271 raeburn 9973: next;
1.827 raeburn 9974: } else {
9975: my %changes;
9976: my $newend = 0;
9977: my $newstart = $now;
1.1271 raeburn 9978: my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
1.827 raeburn 9979: $changes{$action}{$newkey} = {
1.1271 raeburn 9980: type => $accesstype,
1.827 raeburn 9981: time => {
9982: start => $newstart,
9983: end => $newend,
9984: },
9985: };
1.1271 raeburn 9986: if ($accesstype eq 'ip') {
9987: $changes{$action}{$newkey}{'ip'} = [$ip];
9988: }
1.827 raeburn 9989: my ($outcome,$deloutcome,$new_values,$translation) =
9990: &modify_access_controls($file_name,\%changes,$udom,$unum);
1.1271 raeburn 9991: unless ($outcome eq 'ok') {
9992: $errors .= $outcome.' ';
9993: }
1.827 raeburn 9994: }
1.1271 raeburn 9995: }
9996: if ($errors) {
9997: $errors =~ s/\s$//;
9998: return $errors;
1.827 raeburn 9999: } else {
1.1271 raeburn 10000: return 'ok';
1.827 raeburn 10001: }
10002: }
10003:
1.745 raeburn 10004: #------------------------------------------------------Get Marked as Read Only
10005:
10006: sub get_marked_as_readonly {
10007: my ($domain,$user,$what,$group) = @_;
10008: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 10009: my @readonly_files;
1.629 banghart 10010: my $cmp1=$what;
10011: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 10012: while (my ($file_name,$value) = each(%{$current_permissions})) {
10013: if (defined($group)) {
10014: if ($file_name !~ m-^\Q$group\E/-) {
10015: next;
10016: }
10017: }
1.561 banghart 10018: if (ref($value) eq "ARRAY"){
10019: foreach my $stored_what (@{$value}) {
1.629 banghart 10020: my $cmp2=$stored_what;
1.759 albertel 10021: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 10022: $cmp2=join('',@{$stored_what});
1.745 raeburn 10023: }
1.629 banghart 10024: if ($cmp1 eq $cmp2) {
1.561 banghart 10025: push(@readonly_files, $file_name);
1.745 raeburn 10026: last;
1.563 banghart 10027: } elsif (!defined($what)) {
10028: push(@readonly_files, $file_name);
1.745 raeburn 10029: last;
1.561 banghart 10030: }
10031: }
1.745 raeburn 10032: }
1.561 banghart 10033: }
10034: return @readonly_files;
10035: }
1.577 banghart 10036: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 10037:
1.577 banghart 10038: sub get_marked_as_readonly_hash {
1.745 raeburn 10039: my ($current_permissions,$group,$what) = @_;
1.577 banghart 10040: my %readonly_files;
1.745 raeburn 10041: while (my ($file_name,$value) = each(%{$current_permissions})) {
10042: if (defined($group)) {
10043: if ($file_name !~ m-^\Q$group\E/-) {
10044: next;
10045: }
10046: }
1.577 banghart 10047: if (ref($value) eq "ARRAY"){
10048: foreach my $stored_what (@{$value}) {
1.745 raeburn 10049: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 10050: foreach my $lock_descriptor(@{$stored_what}) {
10051: if ($lock_descriptor eq 'graded') {
10052: $readonly_files{$file_name} = 'graded';
10053: } elsif ($lock_descriptor eq 'handback') {
10054: $readonly_files{$file_name} = 'handback';
10055: } else {
10056: if (!exists($readonly_files{$file_name})) {
10057: $readonly_files{$file_name} = 'locked';
10058: }
10059: }
1.745 raeburn 10060: }
1.750 banghart 10061: }
1.577 banghart 10062: }
10063: }
10064: }
10065: return %readonly_files;
10066: }
1.559 banghart 10067: # ------------------------------------------------------------ Unmark as Read Only
10068:
10069: sub unmark_as_readonly {
1.629 banghart 10070: # unmarks $file_name (if $file_name is defined), or all files locked by $what
10071: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 10072: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 10073: $file_name = &declutter_portfile($file_name);
1.634 albertel 10074: my $symb_crs = $what;
10075: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 10076: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 10077: my ($tmp)=keys(%current_permissions);
10078: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 10079: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 10080: foreach my $file (@readonly_files) {
1.759 albertel 10081: my $clean_file = &declutter_portfile($file);
10082: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 10083: my $current_locks = $current_permissions{$file};
1.563 banghart 10084: my @new_locks;
10085: my @del_keys;
10086: if (ref($current_locks) eq "ARRAY"){
10087: foreach my $locker (@{$current_locks}) {
1.632 albertel 10088: my $compare=$locker;
1.749 raeburn 10089: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 10090: $compare=join('',@{$locker});
1.746 raeburn 10091: if ($compare ne $symb_crs) {
10092: push(@new_locks, $locker);
10093: }
1.563 banghart 10094: }
10095: }
1.650 albertel 10096: if (scalar(@new_locks) > 0) {
1.563 banghart 10097: $current_permissions{$file} = \@new_locks;
10098: } else {
10099: push(@del_keys, $file);
1.613 albertel 10100: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 10101: delete($current_permissions{$file});
1.563 banghart 10102: }
10103: }
1.561 banghart 10104: }
1.613 albertel 10105: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 10106: return;
10107: }
1.512 banghart 10108:
1.17 www 10109: # ------------------------------------------------------------ Directory lister
10110:
10111: sub dirlist {
1.955 raeburn 10112: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 10113: $uri=~s/^\///;
10114: $uri=~s/\/$//;
1.253 stredwic 10115: my ($udom, $uname);
1.955 raeburn 10116: if ($getuserdir) {
1.253 stredwic 10117: $udom = $userdomain;
10118: $uname = $username;
1.955 raeburn 10119: } else {
10120: (undef,$udom,$uname)=split(/\//,$uri);
10121: if(defined($userdomain)) {
10122: $udom = $userdomain;
10123: }
10124: if(defined($username)) {
10125: $uname = $username;
10126: }
1.253 stredwic 10127: }
1.955 raeburn 10128: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 10129:
1.955 raeburn 10130: $dirRoot = $perlvar{'lonDocRoot'};
10131: if (defined($getpropath)) {
10132: $dirRoot = &propath($udom,$uname);
1.253 stredwic 10133: $dirRoot =~ s/\/$//;
1.955 raeburn 10134: } elsif (defined($getuserdir)) {
10135: my $subdir=$uname.'__';
10136: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
10137: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
10138: ."/$udom/$subdir/$uname";
10139: } elsif (defined($alternateRoot)) {
10140: $dirRoot = $alternateRoot;
1.751 banghart 10141: }
1.253 stredwic 10142:
10143: if($udom) {
10144: if($uname) {
1.1135 raeburn 10145: my $uhome = &homeserver($uname,$udom);
1.1136 raeburn 10146: if ($uhome eq 'no_host') {
10147: return ([],'no_host');
10148: }
1.955 raeburn 10149: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 10150: .$getuserdir.':'.&escape($dirRoot)
1.1135 raeburn 10151: .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955 raeburn 10152: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 10153: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955 raeburn 10154: } else {
10155: @listing_results = map { &unescape($_); } split(/:/,$listing);
10156: }
1.605 matthew 10157: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 10158: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605 matthew 10159: @listing_results = split(/:/,$listing);
10160: } else {
10161: @listing_results = map { &unescape($_); } split(/:/,$listing);
10162: }
1.1135 raeburn 10163: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
1.1136 raeburn 10164: ($listing eq 'rejected') || ($listing eq 'refused') ||
10165: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
10166: return ([],$listing);
10167: } else {
10168: return (\@listing_results);
1.1135 raeburn 10169: }
1.955 raeburn 10170: } elsif(!$alternateRoot) {
1.1136 raeburn 10171: my (%allusers,%listerror);
1.841 albertel 10172: my %servers = &get_servers($udom,'library');
1.955 raeburn 10173: foreach my $tryserver (keys(%servers)) {
10174: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
10175: &escape($udom),$tryserver);
10176: if ($listing eq 'unknown_cmd') {
10177: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
10178: $udom, $tryserver);
10179: } else {
10180: @listing_results = map { &unescape($_); } split(/:/,$listing);
10181: }
1.841 albertel 10182: if ($listing eq 'unknown_cmd') {
10183: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
10184: $udom, $tryserver);
10185: @listing_results = split(/:/,$listing);
10186: } else {
10187: @listing_results =
10188: map { &unescape($_); } split(/:/,$listing);
10189: }
1.1136 raeburn 10190: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
10191: ($listing eq 'rejected') || ($listing eq 'refused') ||
10192: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
10193: $listerror{$tryserver} = $listing;
10194: } else {
1.841 albertel 10195: foreach my $line (@listing_results) {
10196: my ($entry) = split(/&/,$line,2);
10197: $allusers{$entry} = 1;
10198: }
10199: }
1.253 stredwic 10200: }
1.1136 raeburn 10201: my @alluserslist=();
1.800 albertel 10202: foreach my $user (sort(keys(%allusers))) {
1.1136 raeburn 10203: push(@alluserslist,$user.'&user');
1.253 stredwic 10204: }
1.1136 raeburn 10205: return (\@alluserslist);
1.253 stredwic 10206: } else {
1.1136 raeburn 10207: return ([],'missing username');
1.253 stredwic 10208: }
1.955 raeburn 10209: } elsif(!defined($getpropath)) {
1.1136 raeburn 10210: my $path = $perlvar{'lonDocRoot'}.'/res/';
10211: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
10212: return (\@all_domains);
1.955 raeburn 10213: } else {
1.1136 raeburn 10214: return ([],'missing domain');
1.275 stredwic 10215: }
10216: }
10217:
10218: # --------------------------------------------- GetFileTimestamp
10219: # This function utilizes dirlist and returns the date stamp for
10220: # when it was last modified. It will also return an error of -1
10221: # if an error occurs
10222:
10223: sub GetFileTimestamp {
1.955 raeburn 10224: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 10225: $studentDomain = &LONCAPA::clean_domain($studentDomain);
10226: $studentName = &LONCAPA::clean_username($studentName);
1.1136 raeburn 10227: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
10228: undef,$getuserdir);
10229: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
10230: return -1;
10231: }
10232: if (ref($fileref) eq 'ARRAY') {
10233: my @stats = split('&',$fileref->[0]);
1.375 matthew 10234: # @stats contains first the filename, then the stat output
10235: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 10236: } else {
10237: return -1;
1.253 stredwic 10238: }
1.26 www 10239: }
10240:
1.712 albertel 10241: sub stat_file {
10242: my ($uri) = @_;
1.787 albertel 10243: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 10244:
1.955 raeburn 10245: my ($udom,$uname,$file);
1.712 albertel 10246: if ($uri =~ m-^/(uploaded|editupload)/-) {
10247: ($udom,$uname,$file) =
1.811 albertel 10248: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 10249: $file = 'userfiles/'.$file;
10250: }
10251: if ($uri =~ m-^/res/-) {
10252: ($udom,$uname) =
1.807 albertel 10253: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 10254: $file = $uri;
10255: }
10256:
10257: if (!$udom || !$uname || !$file) {
10258: # unable to handle the uri
10259: return ();
10260: }
1.956 raeburn 10261: my $getpropath;
10262: if ($file =~ /^userfiles\//) {
10263: $getpropath = 1;
10264: }
1.1136 raeburn 10265: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
10266: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
10267: return ();
10268: } else {
10269: if (ref($listref) eq 'ARRAY') {
10270: my @stats = split('&',$listref->[0]);
10271: shift(@stats); #filename is first
10272: return @stats;
10273: }
1.712 albertel 10274: }
10275: return ();
10276: }
10277:
1.1313 raeburn 10278: # --------------------------------------------------------- recursedirs
10279: # Recursive function to traverse either a specific user's Authoring Space
10280: # or corresponding Published Resource Space, and populate the hash ref:
10281: # $dirhashref with URLs of all directories, and if $filehashref hash
10282: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
10283: # or .rights files in resource space, and .meta, .save, .log, and .bak
10284: # files in Authoring Space.
10285: #
10286: # Inputs:
10287: #
10288: # $is_home - true if current server is home server for user's space
10289: # $context - either: priv, or res respectively for Authoring or Resource Space.
10290: # $docroot - Document root (i.e., /home/httpd/html
10291: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
10292: # $relpath - Current path (relative to top level).
10293: # $dirhashref - reference to hash to populate with URLs of directories (Required)
10294: # $filehashref - reference to hash to populate with URLs of files (Optional)
10295: #
10296: # Returns: nothing
10297: #
10298: # Side Effects: populates $dirhashref, and $filehashref (if provided).
10299: #
10300: # Currently used by interface/londocs.pm to create linked select boxes for
10301: # directory and filename to import a Course "Author" resource into a course, and
10302: # also to create linked select boxes for Authoring Space and Directory to choose
10303: # save location for creation of a new "standard" problem from the Course Editor.
10304: #
10305:
10306: sub recursedirs {
10307: my ($is_home,$context,$docroot,$toppath,$relpath,$dirhashref,$filehashref) = @_;
10308: return unless (ref($dirhashref) eq 'HASH');
10309: my $currpath = $docroot.$toppath;
10310: if ($relpath) {
10311: $currpath .= "/$relpath";
10312: }
10313: my $savefile;
10314: if (ref($filehashref)) {
10315: $savefile = 1;
10316: }
10317: if ($is_home) {
10318: if (opendir(my $dirh,$currpath)) {
10319: foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
10320: next if ($item eq '');
10321: if (-d "$currpath/$item") {
10322: my $newpath;
10323: if ($relpath) {
10324: $newpath = "$relpath/$item";
10325: } else {
10326: $newpath = $item;
10327: }
10328: $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
10329: &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
10330: } elsif ($savefile) {
10331: if ($context eq 'priv') {
10332: unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
10333: $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
10334: }
10335: } else {
10336: unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/) || ($item =~ /\.rights$/)) {
10337: $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
10338: }
10339: }
10340: }
10341: }
10342: closedir($dirh);
10343: }
10344: } else {
10345: my ($dirlistref,$listerror) =
10346: &dirlist($toppath.$relpath);
10347: my @dir_lines;
10348: my $dirptr=16384;
10349: if (ref($dirlistref) eq 'ARRAY') {
10350: foreach my $dir_line (sort
10351: {
10352: my ($afile)=split('&',$a,2);
10353: my ($bfile)=split('&',$b,2);
10354: return (lc($afile) cmp lc($bfile));
10355: } (@{$dirlistref})) {
10356: my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
10357: split(/\&/,$dir_line,16);
10358: $item =~ s/\s+$//;
10359: next if (($item =~ /^\.\.?$/) || ($obs));
10360: if ($dirptr&$testdir) {
10361: my $newpath;
10362: if ($relpath) {
10363: $newpath = "$relpath/$item";
10364: } else {
10365: $relpath = '/';
10366: $newpath = $item;
10367: }
10368: $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
10369: &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
10370: } elsif ($savefile) {
10371: if ($context eq 'priv') {
10372: unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
10373: $filehashref->{$relpath}{$item} = 1;
10374: }
10375: } else {
10376: unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/)) {
10377: $filehashref->{$relpath}{$item} = 1;
10378: }
10379: }
10380: }
10381: }
10382: }
10383: }
10384: return;
10385: }
10386:
1.26 www 10387: # -------------------------------------------------------- Value of a Condition
10388:
1.713 albertel 10389: # gets the value of a specific preevaluated condition
10390: # stored in the string $env{user.state.<cid>}
10391: # or looks up a condition reference in the bighash and if if hasn't
10392: # already been evaluated recurses into docondval to get the value of
10393: # the condition, then memoizing it to
10394: # $env{user.state.<cid>.<condition>}
1.40 www 10395: sub directcondval {
10396: my $number=shift;
1.620 albertel 10397: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 10398: &Apache::lonuserstate::evalstate();
10399: }
1.713 albertel 10400: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
10401: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
10402: } elsif ($number =~ /^_/) {
10403: my $sub_condition;
10404: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10405: &GDBM_READER(),0640)) {
10406: $sub_condition=$bighash{'conditions'.$number};
10407: untie(%bighash);
10408: }
10409: my $value = &docondval($sub_condition);
1.949 raeburn 10410: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 10411: return $value;
10412: }
1.620 albertel 10413: if ($env{'user.state.'.$env{'request.course.id'}}) {
10414: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 10415: } else {
10416: return 2;
10417: }
10418: }
10419:
1.713 albertel 10420: # get the collection of conditions for this resource
1.26 www 10421: sub condval {
10422: my $condidx=shift;
1.54 www 10423: my $allpathcond='';
1.713 albertel 10424: foreach my $cond (split(/\|/,$condidx)) {
10425: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
10426: $allpathcond.=
10427: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
10428: }
1.191 harris41 10429: }
1.54 www 10430: $allpathcond=~s/\|$//;
1.713 albertel 10431: return &docondval($allpathcond);
10432: }
10433:
10434: #evaluates an expression of conditions
10435: sub docondval {
10436: my ($allpathcond) = @_;
10437: my $result=0;
10438: if ($env{'request.course.id'}
10439: && defined($allpathcond)) {
10440: my $operand='|';
10441: my @stack;
10442: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
10443: if ($chunk eq '(') {
10444: push @stack,($operand,$result);
10445: } elsif ($chunk eq ')') {
10446: my $before=pop @stack;
10447: if (pop @stack eq '&') {
10448: $result=$result>$before?$before:$result;
10449: } else {
10450: $result=$result>$before?$result:$before;
10451: }
10452: } elsif (($chunk eq '&') || ($chunk eq '|')) {
10453: $operand=$chunk;
10454: } else {
10455: my $new=directcondval($chunk);
10456: if ($operand eq '&') {
10457: $result=$result>$new?$new:$result;
10458: } else {
10459: $result=$result>$new?$result:$new;
10460: }
10461: }
10462: }
1.26 www 10463: }
10464: return $result;
1.421 albertel 10465: }
10466:
10467: # ---------------------------------------------------- Devalidate courseresdata
10468:
10469: sub devalidatecourseresdata {
10470: my ($coursenum,$coursedomain)=@_;
10471: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 10472: &devalidate_cache_new('courseres',$hashid);
1.28 www 10473: }
10474:
1.763 www 10475:
1.200 www 10476: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 10477: #
10478: # Parameters:
10479: # $coursenum - Number of the course.
10480: # $coursedomain - Domain at which the course was created.
10481: # Returns:
10482: # A hash of the course parameters along (I think) with timestamps
10483: # and version info.
1.877 foxr 10484:
1.624 albertel 10485: sub get_courseresdata {
10486: my ($coursenum,$coursedomain)=@_;
1.200 www 10487: my $coursehom=&homeserver($coursenum,$coursedomain);
10488: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 10489: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 10490: my %dumpreply;
1.417 albertel 10491: unless (defined($cached)) {
1.624 albertel 10492: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 10493: $result=\%dumpreply;
1.251 albertel 10494: my ($tmp) = keys(%dumpreply);
10495: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 10496: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 10497: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
10498: return $tmp;
1.416 albertel 10499: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 10500: $result=undef;
1.599 albertel 10501: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 10502: }
10503: }
1.624 albertel 10504: return $result;
10505: }
10506:
1.633 albertel 10507: sub devalidateuserresdata {
10508: my ($uname,$udom)=@_;
10509: my $hashid="$udom:$uname";
10510: &devalidate_cache_new('userres',$hashid);
10511: }
10512:
1.624 albertel 10513: sub get_userresdata {
10514: my ($uname,$udom)=@_;
10515: #most student don\'t have any data set, check if there is some data
10516: if (&EXT_cache_status($udom,$uname)) { return undef; }
10517:
10518: my $hashid="$udom:$uname";
10519: my ($result,$cached)=&is_cached_new('userres',$hashid);
10520: if (!defined($cached)) {
10521: my %resourcedata=&dump('resourcedata',$udom,$uname);
10522: $result=\%resourcedata;
10523: &do_cache_new('userres',$hashid,$result,600);
10524: }
10525: my ($tmp)=keys(%$result);
10526: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
10527: return $result;
10528: }
10529: #error 2 occurs when the .db doesn't exist
10530: if ($tmp!~/error: 2 /) {
1.1294 raeburn 10531: if ((!defined($cached)) || ($tmp ne 'con_lost')) {
10532: &logthis("<font color=\"blue\">WARNING:".
10533: " Trying to get resource data for ".
10534: $uname." at ".$udom.": ".
10535: $tmp."</font>");
10536: }
1.624 albertel 10537: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 10538: #&EXT_cache_set($udom,$uname);
10539: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 10540: undef($tmp); # not really an error so don't send it back
1.624 albertel 10541: }
10542: return $tmp;
10543: }
1.879 foxr 10544: #----------------------------------------------- resdata - return resource data
10545: # Purpose:
10546: # Return resource data for either users or for a course.
10547: # Parameters:
10548: # $name - Course/user name.
10549: # $domain - Name of the domain the user/course is registered on.
1.1311 raeburn 10550: # $type - Type of thing $name is (must be 'course' or 'user')
1.1301 raeburn 10551: # $mapp - decluttered URL of enclosing map
10552: # $recursed - Ref to scalar -- set to 1, if nested maps have been recursed.
10553: # $recurseup - Ref to array of map URLs, starting with map containing
10554: # $mapp up through hierarchy of nested maps to top level map.
10555: # $courseid - CourseID (first part of param identifier).
10556: # $modifier - Middle part of param identifier.
10557: # $what - Last part of param identifier.
1.879 foxr 10558: # @which - Array of names of resources desired.
10559: # Returns:
10560: # The value of the first reasource in @which that is found in the
10561: # resource hash.
10562: # Exceptional Conditions:
10563: # If the $type passed in is not valid (not the string 'course' or
10564: # 'user', an undefined reference is returned.
10565: # If none of the resources are found, an undef is returned
1.624 albertel 10566: sub resdata {
1.1301 raeburn 10567: my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
10568: $modifier,$what,@which)=@_;
1.624 albertel 10569: my $result;
10570: if ($type eq 'course') {
10571: $result=&get_courseresdata($name,$domain);
10572: } elsif ($type eq 'user') {
10573: $result=&get_userresdata($name,$domain);
10574: }
10575: if (!ref($result)) { return $result; }
1.251 albertel 10576: foreach my $item (@which) {
1.1301 raeburn 10577: if ($item->[1] eq 'course') {
10578: if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
10579: unless ($$recursed) {
1.1302 raeburn 10580: @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
1.1301 raeburn 10581: $$recursed = 1;
10582: }
10583: foreach my $item (@${recurseup}) {
10584: my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
10585: last if (defined($result->{$norecursechk}));
10586: my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
10587: if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
10588: }
10589: }
10590: }
10591: if (defined($result->{$item->[0]})) {
1.927 albertel 10592: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 10593: }
1.250 albertel 10594: }
1.291 albertel 10595: return undef;
1.200 www 10596: }
10597:
1.1298 raeburn 10598: sub get_domain_ltitools {
10599: my ($cdom) = @_;
10600: my %ltitools;
10601: my ($result,$cached)=&is_cached_new('ltitools',$cdom);
10602: if (defined($cached)) {
10603: if (ref($result) eq 'HASH') {
10604: %ltitools = %{$result};
10605: }
10606: } else {
10607: my %domconfig = &get_dom('configuration',['ltitools'],$cdom);
10608: if (ref($domconfig{'ltitools'}) eq 'HASH') {
10609: %ltitools = %{$domconfig{'ltitools'}};
10610: }
10611: my $cachetime = 24*60*60;
10612: &do_cache_new('ltitools',$cdom,\%ltitools,$cachetime);
10613: }
10614: return %ltitools;
10615: }
10616:
1.1236 raeburn 10617: sub get_numsuppfiles {
10618: my ($cnum,$cdom,$ignorecache)=@_;
10619: my $hashid=$cnum.':'.$cdom;
10620: my ($suppcount,$cached);
10621: unless ($ignorecache) {
10622: ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
10623: }
10624: unless (defined($cached)) {
10625: my $chome=&homeserver($cnum,$cdom);
10626: unless ($chome eq 'no_host') {
10627: ($suppcount,my $errors) = (0,0);
10628: my $suppmap = 'supplemental.sequence';
10629: ($suppcount,$errors) =
10630: &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
10631: }
10632: &do_cache_new('suppcount',$hashid,$suppcount,600);
10633: }
10634: return $suppcount;
10635: }
10636:
1.379 matthew 10637: #
10638: # EXT resource caching routines
10639: #
10640:
1.1302 raeburn 10641: {
10642: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
10643: #
10644: # The course for which we cache
10645: my $cachedmapkey='';
10646: # The cached recursive maps for this course
10647: my %cachedmaps=();
10648: # When this was last done
10649: my $cachedmaptime='';
10650:
1.379 matthew 10651: sub clear_EXT_cache_status {
1.383 albertel 10652: &delenv('cache.EXT.');
1.379 matthew 10653: }
10654:
10655: sub EXT_cache_status {
10656: my ($target_domain,$target_user) = @_;
1.383 albertel 10657: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 10658: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 10659: # We know already the user has no data
10660: return 1;
10661: } else {
10662: return 0;
10663: }
10664: }
10665:
10666: sub EXT_cache_set {
10667: my ($target_domain,$target_user) = @_;
1.383 albertel 10668: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 10669: #&appenv({$cachename => time});
1.379 matthew 10670: }
10671:
1.28 www 10672: # --------------------------------------------------------- Value of a Variable
1.58 www 10673: sub EXT {
1.715 albertel 10674:
1.1228 raeburn 10675: my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68 www 10676: unless ($varname) { return ''; }
1.218 albertel 10677: #get real user name/domain, courseid and symb
10678: my $courseid;
1.359 albertel 10679: my $publicuser;
1.427 www 10680: if ($symbparm) {
10681: $symbparm=&get_symb_from_alias($symbparm);
10682: }
1.218 albertel 10683: if (!($uname && $udom)) {
1.790 albertel 10684: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 10685: if (!$symbparm) { $symbparm=$cursymb; }
10686: } else {
1.620 albertel 10687: $courseid=$env{'request.course.id'};
1.218 albertel 10688: }
1.48 www 10689: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
10690: my $rest;
1.320 albertel 10691: if (defined($therest[0])) {
1.48 www 10692: $rest=join('.',@therest);
10693: } else {
10694: $rest='';
10695: }
1.320 albertel 10696:
1.57 www 10697: my $qualifierrest=$qualifier;
10698: if ($rest) { $qualifierrest.='.'.$rest; }
10699: my $spacequalifierrest=$space;
10700: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 10701: if ($realm eq 'user') {
1.48 www 10702: # --------------------------------------------------------------- user.resource
10703: if ($space eq 'resource') {
1.651 albertel 10704: if ( (defined($Apache::lonhomework::parsing_a_problem)
10705: || defined($Apache::lonhomework::parsing_a_task))
10706: &&
1.744 albertel 10707: ($symbparm eq &symbread()) ) {
10708: # if we are in the middle of processing the resource the
10709: # get the value we are planning on committing
10710: if (defined($Apache::lonhomework::results{$qualifierrest})) {
10711: return $Apache::lonhomework::results{$qualifierrest};
10712: } else {
10713: return $Apache::lonhomework::history{$qualifierrest};
10714: }
1.335 albertel 10715: } else {
1.359 albertel 10716: my %restored;
1.620 albertel 10717: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 10718: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
10719: } else {
10720: %restored=&restore($symbparm,$courseid,$udom,$uname);
10721: }
1.335 albertel 10722: return $restored{$qualifierrest};
10723: }
1.48 www 10724: # ----------------------------------------------------------------- user.access
10725: } elsif ($space eq 'access') {
1.218 albertel 10726: # FIXME - not supporting calls for a specific user
1.48 www 10727: return &allowed($qualifier,$rest);
10728: # ------------------------------------------ user.preferences, user.environment
10729: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 10730: if (($uname eq $env{'user.name'}) &&
10731: ($udom eq $env{'user.domain'})) {
10732: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 10733: } else {
1.359 albertel 10734: my %returnhash;
10735: if (!$publicuser) {
10736: %returnhash=&userenvironment($udom,$uname,
10737: $qualifierrest);
10738: }
1.218 albertel 10739: return $returnhash{$qualifierrest};
10740: }
1.48 www 10741: # ----------------------------------------------------------------- user.course
10742: } elsif ($space eq 'course') {
1.218 albertel 10743: # FIXME - not supporting calls for a specific user
1.620 albertel 10744: return $env{join('.',('request.course',$qualifier))};
1.48 www 10745: # ------------------------------------------------------------------- user.role
10746: } elsif ($space eq 'role') {
1.218 albertel 10747: # FIXME - not supporting calls for a specific user
1.620 albertel 10748: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 10749: if ($qualifier eq 'value') {
10750: return $role;
10751: } elsif ($qualifier eq 'extent') {
10752: return $where;
10753: }
10754: # ----------------------------------------------------------------- user.domain
10755: } elsif ($space eq 'domain') {
1.218 albertel 10756: return $udom;
1.48 www 10757: # ------------------------------------------------------------------- user.name
10758: } elsif ($space eq 'name') {
1.218 albertel 10759: return $uname;
1.48 www 10760: # ---------------------------------------------------- Any other user namespace
1.29 www 10761: } else {
1.359 albertel 10762: my %reply;
10763: if (!$publicuser) {
10764: %reply=&get($space,[$qualifierrest],$udom,$uname);
10765: }
10766: return $reply{$qualifierrest};
1.48 www 10767: }
1.236 www 10768: } elsif ($realm eq 'query') {
10769: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 10770: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
10771: [$spacequalifierrest]);
1.620 albertel 10772: return $env{'form.'.$spacequalifierrest};
1.236 www 10773: } elsif ($realm eq 'request') {
1.48 www 10774: # ------------------------------------------------------------- request.browser
10775: if ($space eq 'browser') {
1.1145 bisitz 10776: return $env{'browser.'.$qualifier};
1.57 www 10777: # ------------------------------------------------------------ request.filename
10778: } else {
1.620 albertel 10779: return $env{'request.'.$spacequalifierrest};
1.29 www 10780: }
1.28 www 10781: } elsif ($realm eq 'course') {
1.48 www 10782: # ---------------------------------------------------------- course.description
1.620 albertel 10783: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 10784: } elsif ($realm eq 'resource') {
1.165 www 10785:
1.620 albertel 10786: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 10787: if (!$symbparm) { $symbparm=&symbread(); }
10788: }
1.693 albertel 10789:
1.1232 raeburn 10790: if ($qualifier eq '') {
10791: if ($space eq 'title') {
10792: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
10793: return &gettitle($symbparm);
10794: }
1.693 albertel 10795:
1.1232 raeburn 10796: if ($space eq 'map') {
10797: my ($map) = &decode_symb($symbparm);
10798: return &symbread($map);
10799: }
10800: if ($space eq 'maptitle') {
10801: my ($map) = &decode_symb($symbparm);
10802: return &gettitle($map);
10803: }
10804: if ($space eq 'filename') {
10805: if ($symbparm) {
10806: return &clutter((&decode_symb($symbparm))[2]);
10807: }
10808: return &hreflocation('',$env{'request.filename'});
1.905 albertel 10809: }
1.1232 raeburn 10810:
1.1233 raeburn 10811: if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
10812: if ($space eq 'visibleparts') {
10813: my $navmap = Apache::lonnavmaps::navmap->new();
10814: my $item;
10815: if (ref($navmap)) {
10816: my $res = $navmap->getBySymb($symbparm);
10817: my $parts = $res->parts();
10818: if (ref($parts) eq 'ARRAY') {
10819: $item = join(',',@{$parts});
10820: }
10821: undef($navmap);
1.1232 raeburn 10822: }
1.1233 raeburn 10823: return $item;
1.1232 raeburn 10824: }
10825: }
10826: }
1.693 albertel 10827:
1.1301 raeburn 10828: my ($section, $group, @groups, @recurseup, $recursed);
10829: my ($courselevelm,$courseleveli,$courselevel,$mapp);
1.1228 raeburn 10830: if (($courseid eq '') && ($cid)) {
10831: $courseid = $cid;
10832: }
10833: if (($symbparm && $courseid) &&
10834: (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165 www 10835:
1.218 albertel 10836: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 10837:
1.60 www 10838: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 10839: my $symbp=$symbparm;
1.1301 raeburn 10840: $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 10841: my $symbparm=$symbp.'.'.$spacequalifierrest;
1.1301 raeburn 10842: my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
1.218 albertel 10843: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
1.620 albertel 10844: if (($env{'user.name'} eq $uname) &&
10845: ($env{'user.domain'} eq $udom)) {
10846: $section=$env{'request.course.sec'};
1.733 raeburn 10847: @groups = split(/:/,$env{'request.course.groups'});
10848: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 10849: } else {
1.539 albertel 10850: if (! defined($usection)) {
1.551 albertel 10851: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 10852: } else {
10853: $section = $usection;
10854: }
1.733 raeburn 10855: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 10856: }
10857:
10858: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
10859: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
1.1301 raeburn 10860: my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
1.218 albertel 10861: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
10862:
1.593 albertel 10863: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 10864: my $courselevelr=$courseid.'.'.$symbparm;
1.1301 raeburn 10865: $courseleveli=$courseid.'.'.$recurseparm;
1.593 albertel 10866: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 10867:
1.60 www 10868: # ----------------------------------------------------------- first, check user
1.624 albertel 10869:
1.1301 raeburn 10870: my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
10871: \@recurseup,$courseid,'.',$spacequalifierrest,
1.927 albertel 10872: ([$courselevelr,'resource'],
10873: [$courselevelm,'map' ],
1.1301 raeburn 10874: [$courseleveli,'map' ],
1.927 albertel 10875: [$courselevel, 'course' ]));
1.931 albertel 10876: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 10877:
1.594 albertel 10878: # ------------------------------------------------ second, check some of course
1.684 raeburn 10879: my $coursereply;
1.691 raeburn 10880: if (@groups > 0) {
10881: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
1.1301 raeburn 10882: $recurseparm,$mapparm,$spacequalifierrest,
10883: $mapp,\$recursed,\@recurseup);
10884: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 10885: }
1.96 www 10886:
1.684 raeburn 10887: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 10888: $env{'course.'.$courseid.'.domain'},
1.1301 raeburn 10889: 'course',$mapp,\$recursed,\@recurseup,
10890: $courseid,'.['.$section.'].',$spacequalifierrest,
1.927 albertel 10891: ([$seclevelr, 'resource'],
10892: [$seclevelm, 'map' ],
1.1301 raeburn 10893: [$secleveli, 'map' ],
1.927 albertel 10894: [$seclevel, 'course' ],
10895: [$courselevelr,'resource']));
10896: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 10897:
1.60 www 10898: # ------------------------------------------------------ third, check map parms
1.218 albertel 10899: my %parmhash=();
10900: my $thisparm='';
10901: if (tie(%parmhash,'GDBM_File',
1.620 albertel 10902: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 10903: &GDBM_READER(),0640)) {
1.218 albertel 10904: $thisparm=$parmhash{$symbparm};
10905: untie(%parmhash);
10906: }
1.927 albertel 10907: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 10908: }
1.594 albertel 10909: # ------------------------------------------ fourth, look in resource metadata
1.1301 raeburn 10910:
10911: my $what = $spacequalifierrest;
10912: $what=~s/\./\_/;
1.282 albertel 10913: my $filename;
10914: if (!$symbparm) { $symbparm=&symbread(); }
10915: if ($symbparm) {
1.409 www 10916: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 10917: } else {
1.620 albertel 10918: $filename=$env{'request.filename'};
1.282 albertel 10919: }
1.1301 raeburn 10920: my $metadata=&metadata($filename,$what);
1.927 albertel 10921: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.1301 raeburn 10922: $metadata=&metadata($filename,'parameter_'.$what);
1.927 albertel 10923: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 10924:
1.1301 raeburn 10925: # ----------------------------------------------- fifth, look in rest of course
1.593 albertel 10926: if ($symbparm && defined($courseid) &&
1.620 albertel 10927: $courseid eq $env{'request.course.id'}) {
1.624 albertel 10928: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
10929: $env{'course.'.$courseid.'.domain'},
1.1301 raeburn 10930: 'course',$mapp,\$recursed,\@recurseup,
10931: $courseid,'.',$spacequalifierrest,
1.927 albertel 10932: ([$courselevelm,'map' ],
1.1301 raeburn 10933: [$courseleveli,'map' ],
1.927 albertel 10934: [$courselevel, 'course']));
10935: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 10936: }
1.145 www 10937: # ------------------------------------------------------------------ Cascade up
1.218 albertel 10938: unless ($space eq '0') {
1.336 albertel 10939: my @parts=split(/_/,$space);
10940: my $id=pop(@parts);
10941: my $part=join('_',@parts);
10942: if ($part eq '') { $part='0'; }
1.927 albertel 10943: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 10944: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 10945: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 10946: }
1.395 albertel 10947: if ($recurse) { return undef; }
10948: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 10949: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 10950: # ---------------------------------------------------- Any other user namespace
10951: } elsif ($realm eq 'environment') {
10952: # ----------------------------------------------------------------- environment
1.620 albertel 10953: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
10954: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 10955: } else {
1.770 albertel 10956: if ($uname eq 'anonymous' && $udom eq '') {
10957: return '';
10958: }
1.219 albertel 10959: my %returnhash=&userenvironment($udom,$uname,
10960: $spacequalifierrest);
10961: return $returnhash{$spacequalifierrest};
10962: }
1.28 www 10963: } elsif ($realm eq 'system') {
1.48 www 10964: # ----------------------------------------------------------------- system.time
10965: if ($space eq 'time') {
10966: return time;
10967: }
1.696 albertel 10968: } elsif ($realm eq 'server') {
10969: # ----------------------------------------------------------------- system.time
10970: if ($space eq 'name') {
10971: return $ENV{'SERVER_NAME'};
10972: }
1.28 www 10973: }
1.48 www 10974: return '';
1.61 www 10975: }
10976:
1.927 albertel 10977: sub get_reply {
10978: my ($reply_value) = @_;
1.940 raeburn 10979: if (ref($reply_value) eq 'ARRAY') {
10980: if (wantarray) {
10981: return @$reply_value;
10982: }
10983: return $reply_value->[0];
10984: } else {
10985: return $reply_value;
1.927 albertel 10986: }
10987: }
10988:
1.691 raeburn 10989: sub check_group_parms {
1.1301 raeburn 10990: my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
10991: $recursed,$recurseupref) = @_;
10992: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
10993: [$what,'course']);
10994: my $coursereply;
1.691 raeburn 10995: foreach my $group (@{$groups}) {
1.1301 raeburn 10996: my @groupitems = ();
1.691 raeburn 10997: foreach my $level (@levels) {
1.927 albertel 10998: my $item = $courseid.'.['.$group.'].'.$level->[0];
10999: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 11000: }
1.1301 raeburn 11001: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
11002: $env{'course.'.$courseid.'.domain'},
11003: 'course',$mapp,$recursed,$recurseupref,
11004: $courseid,'.['.$group.'].',$what,
11005: @groupitems);
11006: last if (defined($coursereply));
1.691 raeburn 11007: }
11008: return $coursereply;
11009: }
11010:
1.1301 raeburn 11011: sub get_map_hierarchy {
1.1302 raeburn 11012: my ($mapname,$courseid) = @_;
11013: my @recurseup = ();
1.1301 raeburn 11014: if ($mapname) {
1.1302 raeburn 11015: if (($cachedmapkey eq $courseid) &&
11016: (abs($cachedmaptime-time)<5)) {
11017: if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
11018: return @{$cachedmaps{$mapname}};
11019: }
11020: }
1.1301 raeburn 11021: my $navmap = Apache::lonnavmaps::navmap->new();
11022: if (ref($navmap)) {
11023: @recurseup = $navmap->recurseup_maps($mapname);
11024: undef($navmap);
1.1302 raeburn 11025: $cachedmaps{$mapname} = \@recurseup;
11026: $cachedmaptime=time;
11027: $cachedmapkey=$courseid;
1.1301 raeburn 11028: }
11029: }
11030: return @recurseup;
11031: }
11032:
1.1302 raeburn 11033: }
11034:
1.691 raeburn 11035: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 11036: my ($courseid,@groups) = @_;
11037: @groups = sort(@groups);
1.691 raeburn 11038: return @groups;
11039: }
11040:
1.395 albertel 11041: sub packages_tab_default {
11042: my ($uri,$varname)=@_;
11043: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 11044:
11045: my (@extension,@specifics,$do_default);
11046: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 11047: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 11048: if ($pack_type eq 'default') {
11049: $do_default=1;
11050: } elsif ($pack_type eq 'extension') {
11051: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 11052: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 11053: # only look at packages defaults for packages that this id is
1.738 albertel 11054: push(@specifics,[$package,$pack_type,$pack_part]);
11055: }
11056: }
11057: # first look for a package that matches the requested part id
11058: foreach my $package (@specifics) {
11059: my (undef,$pack_type,$pack_part)=@{$package};
11060: next if ($pack_part ne $part);
11061: if (defined($packagetab{"$pack_type&$name&default"})) {
11062: return $packagetab{"$pack_type&$name&default"};
11063: }
11064: }
11065: # look for any possible matching non extension_ package
11066: foreach my $package (@specifics) {
11067: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 11068: if (defined($packagetab{"$pack_type&$name&default"})) {
11069: return $packagetab{"$pack_type&$name&default"};
11070: }
1.585 albertel 11071: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 11072: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
11073: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 11074: }
11075: }
1.738 albertel 11076: # look for any posible extension_ match
11077: foreach my $package (@extension) {
11078: my ($package,$pack_type)=@{$package};
11079: if (defined($packagetab{"$pack_type&$name&default"})) {
11080: return $packagetab{"$pack_type&$name&default"};
11081: }
11082: if (defined($packagetab{$package."&$name&default"})) {
11083: return $packagetab{$package."&$name&default"};
11084: }
11085: }
11086: # look for a global default setting
11087: if ($do_default && defined($packagetab{"default&$name&default"})) {
11088: return $packagetab{"default&$name&default"};
11089: }
1.395 albertel 11090: return undef;
11091: }
11092:
1.334 albertel 11093: sub add_prefix_and_part {
11094: my ($prefix,$part)=@_;
11095: my $keyroot;
11096: if (defined($prefix) && $prefix !~ /^__/) {
11097: # prefix that has a part already
11098: $keyroot=$prefix;
11099: } elsif (defined($prefix)) {
11100: # prefix that is missing a part
11101: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
11102: } else {
11103: # no prefix at all
11104: if (defined($part)) { $keyroot='_'.$part; }
11105: }
11106: return $keyroot;
11107: }
11108:
1.71 www 11109: # ---------------------------------------------------------------- Get metadata
11110:
1.599 albertel 11111: my %metaentry;
1.1070 www 11112: my %importedpartids;
1.71 www 11113: sub metadata {
1.176 www 11114: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 11115: $uri=&declutter($uri);
1.288 albertel 11116: # if it is a non metadata possible uri return quickly
1.529 albertel 11117: if (($uri eq '') ||
11118: (($uri =~ m|^/*adm/|) &&
1.1298 raeburn 11119: ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|exttools?)$})) ||
1.1108 raeburn 11120: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 11121: return undef;
11122: }
1.1261 raeburn 11123: if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv})
1.924 albertel 11124: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 11125: return undef;
1.288 albertel 11126: }
1.73 www 11127: my $filename=$uri;
11128: $uri=~s/\.meta$//;
1.172 www 11129: #
11130: # Is the metadata already cached?
1.177 www 11131: # Look at timestamp of caching
1.172 www 11132: # Everything is cached by the main uri, libraries are never directly cached
11133: #
1.428 albertel 11134: if (!defined($liburi)) {
1.599 albertel 11135: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 11136: if (defined($cached)) { return $result->{':'.$what}; }
11137: }
11138: {
1.1069 www 11139: # Imported parts would go here
1.1070 www 11140: my %importedids=();
11141: my @origfileimportpartids=();
1.1069 www 11142: my $importedparts=0;
1.172 www 11143: #
11144: # Is this a recursive call for a library?
11145: #
1.599 albertel 11146: # if (! exists($metacache{$uri})) {
11147: # $metacache{$uri}={};
11148: # }
1.924 albertel 11149: my $cachetime = 60*60;
1.171 www 11150: if ($liburi) {
11151: $liburi=&declutter($liburi);
11152: $filename=$liburi;
1.401 bowersj2 11153: } else {
1.599 albertel 11154: &devalidate_cache_new('meta',$uri);
11155: undef(%metaentry);
1.401 bowersj2 11156: }
1.140 www 11157: my %metathesekeys=();
1.73 www 11158: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 11159: my $metastring;
1.1140 www 11160: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929 albertel 11161: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 11162: $metastring =
1.929 albertel 11163: &Apache::lonnet::ssi_body($which,
1.924 albertel 11164: ('grade_target' => 'meta'));
11165: $cachetime = 1; # only want this cached in the child not long term
1.1108 raeburn 11166: } elsif (($uri !~ m -^(editupload)/-) &&
11167: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 11168: my $file=&filelocation('',&clutter($filename));
1.599 albertel 11169: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 11170: $metastring=&getfile($file);
1.489 albertel 11171: }
1.208 albertel 11172: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 11173: my $token;
1.140 www 11174: undef %metathesekeys;
1.71 www 11175: while ($token=$parser->get_token) {
1.339 albertel 11176: if ($token->[0] eq 'S') {
11177: if (defined($token->[2]->{'package'})) {
1.172 www 11178: #
11179: # This is a package - get package info
11180: #
1.339 albertel 11181: my $package=$token->[2]->{'package'};
11182: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11183: if (defined($token->[2]->{'id'})) {
11184: $keyroot.='_'.$token->[2]->{'id'};
11185: }
1.599 albertel 11186: if ($metaentry{':packages'}) {
11187: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 11188: } else {
1.599 albertel 11189: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 11190: }
1.736 albertel 11191: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 11192: my $part=$keyroot;
11193: $part=~s/^\_//;
1.736 albertel 11194: if ($pack_entry=~/^\Q$package\E\&/ ||
11195: $pack_entry=~/^\Q$package\E_0\&/) {
11196: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 11197: # ignore package.tab specified default values
11198: # here &package_tab_default() will fetch those
11199: if ($subp eq 'default') { next; }
1.736 albertel 11200: my $value=$packagetab{$pack_entry};
1.432 albertel 11201: my $unikey;
11202: if ($pack =~ /_0$/) {
11203: $unikey='parameter_0_'.$name;
11204: $part=0;
11205: } else {
11206: $unikey='parameter'.$keyroot.'_'.$name;
11207: }
1.339 albertel 11208: if ($subp eq 'display') {
11209: $value.=' [Part: '.$part.']';
11210: }
1.599 albertel 11211: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 11212: $metathesekeys{$unikey}=1;
1.599 albertel 11213: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
11214: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 11215: }
1.599 albertel 11216: if (defined($metaentry{':'.$unikey.'.default'})) {
11217: $metaentry{':'.$unikey}=
11218: $metaentry{':'.$unikey.'.default'};
1.356 albertel 11219: }
1.339 albertel 11220: }
11221: }
11222: } else {
1.172 www 11223: #
11224: # This is not a package - some other kind of start tag
1.339 albertel 11225: #
11226: my $entry=$token->[1];
1.1068 www 11227: my $unikey='';
1.175 www 11228:
1.339 albertel 11229: if ($entry eq 'import') {
1.175 www 11230: #
11231: # Importing a library here
1.339 albertel 11232: #
1.1067 www 11233: my $location=$parser->get_text('/import');
11234: my $dir=$filename;
11235: $dir=~s|[^/]*$||;
11236: $location=&filelocation($dir,$location);
1.1069 www 11237:
1.1068 www 11238: my $importmode=$token->[2]->{'importmode'};
11239: if ($importmode eq 'problem') {
1.1069 www 11240: # Import as problem/response
1.1068 www 11241: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11242: } elsif ($importmode eq 'part') {
11243: # Import as part(s)
1.1069 www 11244: $importedparts=1;
11245: # We need to get the original file and the imported file to get the part order correct
11246: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
11247: # Load and inspect original file
1.1070 www 11248: if ($#origfileimportpartids<0) {
11249: undef(%importedpartids);
11250: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
11251: my $origfile=&getfile($origfilelocation);
11252: @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
11253: }
11254:
1.1069 www 11255: # Load and inspect imported file
11256: my $impfile=&getfile($location);
11257: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
11258: if ($#impfilepartids>=0) {
11259: # This problem had parts
1.1070 www 11260: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 11261: } else {
11262: # Importing by turning a single problem into a problem part
11263: # It gets the import-tags ID as part-ID
11264: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 11265: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 11266: }
1.1068 www 11267: } else {
11268: # Normal import
11269: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11270: if (defined($token->[2]->{'id'})) {
11271: $unikey.='_'.$token->[2]->{'id'};
11272: }
1.1067 www 11273: }
11274:
1.339 albertel 11275: if ($depthcount<20) {
1.736 albertel 11276: my $metadata =
11277: &metadata($uri,'keys', $location,$unikey,
11278: $depthcount+1);
11279: foreach my $meta (split(',',$metadata)) {
11280: $metaentry{':'.$meta}=$metaentry{':'.$meta};
11281: $metathesekeys{$meta}=1;
1.339 albertel 11282: }
1.1068 www 11283:
11284: }
1.1067 www 11285: } else {
11286: #
11287: # Not importing, some other kind of non-package, non-library start tag
11288: #
11289: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
11290: if (defined($token->[2]->{'id'})) {
11291: $unikey.='_'.$token->[2]->{'id'};
11292: }
1.339 albertel 11293: if (defined($token->[2]->{'name'})) {
11294: $unikey.='_'.$token->[2]->{'name'};
11295: }
11296: $metathesekeys{$unikey}=1;
1.736 albertel 11297: foreach my $param (@{$token->[3]}) {
11298: $metaentry{':'.$unikey.'.'.$param} =
11299: $token->[2]->{$param};
1.339 albertel 11300: }
11301: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 11302: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 11303: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
11304: # only ws inside the tag, and not in default, so use default
11305: # as value
1.599 albertel 11306: $metaentry{':'.$unikey}=$default;
1.908 albertel 11307: } elsif ( $internaltext =~ /\S/ ) {
11308: # something interesting inside the tag
11309: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 11310: } else {
1.908 albertel 11311: # no interesting values, don't set a default
1.339 albertel 11312: }
1.172 www 11313: # end of not-a-package not-a-library import
1.339 albertel 11314: }
1.172 www 11315: # end of not-a-package start tag
1.339 albertel 11316: }
1.172 www 11317: # the next is the end of "start tag"
1.339 albertel 11318: }
11319: }
1.483 albertel 11320: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 11321: $extension = lc($extension);
11322: if ($extension eq 'htm') { $extension='html'; }
11323:
1.737 albertel 11324: foreach my $key (keys(%packagetab)) {
1.483 albertel 11325: #no specific packages #how's our extension
11326: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 11327: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 11328: \%metathesekeys);
11329: }
1.883 albertel 11330:
11331: if (!exists($metaentry{':packages'})
11332: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 11333: foreach my $key (keys(%packagetab)) {
1.483 albertel 11334: #no specific packages well let's get default then
11335: if ($key!~/^default&/) { next; }
1.488 albertel 11336: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 11337: \%metathesekeys);
11338: }
11339: }
1.338 www 11340: # are there custom rights to evaluate
1.599 albertel 11341: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 11342:
1.338 www 11343: #
11344: # Importing a rights file here
1.339 albertel 11345: #
11346: unless ($depthcount) {
1.599 albertel 11347: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 11348: my $dir=$filename;
11349: $dir=~s|[^/]*$||;
11350: $location=&filelocation($dir,$location);
1.736 albertel 11351: my $rights_metadata =
11352: &metadata($uri,'keys',$location,'_rights',
11353: $depthcount+1);
11354: foreach my $rights (split(',',$rights_metadata)) {
11355: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
11356: $metathesekeys{$rights}=1;
1.339 albertel 11357: }
11358: }
11359: }
1.737 albertel 11360: # uniqifiy package listing
11361: my %seen;
11362: my @uniq_packages =
11363: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
11364: $metaentry{':packages'} = join(',',@uniq_packages);
11365:
1.1070 www 11366: if ($importedparts) {
11367: # We had imported parts and need to rebuild partorder
11368: $metaentry{':partorder'}='';
11369: $metathesekeys{'partorder'}=1;
11370: for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
11371: if ($origfileimportpartids[$index] eq 'part') {
11372: # original part, part of the problem
11373: $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
11374: } else {
11375: # we have imported parts at this position
11376: $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
11377: }
11378: }
11379: $metaentry{':partorder'}=~s/^\,//;
11380: }
11381:
1.737 albertel 11382: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 11383: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1274 raeburn 11384: $metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924 albertel 11385: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 11386: # this is the end of "was not already recently cached
1.71 www 11387: }
1.599 albertel 11388: return $metaentry{':'.$what};
1.261 albertel 11389: }
11390:
1.488 albertel 11391: sub metadata_create_package_def {
1.483 albertel 11392: my ($uri,$key,$package,$metathesekeys)=@_;
11393: my ($pack,$name,$subp)=split(/\&/,$key);
11394: if ($subp eq 'default') { next; }
11395:
1.599 albertel 11396: if (defined($metaentry{':packages'})) {
11397: $metaentry{':packages'}.=','.$package;
1.483 albertel 11398: } else {
1.599 albertel 11399: $metaentry{':packages'}=$package;
1.483 albertel 11400: }
11401: my $value=$packagetab{$key};
11402: my $unikey;
11403: $unikey='parameter_0_'.$name;
1.599 albertel 11404: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 11405: $$metathesekeys{$unikey}=1;
1.599 albertel 11406: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
11407: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 11408: }
1.599 albertel 11409: if (defined($metaentry{':'.$unikey.'.default'})) {
11410: $metaentry{':'.$unikey}=
11411: $metaentry{':'.$unikey.'.default'};
1.483 albertel 11412: }
11413: }
11414:
1.261 albertel 11415: sub metadata_generate_part0 {
11416: my ($metadata,$metacache,$uri) = @_;
11417: my %allnames;
1.737 albertel 11418: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 11419: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 11420: my $part=$$metacache{':'.$metakey.'.part'};
11421: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 11422: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 11423: $allnames{$name}=$part;
11424: }
11425: }
11426: }
11427: foreach my $name (keys(%allnames)) {
11428: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 11429: my $key=":parameter_0_$name";
1.261 albertel 11430: $$metacache{"$key.part"}='0';
11431: $$metacache{"$key.name"}=$name;
1.428 albertel 11432: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 11433: $allnames{$name}.'_'.$name.
11434: '.type'};
1.428 albertel 11435: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 11436: '.display'};
1.644 www 11437: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 11438: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 11439: $$metacache{"$key.display"}=$olddis;
11440: }
1.71 www 11441: }
11442:
1.764 albertel 11443: # ------------------------------------------------------ Devalidate title cache
11444:
11445: sub devalidate_title_cache {
11446: my ($url)=@_;
11447: if (!$env{'request.course.id'}) { return; }
11448: my $symb=&symbread($url);
11449: if (!$symb) { return; }
11450: my $key=$env{'request.course.id'}."\0".$symb;
11451: &devalidate_cache_new('title',$key);
11452: }
11453:
1.1014 droeschl 11454: # ------------------------------------------------- Get the title of a course
11455:
11456: sub current_course_title {
11457: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
11458: }
1.301 www 11459: # ------------------------------------------------- Get the title of a resource
11460:
11461: sub gettitle {
11462: my $urlsymb=shift;
11463: my $symb=&symbread($urlsymb);
1.534 albertel 11464: if ($symb) {
1.620 albertel 11465: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 11466: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 11467: if (defined($cached)) {
11468: return $result;
11469: }
1.534 albertel 11470: my ($map,$resid,$url)=&decode_symb($symb);
11471: my $title='';
1.907 albertel 11472: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
11473: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
11474: } else {
11475: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11476: &GDBM_READER(),0640)) {
11477: my $mapid=$bighash{'map_pc_'.&clutter($map)};
11478: $title=$bighash{'title_'.$mapid.'.'.$resid};
11479: untie(%bighash);
11480: }
1.534 albertel 11481: }
11482: $title=~s/\&colon\;/\:/gs;
11483: if ($title) {
1.1159 www 11484: # Remember both $symb and $title for dynamic metadata
11485: $accesshash{$symb.'___crstitle'}=$title;
1.1161 www 11486: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159 www 11487: # Cache this title and then return it
1.599 albertel 11488: return &do_cache_new('title',$key,$title,600);
1.534 albertel 11489: }
11490: $urlsymb=$url;
11491: }
11492: my $title=&metadata($urlsymb,'title');
11493: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
11494: return $title;
1.301 www 11495: }
1.613 albertel 11496:
1.614 albertel 11497: sub get_slot {
11498: my ($which,$cnum,$cdom)=@_;
11499: if (!$cnum || !$cdom) {
1.790 albertel 11500: (undef,my $courseid)=&whichuser();
1.620 albertel 11501: $cdom=$env{'course.'.$courseid.'.domain'};
11502: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 11503: }
1.703 albertel 11504: my $key=join("\0",'slots',$cdom,$cnum,$which);
11505: my %slotinfo;
11506: if (exists($remembered{$key})) {
11507: $slotinfo{$which} = $remembered{$key};
11508: } else {
11509: %slotinfo=&get('slots',[$which],$cdom,$cnum);
11510: &Apache::lonhomework::showhash(%slotinfo);
11511: my ($tmp)=keys(%slotinfo);
11512: if ($tmp=~/^error:/) { return (); }
11513: $remembered{$key} = $slotinfo{$which};
11514: }
1.616 albertel 11515: if (ref($slotinfo{$which}) eq 'HASH') {
11516: return %{$slotinfo{$which}};
11517: }
11518: return $slotinfo{$which};
1.614 albertel 11519: }
1.1150 raeburn 11520:
11521: sub get_reservable_slots {
11522: my ($cnum,$cdom,$uname,$udom) = @_;
11523: my $now = time;
11524: my $reservable_info;
11525: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
11526: if (exists($remembered{$key})) {
11527: $reservable_info = $remembered{$key};
11528: } else {
11529: my %resv;
11530: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
11531: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
11532: $reservable_info = \%resv;
11533: $remembered{$key} = $reservable_info;
11534: }
11535: return $reservable_info;
11536: }
11537:
11538: sub get_course_slots {
11539: my ($cnum,$cdom) = @_;
11540: my $hashid=$cnum.':'.$cdom;
11541: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
11542: if (defined($cached)) {
11543: if (ref($result) eq 'HASH') {
11544: return %{$result};
11545: }
11546: } else {
11547: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
11548: my ($tmp) = keys(%slots);
11549: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1219 raeburn 11550: &do_cache_new('allslots',$hashid,\%slots,600);
1.1150 raeburn 11551: return %slots;
11552: }
11553: }
11554: return;
11555: }
11556:
11557: sub devalidate_slots_cache {
11558: my ($cnum,$cdom)=@_;
11559: my $hashid=$cnum.':'.$cdom;
11560: &devalidate_cache_new('allslots',$hashid);
11561: }
11562:
1.1181 raeburn 11563: sub get_coursechange {
11564: my ($cdom,$cnum) = @_;
11565: if ($cdom eq '' || $cnum eq '') {
11566: return unless ($env{'request.course.id'});
11567: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
11568: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
11569: }
11570: my $hashid=$cdom.'_'.$cnum;
11571: my ($change,$cached)=&is_cached_new('crschange',$hashid);
11572: if ((defined($cached)) && ($change ne '')) {
11573: return $change;
11574: } else {
11575: my %crshash;
11576: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
11577: if ($crshash{'internal.contentchange'} eq '') {
11578: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
11579: if ($change eq '') {
11580: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
11581: $change = $crshash{'internal.created'};
11582: }
11583: } else {
11584: $change = $crshash{'internal.contentchange'};
11585: }
11586: my $cachetime = 600;
11587: &do_cache_new('crschange',$hashid,$change,$cachetime);
11588: }
11589: return $change;
11590: }
11591:
11592: sub devalidate_coursechange_cache {
11593: my ($cnum,$cdom)=@_;
11594: my $hashid=$cnum.':'.$cdom;
11595: &devalidate_cache_new('crschange',$hashid);
11596: }
11597:
1.31 www 11598: # ------------------------------------------------- Update symbolic store links
11599:
11600: sub symblist {
11601: my ($mapname,%newhash)=@_;
1.438 www 11602: $mapname=&deversion(&declutter($mapname));
1.31 www 11603: my %hash;
1.620 albertel 11604: if (($env{'request.course.fn'}) && (%newhash)) {
11605: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 11606: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 11607: foreach my $url (keys(%newhash)) {
1.711 albertel 11608: next if ($url eq 'last_known'
11609: && $env{'form.no_update_last_known'});
11610: $hash{declutter($url)}=&encode_symb($mapname,
11611: $newhash{$url}->[1],
11612: $newhash{$url}->[0]);
1.191 harris41 11613: }
1.31 www 11614: if (untie(%hash)) {
11615: return 'ok';
11616: }
11617: }
11618: }
11619: return 'error';
1.212 www 11620: }
11621:
11622: # --------------------------------------------------------------- Verify a symb
11623:
11624: sub symbverify {
1.1190 raeburn 11625: my ($symb,$thisurl,$encstate)=@_;
1.510 www 11626: my $thisfn=$thisurl;
1.439 www 11627: $thisfn=&declutter($thisfn);
1.215 www 11628: # direct jump to resource in page or to a sequence - will construct own symbs
11629: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
11630: # check URL part
1.409 www 11631: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 11632:
1.431 www 11633: unless ($url eq $thisfn) { return 0; }
1.213 www 11634:
1.216 www 11635: $symb=&symbclean($symb);
1.510 www 11636: $thisurl=&deversion($thisurl);
1.439 www 11637: $thisfn=&deversion($thisfn);
1.213 www 11638:
11639: my %bighash;
11640: my $okay=0;
1.431 www 11641:
1.620 albertel 11642: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 11643: &GDBM_READER(),0640)) {
1.1204 raeburn 11644: my $noclutter;
1.1032 raeburn 11645: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
11646: $thisurl =~ s/\?.+$//;
1.1204 raeburn 11647: if ($map =~ m{^uploaded/.+\.page$}) {
11648: $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
11649: $thisurl =~ s{^\Qhttp://https://\E}{https://};
11650: $noclutter = 1;
11651: }
11652: }
11653: my $ids;
11654: if ($noclutter) {
11655: $ids=$bighash{'ids_'.$thisurl};
11656: } else {
11657: $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032 raeburn 11658: }
1.1102 raeburn 11659: unless ($ids) {
11660: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
11661: $ids=$bighash{$idkey};
1.216 www 11662: }
11663: if ($ids) {
11664: # ------------------------------------------------------------------- Has ID(s)
1.1202 raeburn 11665: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
1.1203 raeburn 11666: $symb =~ s/\?.+$//;
1.1202 raeburn 11667: }
1.800 albertel 11668: foreach my $id (split(/\,/,$ids)) {
11669: my ($mapid,$resid)=split(/\./,$id);
1.216 www 11670: if (
11671: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190 raeburn 11672: eq $symb) {
11673: if (ref($encstate)) {
11674: $$encstate = $bighash{'encrypted_'.$id};
11675: }
1.620 albertel 11676: if (($env{'request.role.adv'}) ||
1.1101 raeburn 11677: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
11678: ($thisurl eq '/adm/navmaps')) {
1.1190 raeburn 11679: $okay=1;
1.1202 raeburn 11680: last;
1.582 albertel 11681: }
11682: }
1.216 www 11683: }
11684: }
1.213 www 11685: untie(%bighash);
11686: }
11687: return $okay;
1.31 www 11688: }
11689:
1.210 www 11690: # --------------------------------------------------------------- Clean-up symb
11691:
11692: sub symbclean {
11693: my $symb=shift;
1.568 albertel 11694: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 11695: # remove version from map
11696: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 11697:
1.210 www 11698: # remove version from URL
11699: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 11700:
1.507 www 11701: # remove wrapper
11702:
1.510 www 11703: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 11704: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 11705: return $symb;
1.409 www 11706: }
11707:
11708: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 11709:
11710: sub encode_symb {
11711: my ($map,$resid,$url)=@_;
11712: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
11713: }
1.409 www 11714:
11715: sub decode_symb {
1.568 albertel 11716: my $symb=shift;
11717: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
11718: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 11719: return (&fixversion($map),$resid,&fixversion($url));
11720: }
11721:
11722: sub fixversion {
11723: my $fn=shift;
1.609 banghart 11724: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 11725: my %bighash;
11726: my $uri=&clutter($fn);
1.620 albertel 11727: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 11728: # is this cached?
1.599 albertel 11729: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 11730: if (defined($cached)) { return $result; }
11731: # unfortunately not cached, or expired
1.620 albertel 11732: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 11733: &GDBM_READER(),0640)) {
11734: if ($bighash{'version_'.$uri}) {
11735: my $version=$bighash{'version_'.$uri};
1.444 www 11736: unless (($version eq 'mostrecent') ||
11737: ($version==&getversion($uri))) {
1.440 www 11738: $uri=~s/\.(\w+)$/\.$version\.$1/;
11739: }
11740: }
11741: untie %bighash;
1.413 www 11742: }
1.599 albertel 11743: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 11744: }
11745:
11746: sub deversion {
11747: my $url=shift;
11748: $url=~s/\.\d+\.(\w+)$/\.$1/;
11749: return $url;
1.210 www 11750: }
11751:
1.31 www 11752: # ------------------------------------------------------ Return symb list entry
11753:
11754: sub symbread {
1.1282 raeburn 11755: my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
1.1265 raeburn 11756: my $cache_str='request.symbread.cached.'.$thisfn;
1.1282 raeburn 11757: if (defined($env{$cache_str})) {
11758: if ($ignorecachednull) {
11759: return $env{$cache_str} unless ($env{$cache_str} eq '');
11760: } else {
11761: return $env{$cache_str};
11762: }
11763: }
1.242 www 11764: # no filename provided? try from environment
1.1265 raeburn 11765: unless ($thisfn) {
1.620 albertel 11766: if ($env{'request.symb'}) {
11767: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 11768: }
1.620 albertel 11769: $thisfn=$env{'request.filename'};
1.44 www 11770: }
1.569 albertel 11771: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 11772: # is that filename actually a symb? Verify, clean, and return
11773: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 11774: if (&symbverify($thisfn,$1)) {
1.620 albertel 11775: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 11776: }
1.242 www 11777: }
1.44 www 11778: $thisfn=declutter($thisfn);
1.31 www 11779: my %hash;
1.37 www 11780: my %bighash;
11781: my $syval='';
1.620 albertel 11782: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 11783: my $targetfn = $thisfn;
1.609 banghart 11784: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 11785: $targetfn = 'adm/wrapper/'.$thisfn;
11786: }
1.687 albertel 11787: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
11788: $targetfn=$1;
11789: }
1.620 albertel 11790: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 11791: &GDBM_READER(),0640)) {
1.481 raeburn 11792: $syval=$hash{$targetfn};
1.37 www 11793: untie(%hash);
11794: }
11795: # ---------------------------------------------------------- There was an entry
11796: if ($syval) {
1.601 albertel 11797: #unless ($syval=~/\_\d+$/) {
1.620 albertel 11798: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 11799: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 11800: #return $env{$cache_str}='';
1.601 albertel 11801: #}
11802: #$syval.=$1;
11803: #}
1.37 www 11804: } else {
11805: # ------------------------------------------------------- Was not in symb table
1.620 albertel 11806: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 11807: &GDBM_READER(),0640)) {
1.37 www 11808: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 11809: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 11810: unless ($ids) {
11811: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 11812: }
11813: unless ($ids) {
11814: # alias?
11815: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 11816: }
1.37 www 11817: if ($ids) {
11818: # ------------------------------------------------------------------- Has ID(s)
11819: my @possibilities=split(/\,/,$ids);
1.39 www 11820: if ($#possibilities==0) {
11821: # ----------------------------------------------- There is only one possibility
1.37 www 11822: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 11823: $syval=&encode_symb($bighash{'map_id_'.$mapid},
11824: $resid,$thisfn);
1.1282 raeburn 11825: if (ref($possibles) eq 'HASH') {
11826: $possibles->{$syval} = 1;
11827: }
11828: if ($checkforblock) {
11829: my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
11830: if (@blockers) {
11831: $syval = '';
11832: return;
11833: }
11834: }
11835: } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39 www 11836: # ------------------------------------------ There is more than one possibility
11837: my $realpossible=0;
1.800 albertel 11838: foreach my $id (@possibilities) {
11839: my $file=$bighash{'src_'.$id};
1.1282 raeburn 11840: my $canaccess;
11841: if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
11842: $canaccess = 1;
11843: } else {
11844: $canaccess = &allowed('bre',$file);
11845: }
11846: if ($canaccess) {
11847: my ($mapid,$resid)=split(/\./,$id);
11848: if ($bighash{'map_type_'.$mapid} ne 'page') {
11849: my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
11850: $resid,$thisfn);
11851: if (ref($possibles) eq 'HASH') {
11852: $possibles->{$syval} = 1;
11853: }
11854: if ($checkforblock) {
11855: my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
11856: unless (@blockers > 0) {
11857: $syval = $poss_syval;
11858: $realpossible++;
11859: }
11860: } else {
11861: $syval = $poss_syval;
11862: $realpossible++;
11863: }
11864: }
1.39 www 11865: }
1.191 harris41 11866: }
1.39 www 11867: if ($realpossible!=1) { $syval=''; }
1.249 www 11868: } else {
11869: $syval='';
1.37 www 11870: }
11871: }
1.1282 raeburn 11872: untie(%bighash);
1.481 raeburn 11873: }
1.31 www 11874: }
1.62 www 11875: if ($syval) {
1.620 albertel 11876: return $env{$cache_str}=$syval;
1.62 www 11877: }
1.31 www 11878: }
1.949 raeburn 11879: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 11880: return $env{$cache_str}='';
1.31 www 11881: }
11882:
11883: # ---------------------------------------------------------- Return random seed
11884:
1.32 www 11885: sub numval {
11886: my $txt=shift;
11887: $txt=~tr/A-J/0-9/;
11888: $txt=~tr/a-j/0-9/;
11889: $txt=~tr/K-T/0-9/;
11890: $txt=~tr/k-t/0-9/;
11891: $txt=~tr/U-Z/0-5/;
11892: $txt=~tr/u-z/0-5/;
11893: $txt=~s/\D//g;
1.564 albertel 11894: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 11895: return int($txt);
1.368 albertel 11896: }
11897:
1.484 albertel 11898: sub numval2 {
11899: my $txt=shift;
11900: $txt=~tr/A-J/0-9/;
11901: $txt=~tr/a-j/0-9/;
11902: $txt=~tr/K-T/0-9/;
11903: $txt=~tr/k-t/0-9/;
11904: $txt=~tr/U-Z/0-5/;
11905: $txt=~tr/u-z/0-5/;
11906: $txt=~s/\D//g;
11907: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
11908: my $total;
11909: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 11910: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 11911: return int($total);
11912: }
11913:
1.575 albertel 11914: sub numval3 {
11915: use integer;
11916: my $txt=shift;
11917: $txt=~tr/A-J/0-9/;
11918: $txt=~tr/a-j/0-9/;
11919: $txt=~tr/K-T/0-9/;
11920: $txt=~tr/k-t/0-9/;
11921: $txt=~tr/U-Z/0-5/;
11922: $txt=~tr/u-z/0-5/;
11923: $txt=~s/\D//g;
11924: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
11925: my $total;
11926: foreach my $val (@txts) { $total+=$val; }
11927: if ($_64bit) { $total=(($total<<32)>>32); }
11928: return $total;
11929: }
11930:
1.675 albertel 11931: sub digest {
11932: my ($data)=@_;
11933: my $digest=&Digest::MD5::md5($data);
11934: my ($a,$b,$c,$d)=unpack("iiii",$digest);
11935: my ($e,$f);
11936: {
11937: use integer;
11938: $e=($a+$b);
11939: $f=($c+$d);
11940: if ($_64bit) {
11941: $e=(($e<<32)>>32);
11942: $f=(($f<<32)>>32);
11943: }
11944: }
11945: if (wantarray) {
11946: return ($e,$f);
11947: } else {
11948: my $g;
11949: {
11950: use integer;
11951: $g=($e+$f);
11952: if ($_64bit) {
11953: $g=(($g<<32)>>32);
11954: }
11955: }
11956: return $g;
11957: }
11958: }
11959:
1.368 albertel 11960: sub latest_rnd_algorithm_id {
1.675 albertel 11961: return '64bit5';
1.366 albertel 11962: }
1.32 www 11963:
1.503 albertel 11964: sub get_rand_alg {
11965: my ($courseid)=@_;
1.790 albertel 11966: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 11967: if ($courseid) {
1.620 albertel 11968: return $env{"course.$courseid.rndseed"};
1.503 albertel 11969: }
11970: return &latest_rnd_algorithm_id();
11971: }
11972:
1.562 albertel 11973: sub validCODE {
11974: my ($CODE)=@_;
11975: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
11976: return 0;
11977: }
11978:
1.491 albertel 11979: sub getCODE {
1.620 albertel 11980: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 11981: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
11982: defined($Apache::lonhomework::parsing_a_task) ) &&
11983: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 11984: return $Apache::lonhomework::history{'resource.CODE'};
11985: }
11986: return undef;
11987: }
1.1133 foxr 11988: #
11989: # Determines the random seed for a specific context:
11990: #
11991: # parameters:
11992: # symb - in course context the symb for the seed.
11993: # course_id - The course id of the form domain_coursenum.
11994: # domain - Domain for the user.
11995: # course - Course for the user.
11996: # cenv - environment of the course.
11997: #
11998: # NOTE:
11999: # All parameters are picked out of the environment if missing
12000: # or not defined.
12001: # If a symb cannot be determined the current time is used instead.
12002: #
12003: # For a given well defined symb, courside, domain, username,
12004: # and course environment, the seed is reproducible.
12005: #
1.31 www 12006: sub rndseed {
1.1133 foxr 12007: my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790 albertel 12008: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 12009: if (!defined($symb)) {
1.366 albertel 12010: unless ($symb=$wsymb) { return time; }
12011: }
1.1146 foxr 12012: if (!defined $courseid) {
12013: $courseid=$wcourseid;
12014: }
12015: if (!defined $domain) { $domain=$wdomain; }
12016: if (!defined $username) { $username=$wusername }
1.1133 foxr 12017:
12018: my $which;
12019: if (defined($cenv->{'rndseed'})) {
12020: $which = $cenv->{'rndseed'};
12021: } else {
12022: $which =&get_rand_alg($courseid);
12023: }
1.491 albertel 12024: if (defined(&getCODE())) {
1.1133 foxr 12025:
1.675 albertel 12026: if ($which eq '64bit5') {
12027: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
12028: } elsif ($which eq '64bit4') {
1.575 albertel 12029: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
12030: } else {
12031: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
12032: }
1.675 albertel 12033: } elsif ($which eq '64bit5') {
12034: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 12035: } elsif ($which eq '64bit4') {
12036: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 12037: } elsif ($which eq '64bit3') {
12038: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 12039: } elsif ($which eq '64bit2') {
12040: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 12041: } elsif ($which eq '64bit') {
12042: return &rndseed_64bit($symb,$courseid,$domain,$username);
12043: }
12044: return &rndseed_32bit($symb,$courseid,$domain,$username);
12045: }
12046:
12047: sub rndseed_32bit {
12048: my ($symb,$courseid,$domain,$username)=@_;
12049: {
12050: use integer;
12051: my $symbchck=unpack("%32C*",$symb) << 27;
12052: my $symbseed=numval($symb) << 22;
12053: my $namechck=unpack("%32C*",$username) << 17;
12054: my $nameseed=numval($username) << 12;
12055: my $domainseed=unpack("%32C*",$domain) << 7;
12056: my $courseseed=unpack("%32C*",$courseid);
12057: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 12058: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12059: #&logthis("rndseed :$num:$symb");
1.564 albertel 12060: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 12061: return $num;
12062: }
12063: }
12064:
12065: sub rndseed_64bit {
12066: my ($symb,$courseid,$domain,$username)=@_;
12067: {
12068: use integer;
12069: my $symbchck=unpack("%32S*",$symb) << 21;
12070: my $symbseed=numval($symb) << 10;
12071: my $namechck=unpack("%32S*",$username);
12072:
12073: my $nameseed=numval($username) << 21;
12074: my $domainseed=unpack("%32S*",$domain) << 10;
12075: my $courseseed=unpack("%32S*",$courseid);
12076:
12077: my $num1=$symbchck+$symbseed+$namechck;
12078: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 12079: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12080: #&logthis("rndseed :$num:$symb");
1.564 albertel 12081: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 12082: return "$num1,$num2";
1.155 albertel 12083: }
1.366 albertel 12084: }
12085:
1.443 albertel 12086: sub rndseed_64bit2 {
12087: my ($symb,$courseid,$domain,$username)=@_;
12088: {
12089: use integer;
12090: # strings need to be an even # of cahracters long, it it is odd the
12091: # last characters gets thrown away
12092: my $symbchck=unpack("%32S*",$symb.' ') << 21;
12093: my $symbseed=numval($symb) << 10;
12094: my $namechck=unpack("%32S*",$username.' ');
12095:
12096: my $nameseed=numval($username) << 21;
1.501 albertel 12097: my $domainseed=unpack("%32S*",$domain.' ') << 10;
12098: my $courseseed=unpack("%32S*",$courseid.' ');
12099:
12100: my $num1=$symbchck+$symbseed+$namechck;
12101: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 12102: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12103: #&logthis("rndseed :$num:$symb");
1.803 albertel 12104: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 12105: return "$num1,$num2";
12106: }
12107: }
12108:
12109: sub rndseed_64bit3 {
12110: my ($symb,$courseid,$domain,$username)=@_;
12111: {
12112: use integer;
12113: # strings need to be an even # of cahracters long, it it is odd the
12114: # last characters gets thrown away
12115: my $symbchck=unpack("%32S*",$symb.' ') << 21;
12116: my $symbseed=numval2($symb) << 10;
12117: my $namechck=unpack("%32S*",$username.' ');
12118:
12119: my $nameseed=numval2($username) << 21;
1.443 albertel 12120: my $domainseed=unpack("%32S*",$domain.' ') << 10;
12121: my $courseseed=unpack("%32S*",$courseid.' ');
12122:
12123: my $num1=$symbchck+$symbseed+$namechck;
12124: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 12125: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12126: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 12127: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 12128:
1.503 albertel 12129: return "$num1:$num2";
1.443 albertel 12130: }
12131: }
12132:
1.575 albertel 12133: sub rndseed_64bit4 {
12134: my ($symb,$courseid,$domain,$username)=@_;
12135: {
12136: use integer;
12137: # strings need to be an even # of cahracters long, it it is odd the
12138: # last characters gets thrown away
12139: my $symbchck=unpack("%32S*",$symb.' ') << 21;
12140: my $symbseed=numval3($symb) << 10;
12141: my $namechck=unpack("%32S*",$username.' ');
12142:
12143: my $nameseed=numval3($username) << 21;
12144: my $domainseed=unpack("%32S*",$domain.' ') << 10;
12145: my $courseseed=unpack("%32S*",$courseid.' ');
12146:
12147: my $num1=$symbchck+$symbseed+$namechck;
12148: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 12149: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12150: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 12151: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 12152:
1.575 albertel 12153: return "$num1:$num2";
12154: }
12155: }
12156:
1.675 albertel 12157: sub rndseed_64bit5 {
12158: my ($symb,$courseid,$domain,$username)=@_;
12159: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
12160: return "$num1:$num2";
12161: }
12162:
1.366 albertel 12163: sub rndseed_CODE_64bit {
12164: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 12165: {
1.366 albertel 12166: use integer;
1.443 albertel 12167: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 12168: my $symbseed=numval2($symb);
1.491 albertel 12169: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
12170: my $CODEseed=numval(&getCODE());
1.443 albertel 12171: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 12172: my $num1=$symbseed+$CODEchck;
12173: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 12174: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
12175: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 12176: if ($_64bit) { $num1=(($num1<<32)>>32); }
12177: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 12178: return "$num1:$num2";
1.366 albertel 12179: }
12180: }
12181:
1.575 albertel 12182: sub rndseed_CODE_64bit4 {
12183: my ($symb,$courseid,$domain,$username)=@_;
12184: {
12185: use integer;
12186: my $symbchck=unpack("%32S*",$symb.' ') << 16;
12187: my $symbseed=numval3($symb);
12188: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
12189: my $CODEseed=numval3(&getCODE());
12190: my $courseseed=unpack("%32S*",$courseid.' ');
12191: my $num1=$symbseed+$CODEchck;
12192: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 12193: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
12194: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 12195: if ($_64bit) { $num1=(($num1<<32)>>32); }
12196: if ($_64bit) { $num2=(($num2<<32)>>32); }
12197: return "$num1:$num2";
12198: }
12199: }
12200:
1.675 albertel 12201: sub rndseed_CODE_64bit5 {
12202: my ($symb,$courseid,$domain,$username)=@_;
12203: my $code = &getCODE();
12204: my ($num1,$num2)=&digest("$symb,$courseid,$code");
12205: return "$num1:$num2";
12206: }
12207:
1.366 albertel 12208: sub setup_random_from_rndseed {
12209: my ($rndseed)=@_;
1.503 albertel 12210: if ($rndseed =~/([,:])/) {
1.1262 raeburn 12211: my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
12212: if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
12213: &Math::Random::random_set_seed_from_phrase($rndseed);
12214: } else {
12215: &Math::Random::random_set_seed($num1,$num2);
12216: }
1.366 albertel 12217: } else {
12218: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 12219: }
1.36 albertel 12220: }
12221:
1.474 albertel 12222: sub latest_receipt_algorithm_id {
1.835 albertel 12223: return 'receipt3';
1.474 albertel 12224: }
12225:
1.480 www 12226: sub recunique {
12227: my $fucourseid=shift;
12228: my $unique;
1.835 albertel 12229: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
12230: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 12231: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 12232: } else {
12233: $unique=$perlvar{'lonReceipt'};
12234: }
12235: return unpack("%32C*",$unique);
12236: }
12237:
12238: sub recprefix {
12239: my $fucourseid=shift;
12240: my $prefix;
1.835 albertel 12241: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
12242: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 12243: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 12244: } else {
12245: $prefix=$perlvar{'lonHostID'};
12246: }
12247: return unpack("%32C*",$prefix);
12248: }
12249:
1.76 www 12250: sub ireceipt {
1.474 albertel 12251: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 12252:
12253: my $return =&recprefix($fucourseid).'-';
12254:
12255: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
12256: $env{'request.state'} eq 'construct') {
12257: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
12258: return $return;
12259: }
12260:
1.76 www 12261: my $cuname=unpack("%32C*",$funame);
12262: my $cudom=unpack("%32C*",$fudom);
12263: my $cucourseid=unpack("%32C*",$fucourseid);
12264: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 12265: my $cunique=&recunique($fucourseid);
1.474 albertel 12266: my $cpart=unpack("%32S*",$part);
1.835 albertel 12267: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
12268:
1.790 albertel 12269: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 12270:
12271: $return.= ($cunique%$cuname+
12272: $cunique%$cudom+
12273: $cusymb%$cuname+
12274: $cusymb%$cudom+
12275: $cucourseid%$cuname+
12276: $cucourseid%$cudom+
12277: $cpart%$cuname+
12278: $cpart%$cudom);
12279: } else {
12280: $return.= ($cunique%$cuname+
12281: $cunique%$cudom+
12282: $cusymb%$cuname+
12283: $cusymb%$cudom+
12284: $cucourseid%$cuname+
12285: $cucourseid%$cudom);
12286: }
12287: return $return;
1.76 www 12288: }
12289:
12290: sub receipt {
1.474 albertel 12291: my ($part)=@_;
1.790 albertel 12292: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 12293: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 12294: }
1.260 ng 12295:
1.790 albertel 12296: sub whichuser {
12297: my ($passedsymb)=@_;
12298: my ($symb,$courseid,$domain,$name,$publicuser);
12299: if (defined($env{'form.grade_symb'})) {
12300: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
12301: my $allowed=&allowed('vgr',$tmp_courseid);
12302: if (!$allowed &&
12303: exists($env{'request.course.sec'}) &&
12304: $env{'request.course.sec'} !~ /^\s*$/) {
12305: $allowed=&allowed('vgr',$tmp_courseid.
12306: '/'.$env{'request.course.sec'});
12307: }
12308: if ($allowed) {
12309: ($symb)=&get_env_multiple('form.grade_symb');
12310: $courseid=$tmp_courseid;
12311: ($domain)=&get_env_multiple('form.grade_domain');
12312: ($name)=&get_env_multiple('form.grade_username');
12313: return ($symb,$courseid,$domain,$name,$publicuser);
12314: }
12315: }
12316: if (!$passedsymb) {
12317: $symb=&symbread();
12318: } else {
12319: $symb=$passedsymb;
12320: }
12321: $courseid=$env{'request.course.id'};
12322: $domain=$env{'user.domain'};
12323: $name=$env{'user.name'};
12324: if ($name eq 'public' && $domain eq 'public') {
12325: if (!defined($env{'form.username'})) {
12326: $env{'form.username'}.=time.rand(10000000);
12327: }
12328: $name.=$env{'form.username'};
12329: }
12330: return ($symb,$courseid,$domain,$name,$publicuser);
12331:
12332: }
12333:
1.36 albertel 12334: # ------------------------------------------------------------ Serves up a file
1.472 albertel 12335: # returns either the contents of the file or
12336: # -1 if the file doesn't exist
1.481 raeburn 12337: #
12338: # if the target is a file that was uploaded via DOCS,
12339: # a check will be made to see if a current copy exists on the local server,
12340: # if it does this will be served, otherwise a copy will be retrieved from
12341: # the home server for the course and stored in /home/httpd/html/userfiles on
12342: # the local server.
1.472 albertel 12343:
1.36 albertel 12344: sub getfile {
1.538 albertel 12345: my ($file) = @_;
1.609 banghart 12346: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 12347: &repcopy($file);
12348: return &readfile($file);
12349: }
12350:
12351: sub repcopy_userfile {
12352: my ($file)=@_;
1.1142 raeburn 12353: my $londocroot = $perlvar{'lonDocRoot'};
12354: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164 raeburn 12355: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538 albertel 12356: my ($cdom,$cnum,$filename) =
1.811 albertel 12357: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 12358: my $uri="/uploaded/$cdom/$cnum/$filename";
12359: if (-e "$file") {
1.828 www 12360: # we already have a local copy, check it out
1.538 albertel 12361: my @fileinfo = stat($file);
1.828 www 12362: my $rtncode;
12363: my $info;
1.538 albertel 12364: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 12365: if ($lwpresp ne 'ok') {
1.828 www 12366: # there is no such file anymore, even though we had a local copy
1.482 albertel 12367: if ($rtncode eq '404') {
1.538 albertel 12368: unlink($file);
1.482 albertel 12369: }
12370: return -1;
12371: }
12372: if ($info < $fileinfo[9]) {
1.828 www 12373: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 12374: return 'ok';
1.828 www 12375: } else {
12376: # the file is outdated, get rid of it
12377: unlink($file);
1.482 albertel 12378: }
1.828 www 12379: }
12380: # one way or the other, at this point, we don't have the file
12381: # construct the correct path for the file
12382: my @parts = ($cdom,$cnum);
12383: if ($filename =~ m|^(.+)/[^/]+$|) {
12384: push @parts, split(/\//,$1);
12385: }
12386: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
12387: foreach my $part (@parts) {
12388: $path .= '/'.$part;
12389: if (!-e $path) {
12390: mkdir($path,0770);
1.482 albertel 12391: }
12392: }
1.828 www 12393: # now the path exists for sure
12394: # get a user agent
12395: my $ua=new LWP::UserAgent;
12396: my $transferfile=$file.'.in.transfer';
12397: # FIXME: this should flock
12398: if (-e $transferfile) { return 'ok'; }
12399: my $request;
12400: $uri=~s/^\///;
1.980 raeburn 12401: my $homeserver = &homeserver($cnum,$cdom);
12402: my $protocol = $protocol{$homeserver};
12403: $protocol = 'http' if ($protocol ne 'https');
12404: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 12405: my $response=$ua->request($request,$transferfile);
12406: # did it work?
12407: if ($response->is_error()) {
12408: unlink($transferfile);
12409: &logthis("Userfile repcopy failed for $uri");
12410: return -1;
12411: }
12412: # worked, rename the transfer file
12413: rename($transferfile,$file);
1.607 raeburn 12414: return 'ok';
1.481 raeburn 12415: }
12416:
1.517 albertel 12417: sub tokenwrapper {
12418: my $uri=shift;
1.980 raeburn 12419: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 12420: $uri=~s|^/||;
1.620 albertel 12421: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 12422: my $token=$1;
1.552 albertel 12423: my (undef,$udom,$uname,$file)=split('/',$uri,4);
12424: if ($udom && $uname && $file) {
12425: $file=~s|(\?\.*)*$||;
1.949 raeburn 12426: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 12427: my $homeserver = &homeserver($uname,$udom);
12428: my $protocol = $protocol{$homeserver};
12429: $protocol = 'http' if ($protocol ne 'https');
12430: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 12431: (($uri=~/\?/)?'&':'?').'token='.$token.
12432: '&tokenissued='.$perlvar{'lonHostID'};
12433: } else {
12434: return '/adm/notfound.html';
12435: }
12436: }
12437:
1.828 www 12438: # call with reqtype HEAD: get last modification time
12439: # call with reqtype GET: get the file contents
12440: # Do not call this with reqtype GET for large files! It loads everything into memory
12441: #
1.481 raeburn 12442: sub getuploaded {
12443: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
12444: $uri=~s/^\///;
1.980 raeburn 12445: my $homeserver = &homeserver($cnum,$cdom);
12446: my $protocol = $protocol{$homeserver};
12447: $protocol = 'http' if ($protocol ne 'https');
12448: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 12449: my $ua=new LWP::UserAgent;
12450: my $request=new HTTP::Request($reqtype,$uri);
12451: my $response=$ua->request($request);
12452: $$rtncode = $response->code;
1.482 albertel 12453: if (! $response->is_success()) {
12454: return 'failed';
12455: }
12456: if ($reqtype eq 'HEAD') {
1.486 www 12457: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 12458: } elsif ($reqtype eq 'GET') {
12459: $$info = $response->content;
1.472 albertel 12460: }
1.482 albertel 12461: return 'ok';
1.36 albertel 12462: }
12463:
1.481 raeburn 12464: sub readfile {
12465: my $file = shift;
12466: if ( (! -e $file ) || ($file eq '') ) { return -1; };
12467: my $fh;
12468: open($fh,"<$file");
12469: my $a='';
1.800 albertel 12470: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 12471: return $a;
12472: }
12473:
1.36 albertel 12474: sub filelocation {
1.590 banghart 12475: my ($dir,$file) = @_;
12476: my $location;
12477: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 12478:
12479: if ($file =~ m-^/adm/-) {
12480: $file=~s-^/adm/wrapper/-/-;
12481: $file=~s-^/adm/coursedocs/showdoc/-/-;
12482: }
1.882 albertel 12483:
1.1139 www 12484: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956 raeburn 12485: $location = $file;
1.609 banghart 12486: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 12487: my ($udom,$uname,$filename)=
1.811 albertel 12488: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 12489: my $home=&homeserver($uname,$udom);
12490: my $is_me=0;
12491: my @ids=¤t_machine_ids();
12492: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
12493: if ($is_me) {
1.1117 foxr 12494: $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 12495: } else {
12496: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
12497: $udom.'/'.$uname.'/'.$filename;
12498: }
1.882 albertel 12499: } elsif ($file =~ m-^/adm/-) {
12500: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 12501: } else {
12502: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139 www 12503: $file=~s:^/(res|priv)/:/:;
12504: my $space=$1;
1.590 banghart 12505: if ( !( $file =~ m:^/:) ) {
12506: $location = $dir. '/'.$file;
12507: } else {
1.1142 raeburn 12508: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590 banghart 12509: }
1.59 albertel 12510: }
1.590 banghart 12511: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 12512: while ($location=~m{/\.\./}) {
12513: if ($location =~ m{/[^/]+/\.\./}) {
12514: $location=~ s{/[^/]+/\.\./}{/}g;
12515: } else {
12516: $location=~ s{/\.\./}{/}g;
12517: }
12518: } #remove dir/..
1.590 banghart 12519: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
12520: return $location;
1.46 www 12521: }
1.36 albertel 12522:
1.46 www 12523: sub hreflocation {
12524: my ($dir,$file)=@_;
1.980 raeburn 12525: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 12526: $file=filelocation($dir,$file);
1.700 albertel 12527: } elsif ($file=~m-^/adm/-) {
12528: $file=~s-^/adm/wrapper/-/-;
12529: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 12530: }
12531: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
12532: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
12533: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143 raeburn 12534: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
12535: {/uploaded/$1/$2/}x;
1.46 www 12536: }
1.913 albertel 12537: if ($file=~ m{^/userfiles/}) {
12538: $file =~ s{^/userfiles/}{/uploaded/};
12539: }
1.462 albertel 12540: return $file;
1.465 albertel 12541: }
12542:
1.1139 www 12543:
12544:
12545:
12546:
1.465 albertel 12547: sub current_machine_domains {
1.853 albertel 12548: return &machine_domains(&hostname($perlvar{'lonHostID'}));
12549: }
12550:
12551: sub machine_domains {
12552: my ($hostname) = @_;
1.465 albertel 12553: my @domains;
1.838 albertel 12554: my %hostname = &all_hostnames();
1.465 albertel 12555: while( my($id, $name) = each(%hostname)) {
1.467 matthew 12556: # &logthis("-$id-$name-$hostname-");
1.465 albertel 12557: if ($hostname eq $name) {
1.844 albertel 12558: push(@domains,&host_domain($id));
1.465 albertel 12559: }
12560: }
12561: return @domains;
12562: }
12563:
12564: sub current_machine_ids {
1.853 albertel 12565: return &machine_ids(&hostname($perlvar{'lonHostID'}));
12566: }
12567:
12568: sub machine_ids {
12569: my ($hostname) = @_;
12570: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 12571: my @ids;
1.888 albertel 12572: my %name_to_host = &all_names();
1.889 albertel 12573: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
12574: return @{ $name_to_host{$hostname} };
12575: }
12576: return;
1.31 www 12577: }
12578:
1.824 raeburn 12579: sub additional_machine_domains {
12580: my @domains;
12581: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
12582: while( my $line = <$fh>) {
12583: $line =~ s/\s//g;
12584: push(@domains,$line);
12585: }
12586: return @domains;
12587: }
12588:
12589: sub default_login_domain {
12590: my $domain = $perlvar{'lonDefDomain'};
12591: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
12592: foreach my $posdom (¤t_machine_domains(),
12593: &additional_machine_domains()) {
12594: if (lc($posdom) eq lc($testdomain)) {
12595: $domain=$posdom;
12596: last;
12597: }
12598: }
12599: return $domain;
12600: }
12601:
1.31 www 12602: # ------------------------------------------------------------- Declutters URLs
12603:
12604: sub declutter {
12605: my $thisfn=shift;
1.569 albertel 12606: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1261 raeburn 12607: unless ($thisfn=~m{^/home/httpd/html/priv/}) {
12608: $thisfn=~s{^/home/httpd/html}{};
12609: }
1.31 www 12610: $thisfn=~s/^\///;
1.697 albertel 12611: $thisfn=~s|^adm/wrapper/||;
12612: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 12613: $thisfn=~s/^res\///;
1.1172 bisitz 12614: $thisfn=~s/^priv\///;
1.1032 raeburn 12615: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
12616: $thisfn=~s/\?.+$//;
12617: }
1.268 www 12618: return $thisfn;
12619: }
12620:
12621: # ------------------------------------------------------------- Clutter up URLs
12622:
12623: sub clutter {
12624: my $thisfn='/'.&declutter(shift);
1.887 albertel 12625: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 12626: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 12627: $thisfn='/res'.$thisfn;
12628: }
1.1031 raeburn 12629: if ($thisfn !~m|^/adm|) {
12630: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 12631: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 12632: } else {
12633: my ($ext) = ($thisfn =~ /\.(\w+)$/);
12634: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 12635: if ($embstyle eq 'ssi'
12636: || ($embstyle eq 'hdn')
12637: || ($embstyle eq 'rat')
12638: || ($embstyle eq 'prv')
12639: || ($embstyle eq 'ign')) {
12640: #do nothing with these
12641: } elsif (($embstyle eq 'img')
1.695 albertel 12642: || ($embstyle eq 'emb')
12643: || ($embstyle eq 'wrp')) {
12644: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 12645: } elsif ($embstyle eq 'unk'
12646: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 12647: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 12648: } else {
1.718 www 12649: # &logthis("Got a blank emb style");
1.695 albertel 12650: }
1.694 albertel 12651: }
1.1298 raeburn 12652: } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/exttools?$}) {
12653: $thisfn='/adm/wrapper'.$thisfn;
1.694 albertel 12654: }
1.31 www 12655: return $thisfn;
1.12 www 12656: }
12657:
1.787 albertel 12658: sub clutter_with_no_wrapper {
12659: my $uri = &clutter(shift);
12660: if ($uri =~ m-^/adm/-) {
12661: $uri =~ s-^/adm/wrapper/-/-;
12662: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
12663: }
12664: return $uri;
12665: }
12666:
1.557 albertel 12667: sub freeze_escape {
12668: my ($value)=@_;
12669: if (ref($value)) {
12670: $value=&nfreeze($value);
12671: return '__FROZEN__'.&escape($value);
12672: }
12673: return &escape($value);
12674: }
12675:
1.11 www 12676:
1.557 albertel 12677: sub thaw_unescape {
12678: my ($value)=@_;
12679: if ($value =~ /^__FROZEN__/) {
12680: substr($value,0,10,undef);
12681: $value=&unescape($value);
12682: return &thaw($value);
12683: }
12684: return &unescape($value);
12685: }
12686:
1.436 albertel 12687: sub correct_line_ends {
12688: my ($result)=@_;
12689: $$result =~s/\r\n/\n/mg;
12690: $$result =~s/\r/\n/mg;
1.415 albertel 12691: }
1.1 albertel 12692: # ================================================================ Main Program
12693:
1.184 www 12694: sub goodbye {
1.204 albertel 12695: &logthis("Starting Shut down");
1.443 albertel 12696: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 12697: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 12698: #converted
1.599 albertel 12699: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 12700: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
12701: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
12702: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 12703: #1.1 only
1.870 albertel 12704: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
12705: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
12706: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
12707: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
12708: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 12709: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
12710: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 12711: &flushcourselogs();
12712: &logthis("Shutting down");
12713: }
12714:
1.852 albertel 12715: sub get_dns {
1.1210 raeburn 12716: my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869 albertel 12717: if (!$ignore_cache) {
12718: my ($content,$cached)=
12719: &Apache::lonnet::is_cached_new('dns',$url);
12720: if ($cached) {
1.1210 raeburn 12721: &$func($content,$hashref);
1.869 albertel 12722: return;
12723: }
12724: }
12725:
12726: my %alldns;
1.852 albertel 12727: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
12728: foreach my $dns (<$config>) {
12729: next if ($dns !~ /^\^(\S*)/x);
1.979 raeburn 12730: my $line = $1;
12731: my ($host,$protocol) = split(/:/,$line);
12732: if ($protocol ne 'https') {
12733: $protocol = 'http';
12734: }
12735: $alldns{$host} = $protocol;
1.869 albertel 12736: }
12737: while (%alldns) {
1.1263 raeburn 12738: my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852 albertel 12739: my $ua=new LWP::UserAgent;
1.1134 raeburn 12740: $ua->timeout(30);
1.979 raeburn 12741: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 12742: my $response=$ua->request($request);
1.979 raeburn 12743: delete($alldns{$dns});
1.852 albertel 12744: next if ($response->is_error());
12745: my @content = split("\n",$response->content);
1.1210 raeburn 12746: unless ($nocache) {
1.1219 raeburn 12747: &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1210 raeburn 12748: }
12749: &$func(\@content,$hashref);
1.869 albertel 12750: return;
1.852 albertel 12751: }
12752: close($config);
1.871 albertel 12753: my $which = (split('/',$url))[3];
12754: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
12755: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 12756: my @content = <$config>;
1.1210 raeburn 12757: &$func(\@content,$hashref);
12758: return;
12759: }
12760:
12761: # ------------------------------------------------------Get DNS checksums file
1.1211 raeburn 12762: sub parse_dns_checksums_tab {
1.1210 raeburn 12763: my ($lines,$hashref) = @_;
1.1264 raeburn 12764: my $lonhost = $perlvar{'lonHostID'};
12765: my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1210 raeburn 12766: my $loncaparev = &get_server_loncaparev($machine_dom);
1.1264 raeburn 12767: my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
12768: my $webconfdir = '/etc/httpd/conf';
12769: if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
12770: $webconfdir = '/etc/apache2';
12771: } elsif ($distro =~ /^sles(\d+)$/) {
12772: if ($1 >= 10) {
12773: $webconfdir = '/etc/apache2';
12774: }
12775: } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
12776: if ($1 >= 10.0) {
12777: $webconfdir = '/etc/apache2';
12778: }
12779: }
1.1210 raeburn 12780: my ($release,$timestamp) = split(/\-/,$loncaparev);
12781: my (%chksum,%revnum);
12782: if (ref($lines) eq 'ARRAY') {
12783: chomp(@{$lines});
1.1238 raeburn 12784: my $version = shift(@{$lines});
12785: if ($version eq $release) {
1.1210 raeburn 12786: foreach my $line (@{$lines}) {
1.1238 raeburn 12787: my ($file,$version,$shasum) = split(/,/,$line);
1.1264 raeburn 12788: if ($file =~ m{^/etc/httpd/conf}) {
12789: if ($webconfdir eq '/etc/apache2') {
12790: $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
12791: }
12792: }
1.1238 raeburn 12793: $chksum{$file} = $shasum;
12794: $revnum{$file} = $version;
1.1210 raeburn 12795: }
12796: if (ref($hashref) eq 'HASH') {
12797: %{$hashref} = (
12798: sums => \%chksum,
12799: versions => \%revnum,
12800: );
12801: }
12802: }
12803: }
1.869 albertel 12804: return;
1.852 albertel 12805: }
1.1210 raeburn 12806:
12807: sub fetch_dns_checksums {
1.1238 raeburn 12808: my %checksums;
12809: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1260 raeburn 12810: my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1238 raeburn 12811: my ($release,$timestamp) = split(/\-/,$loncaparev);
12812: &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1211 raeburn 12813: \%checksums);
1.1210 raeburn 12814: return \%checksums;
12815: }
12816:
1.327 albertel 12817: # ------------------------------------------------------------ Read domain file
12818: {
1.852 albertel 12819: my $loaded;
1.846 albertel 12820: my %domain;
12821:
1.852 albertel 12822: sub parse_domain_tab {
12823: my ($lines) = @_;
12824: foreach my $line (@$lines) {
12825: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 12826:
1.846 albertel 12827: chomp($line);
1.852 albertel 12828: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 12829: my %this_domain;
12830: foreach my $field ('description', 'auth_def', 'auth_arg_def',
12831: 'lang_def', 'city', 'longi', 'lati',
12832: 'primary') {
12833: $this_domain{$field} = shift(@elements);
12834: }
12835: $domain{$name} = \%this_domain;
1.852 albertel 12836: }
12837: }
1.864 albertel 12838:
12839: sub reset_domain_info {
12840: undef($loaded);
12841: undef(%domain);
12842: }
12843:
1.852 albertel 12844: sub load_domain_tab {
1.1293 raeburn 12845: my ($ignore_cache,$nocache) = @_;
12846: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852 albertel 12847: my $fh;
12848: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
12849: my @lines = <$fh>;
12850: &parse_domain_tab(\@lines);
1.448 albertel 12851: }
1.852 albertel 12852: close($fh);
12853: $loaded = 1;
1.327 albertel 12854: }
1.846 albertel 12855:
12856: sub domain {
1.852 albertel 12857: &load_domain_tab() if (!$loaded);
12858:
1.846 albertel 12859: my ($name,$what) = @_;
12860: return if ( !exists($domain{$name}) );
12861:
12862: if (!$what) {
12863: return $domain{$name}{'description'};
12864: }
12865: return $domain{$name}{$what};
12866: }
1.974 raeburn 12867:
12868: sub domain_info {
12869: &load_domain_tab() if (!$loaded);
12870: return %domain;
12871: }
12872:
1.327 albertel 12873: }
12874:
12875:
1.1 albertel 12876: # ------------------------------------------------------------- Read hosts file
12877: {
1.838 albertel 12878: my %hostname;
1.844 albertel 12879: my %hostdom;
1.845 albertel 12880: my %libserv;
1.852 albertel 12881: my $loaded;
1.888 albertel 12882: my %name_to_host;
1.1074 raeburn 12883: my %internetdom;
1.1107 raeburn 12884: my %LC_dns_serv;
1.852 albertel 12885:
12886: sub parse_hosts_tab {
12887: my ($file) = @_;
12888: foreach my $configline (@$file) {
12889: next if ($configline =~ /^(\#|\s*$ )/x);
1.1107 raeburn 12890: chomp($configline);
12891: if ($configline =~ /^\^/) {
12892: if ($configline =~ /^\^([\w.\-]+)/) {
12893: $LC_dns_serv{$1} = 1;
12894: }
12895: next;
12896: }
1.1074 raeburn 12897: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 12898: $name=~s/\s//g;
12899: if ($id && $domain && $role && $name) {
12900: $hostname{$id}=$name;
1.888 albertel 12901: push(@{$name_to_host{$name}}, $id);
1.852 albertel 12902: $hostdom{$id}=$domain;
12903: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 12904: if (defined($protocol)) {
12905: if ($protocol eq 'https') {
12906: $protocol{$id} = $protocol;
12907: } else {
12908: $protocol{$id} = 'http';
12909: }
1.968 raeburn 12910: } else {
1.969 raeburn 12911: $protocol{$id} = 'http';
1.968 raeburn 12912: }
1.1074 raeburn 12913: if (defined($intdom)) {
12914: $internetdom{$id} = $intdom;
12915: }
1.852 albertel 12916: }
12917: }
12918: }
1.864 albertel 12919:
12920: sub reset_hosts_info {
1.897 albertel 12921: &purge_remembered();
1.864 albertel 12922: &reset_domain_info();
12923: &reset_hosts_ip_info();
1.892 albertel 12924: undef(%name_to_host);
1.864 albertel 12925: undef(%hostname);
12926: undef(%hostdom);
12927: undef(%libserv);
12928: undef($loaded);
12929: }
1.1 albertel 12930:
1.852 albertel 12931: sub load_hosts_tab {
1.1293 raeburn 12932: my ($ignore_cache,$nocache) = @_;
12933: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.852 albertel 12934: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
12935: my @config = <$config>;
12936: &parse_hosts_tab(\@config);
12937: close($config);
12938: $loaded=1;
1.1 albertel 12939: }
1.852 albertel 12940:
1.838 albertel 12941: sub hostname {
1.852 albertel 12942: &load_hosts_tab() if (!$loaded);
12943:
1.838 albertel 12944: my ($lonid) = @_;
12945: return $hostname{$lonid};
12946: }
1.845 albertel 12947:
1.838 albertel 12948: sub all_hostnames {
1.852 albertel 12949: &load_hosts_tab() if (!$loaded);
12950:
1.838 albertel 12951: return %hostname;
12952: }
1.845 albertel 12953:
1.888 albertel 12954: sub all_names {
1.1293 raeburn 12955: my ($ignore_cache,$nocache) = @_;
12956: &load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888 albertel 12957:
12958: return %name_to_host;
12959: }
12960:
1.974 raeburn 12961: sub all_host_domain {
12962: &load_hosts_tab() if (!$loaded);
12963: return %hostdom;
12964: }
12965:
1.845 albertel 12966: sub is_library {
1.852 albertel 12967: &load_hosts_tab() if (!$loaded);
12968:
1.845 albertel 12969: return exists($libserv{$_[0]});
12970: }
12971:
12972: sub all_library {
1.852 albertel 12973: &load_hosts_tab() if (!$loaded);
12974:
1.845 albertel 12975: return %libserv;
12976: }
12977:
1.1062 droeschl 12978: sub unique_library {
12979: #2x reverse removes all hostnames that appear more than once
12980: my %unique = reverse &all_library();
12981: return reverse %unique;
12982: }
12983:
1.841 albertel 12984: sub get_servers {
1.852 albertel 12985: &load_hosts_tab() if (!$loaded);
12986:
1.841 albertel 12987: my ($domain,$type) = @_;
12988: my %possible_hosts = ($type eq 'library') ? %libserv
12989: : %hostname;
12990: my %result;
1.842 albertel 12991: if (ref($domain) eq 'ARRAY') {
12992: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 12993: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 12994: $result{$host} = $hostname;
12995: }
12996: }
12997: } else {
12998: while ( my ($host,$hostname) = each(%possible_hosts)) {
12999: if ($hostdom{$host} eq $domain) {
13000: $result{$host} = $hostname;
13001: }
1.841 albertel 13002: }
13003: }
13004: return %result;
13005: }
1.845 albertel 13006:
1.1062 droeschl 13007: sub get_unique_servers {
13008: my %unique = reverse &get_servers(@_);
13009: return reverse %unique;
13010: }
13011:
1.844 albertel 13012: sub host_domain {
1.852 albertel 13013: &load_hosts_tab() if (!$loaded);
13014:
1.844 albertel 13015: my ($lonid) = @_;
13016: return $hostdom{$lonid};
13017: }
13018:
1.841 albertel 13019: sub all_domains {
1.852 albertel 13020: &load_hosts_tab() if (!$loaded);
13021:
1.841 albertel 13022: my %seen;
13023: my @uniq = grep(!$seen{$_}++, values(%hostdom));
13024: return @uniq;
13025: }
1.1074 raeburn 13026:
13027: sub internet_dom {
13028: &load_hosts_tab() if (!$loaded);
13029:
13030: my ($lonid) = @_;
13031: return $internetdom{$lonid};
13032: }
1.1107 raeburn 13033:
13034: sub is_LC_dns {
13035: &load_hosts_tab() if (!$loaded);
13036:
13037: my ($hostname) = @_;
13038: return exists($LC_dns_serv{$hostname});
13039: }
13040:
1.1 albertel 13041: }
13042:
1.847 albertel 13043: {
13044: my %iphost;
1.856 albertel 13045: my %name_to_ip;
13046: my %lonid_to_ip;
1.869 albertel 13047:
1.847 albertel 13048: sub get_hosts_from_ip {
13049: my ($ip) = @_;
13050: my %iphosts = &get_iphost();
13051: if (ref($iphosts{$ip})) {
13052: return @{$iphosts{$ip}};
13053: }
13054: return;
1.839 albertel 13055: }
1.864 albertel 13056:
13057: sub reset_hosts_ip_info {
13058: undef(%iphost);
13059: undef(%name_to_ip);
13060: undef(%lonid_to_ip);
13061: }
1.856 albertel 13062:
13063: sub get_host_ip {
13064: my ($lonid) = @_;
13065: if (exists($lonid_to_ip{$lonid})) {
13066: return $lonid_to_ip{$lonid};
13067: }
13068: my $name=&hostname($lonid);
13069: my $ip = gethostbyname($name);
13070: return if (!$ip || length($ip) ne 4);
13071: $ip=inet_ntoa($ip);
13072: $name_to_ip{$name} = $ip;
13073: $lonid_to_ip{$lonid} = $ip;
13074: return $ip;
13075: }
1.847 albertel 13076:
13077: sub get_iphost {
1.1293 raeburn 13078: my ($ignore_cache,$nocache) = @_;
1.894 albertel 13079:
1.869 albertel 13080: if (!$ignore_cache) {
13081: if (%iphost) {
13082: return %iphost;
13083: }
13084: my ($ip_info,$cached)=
13085: &Apache::lonnet::is_cached_new('iphost','iphost');
13086: if ($cached) {
13087: %iphost = %{$ip_info->[0]};
13088: %name_to_ip = %{$ip_info->[1]};
13089: %lonid_to_ip = %{$ip_info->[2]};
13090: return %iphost;
13091: }
13092: }
1.894 albertel 13093:
13094: # get yesterday's info for fallback
13095: my %old_name_to_ip;
13096: my ($ip_info,$cached)=
13097: &Apache::lonnet::is_cached_new('iphost','iphost');
13098: if ($cached) {
13099: %old_name_to_ip = %{$ip_info->[1]};
13100: }
13101:
1.1293 raeburn 13102: my %name_to_host = &all_names($ignore_cache,$nocache);
1.888 albertel 13103: foreach my $name (keys(%name_to_host)) {
1.847 albertel 13104: my $ip;
13105: if (!exists($name_to_ip{$name})) {
13106: $ip = gethostbyname($name);
13107: if (!$ip || length($ip) ne 4) {
1.894 albertel 13108: if (defined($old_name_to_ip{$name})) {
13109: $ip = $old_name_to_ip{$name};
13110: &logthis("Can't find $name defaulting to old $ip");
13111: } else {
13112: &logthis("Name $name no IP found");
13113: next;
13114: }
13115: } else {
13116: $ip=inet_ntoa($ip);
1.847 albertel 13117: }
13118: $name_to_ip{$name} = $ip;
13119: } else {
13120: $ip = $name_to_ip{$name};
1.653 albertel 13121: }
1.888 albertel 13122: foreach my $id (@{ $name_to_host{$name} }) {
13123: $lonid_to_ip{$id} = $ip;
13124: }
13125: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 13126: }
1.1293 raeburn 13127: unless ($nocache) {
13128: &do_cache_new('iphost','iphost',
13129: [\%iphost,\%name_to_ip,\%lonid_to_ip],
13130: 48*60*60);
13131: }
1.869 albertel 13132:
1.847 albertel 13133: return %iphost;
1.598 albertel 13134: }
13135:
1.992 raeburn 13136: #
13137: # Given a DNS returns the loncapa host name for that DNS
13138: #
13139: sub host_from_dns {
13140: my ($dns) = @_;
13141: my @hosts;
13142: my $ip;
13143:
1.993 raeburn 13144: if (exists($name_to_ip{$dns})) {
1.992 raeburn 13145: $ip = $name_to_ip{$dns};
13146: }
13147: if (!$ip) {
13148: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
13149: if (length($ip) == 4) {
13150: $ip = &IO::Socket::inet_ntoa($ip);
13151: }
13152: }
13153: if ($ip) {
13154: @hosts = get_hosts_from_ip($ip);
13155: return $hosts[0];
13156: }
13157: return undef;
1.986 foxr 13158: }
1.992 raeburn 13159:
1.1074 raeburn 13160: sub get_internet_names {
13161: my ($lonid) = @_;
13162: return if ($lonid eq '');
13163: my ($idnref,$cached)=
13164: &Apache::lonnet::is_cached_new('internetnames',$lonid);
13165: if ($cached) {
13166: return $idnref;
13167: }
13168: my $ip = &get_host_ip($lonid);
13169: my @hosts = &get_hosts_from_ip($ip);
13170: my %iphost = &get_iphost();
13171: my (@idns,%seen);
13172: foreach my $id (@hosts) {
13173: my $dom = &host_domain($id);
13174: my $prim_id = &domain($dom,'primary');
13175: my $prim_ip = &get_host_ip($prim_id);
13176: next if ($seen{$prim_ip});
13177: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
13178: foreach my $id (@{$iphost{$prim_ip}}) {
13179: my $intdom = &internet_dom($id);
13180: unless (grep(/^\Q$intdom\E$/,@idns)) {
13181: push(@idns,$intdom);
13182: }
13183: }
13184: }
13185: $seen{$prim_ip} = 1;
13186: }
1.1219 raeburn 13187: return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074 raeburn 13188: }
13189:
1.986 foxr 13190: }
13191:
1.1079 raeburn 13192: sub all_loncaparevs {
1.1249 raeburn 13193: 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 13194: }
13195:
1.1227 raeburn 13196: # ---------------------------------------------------------- Read loncaparev table
13197: {
13198: sub load_loncaparevs {
13199: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
13200: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
13201: while (my $configline=<$config>) {
13202: chomp($configline);
13203: my ($hostid,$loncaparev)=split(/:/,$configline);
13204: $loncaparevs{$hostid}=$loncaparev;
13205: }
13206: close($config);
13207: }
13208: }
13209: }
13210: }
13211:
13212: # ---------------------------------------------------------- Read serverhostID table
13213: {
13214: sub load_serverhomeIDs {
13215: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
13216: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
13217: while (my $configline=<$config>) {
13218: chomp($configline);
13219: my ($name,$id)=split(/:/,$configline);
13220: $serverhomeIDs{$name}=$id;
13221: }
13222: close($config);
13223: }
13224: }
13225: }
13226: }
13227:
13228:
1.862 albertel 13229: BEGIN {
13230:
13231: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
13232: unless ($readit) {
13233: {
13234: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
13235: %perlvar = (%perlvar,%{$configvars});
13236: }
13237:
13238:
1.1 albertel 13239: # ------------------------------------------------------ Read spare server file
13240: {
1.448 albertel 13241: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 13242:
13243: while (my $configline=<$config>) {
13244: chomp($configline);
1.284 matthew 13245: if ($configline) {
1.784 albertel 13246: my ($host,$type) = split(':',$configline,2);
1.785 albertel 13247: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 13248: push(@{ $spareid{$type} }, $host);
1.1 albertel 13249: }
13250: }
1.448 albertel 13251: close($config);
1.1 albertel 13252: }
1.11 www 13253: # ------------------------------------------------------------ Read permissions
13254: {
1.448 albertel 13255: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 13256:
13257: while (my $configline=<$config>) {
1.448 albertel 13258: chomp($configline);
13259: if ($configline) {
13260: my ($role,$perm)=split(/ /,$configline);
13261: if ($perm ne '') { $pr{$role}=$perm; }
13262: }
1.11 www 13263: }
1.448 albertel 13264: close($config);
1.11 www 13265: }
13266:
13267: # -------------------------------------------- Read plain texts for permissions
13268: {
1.448 albertel 13269: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 13270:
13271: while (my $configline=<$config>) {
1.448 albertel 13272: chomp($configline);
13273: if ($configline) {
1.742 raeburn 13274: my ($short,@plain)=split(/:/,$configline);
13275: %{$prp{$short}} = ();
13276: if (@plain > 0) {
13277: $prp{$short}{'std'} = $plain[0];
13278: for (my $i=1; $i<@plain; $i++) {
13279: $prp{$short}{'alt'.$i} = $plain[$i];
13280: }
13281: }
1.448 albertel 13282: }
1.135 www 13283: }
1.448 albertel 13284: close($config);
1.135 www 13285: }
13286:
13287: # ---------------------------------------------------------- Read package table
13288: {
1.448 albertel 13289: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 13290:
13291: while (my $configline=<$config>) {
1.483 albertel 13292: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 13293: chomp($configline);
13294: my ($short,$plain)=split(/:/,$configline);
13295: my ($pack,$name)=split(/\&/,$short);
13296: if ($plain ne '') {
13297: $packagetab{$pack.'&'.$name.'&name'}=$name;
13298: $packagetab{$short}=$plain;
13299: }
1.11 www 13300: }
1.448 albertel 13301: close($config);
1.329 matthew 13302: }
13303:
1.1073 raeburn 13304: # ---------------------------------------------------------- Read loncaparev table
1.1227 raeburn 13305:
13306: &load_loncaparevs();
1.1073 raeburn 13307:
1.1074 raeburn 13308: # ---------------------------------------------------------- Read serverhostID table
13309:
1.1227 raeburn 13310: &load_serverhomeIDs();
13311:
13312: # ---------------------------------------------------------- Read releaseslist XML
1.1079 raeburn 13313: {
13314: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
13315: if (-e $file) {
13316: my $parser = HTML::LCParser->new($file);
13317: while (my $token = $parser->get_token()) {
13318: if ($token->[0] eq 'S') {
13319: my $item = $token->[1];
13320: my $name = $token->[2]{'name'};
13321: my $value = $token->[2]{'value'};
1.1285 raeburn 13322: my $valuematch = $token->[2]{'valuematch'};
1.1303 raeburn 13323: my $namematch = $token->[2]{'namematch'};
13324: if ($item eq 'parameter') {
13325: if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
13326: my $release = $parser->get_text();
13327: $release =~ s/(^\s*|\s*$ )//gx;
13328: $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
13329: }
13330: } elsif ($item ne '' && $name ne '') {
1.1079 raeburn 13331: my $release = $parser->get_text();
13332: $release =~ s/(^\s*|\s*$ )//gx;
1.1303 raeburn 13333: $needsrelease{$item.':'.$name.':'.$value} = $release;
1.1079 raeburn 13334: }
13335: }
13336: }
13337: }
1.1073 raeburn 13338: }
13339:
1.1138 raeburn 13340: # ---------------------------------------------------------- Read managers table
13341: {
13342: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
13343: if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
13344: while (my $configline=<$config>) {
13345: chomp($configline);
13346: next if ($configline =~ /^\#/);
13347: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
13348: $managerstab{$configline} = 1;
13349: }
13350: }
13351: close($config);
13352: }
13353: }
13354: }
13355:
1.329 matthew 13356: # ------------- set up temporary directory
13357: {
1.1117 foxr 13358: $tmpdir = LONCAPA::tempdir();
1.329 matthew 13359:
1.11 www 13360: }
13361:
1.794 albertel 13362: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
13363: 'compress_threshold'=> 20_000,
13364: });
1.185 www 13365:
1.281 www 13366: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 13367: $dumpcount=0;
1.958 www 13368: $locknum=0;
1.22 www 13369:
1.163 harris41 13370: &logtouch();
1.672 albertel 13371: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 13372: $readit=1;
1.564 albertel 13373: {
13374: use integer;
13375: my $test=(2**32)+1;
1.568 albertel 13376: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 13377: &logthis(" Detected 64bit platform ($_64bit)");
13378: }
1.195 www 13379: }
1.1 albertel 13380: }
1.179 www 13381:
1.1 albertel 13382: 1;
1.191 harris41 13383: __END__
13384:
1.243 albertel 13385: =pod
13386:
1.191 harris41 13387: =head1 NAME
13388:
1.243 albertel 13389: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 13390:
13391: =head1 SYNOPSIS
13392:
1.243 albertel 13393: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 13394:
13395: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
13396:
1.243 albertel 13397: Common parameters:
13398:
13399: =over 4
13400:
13401: =item *
13402:
13403: $uname : an internal username (if $cname expecting a course Id specifically)
13404:
13405: =item *
13406:
13407: $udom : a domain (if $cdom expecting a course's domain specifically)
13408:
13409: =item *
13410:
13411: $symb : a resource instance identifier
13412:
13413: =item *
13414:
13415: $namespace : the name of a .db file that contains the data needed or
13416: being set.
13417:
13418: =back
13419:
1.394 bowersj2 13420: =head1 OVERVIEW
1.191 harris41 13421:
1.394 bowersj2 13422: lonnet provides subroutines which interact with the
13423: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
13424: about classes, users, and resources.
1.243 albertel 13425:
13426: For many of these objects you can also use this to store data about
13427: them or modify them in various ways.
1.191 harris41 13428:
1.394 bowersj2 13429: =head2 Symbs
1.191 harris41 13430:
1.394 bowersj2 13431: To identify a specific instance of a resource, LON-CAPA uses symbols
13432: or "symbs"X<symb>. These identifiers are built from the URL of the
13433: map, the resource number of the resource in the map, and the URL of
13434: the resource itself. The latter is somewhat redundant, but might help
13435: if maps change.
13436:
13437: An example is
13438:
13439: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
13440:
13441: The respective map entry is
13442:
13443: <resource id="19" src="/res/msu/korte/tests/part12.problem"
13444: title="Problem 2">
13445: </resource>
13446:
13447: Symbs are used by the random number generator, as well as to store and
13448: restore data specific to a certain instance of for example a problem.
13449:
13450: =head2 Storing And Retrieving Data
13451:
13452: X<store()>X<cstore()>X<restore()>Three of the most important functions
13453: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
13454: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
13455: is is the non-critical message twin of cstore. These functions are for
13456: handlers to store a perl hash to a user's permanent data space in an
13457: easy manner, and to retrieve it again on another call. It is expected
13458: that a handler would use this once at the beginning to retrieve data,
13459: and then again once at the end to send only the new data back.
13460:
13461: The data is stored in the user's data directory on the user's
13462: homeserver under the ID of the course.
13463:
13464: The hash that is returned by restore will have all of the previous
13465: value for all of the elements of the hash.
13466:
13467: Example:
13468:
13469: #creating a hash
13470: my %hash;
13471: $hash{'foo'}='bar';
13472:
13473: #storing it
13474: &Apache::lonnet::cstore(\%hash);
13475:
13476: #changing a value
13477: $hash{'foo'}='notbar';
13478:
13479: #adding a new value
13480: $hash{'bar'}='foo';
13481: &Apache::lonnet::cstore(\%hash);
13482:
13483: #retrieving the hash
13484: my %history=&Apache::lonnet::restore();
13485:
13486: #print the hash
13487: foreach my $key (sort(keys(%history))) {
13488: print("\%history{$key} = $history{$key}");
13489: }
13490:
13491: Will print out:
1.191 harris41 13492:
1.394 bowersj2 13493: %history{1:foo} = bar
13494: %history{1:keys} = foo:timestamp
13495: %history{1:timestamp} = 990455579
13496: %history{2:bar} = foo
13497: %history{2:foo} = notbar
13498: %history{2:keys} = foo:bar:timestamp
13499: %history{2:timestamp} = 990455580
13500: %history{bar} = foo
13501: %history{foo} = notbar
13502: %history{timestamp} = 990455580
13503: %history{version} = 2
13504:
13505: Note that the special hash entries C<keys>, C<version> and
13506: C<timestamp> were added to the hash. C<version> will be equal to the
13507: total number of versions of the data that have been stored. The
13508: C<timestamp> attribute will be the UNIX time the hash was
13509: stored. C<keys> is available in every historical section to list which
13510: keys were added or changed at a specific historical revision of a
13511: hash.
13512:
13513: B<Warning>: do not store the hash that restore returns directly. This
13514: will cause a mess since it will restore the historical keys as if the
13515: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 13516:
1.394 bowersj2 13517: Calling convention:
1.191 harris41 13518:
1.1225 raeburn 13519: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1269 raeburn 13520: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191 harris41 13521:
1.394 bowersj2 13522: For more detailed information, see lonnet specific documentation.
1.191 harris41 13523:
1.394 bowersj2 13524: =head1 RETURN MESSAGES
1.191 harris41 13525:
1.394 bowersj2 13526: =over 4
1.191 harris41 13527:
1.394 bowersj2 13528: =item * B<con_lost>: unable to contact remote host
1.191 harris41 13529:
1.394 bowersj2 13530: =item * B<con_delayed>: unable to contact remote host, message will be delivered
13531: when the connection is brought back up
1.191 harris41 13532:
1.394 bowersj2 13533: =item * B<con_failed>: unable to contact remote host and unable to save message
13534: for later delivery
1.191 harris41 13535:
1.967 bisitz 13536: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 13537:
1.394 bowersj2 13538: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 13539: that was requested
1.191 harris41 13540:
1.243 albertel 13541: =back
1.191 harris41 13542:
1.243 albertel 13543: =head1 PUBLIC SUBROUTINES
1.191 harris41 13544:
1.243 albertel 13545: =head2 Session Environment Functions
1.191 harris41 13546:
1.243 albertel 13547: =over 4
1.191 harris41 13548:
1.394 bowersj2 13549: =item *
13550: X<appenv()>
1.949 raeburn 13551: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 13552: the user envirnoment file, and will be restored for each access this
1.620 albertel 13553: user makes during this session, also modifies the %env for the current
1.949 raeburn 13554: process. Optional rolesarrayref - if defined contains a reference to an array
13555: of roles which are exempt from the restriction on modifying user.role entries
13556: in the user's environment.db and in %env.
1.191 harris41 13557:
13558: =item *
1.394 bowersj2 13559: X<delenv()>
1.987 raeburn 13560: B<delenv($delthis,$regexp)>: removes all items from the session
13561: environment file that begin with $delthis. If the
13562: optional second arg - $regexp - is true, $delthis is treated as a
13563: regular expression, otherwise \Q$delthis\E is used.
13564: The values are also deleted from the current processes %env.
1.191 harris41 13565:
1.795 albertel 13566: =item * get_env_multiple($name)
13567:
13568: gets $name from the %env hash, it seemlessly handles the cases where multiple
13569: values may be defined and end up as an array ref.
13570:
13571: returns an array of values
13572:
1.243 albertel 13573: =back
13574:
13575: =head2 User Information
1.191 harris41 13576:
1.243 albertel 13577: =over 4
1.191 harris41 13578:
13579: =item *
1.394 bowersj2 13580: X<queryauthenticate()>
13581: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 13582: authentication scheme
13583:
13584: =item *
1.394 bowersj2 13585: X<authenticate()>
1.1073 raeburn 13586: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 13587: authenticate user from domain's lib servers (first use the current
13588: one). C<$upass> should be the users password.
1.1073 raeburn 13589: $checkdefauth is optional (value is 1 if a check should be made to
13590: authenticate user using default authentication method, and allow
13591: account creation if username does not have account in the domain).
13592: $clientcancheckhost is optional (value is 1 if checking whether the
13593: server can host will occur on the client side in lonauth.pm).
1.191 harris41 13594:
13595: =item *
1.394 bowersj2 13596: X<homeserver()>
13597: B<homeserver($uname,$udom)>: find the server which has
13598: the user's directory and files (there must be only one), this caches
13599: the answer, and also caches if there is a borken connection.
1.191 harris41 13600:
13601: =item *
1.394 bowersj2 13602: X<idget()>
1.1300 raeburn 13603: B<idget($udom,$idsref,$namespace)>: find the usernames behind either
13604: a list of student/employee IDs or clicker IDs
13605: (student/employee IDs are a unique resource in a domain, there must be
13606: only 1 ID per username, and only 1 username per ID in a specific domain).
13607: clickerIDs are not necessarily unique, as students might share clickers.
13608: (returns hash: id=>name,id=>name)
1.191 harris41 13609:
13610: =item *
1.394 bowersj2 13611: X<idrget()>
13612: B<idrget($udom,@unames)>: find the IDs behind a list of
13613: usernames (returns hash: name=>id,name=>id)
1.191 harris41 13614:
13615: =item *
1.394 bowersj2 13616: X<idput()>
1.1300 raeburn 13617: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of
13618: names and associated student/employee IDs or clicker IDs.
13619:
13620: =item *
13621: X<iddel()>
13622: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted
13623: student/employee ID or clicker ID username look-ups from domain.
13624: The homeserver ($uhome) and namespace ($namespace) are optional.
13625: If no $uhome is provided, it will be determined usig &homeserver()
13626: for each user. If no $namespace is provided, the default is ids.
13627:
13628: =item *
13629: X<updateclickers()>
13630: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update
13631: clicker ID-to-username look-ups in clickers.db on library server.
13632: Permitted actions are add or del (i.e., add or delete). The
13633: clickers.db contains clickerID as keys (escaped), and each corresponding
13634: value is an escaped comma-separated list of usernames (for whom the
13635: library server is the homeserver), who registered that particular ID.
13636: If $critical is true, the update will be sent via &critical, otherwise
13637: &reply() will be used.
1.191 harris41 13638:
13639: =item *
1.394 bowersj2 13640: X<rolesinit()>
1.1169 droeschl 13641: B<rolesinit($udom,$username)>: get user privileges.
13642: returns user role, first access and timer interval hashes
1.243 albertel 13643:
13644: =item *
1.1171 droeschl 13645: X<privileged()>
13646: B<privileged($username,$domain)>: returns a true if user has a
13647: privileged and active role (i.e. su or dc), false otherwise.
13648:
13649: =item *
1.551 albertel 13650: X<getsection()>
13651: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 13652: course $cname, return section name/number or '' for "not in course"
13653: and '-1' for "no section"
13654:
13655: =item *
1.394 bowersj2 13656: X<userenvironment()>
13657: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 13658: passed in @what from the requested user's environment, returns a hash
13659:
1.858 raeburn 13660: =item *
13661: X<userlog_query()>
1.859 albertel 13662: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
13663: activity.log file. %filters defines filters applied when parsing the
13664: log file. These can be start or end timestamps, or the type of action
13665: - log to look for Login or Logout events, check for Checkin or
13666: Checkout, role for role selection. The response is in the form
13667: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
13668: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 13669:
1.243 albertel 13670: =back
13671:
13672: =head2 User Roles
13673:
13674: =over 4
13675:
13676: =item *
13677:
1.1284 raeburn 13678: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege;
13679: returns codes for allowed actions.
13680:
13681: The first argument is required, all others are optional.
13682:
13683: $priv is the privilege being checked.
13684: $uri contains additional information about what is being checked for access (e.g.,
13685: URL, course ID etc.).
13686: $symb is the unique resource instance identifier in a course; if needed,
13687: but not provided, it will be retrieved via a call to &symbread().
13688: $role is the role for which a priv is being checked (only used if priv is evb).
13689: $clientip is the user's IP address (only used when checking for access to portfolio
13690: files).
13691: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
13692: prevents recursive calls to &allowed.
13693:
1.243 albertel 13694: F: full access
13695: U,I,K: authentication modes (cxx only)
13696: '': forbidden
13697: 1: user needs to choose course
13698: 2: browse allowed
1.766 albertel 13699: A: passphrase authentication needed
1.1284 raeburn 13700: B: access temporarily blocked because of a blocking event in a course.
1.243 albertel 13701:
13702: =item *
13703:
1.1192 raeburn 13704: constructaccess($url,$setpriv) : check for access to construction space URL
13705:
13706: See if the owner domain and name in the URL match those in the
13707: expected environment. If so, return three element list
13708: ($ownername,$ownerdomain,$ownerhome).
13709:
13710: Otherwise return the null string.
13711:
13712: If second argument 'setpriv' is true, it assigns the privileges,
13713: and returns the same three element list, unless the owner has
13714: blocked "ad hoc" Domain Coordinator access to the Author Space,
13715: in which case the null string is returned.
13716:
13717: =item *
13718:
1.243 albertel 13719: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
13720: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
13721: and course level
13722:
13723: =item *
13724:
1.988 raeburn 13725: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
13726: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 13727: $type is Course (default) or Community.
1.988 raeburn 13728: If $forcedefault evaluates to true, text returned will be default
13729: text for $type. Otherwise, if this is a course, the text returned
13730: will be a custom name for the role (if defined in the course's
13731: environment). If no custom name is defined the default is returned.
13732:
1.832 raeburn 13733: =item *
13734:
1.1219 raeburn 13735: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858 raeburn 13736: All arguments are optional. Returns a hash of a roles, either for
13737: co-author/assistant author roles for a user's Construction Space
1.906 albertel 13738: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 13739: In the hash, keys are set to colon-separated $uname,$udom,$role, and
13740: (optionally) if $withsec is true, a fourth colon-separated item - $section.
13741: For each key, value is set to colon-separated start and end times for
13742: the role. If no username and domain are specified, will default to
1.934 raeburn 13743: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 13744: of role statuses (active, future or previous), roles
13745: (e.g., cc,in, st etc.) and domains of the roles which can be used
13746: to restrict the list of roles reported. If no array ref is
13747: provided for types, will default to return only active roles.
1.834 albertel 13748:
1.1195 raeburn 13749: =item *
13750:
13751: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196 raeburn 13752: user: $uname:$udom has a role in the course: $cdom_$cnum.
13753:
13754: Additional optional arguments are: $type (if role checking is to be restricted
13755: to certain user status types -- previous (expired roles), active (currently
1.1195 raeburn 13756: available roles) or future (roles available in the future), and
13757: $hideprivileged -- if true will not report course roles for users who
1.1219 raeburn 13758: have active Domain Coordinator role in course's domain or in additional
13759: domains (specified in 'Domains to check for privileged users' in course
13760: environment -- set via: Course Settings -> Classlists and staff listing).
13761:
13762: =item *
13763:
13764: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
13765: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
13766: $possdomains and $possroles are optional array refs -- to domains to check and
13767: roles to check. If $possdomains is not specified, a dump will be done of the
13768: users' roles.db to check for a dc or su role in any domain. This can be
13769: time consuming if &privileged is called repeatedly (e.g., when displaying a
13770: classlist), so in such cases, supplying a $possdomains array is preferred, as
13771: this then allows &privileged_by_domain() to be used, which caches the identity
13772: of privileged users, eliminating the need for repeated calls to &dump().
13773:
13774: =item *
13775:
13776: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
13777: where the outer hash keys are domains specified in the $possdomains array ref,
13778: next inner hash keys are privileged roles specified in the $roles array ref,
13779: and the innermost hash contains key = value pairs for username:domain = end:start
13780: for active or future "privileged" users with that role in that domain. To avoid
13781: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
13782: innerhash are cached using priv_$role and $dom as the identifiers.
1.1195 raeburn 13783:
1.243 albertel 13784: =back
13785:
13786: =head2 User Modification
13787:
13788: =over 4
13789:
13790: =item *
13791:
1.957 raeburn 13792: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 13793: user for the level given by URL. Optional start and end dates (leave empty
13794: string or zero for "no date")
1.191 harris41 13795:
13796: =item *
13797:
1.243 albertel 13798: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
13799: change a users, password, possible return values are: ok,
13800: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
13801: refused
1.191 harris41 13802:
13803: =item *
13804:
1.243 albertel 13805: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 13806:
13807: =item *
13808:
1.1058 raeburn 13809: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
13810: $forceid,$desiredhome,$email,$inststatus,$candelete) :
13811:
13812: will update user information (firstname,middlename,lastname,generation,
13813: permanentemail), and if forceid is true, student/employee ID also.
13814: A user's institutional affiliation(s) can also be updated.
13815: User information fields will not be overwritten with empty entries
13816: unless the field is included in the $candelete array reference.
13817: This array is included when a single user is modified via "Manage Users",
13818: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 13819:
13820: =item *
13821:
1.286 matthew 13822: modifystudent
13823:
1.957 raeburn 13824: modify a student's enrollment and identification information.
1.1235 raeburn 13825: The course id is resolved based on the current user's environment.
13826: This means the invoking user must be a course coordinator or otherwise
1.286 matthew 13827: associated with a course.
13828:
1.297 matthew 13829: This call is essentially a wrapper for lonnet::modifyuser and
13830: lonnet::modify_student_enrollment
1.286 matthew 13831:
13832: Inputs:
13833:
13834: =over 4
13835:
1.957 raeburn 13836: =item B<$udom> Student's loncapa domain
1.286 matthew 13837:
1.957 raeburn 13838: =item B<$uname> Student's loncapa login name
1.286 matthew 13839:
1.964 bisitz 13840: =item B<$uid> Student/Employee ID
1.286 matthew 13841:
1.957 raeburn 13842: =item B<$umode> Student's authentication mode
1.286 matthew 13843:
1.957 raeburn 13844: =item B<$upass> Student's password
1.286 matthew 13845:
1.957 raeburn 13846: =item B<$first> Student's first name
1.286 matthew 13847:
1.957 raeburn 13848: =item B<$middle> Student's middle name
1.286 matthew 13849:
1.957 raeburn 13850: =item B<$last> Student's last name
1.286 matthew 13851:
1.957 raeburn 13852: =item B<$gene> Student's generation
1.286 matthew 13853:
1.957 raeburn 13854: =item B<$usec> Student's section in course
1.286 matthew 13855:
13856: =item B<$end> Unix time of the roles expiration
13857:
13858: =item B<$start> Unix time of the roles start date
13859:
13860: =item B<$forceid> If defined, allow $uid to be changed
13861:
13862: =item B<$desiredhome> server to use as home server for student
13863:
1.957 raeburn 13864: =item B<$email> Student's permanent e-mail address
13865:
13866: =item B<$type> Type of enrollment (auto or manual)
13867:
1.963 raeburn 13868: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
13869:
13870: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 13871:
1.963 raeburn 13872: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 13873:
1.963 raeburn 13874: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 13875:
1.1216 raeburn 13876: =item B<$inststatus> institutional status of user - : separated string of escaped status types
13877:
13878: =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 13879:
1.286 matthew 13880: =back
1.297 matthew 13881:
13882: =item *
13883:
13884: modify_student_enrollment
13885:
1.1235 raeburn 13886: Change a student's enrollment status in a class. The environment variable
1.297 matthew 13887: 'role.request.course' must be defined for this function to proceed.
13888:
13889: Inputs:
13890:
13891: =over 4
13892:
1.1235 raeburn 13893: =item $udom, student's domain
1.297 matthew 13894:
1.1235 raeburn 13895: =item $uname, student's name
1.297 matthew 13896:
1.1235 raeburn 13897: =item $uid, student's user id
1.297 matthew 13898:
1.1235 raeburn 13899: =item $first, student's first name
1.297 matthew 13900:
13901: =item $middle
13902:
13903: =item $last
13904:
13905: =item $gene
13906:
13907: =item $usec
13908:
13909: =item $end
13910:
13911: =item $start
13912:
1.957 raeburn 13913: =item $type
13914:
13915: =item $locktype
13916:
13917: =item $cid
13918:
13919: =item $selfenroll
13920:
13921: =item $context
13922:
1.1216 raeburn 13923: =item $credits, number of credits student will earn from this class
13924:
1.1314 raeburn 13925: =item $instsec, institutional course section code for student
13926:
1.297 matthew 13927: =back
13928:
1.191 harris41 13929:
13930: =item *
13931:
1.243 albertel 13932: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
13933: custom role; give a custom role to a user for the level given by URL. Specify
13934: name and domain of role author, and role name
1.191 harris41 13935:
13936: =item *
13937:
1.243 albertel 13938: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 13939:
13940: =item *
13941:
1.243 albertel 13942: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
13943:
13944: =back
13945:
13946: =head2 Course Infomation
13947:
13948: =over 4
1.191 harris41 13949:
13950: =item *
13951:
1.1118 foxr 13952: coursedescription($courseid,$options) : returns a hash of information about the
1.631 albertel 13953: specified course id, including all environment settings for the
13954: course, the description of the course will be in the hash under the
13955: key 'description'
1.191 harris41 13956:
1.1118 foxr 13957: $options is an optional parameter that if supplied is a hash reference that controls
13958: what how this function works. It has the following key/values:
13959:
13960: =over 4
13961:
13962: =item freshen_cache
13963:
13964: If defined, and the environment cache for the course is valid, it is
13965: returned in the returned hash.
13966:
13967: =item one_time
13968:
13969: If defined, the last cache time is set to _now_
13970:
13971: =item user
13972:
13973: If defined, the supplied username is used instead of the current user.
13974:
13975:
13976: =back
13977:
1.191 harris41 13978: =item *
13979:
1.624 albertel 13980: resdata($name,$domain,$type,@which) : request for current parameter
13981: setting for a specific $type, where $type is either 'course' or 'user',
13982: @what should be a list of parameters to ask about. This routine caches
1.1235 raeburn 13983: answers for 10 minutes.
1.243 albertel 13984:
1.877 foxr 13985: =item *
13986:
13987: get_courseresdata($courseid, $domain) : dump the entire course resource
13988: data base, returning a hash that is keyed by the resource name and has
13989: values that are the resource value. I believe that the timestamps and
13990: versions are also returned.
13991:
1.1236 raeburn 13992: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
13993: supplemental content area. This routine caches the number of files for
13994: 10 minutes.
13995:
1.243 albertel 13996: =back
13997:
13998: =head2 Course Modification
13999:
14000: =over 4
1.191 harris41 14001:
14002: =item *
14003:
1.243 albertel 14004: writecoursepref($courseid,%prefs) : write preferences (environment
14005: database) for a course
1.191 harris41 14006:
14007: =item *
14008:
1.1011 raeburn 14009: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
14010:
14011: =item *
14012:
1.1038 raeburn 14013: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 14014:
1.1167 droeschl 14015: =item *
14016:
14017: is_course($courseid), is_course($cdom, $cnum)
14018:
14019: Accepts either a combined $courseid (in the form of domain_courseid) or the
14020: two component version $cdom, $cnum. It checks if the specified course exists.
14021:
14022: Returns:
14023: undef if the course doesn't exist, otherwise
14024: in scalar context the combined courseid.
14025: in list context the two components of the course identifier, domain and
14026: courseid.
14027:
1.243 albertel 14028: =back
14029:
14030: =head2 Resource Subroutines
14031:
14032: =over 4
1.191 harris41 14033:
14034: =item *
14035:
1.243 albertel 14036: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 14037:
14038: =item *
14039:
1.243 albertel 14040: repcopy($filename) : subscribes to the requested file, and attempts to
14041: replicate from the owning library server, Might return
1.607 raeburn 14042: 'unavailable', 'not_found', 'forbidden', 'ok', or
14043: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 14044: resource. Expects the local filesystem pathname
14045: (/home/httpd/html/res/....)
14046:
14047: =back
14048:
14049: =head2 Resource Information
14050:
14051: =over 4
1.191 harris41 14052:
14053: =item *
14054:
1.1228 raeburn 14055: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates
14056: and returns the value of a variety of different possible values,
14057: $varname should be a request string, and the other parameters can be
14058: used to specify who and what one is asking about. Ordinarily, $cid
14059: does not need to be specified, as it is retrived from
14060: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
14061: within lonuserstate::loadmap() when initializing a course, before
14062: $env{'request.course.id'} has been set, so it needs to be provided
14063: in that one case.
1.243 albertel 14064:
14065: Possible values for $varname are environment.lastname (or other item
14066: from the envirnment hash), user.name (or someother aspect about the
14067: user), resource.0.maxtries (or some other part and parameter of a
14068: resource)
1.204 albertel 14069:
14070: =item *
14071:
1.243 albertel 14072: directcondval($number) : get current value of a condition; reads from a state
14073: string
1.204 albertel 14074:
14075: =item *
14076:
1.243 albertel 14077: condval($condidx) : value of condition index based on state
1.204 albertel 14078:
14079: =item *
14080:
1.243 albertel 14081: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
14082: resource's metadata, $what should be either a specific key, or either
14083: 'keys' (to get a list of possible keys) or 'packages' to get a list of
14084: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
14085:
14086: this function automatically caches all requests
1.191 harris41 14087:
14088: =item *
14089:
1.243 albertel 14090: metadata_query($query,$custom,$customshow) : make a metadata query against the
14091: network of library servers; returns file handle of where SQL and regex results
14092: will be stored for query
1.191 harris41 14093:
14094: =item *
14095:
1.1282 raeburn 14096: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
14097: return symbolic list entry (all arguments optional).
14098:
14099: Args: filename is the filename (including path) for the file for which a symb
14100: is required; donotrecurse, if true will prevent calls to allowed() being made
14101: to check access status if more than one resource was found in the bighash
14102: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
14103: a randompick); ignorecachednull, if true will prevent a symb of '' being
14104: returned if $env{$cache_str} is defined as ''; checkforblock if true will
14105: cause possible symbs to be checked to determine if they are subject to content
14106: blocking, if so they will not be included as possible symbs; possibles is a
14107: ref to a hash, which, as a side effect, will be populated with all possible
14108: symbs (content blocking not tested).
14109:
1.243 albertel 14110: returns the data handle
1.191 harris41 14111:
14112: =item *
14113:
1.1190 raeburn 14114: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
14115: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582 albertel 14116: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190 raeburn 14117: on failure, user must be in a course, as it assumes the existence of
14118: the course initial hash, and uses $env('request.course.id'}. The third
14119: arg is an optional reference to a scalar. If this arg is passed in the
14120: call to symbverify, it will be set to 1 if the symb has been set to be
14121: encrypted; otherwise it will be null.
1.191 harris41 14122:
14123: =item *
14124:
1.243 albertel 14125: symbclean($symb) : removes versions numbers from a symb, returns the
14126: cleaned symb
1.191 harris41 14127:
14128: =item *
14129:
1.243 albertel 14130: is_on_map($uri) : checks if the $uri is somewhere on the current
14131: course map, user must be in a course for it to work.
1.191 harris41 14132:
14133: =item *
14134:
1.243 albertel 14135: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 14136:
14137: =item *
14138:
1.243 albertel 14139: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
14140: a random seed, all arguments are optional, if they aren't sent it uses the
14141: environment to derive them. Note: if symb isn't sent and it can't get one
14142: from &symbread it will use the current time as its return value
1.191 harris41 14143:
14144: =item *
14145:
1.243 albertel 14146: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
14147: unfakeable, receipt
1.191 harris41 14148:
14149: =item *
14150:
1.620 albertel 14151: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 14152:
14153: =item *
14154:
1.243 albertel 14155: countacc($url) : count the number of accesses to a given URL
1.191 harris41 14156:
14157: =item *
14158:
1.243 albertel 14159: 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 14160:
14161: =item *
14162:
1.243 albertel 14163: 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 14164:
14165: =item *
14166:
1.243 albertel 14167: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 14168:
14169: =item *
14170:
1.243 albertel 14171: devalidate($symb) : devalidate temporary spreadsheet calculations,
14172: forcing spreadsheet to reevaluate the resource scores next time.
14173:
1.1195 raeburn 14174: =item *
14175:
1.1196 raeburn 14176: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
14177: when viewing in course context.
1.1195 raeburn 14178:
1.1196 raeburn 14179: input: six args -- filename (decluttered), course number, course domain,
14180: url, symb (if registered) and group (if this is a
14181: group item -- e.g., bulletin board, group page etc.).
1.1195 raeburn 14182:
1.1196 raeburn 14183: output: array of five scalars --
1.1195 raeburn 14184: $cfile -- url for file editing if editable on current server
14185: $home -- homeserver of resource (i.e., for author if published,
14186: or course if uploaded.).
14187: $switchserver -- 1 if server switch will be needed.
1.1196 raeburn 14188: $forceedit -- 1 if icon/link should be to go to edit mode
14189: $forceview -- 1 if icon/link should be to go to view mode
1.1195 raeburn 14190:
14191: =item *
14192:
14193: is_course_upload($file,$cnum,$cdom)
14194:
14195: Used in course context to determine if current file was uploaded to
14196: the course (i.e., would be found in /userfiles/docs on the course's
14197: homeserver.
14198:
14199: input: 3 args -- filename (decluttered), course number and course domain.
14200: output: boolean -- 1 if file was uploaded.
14201:
1.243 albertel 14202: =back
14203:
14204: =head2 Storing/Retreiving Data
14205:
14206: =over 4
1.191 harris41 14207:
14208: =item *
14209:
1.1269 raeburn 14210: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
14211: permanently for this url; hashref needs to be given and should be a \%hashname;
14212: the remaining args aren't required and if they aren't passed or are '' they will
14213: be derived from the env (with the exception of $laststore, which is an
14214: optional arg used when a user's submission is stored in grading).
14215: $laststore is $version=$timestamp, where $version is the most recent version
14216: number retrieved for the corresponding $symb in the $namespace db file, and
14217: $timestamp is the timestamp for that transaction (UNIX time).
14218: $laststore is currently only passed when cstore() is called by
14219: structuretags::finalize_storage().
1.191 harris41 14220:
14221: =item *
14222:
1.1269 raeburn 14223: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
14224: but uses critical subroutine
1.191 harris41 14225:
14226: =item *
14227:
1.243 albertel 14228: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
14229: all args are optional
1.191 harris41 14230:
14231: =item *
14232:
1.717 albertel 14233: dumpstore($namespace,$udom,$uname,$regexp,$range) :
14234: dumps the complete (or key matching regexp) namespace into a hash
14235: ($udom, $uname, $regexp, $range are optional) for a namespace that is
14236: normally &store()ed into
14237:
14238: $range should be either an integer '100' (give me the first 100
14239: matching records)
14240: or be two integers sperated by a - with no spaces
14241: '30-50' (give me the 30th through the 50th matching
14242: records)
14243:
14244:
14245: =item *
14246:
1.1269 raeburn 14247: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717 albertel 14248: replaces a &store() version of data with a replacement set of data
14249: for a particular resource in a namespace passed in the $storehash hash
1.1269 raeburn 14250: reference. If $tolog is true, the transaction is logged in the courselog
14251: with an action=PUTSTORE.
1.717 albertel 14252:
14253: =item *
14254:
1.243 albertel 14255: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
14256: works very similar to store/cstore, but all data is stored in a
14257: temporary location and can be reset using tmpreset, $storehash should
14258: be a hash reference, returns nothing on success
1.191 harris41 14259:
14260: =item *
14261:
1.243 albertel 14262: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
14263: similar to restore, but all data is stored in a temporary location and
14264: can be reset using tmpreset. Returns a hash of values on success,
14265: error string otherwise.
1.191 harris41 14266:
14267: =item *
14268:
1.243 albertel 14269: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
14270: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 14271:
14272: =item *
14273:
1.243 albertel 14274: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
14275: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 14276:
14277: =item *
14278:
1.243 albertel 14279: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
14280: namesp ($udom and $uname are optional)
1.191 harris41 14281:
14282: =item *
14283:
1.702 albertel 14284: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 14285: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 14286: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 14287:
1.702 albertel 14288: $range should be either an integer '100' (give me the first 100
14289: matching records)
14290: or be two integers sperated by a - with no spaces
14291: '30-50' (give me the 30th through the 50th matching
14292: records)
1.449 matthew 14293: =item *
14294:
14295: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
14296: $store can be a scalar, an array reference, or if the amount to be
14297: incremented is > 1, a hash reference.
14298:
14299: ($udom and $uname are optional)
1.191 harris41 14300:
14301: =item *
14302:
1.243 albertel 14303: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
14304: ($udom and $uname are optional)
1.191 harris41 14305:
14306: =item *
14307:
1.243 albertel 14308: cput($namespace,$storehash,$udom,$uname) : critical put
14309: ($udom and $uname are optional)
1.191 harris41 14310:
14311: =item *
14312:
1.748 albertel 14313: newput($namespace,$storehash,$udom,$uname) :
14314:
14315: Attempts to store the items in the $storehash, but only if they don't
14316: currently exist, if this succeeds you can be certain that you have
14317: successfully created a new key value pair in the $namespace db.
14318:
14319:
14320: Args:
14321: $namespace: name of database to store values to
14322: $storehash: hashref to store to the db
14323: $udom: (optional) domain of user containing the db
14324: $uname: (optional) name of user caontaining the db
14325:
14326: Returns:
14327: 'ok' -> succeeded in storing all keys of $storehash
14328: 'key_exists: <key>' -> failed to anything out of $storehash, as at
14329: least <key> already existed in the db (other
14330: requested keys may also already exist)
1.967 bisitz 14331: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 14332: 'con_lost' -> unable to contact request server
14333: 'refused' -> action was not allowed by remote machine
14334:
14335:
14336: =item *
14337:
1.243 albertel 14338: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
14339: reference filled in from namesp (encrypts the return communication)
14340: ($udom and $uname are optional)
1.191 harris41 14341:
14342: =item *
14343:
1.243 albertel 14344: log($udom,$name,$home,$message) : write to permanent log for user; use
14345: critical subroutine
14346:
1.806 raeburn 14347: =item *
14348:
1.860 raeburn 14349: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
14350: array reference filled in from namespace found in domain level on either
14351: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 14352:
14353: =item *
14354:
1.860 raeburn 14355: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
14356: domain level either on specified domain server ($uhome) or primary domain
14357: server ($udom and $uhome are optional)
1.806 raeburn 14358:
1.943 raeburn 14359: =item *
14360:
1.1240 raeburn 14361: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
14362: for: authentication, language, quotas, timezone, date locale, and portal URL in
14363: the target domain.
14364:
14365: May also include additional key => value pairs for the following groups:
14366:
14367: =over
14368:
14369: =item
14370: disk quotas (MB allocated by default to portfolios and authoring spaces).
14371:
14372: =over
14373:
14374: =item defaultquota, authorquota
14375:
14376: =back
14377:
14378: =item
14379: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
14380: portfolio for users).
14381:
14382: =over
14383:
14384: =item
14385: aboutme, blog, webdav, portfolio
14386:
14387: =back
14388:
14389: =item
14390: requestcourses: ability to request courses, and how requests are processed.
14391:
14392: =over
14393:
14394: =item
1.1305 raeburn 14395: official, unofficial, community, textbook, placement
1.1240 raeburn 14396:
14397: =back
14398:
14399: =item
14400: inststatus: types of institutional affiliation, and order in which they are displayed.
14401:
14402: =over
14403:
14404: =item
1.1256 raeburn 14405: inststatustypes, inststatusorder, inststatusguest
1.1240 raeburn 14406:
14407: =back
14408:
14409: =item
14410: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
14411: for course's uploaded content.
14412:
14413: =over
14414:
14415: =item
1.1246 raeburn 14416: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
1.1305 raeburn 14417: communityquota, textbookquota, placementquota
1.1240 raeburn 14418:
14419: =back
14420:
14421: =item
14422: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
14423: on your servers.
14424:
14425: =over
14426:
14427: =item
14428: remotesessions, hostedsessions
14429:
14430: =back
14431:
14432: =back
14433:
14434: In cases where a domain coordinator has never used the "Set Domain Configuration"
14435: utility to create a configuration.db file on a domain's primary library server
14436: only the following domain defaults: auth_def, auth_arg_def, lang_def
14437: -- corresponding values are authentication type (internal, krb4, krb5,
14438: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
14439: will be available. Values are retrieved from cache (if current), unless the
14440: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
14441: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
14442:
14443: Typical usage:
1.943 raeburn 14444:
1.1240 raeburn 14445: %domdefaults = &get_domain_defaults($target_domain);
1.943 raeburn 14446:
1.243 albertel 14447: =back
14448:
14449: =head2 Network Status Functions
14450:
14451: =over 4
1.191 harris41 14452:
14453: =item *
14454:
1.1137 raeburn 14455: dirlist() : return directory list based on URI (first arg).
14456:
14457: Inputs: 1 required, 5 optional.
14458:
14459: =over
14460:
14461: =item
14462: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
14463:
14464: =item
14465: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
14466:
14467: =item
14468: $username - username of user/course to be listed. Extracted from $uri if absent.
14469:
14470: =item
14471: $getpropath - boolean: 1 if prepend path using &propath().
14472:
14473: =item
14474: $getuserdir - boolean: 1 if prepend path for "userfiles".
14475:
14476: =item
14477: $alternateRoot - path to prepend in place of path from $uri.
14478:
14479: =back
14480:
14481: Returns: Array of up to two items.
14482:
14483: =over
14484:
14485: a reference to an array of files/subdirectories
14486:
14487: =over
14488:
14489: Each element in the array of files/subdirectories is a & separated list of
14490: item name and the result of running stat on the item. If dirlist was requested
14491: for a file instead of a directory, the item name will be ''. For a directory
14492: listing, if the item is a metadata file, the element will end &N&M
14493: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
14494: default copyright set (1).
14495:
14496: =back
14497:
14498: a scalar containing error condition (if encountered).
14499:
14500: =over
14501:
14502: =item
14503: no_host (no homeserver identified for $username:$domain).
14504:
14505: =item
14506: no_such_host (server contacted for listing not identified as valid host).
14507:
14508: =item
14509: con_lost (connection to remote server failed).
14510:
14511: =item
14512: refused (invalid $username:$domain received on lond side).
14513:
14514: =item
14515: no_such_dir (directory at specified path on lond side does not exist).
14516:
14517: =item
14518: empty (directory at specified path on lond side is empty).
14519:
14520: =over
14521:
14522: This is currently not encountered because the &ls3, &ls2,
14523: &ls (_handler) routines on the lond side do not filter out
14524: . and .. from a directory listing.
14525:
14526: =back
14527:
14528: =back
14529:
14530: =back
1.191 harris41 14531:
14532: =item *
14533:
1.243 albertel 14534: spareserver() : find server with least workload from spare.tab
14535:
1.986 foxr 14536:
14537: =item *
14538:
14539: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
14540: if there is no corresponding loncapa host.
14541:
1.243 albertel 14542: =back
14543:
1.986 foxr 14544:
1.243 albertel 14545: =head2 Apache Request
14546:
14547: =over 4
1.191 harris41 14548:
14549: =item *
14550:
1.243 albertel 14551: ssi($url,%hash) : server side include, does a complete request cycle on url to
14552: localhost, posts hash
14553:
14554: =back
14555:
14556: =head2 Data to String to Data
14557:
14558: =over 4
1.191 harris41 14559:
14560: =item *
14561:
1.243 albertel 14562: hash2str(%hash) : convert a hash into a string complete with escaping and '='
14563: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 14564:
14565: =item *
14566:
1.243 albertel 14567: hashref2str($hashref) : convert a hashref into a string complete with
14568: escaping and '=' and '&' separators, supports elements that are
14569: arrayrefs and hashrefs
1.191 harris41 14570:
14571: =item *
14572:
1.243 albertel 14573: arrayref2str($arrayref) : convert an arrayref into a string complete
14574: with escaping and '&' separators, supports elements that are arrayrefs
14575: and hashrefs
1.191 harris41 14576:
14577: =item *
14578:
1.243 albertel 14579: str2hash($string) : convert string to hash using unescaping and
14580: splitting on '=' and '&', supports elements that are arrayrefs and
14581: hashrefs
1.191 harris41 14582:
14583: =item *
14584:
1.243 albertel 14585: str2array($string) : convert string to hash using unescaping and
14586: splitting on '&', supports elements that are arrayrefs and hashrefs
14587:
14588: =back
14589:
14590: =head2 Logging Routines
14591:
14592:
14593: These routines allow one to make log messages in the lonnet.log and
14594: lonnet.perm logfiles.
1.191 harris41 14595:
1.1119 foxr 14596: =over 4
14597:
1.191 harris41 14598: =item *
14599:
1.243 albertel 14600: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 14601:
14602: =item *
14603:
1.243 albertel 14604: logthis() : append message to the normal lonnet.log file, it gets
14605: preiodically rolled over and deleted.
1.191 harris41 14606:
14607: =item *
14608:
1.243 albertel 14609: logperm() : append a permanent message to lonnet.perm.log, this log
14610: file never gets deleted by any automated portion of the system, only
14611: messages of critical importance should go in here.
14612:
1.1119 foxr 14613:
1.243 albertel 14614: =back
14615:
14616: =head2 General File Helper Routines
14617:
14618: =over 4
1.191 harris41 14619:
14620: =item *
14621:
1.481 raeburn 14622: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
14623: (a) files in /uploaded
14624: (i) If a local copy of the file exists -
14625: compares modification date of local copy with last-modified date for
14626: definitive version stored on home server for course. If local copy is
14627: stale, requests a new version from the home server and stores it.
14628: If the original has been removed from the home server, then local copy
14629: is unlinked.
14630: (ii) If local copy does not exist -
14631: requests the file from the home server and stores it.
14632:
14633: If $caller is 'uploadrep':
14634: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
14635: for request for files originally uploaded via DOCS.
14636: - returns 'ok' if fresh local copy now available, -1 otherwise.
14637:
14638: Otherwise:
14639: This indicates a call from the content generation phase of the request.
14640: - returns the entire contents of the file or -1.
14641:
14642: (b) files in /res
14643: - returns the entire contents of a file or -1;
14644: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 14645:
1.712 albertel 14646:
14647: =item *
14648:
14649: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
14650: reference
14651:
14652: returns either a stat() list of data about the file or an empty list
14653: if the file doesn't exist or couldn't find out about it (connection
14654: problems or user unknown)
14655:
1.191 harris41 14656: =item *
14657:
1.243 albertel 14658: filelocation($dir,$file) : returns file system location of a file
14659: based on URI; meant to be "fairly clean" absolute reference, $dir is a
14660: directory that relative $file lookups are to looked in ($dir of /a/dir
14661: and a file of ../bob will become /a/bob)
1.191 harris41 14662:
14663: =item *
14664:
14665: hreflocation($dir,$file) : returns file system location or a URL; same as
14666: filelocation except for hrefs
14667:
14668: =item *
14669:
1.1261 raeburn 14670: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
14671: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191 harris41 14672:
1.243 albertel 14673: =back
14674:
1.608 albertel 14675: =head2 Usererfile file routines (/uploaded*)
14676:
14677: =over 4
14678:
14679: =item *
14680:
14681: userfileupload(): main rotine for putting a file in a user or course's
14682: filespace, arguments are,
14683:
1.620 albertel 14684: formname - required - this is the name of the element in $env where the
1.608 albertel 14685: filename, and the contents of the file to create/modifed exist
1.620 albertel 14686: the filename is in $env{'form.'.$formname.'.filename'} and the
14687: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 14688: context - if coursedoc, store the file in the course of the active role
14689: of the current user;
14690: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
14691: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 14692: subdir - required - subdirectory to put the file in under ../userfiles/
14693: if undefined, it will be placed in "unknown"
14694:
14695: (This routine calls clean_filename() to remove any dangerous
14696: characters from the filename, and then calls finuserfileupload() to
14697: complete the transaction)
14698:
14699: returns either the url of the uploaded file (/uploaded/....) if successful
14700: and /adm/notfound.html if unsuccessful
14701:
14702: =item *
14703:
14704: clean_filename(): routine for cleaing a filename up for storage in
14705: userfile space, argument is:
14706:
14707: filename - proposed filename
14708:
14709: returns: the new clean filename
14710:
14711: =item *
14712:
1.1090 raeburn 14713: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 14714: userspace, probably shouldn't be called directly
14715:
14716: docuname: username or courseid of destination for the file
14717: docudom: domain of user/course of destination for the file
14718: formname: same as for userfileupload()
1.1090 raeburn 14719: fname: filename (including subdirectories) for the file
14720: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
14721: allfiles: reference to hash used to store objects found by parser
14722: codebase: reference to hash used for codebases of java objects found by parser
14723: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
14724: thumbheight: height (pixels) of thumbnail to be created for uploaded image
14725: resizewidth: width to be used to resize image using resizeImage from ImageMagick
14726: resizeheight: height to be used to resize image using resizeImage from ImageMagick
14727: context: if 'overwrite', will move the uploaded file from its temporary location to
14728: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 14729: mimetype: reference to scalar to accommodate mime type determined
14730: from File::MMagic if $parser = parse.
1.608 albertel 14731:
14732: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 14733: and /adm/notfound.html if unsuccessful (or an error message if context
14734: was 'overwrite').
14735:
1.608 albertel 14736:
14737: =item *
14738:
14739: renameuserfile(): renames an existing userfile to a new name
14740:
14741: Args:
14742: docuname: username or courseid of destination for the file
14743: docudom: domain of user/course of destination for the file
14744: old: current file name (including any subdirs under userfiles)
14745: new: desired file name (including any subdirs under userfiles)
14746:
14747: =item *
14748:
14749: mkdiruserfile(): creates a directory is a userfiles dir
14750:
14751: Args:
14752: docuname: username or courseid of destination for the file
14753: docudom: domain of user/course of destination for the file
14754: dir: dir to create (including any subdirs under userfiles)
14755:
14756: =item *
14757:
14758: removeuserfile(): removes a file that exists in userfiles
14759:
14760: Args:
14761: docuname: username or courseid of destination for the file
14762: docudom: domain of user/course of destination for the file
14763: fname: filname to delete (including any subdirs under userfiles)
14764:
14765: =item *
14766:
14767: removeuploadedurl(): convience function for removeuserfile()
14768:
14769: Args:
14770: url: a full /uploaded/... url to delete
14771:
1.747 albertel 14772: =item *
14773:
14774: get_portfile_permissions():
14775: Args:
14776: domain: domain of user or course contain the portfolio files
14777: user: name of user or num of course contain the portfolio files
14778: Returns:
14779: hashref of a dump of the proper file_permissions.db
14780:
14781:
14782: =item *
14783:
14784: get_access_controls():
14785:
14786: Args:
14787: current_permissions: the hash ref returned from get_portfile_permissions()
14788: group: (optional) the group you want the files associated with
14789: file: (optional) the file you want access info on
14790:
14791: Returns:
1.749 raeburn 14792: a hash (keys are file names) of hashes containing
14793: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
14794: values are XML containing access control settings (see below)
1.747 albertel 14795:
14796: Internal notes:
14797:
1.749 raeburn 14798: access controls are stored in file_permissions.db as key=value pairs.
14799: key -> path to file/file_name\0uniqueID:scope_end_start
14800: where scope -> public,guest,course,group,domains or users.
14801: end -> UNIX time for end of access (0 -> no end date)
14802: start -> UNIX time for start of access
14803:
14804: value -> XML description of access control
14805: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
14806: <start></start>
14807: <end></end>
14808:
14809: <password></password> for scope type = guest
14810:
14811: <domain></domain> for scope type = course or group
14812: <number></number>
14813: <roles id="">
14814: <role></role>
14815: <access></access>
14816: <section></section>
14817: <group></group>
14818: </roles>
14819:
14820: <dom></dom> for scope type = domains
14821:
14822: <users> for scope type = users
14823: <user>
14824: <uname></uname>
14825: <udom></udom>
14826: </user>
14827: </users>
14828: </scope>
14829:
14830: Access data is also aggregated for each file in an additional key=value pair:
14831: key -> path to file/file_name\0accesscontrol
14832: value -> reference to hash
14833: hash contains key = value pairs
14834: where key = uniqueID:scope_end_start
14835: value = UNIX time record was last updated
14836:
14837: Used to improve speed of look-ups of access controls for each file.
14838:
14839: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
14840:
1.1198 raeburn 14841: =item *
14842:
1.749 raeburn 14843: modify_access_controls():
14844:
14845: Modifies access controls for a portfolio file
14846: Args
14847: 1. file name
14848: 2. reference to hash of required changes,
14849: 3. domain
14850: 4. username
14851: where domain,username are the domain of the portfolio owner
14852: (either a user or a course)
14853:
14854: Returns:
14855: 1. result of additions or updates ('ok' or 'error', with error message).
14856: 2. result of deletions ('ok' or 'error', with error message).
14857: 3. reference to hash of any new or updated access controls.
14858: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
14859: key = integer (inbound ID)
1.1198 raeburn 14860: value = uniqueID
14861:
14862: =item *
14863:
14864: get_timebased_id():
14865:
14866: Attempts to get a unique timestamp-based suffix for use with items added to a
14867: course via the Course Editor (e.g., folders, composite pages,
14868: group bulletin boards).
14869:
14870: Args: (first three required; six others optional)
14871:
14872: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
14873: docssequence, or name of group
14874:
14875: 2. keyid (alphanumeric): name of temporary locking key in hash,
14876: e.g., num, boardids
14877:
14878: 3. namespace: name of gdbm file used to store suffixes already assigned;
14879: file will be named nohist_namespace.db
14880:
14881: 4. cdom: domain of course; default is current course domain from %env
14882:
14883: 5. cnum: course number; default is current course number from %env
14884:
14885: 6. idtype: set to concat if an additional digit is to be appended to the
14886: unix timestamp to form the suffix, if the plain timestamp is already
14887: in use. Default is to not do this, but simply increment the unix
14888: timestamp by 1 until a unique key is obtained.
14889:
14890: 7. who: holder of locking key; defaults to user:domain for user.
14891:
14892: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
14893: retrying); default is 3.
14894:
14895: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
14896:
14897: Returns:
14898:
14899: 1. suffix obtained (numeric)
14900:
14901: 2. result of deleting locking key (ok if deleted, or lock never obtained)
14902:
14903: 3. error: contains (localized) error message if an error occurred.
14904:
1.747 albertel 14905:
1.608 albertel 14906: =back
14907:
1.243 albertel 14908: =head2 HTTP Helper Routines
14909:
14910: =over 4
14911:
1.191 harris41 14912: =item *
14913:
14914: escape() : unpack non-word characters into CGI-compatible hex codes
14915:
14916: =item *
14917:
14918: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
14919:
1.243 albertel 14920: =back
14921:
14922: =head1 PRIVATE SUBROUTINES
14923:
14924: =head2 Underlying communication routines (Shouldn't call)
14925:
14926: =over 4
14927:
14928: =item *
14929:
14930: subreply() : tries to pass a message to lonc, returns con_lost if incapable
14931:
14932: =item *
14933:
14934: reply() : uses subreply to send a message to remote machine, logs all failures
14935:
14936: =item *
14937:
14938: critical() : passes a critical message to another server; if cannot
14939: get through then place message in connection buffer directory and
14940: returns con_delayed, if incapable of saving message, returns
14941: con_failed
14942:
14943: =item *
14944:
14945: reconlonc() : tries to reconnect lonc client processes.
14946:
14947: =back
14948:
14949: =head2 Resource Access Logging
14950:
14951: =over 4
14952:
14953: =item *
14954:
14955: flushcourselogs() : flush (save) buffer logs and access logs
14956:
14957: =item *
14958:
14959: courselog($what) : save message for course in hash
14960:
14961: =item *
14962:
14963: courseacclog($what) : save message for course using &courselog(). Perform
14964: special processing for specific resource types (problems, exams, quizzes, etc).
14965:
1.191 harris41 14966: =item *
14967:
14968: goodbye() : flush course logs and log shutting down; it is called in srm.conf
14969: as a PerlChildExitHandler
1.243 albertel 14970:
14971: =back
14972:
14973: =head2 Other
14974:
14975: =over 4
14976:
14977: =item *
14978:
14979: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 14980:
14981: =back
14982:
14983: =cut
1.877 foxr 14984:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>