Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1533
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1533 ! raeburn 4: # $Id: lonnet.pm,v 1.1532 2024/12/27 02:32:55 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.486 www 74: use HTTP::Date;
1.977 amueller 75: use Image::Magick;
1.1389 raeburn 76: use CGI::Cookie;
1.1182 foxr 77:
1.1173 foxr 78: use Encode;
79:
1.1405 raeburn 80: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir $deftex
1.1138 raeburn 81: $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
1.1416 raeburn 82: %managerstab $passwdmin);
1.871 albertel 83:
84: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
85: %userrolehash, $processmarker, $dumpcount, %coursedombuf,
86: %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958 www 87: %courseownerbuf, %coursetypebuf,$locknum);
1.403 www 88:
1.1 albertel 89: use IO::Socket;
1.31 www 90: use GDBM_File;
1.208 albertel 91: use HTML::LCParser;
1.88 www 92: use Fcntl qw(:flock);
1.870 albertel 93: use Storable qw(thaw nfreeze);
1.1289 damieng 94: use Time::HiRes qw( sleep gettimeofday tv_interval );
1.599 albertel 95: use Cache::Memcached;
1.676 albertel 96: use Digest::MD5;
1.790 albertel 97: use Math::Random;
1.1024 raeburn 98: use File::MMagic;
1.1434 raeburn 99: use Net::CIDR;
1.1456 raeburn 100: use Sys::Hostname::FQDN();
1.807 albertel 101: use LONCAPA qw(:DEFAULT :match);
1.740 www 102: use LONCAPA::Configuration;
1.1160 www 103: use LONCAPA::lonmetadata;
1.1167 droeschl 104: use LONCAPA::Lond;
1.1345 raeburn 105: use LONCAPA::LWPReq;
1.1406 raeburn 106: use LONCAPA::transliterate;
1.1117 foxr 107:
1.1090 raeburn 108: use File::Copy;
1.676 albertel 109:
1.195 www 110: my $readit;
1.1288 damieng 111: my $max_connection_retries = 20; # Or some such value.
1.1 albertel 112:
1.619 albertel 113: require Exporter;
114:
115: our @ISA = qw (Exporter);
116: our @EXPORT = qw(%env);
117:
1.449 matthew 118:
1.1187 raeburn 119: # ------------------------------------ Logging (parameters, docs, slots, roles)
1.729 www 120: {
121: my $logid;
1.1187 raeburn 122: sub write_log {
1.1188 raeburn 123: my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
1.1184 raeburn 124: if ($context eq 'course') {
125: if (($cnum eq '') || ($cdom eq '')) {
126: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
127: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
128: }
1.957 raeburn 129: }
1.1184 raeburn 130: $logid ++;
1.957 raeburn 131: my $now = time();
132: my $id=$now.'00000'.$$.'00000'.$logid;
1.1434 raeburn 133: my $ip = &get_requestor_ip();
1.1184 raeburn 134: my $logentry = {
135: $id => {
136: 'exe_uname' => $env{'user.name'},
137: 'exe_udom' => $env{'user.domain'},
138: 'exe_time' => $now,
1.1434 raeburn 139: 'exe_ip' => $ip,
1.1184 raeburn 140: 'delflag' => $delflag,
141: 'logentry' => $storehash,
142: 'uname' => $uname,
143: 'udom' => $udom,
144: }
145: };
146: return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
1.729 www 147: }
148: }
1.1 albertel 149:
1.163 harris41 150: sub logtouch {
151: my $execdir=$perlvar{'lonDaemons'};
1.448 albertel 152: unless (-e "$execdir/logs/lonnet.log") {
1.1359 raeburn 153: open(my $fh,">>","$execdir/logs/lonnet.log");
1.163 harris41 154: close $fh;
155: }
156: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
157: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
158: }
159:
1.1 albertel 160: sub logthis {
161: my $message=shift;
162: my $execdir=$perlvar{'lonDaemons'};
163: my $now=time;
164: my $local=localtime($now);
1.1359 raeburn 165: if (open(my $fh,">>","$execdir/logs/lonnet.log")) {
1.986 foxr 166: my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
167: print $fh $logstring;
1.448 albertel 168: close($fh);
169: }
1.1 albertel 170: return 1;
171: }
172:
173: sub logperm {
174: my $message=shift;
175: my $execdir=$perlvar{'lonDaemons'};
176: my $now=time;
177: my $local=localtime($now);
1.1359 raeburn 178: if (open(my $fh,">>","$execdir/logs/lonnet.perm.log")) {
1.448 albertel 179: print $fh "$now:$message:$local\n";
180: close($fh);
181: }
1.1 albertel 182: return 1;
183: }
184:
1.850 albertel 185: sub create_connection {
1.853 albertel 186: my ($hostname,$lonid) = @_;
1.851 albertel 187: my $client=IO::Socket::UNIX->new(Peer => $perlvar{'lonSockCreate'},
1.850 albertel 188: Type => SOCK_STREAM,
189: Timeout => 10);
190: return 0 if (!$client);
1.1528 raeburn 191: if ($loncaparevs{$lonid} =~ /^(\d+\.\d+\.[\w.]+)-\d+$/) {
192: print $client (join(':',$hostname,$lonid,$1,&machine_ids($hostname))."\n");
193: } else {
194: print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
195: }
1.850 albertel 196: my $result = <$client>;
197: chomp($result);
198: return 1 if ($result eq 'done');
199: return 0;
200: }
201:
1.983 raeburn 202: sub get_server_timezone {
203: my ($cnum,$cdom) = @_;
204: my $home=&homeserver($cnum,$cdom);
205: if ($home ne 'no_host') {
206: my $cachetime = 24*3600;
207: my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
208: if (defined($cached)) {
209: return $timezone;
210: } else {
211: my $timezone = &reply('servertimezone',$home);
212: return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
213: }
214: }
215: }
1.850 albertel 216:
1.1106 raeburn 217: sub get_server_distarch {
218: my ($lonhost,$ignore_cache) = @_;
219: if (defined($lonhost)) {
220: if (!defined(&hostname($lonhost))) {
221: return;
222: }
223: my $cachetime = 12*3600;
224: if (!$ignore_cache) {
225: my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
226: if (defined($cached)) {
227: return $distarch;
228: }
229: }
230: my $rep = &reply('serverdistarch',$lonhost);
1.1531 raeburn 231: unless ($rep eq 'unknown_cmd' || $rep eq 'no_such_host' ||
1.1106 raeburn 232: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
233: $rep eq '') {
234: return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
235: }
236: }
237: return;
238: }
239:
1.1315 raeburn 240: sub get_servercerts_info {
1.1383 raeburn 241: my ($lonhost,$hostname,$context) = @_;
242: return if ($lonhost eq '');
243: if ($hostname eq '') {
244: $hostname = &hostname($lonhost);
245: }
246: return if ($hostname eq '');
1.1315 raeburn 247: my ($rep,$uselocal);
1.1388 raeburn 248: if ($context eq 'install') {
1.1387 raeburn 249: $uselocal = 1;
250: } elsif (grep { $_ eq $lonhost } ¤t_machine_ids()) {
1.1315 raeburn 251: $uselocal = 1;
252: }
1.1387 raeburn 253: if (($context ne 'cgi') && ($context ne 'install') && ($uselocal)) {
1.1315 raeburn 254: my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
1.1323 raeburn 255: if ($distro eq '') {
256: $uselocal = 0;
257: } elsif ($distro =~ /^(?:centos|redhat|scientific)(\d+)$/) {
1.1315 raeburn 258: if ($1 < 6) {
259: $uselocal = 0;
260: }
1.1346 raeburn 261: } elsif ($distro =~ /^(?:sles)(\d+)$/) {
262: if ($1 < 12) {
263: $uselocal = 0;
264: }
1.1315 raeburn 265: }
266: }
267: if ($uselocal) {
1.1383 raeburn 268: $rep = LONCAPA::Lond::server_certs(\%perlvar,$lonhost,$hostname);
1.1315 raeburn 269: } else {
270: $rep=&reply('servercerts',$lonhost);
271: }
272: my ($result,%returnhash);
273: if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
274: ($rep eq 'unknown_cmd')) {
275: $result = $rep;
276: } else {
277: $result = 'ok';
278: my @pairs=split(/\&/,$rep);
279: foreach my $item (@pairs) {
280: my ($key,$value)=split(/=/,$item,2);
281: my $what = &unescape($key);
282: $returnhash{$what}=&thaw_unescape($value);
283: }
284: }
285: return ($result,\%returnhash);
286: }
287:
1.993 raeburn 288: sub get_server_loncaparev {
1.1073 raeburn 289: my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993 raeburn 290: if (defined($lonhost)) {
291: if (!defined(&hostname($lonhost))) {
292: undef($lonhost);
293: }
294: }
295: if (!defined($lonhost)) {
296: if (defined(&domain($dom,'primary'))) {
297: $lonhost=&domain($dom,'primary');
298: if ($lonhost eq 'no_host') {
299: undef($lonhost);
300: }
301: }
302: }
303: if (defined($lonhost)) {
1.1073 raeburn 304: my $cachetime = 12*3600;
305: if (!$ignore_cache) {
306: my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
307: if (defined($cached)) {
308: return $loncaparev;
309: }
310: }
311: my ($answer,$loncaparev);
312: my @ids=¤t_machine_ids();
313: if (grep(/^\Q$lonhost\E$/,@ids)) {
314: $answer = $perlvar{'lonVersion'};
1.1081 raeburn 315: if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 316: $loncaparev = $1;
317: }
318: } else {
319: $answer = &reply('serverloncaparev',$lonhost);
320: if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
321: if ($caller eq 'loncron') {
1.1397 raeburn 322: my $hostname = &hostname($lonhost);
1.1073 raeburn 323: my $protocol = $protocol{$lonhost};
324: $protocol = 'http' if ($protocol ne 'https');
1.1397 raeburn 325: my $url = $protocol.'://'.$hostname.'/adm/about.html';
1.1073 raeburn 326: my $request=new HTTP::Request('GET',$url);
1.1345 raeburn 327: my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,4,1);
1.1073 raeburn 328: unless ($response->is_error()) {
329: my $content = $response->content;
1.1081 raeburn 330: if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073 raeburn 331: $loncaparev = $1;
332: }
333: }
334: } else {
335: $loncaparev = $loncaparevs{$lonhost};
336: }
1.1081 raeburn 337: } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 338: $loncaparev = $1;
339: }
1.993 raeburn 340: }
1.1073 raeburn 341: return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993 raeburn 342: }
343: }
344:
1.1074 raeburn 345: sub get_server_homeID {
346: my ($hostname,$ignore_cache,$caller) = @_;
347: unless ($ignore_cache) {
348: my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
349: if (defined($cached)) {
350: return $serverhomeID;
351: }
352: }
353: my $cachetime = 12*3600;
354: my $serverhomeID;
355: if ($caller eq 'loncron') {
356: my @machine_ids = &machine_ids($hostname);
357: foreach my $id (@machine_ids) {
358: my $response = &reply('serverhomeID',$id);
359: unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
360: $serverhomeID = $response;
361: last;
362: }
363: }
364: if ($serverhomeID eq '') {
365: $serverhomeID = $machine_ids[-1];
366: }
367: } else {
368: $serverhomeID = $serverhomeIDs{$hostname};
369: }
370: return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
371: }
372:
1.1121 raeburn 373: sub get_remote_globals {
374: my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125 raeburn 375: my ($result,%returnhash,%whatneeded);
376: if (ref($whathash) eq 'HASH') {
1.1121 raeburn 377: foreach my $what (sort(keys(%{$whathash}))) {
378: my $hashid = $lonhost.'-'.$what;
1.1125 raeburn 379: my ($response,$cached);
1.1121 raeburn 380: unless ($ignore_cache) {
1.1125 raeburn 381: ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121 raeburn 382: }
383: if (defined($cached)) {
1.1125 raeburn 384: $returnhash{$what} = $response;
1.1121 raeburn 385: } else {
1.1125 raeburn 386: $whatneeded{$what} = 1;
1.1121 raeburn 387: }
388: }
1.1125 raeburn 389: if (keys(%whatneeded) == 0) {
390: $result = 'ok';
391: } else {
1.1121 raeburn 392: my $requested = &freeze_escape(\%whatneeded);
393: my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125 raeburn 394: if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
395: ($rep eq 'unknown_cmd')) {
396: $result = $rep;
397: } else {
398: $result = 'ok';
1.1121 raeburn 399: my @pairs=split(/\&/,$rep);
1.1125 raeburn 400: foreach my $item (@pairs) {
401: my ($key,$value)=split(/=/,$item,2);
402: my $what = &unescape($key);
403: my $hashid = $lonhost.'-'.$what;
404: $returnhash{$what}=&thaw_unescape($value);
405: &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121 raeburn 406: }
407: }
408: }
409: }
1.1125 raeburn 410: return ($result,\%returnhash);
1.1121 raeburn 411: }
412:
1.1124 raeburn 413: sub remote_devalidate_cache {
1.1241 raeburn 414: my ($lonhost,$cachekeys) = @_;
415: my $items;
416: return unless (ref($cachekeys) eq 'ARRAY');
417: my $cachestr = join('&',@{$cachekeys});
418: my $response = &reply('devalidatecache:'.&escape($cachestr),$lonhost);
1.1124 raeburn 419: return $response;
420: }
421:
1.1510 raeburn 422: sub sign_lti {
1.1511 raeburn 423: my ($cdom,$cnum,$crsdef,$type,$context,$url,$ltinum,$keynum,$paramsref,$inforef) = @_;
1.1510 raeburn 424: my $chome;
425: if (&domain($cdom) ne '') {
1.1511 raeburn 426: if ($crsdef) {
1.1510 raeburn 427: $chome = &homeserver($cnum,$cdom);
428: } else {
429: $chome = &domain($cdom,'primary');
430: }
431: }
432: if ($cdom && $chome && ($chome ne 'no_host')) {
433: if ((ref($paramsref) eq 'HASH') &&
434: (ref($inforef) eq 'HASH')) {
435: my $rep;
436: if (grep { $_ eq $chome } ¤t_machine_ids()) {
437: # domain information is hosted on this machine
438: $rep =
1.1511 raeburn 439: &LONCAPA::Lond::sign_lti_payload($cdom,$cnum,$crsdef,$type,
440: $context,$url,$ltinum,$keynum,
441: $perlvar{'lonVersion'},
442: $paramsref,$inforef);
443: if (ref($rep) eq 'HASH') {
1.1510 raeburn 444: return ('ok',$rep);
445: }
446: } else {
447: my ($escurl,$params,$info);
448: $escurl = &escape($url);
449: if (ref($paramsref) eq 'HASH') {
450: $params = &freeze_escape($paramsref);
451: }
452: if (ref($inforef) eq 'HASH') {
453: $info = &freeze_escape($inforef);
454: }
1.1511 raeburn 455: $rep=&reply("encrypt:signlti:$cdom:$cnum:$crsdef:$type:$context:$escurl:$ltinum:$keynum:$params:$info",$chome);
1.1510 raeburn 456: }
457: if (($rep eq '') || ($rep =~ /^con_lost|error|no_such_host|unknown_cmd/i)) {
458: return ();
1.1511 raeburn 459: } elsif (($inforef->{'respfmt'} eq 'to_post_body') ||
460: ($inforef->{'respfmt'} eq 'to_authorization_header')) {
461: return ('ok',$rep);
1.1510 raeburn 462: } else {
463: my %returnhash;
464: foreach my $item (split(/\&/,$rep)) {
465: my ($name,$value)=split(/\=/,$item);
466: $returnhash{&unescape($name)}=&thaw_unescape($value);
467: }
468: return('ok',\%returnhash);
469: }
470: } else {
471: return ();
472: }
473: } else {
474: return ();
475: &logthis("sign_lti failed - no homeserver and/or domain ($cdom) ($chome)");
476: }
477: }
478:
1.1 albertel 479: # -------------------------------------------------- Non-critical communication
480: sub subreply {
481: my ($cmd,$server)=@_;
1.838 albertel 482: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549 foxr 483: #
484: # With loncnew process trimming, there's a timing hole between lonc server
485: # process exit and the master server picking up the listen on the AF_UNIX
486: # socket. In that time interval, a lock file will exist:
487:
488: my $lockfile=$peerfile.".lock";
489: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
1.1289 damieng 490: sleep(0.1);
1.549 foxr 491: }
492: # At this point, either a loncnew parent is listening or an old lonc
1.550 foxr 493: # or loncnew child is listening so we can connect or everything's dead.
1.549 foxr 494: #
1.550 foxr 495: # We'll give the connection a few tries before abandoning it. If
496: # connection is not possible, we'll con_lost back to the client.
497: #
498: my $client;
499: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
500: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
501: Type => SOCK_STREAM,
502: Timeout => 10);
1.869 albertel 503: if ($client) {
1.550 foxr 504: last; # Connected!
1.850 albertel 505: } else {
1.853 albertel 506: &create_connection(&hostname($server),$server);
1.550 foxr 507: }
1.1289 damieng 508: sleep(0.1); # Try again later if failed connection.
1.550 foxr 509: }
510: my $answer;
511: if ($client) {
1.704 albertel 512: print $client "sethost:$server:$cmd\n";
1.550 foxr 513: $answer=<$client>;
514: if (!$answer) { $answer="con_lost"; }
515: chomp($answer);
516: } else {
517: $answer = 'con_lost'; # Failed connection.
518: }
1.1 albertel 519: return $answer;
520: }
521:
522: sub reply {
523: my ($cmd,$server)=@_;
1.838 albertel 524: unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1 albertel 525: my $answer=subreply($cmd,$server);
1.65 www 526: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.1396 raeburn 527: my $logged = $cmd;
528: if ($cmd =~ /^encrypt:([^:]+):/) {
529: my $subcmd = $1;
530: if (($subcmd eq 'auth') || ($subcmd eq 'passwd') ||
531: ($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
1.1462 raeburn 532: ($subcmd eq 'putdom') || ($subcmd eq 'autoexportgrades') ||
533: ($subcmd eq 'put')) {
1.1396 raeburn 534: (undef,undef,my @rest) = split(/:/,$cmd);
535: if (($subcmd eq 'auth') || ($subcmd eq 'putdom')) {
536: splice(@rest,2,1,'Hidden');
537: } elsif ($subcmd eq 'passwd') {
538: splice(@rest,2,2,('Hidden','Hidden'));
539: } elsif (($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
1.1462 raeburn 540: ($subcmd eq 'autoexportgrades') || ($subcmd eq 'put')) {
1.1396 raeburn 541: splice(@rest,3,1,'Hidden');
542: }
543: $logged = join(':',('encrypt:'.$subcmd,@rest));
544: }
545: }
546: &logthis("<font color=\"blue\">WARNING:".
547: " $logged to $server returned $answer</font>");
1.12 www 548: }
1.1 albertel 549: return $answer;
550: }
551:
552: # ----------------------------------------------------------- Send USR1 to lonc
553:
554: sub reconlonc {
1.891 albertel 555: my ($lonid) = @_;
556: if ($lonid) {
1.1295 raeburn 557: my $hostname = &hostname($lonid);
1.891 albertel 558: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
559: if ($hostname && -e $peerfile) {
560: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
561: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
562: Type => SOCK_STREAM,
563: Timeout => 10);
564: if ($client) {
565: print $client ("reset_retries\n");
566: my $answer=<$client>;
567: #reset just this one.
568: }
569: }
570: return;
571: }
572:
1.836 www 573: &logthis("Trying to reconnect lonc");
1.1 albertel 574: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.1359 raeburn 575: if (open(my $fh,"<",$loncfile)) {
1.1 albertel 576: my $loncpid=<$fh>;
577: chomp($loncpid);
578: if (kill 0 => $loncpid) {
579: &logthis("lonc at pid $loncpid responding, sending USR1");
580: kill USR1 => $loncpid;
581: sleep 1;
1.1295 raeburn 582: } else {
1.12 www 583: &logthis(
1.672 albertel 584: "<font color=\"blue\">WARNING:".
1.12 www 585: " lonc at pid $loncpid not responding, giving up</font>");
1.1 albertel 586: }
587: } else {
1.836 www 588: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1 albertel 589: }
590: }
591:
592: # ------------------------------------------------------ Critical communication
1.12 www 593:
1.1 albertel 594: sub critical {
595: my ($cmd,$server)=@_;
1.838 albertel 596: unless (&hostname($server)) {
1.672 albertel 597: &logthis("<font color=\"blue\">WARNING:".
1.89 www 598: " Critical message to unknown server ($server)</font>");
599: return 'no_such_host';
600: }
1.1 albertel 601: my $answer=reply($cmd,$server);
602: if ($answer eq 'con_lost') {
1.1295 raeburn 603: &reconlonc($server);
1.589 albertel 604: my $answer=reply($cmd,$server);
1.1 albertel 605: if ($answer eq 'con_lost') {
606: my $now=time;
607: my $middlename=$cmd;
1.5 www 608: $middlename=substr($middlename,0,16);
1.1 albertel 609: $middlename=~s/\W//g;
610: my $dfilename=
1.305 www 611: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
612: $dumpcount++;
1.1 albertel 613: {
1.448 albertel 614: my $dfh;
1.1359 raeburn 615: if (open($dfh,">",$dfilename)) {
1.448 albertel 616: print $dfh "$cmd\n";
617: close($dfh);
618: }
1.1 albertel 619: }
1.1288 damieng 620: sleep 1;
1.1 albertel 621: my $wcmd='';
622: {
1.448 albertel 623: my $dfh;
1.1359 raeburn 624: if (open($dfh,"<",$dfilename)) {
1.448 albertel 625: $wcmd=<$dfh>;
626: close($dfh);
627: }
1.1 albertel 628: }
629: chomp($wcmd);
1.7 www 630: if ($wcmd eq $cmd) {
1.672 albertel 631: &logthis("<font color=\"blue\">WARNING: ".
1.12 www 632: "Connection buffer $dfilename: $cmd</font>");
1.1 albertel 633: &logperm("D:$server:$cmd");
634: return 'con_delayed';
635: } else {
1.672 albertel 636: &logthis("<font color=\"red\">CRITICAL:"
1.12 www 637: ." Critical connection failed: $server $cmd</font>");
1.1 albertel 638: &logperm("F:$server:$cmd");
639: return 'con_failed';
640: }
641: }
642: }
643: return $answer;
1.405 albertel 644: }
645:
1.755 albertel 646: # ------------------------------------------- check if return value is an error
647:
648: sub error {
649: my ($result) = @_;
1.756 albertel 650: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755 albertel 651: if ($2 == 2) { return undef; }
652: return $1;
653: }
654: return undef;
655: }
656:
1.783 albertel 657: sub convert_and_load_session_env {
658: my ($lonidsdir,$handle)=@_;
659: my @profile;
660: {
1.917 albertel 661: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
662: if (!$opened) {
1.915 albertel 663: return 0;
664: }
1.783 albertel 665: flock($idf,LOCK_SH);
666: @profile=<$idf>;
667: close($idf);
668: }
669: my %temp_env;
670: foreach my $line (@profile) {
1.786 albertel 671: if ($line !~ m/=/) {
672: return 0;
673: }
1.783 albertel 674: chomp($line);
675: my ($envname,$envvalue)=split(/=/,$line,2);
676: $temp_env{&unescape($envname)} = &unescape($envvalue);
677: }
678: unlink("$lonidsdir/$handle.id");
679: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
680: 0640)) {
681: %disk_env = %temp_env;
682: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
683: untie(%disk_env);
684: }
1.786 albertel 685: return 1;
1.783 albertel 686: }
687:
1.374 www 688: # ------------------------------------------- Transfer profile into environment
1.780 albertel 689: my $env_loaded;
690: sub transfer_profile_to_env {
1.788 albertel 691: my ($lonidsdir,$handle,$force_transfer) = @_;
692: if (!$force_transfer && $env_loaded) { return; }
1.374 www 693:
1.720 albertel 694: if (!defined($lonidsdir)) {
695: $lonidsdir = $perlvar{'lonIDsDir'};
696: }
697: if (!defined($handle)) {
698: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
699: }
700:
1.786 albertel 701: my $convert;
702: {
1.917 albertel 703: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
704: if (!$opened) {
1.915 albertel 705: return;
706: }
1.786 albertel 707: flock($idf,LOCK_SH);
708: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
709: &GDBM_READER(),0640)) {
710: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
711: untie(%disk_env);
712: } else {
713: $convert = 1;
714: }
715: }
716: if ($convert) {
717: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
718: &logthis("Failed to load session, or convert session.");
719: }
1.374 www 720: }
1.783 albertel 721:
1.786 albertel 722: my %remove;
1.783 albertel 723: while ( my $envname = each(%env) ) {
1.433 matthew 724: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
725: if ($time < time-300) {
1.783 albertel 726: $remove{$key}++;
1.433 matthew 727: }
728: }
729: }
1.783 albertel 730:
1.619 albertel 731: $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780 albertel 732: $env_loaded=1;
1.783 albertel 733: foreach my $expired_key (keys(%remove)) {
1.433 matthew 734: &delenv($expired_key);
1.374 www 735: }
1.1 albertel 736: }
737:
1.916 albertel 738: # ---------------------------------------------------- Check for valid session
739: sub check_for_valid_session {
1.1355 raeburn 740: my ($r,$name,$userhashref,$domref) = @_;
1.916 albertel 741: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1378 raeburn 742: my ($lonidsdir,$linkname,$pubname,$secure,$lonid);
743: if ($name eq 'lonDAV') {
744: $lonidsdir=$r->dir_config('lonDAVsessDir');
745: } else {
746: $lonidsdir=$r->dir_config('lonIDsDir');
747: if ($name eq '') {
748: $name = 'lonID';
749: }
750: }
751: if ($name eq 'lonID') {
752: $secure = 'lonSID';
1.1337 raeburn 753: $linkname = 'lonLinkID';
754: $pubname = 'lonPubID';
1.1378 raeburn 755: if (exists($cookies{$secure})) {
756: $lonid=$cookies{$secure};
757: } elsif (exists($cookies{$name})) {
758: $lonid=$cookies{$name};
1.1400 raeburn 759: } elsif ((exists($cookies{$linkname})) && ($ENV{'SERVER_PORT'} != 443)) {
1.1337 raeburn 760: $lonid=$cookies{$linkname};
1.1378 raeburn 761: } elsif (exists($cookies{$pubname})) {
762: $lonid=$cookies{$pubname};
1.1337 raeburn 763: }
1.1378 raeburn 764: } else {
765: $lonid=$cookies{$name};
1.1337 raeburn 766: }
1.916 albertel 767: return undef if (!$lonid);
768:
769: my $handle=&LONCAPA::clean_handle($lonid->value);
1.1378 raeburn 770: if (-l "$lonidsdir/$handle.id") {
771: my $link = readlink("$lonidsdir/$handle.id");
772: if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
773: $handle = $1;
774: }
1.1155 raeburn 775: }
1.1355 raeburn 776: if (!-e "$lonidsdir/$handle.id") {
777: if ((ref($domref)) && ($name eq 'lonID') &&
778: ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
779: my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
780: if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
781: $$domref = $possudom;
782: }
783: }
784: return undef;
785: }
1.916 albertel 786:
1.917 albertel 787: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
788: return undef if (!$opened);
1.916 albertel 789:
790: flock($idf,LOCK_SH);
791: my %disk_env;
792: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
793: &GDBM_READER(),0640)) {
794: return undef;
795: }
796:
797: if (!defined($disk_env{'user.name'})
798: || !defined($disk_env{'user.domain'})) {
1.1394 raeburn 799: untie(%disk_env);
1.916 albertel 800: return undef;
801: }
1.1245 raeburn 802:
803: if (ref($userhashref) eq 'HASH') {
804: $userhashref->{'name'} = $disk_env{'user.name'};
805: $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1448 raeburn 806: if ($disk_env{'request.role'}) {
807: $userhashref->{'role'} = $disk_env{'request.role'};
808: }
1.1361 raeburn 809: $userhashref->{'lti'} = $disk_env{'request.lti.login'};
1.1375 raeburn 810: if ($userhashref->{'lti'}) {
811: $userhashref->{'ltitarget'} = $disk_env{'request.lti.target'};
812: $userhashref->{'ltiuri'} = $disk_env{'request.lti.uri'};
813: }
1.1212 raeburn 814: }
1.1394 raeburn 815: untie(%disk_env);
1.1245 raeburn 816:
1.916 albertel 817: return $handle;
818: }
819:
1.830 albertel 820: sub timed_flock {
821: my ($file,$lock_type) = @_;
822: my $failed=0;
823: eval {
824: local $SIG{__DIE__}='DEFAULT';
825: local $SIG{ALRM}=sub {
826: $failed=1;
827: die("failed lock");
828: };
829: alarm(13);
830: flock($file,$lock_type);
831: alarm(0);
832: };
833: if ($failed) {
834: return undef;
835: } else {
836: return 1;
837: }
838: }
839:
1.1392 raeburn 840: sub get_sessionfile_vars {
841: my ($handle,$lonidsdir,$storearr) = @_;
842: my %returnhash;
843: unless (ref($storearr) eq 'ARRAY') {
844: return %returnhash;
845: }
846: if (-l "$lonidsdir/$handle.id") {
847: my $link = readlink("$lonidsdir/$handle.id");
848: if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
849: $handle = $1;
850: }
851: }
852: if ((-e "$lonidsdir/$handle.id") &&
853: ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
854: my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
855: if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
856: if (open(my $idf,'+<',"$lonidsdir/$handle.id")) {
857: flock($idf,LOCK_SH);
858: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
859: &GDBM_READER(),0640)) {
860: foreach my $item (@{$storearr}) {
861: $returnhash{$item} = $disk_env{$item};
862: }
863: untie(%disk_env);
864: }
865: }
866: }
867: }
868: return %returnhash;
869: }
870:
1.5 www 871: # ---------------------------------------------------------- Append Environment
872:
873: sub appenv {
1.949 raeburn 874: my ($newenv,$roles) = @_;
875: if (ref($newenv) eq 'HASH') {
876: foreach my $key (keys(%{$newenv})) {
877: my $refused = 0;
878: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
879: $refused = 1;
880: if (ref($roles) eq 'ARRAY') {
1.1250 raeburn 881: my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949 raeburn 882: if (grep(/^\Q$role\E$/,@{$roles})) {
883: $refused = 0;
884: }
885: }
886: }
887: if ($refused) {
888: &logthis("<font color=\"blue\">WARNING: ".
889: "Attempt to modify environment ".$key." to ".$newenv->{$key}
890: .'</font>');
891: delete($newenv->{$key});
892: } else {
893: $env{$key}=$newenv->{$key};
894: }
895: }
1.1376 raeburn 896: my $lonids = $perlvar{'lonIDsDir'};
897: if ($env{'user.environment'} =~ m{^\Q$lonids/\E$match_username\_\d+\_$match_domain\_[\w\-.]+\.id$}) {
898: my $opened = open(my $env_file,'+<',$env{'user.environment'});
899: if ($opened
900: && &timed_flock($env_file,LOCK_EX)
901: &&
902: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
903: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
904: while (my ($key,$value) = each(%{$newenv})) {
905: $disk_env{$key} = $value;
906: }
907: untie(%disk_env);
908: }
1.35 www 909: }
1.191 harris41 910: }
1.56 www 911: return 'ok';
912: }
913: # ----------------------------------------------------- Delete from Environment
914:
915: sub delenv {
1.1104 raeburn 916: my ($delthis,$regexp,$roles) = @_;
917: if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
918: my $refused = 1;
919: if (ref($roles) eq 'ARRAY') {
920: my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
921: if (grep(/^\Q$role\E$/,@{$roles})) {
922: $refused = 0;
923: }
924: }
925: if ($refused) {
926: &logthis("<font color=\"blue\">WARNING: ".
927: "Attempt to delete from environment ".$delthis);
928: return 'error';
929: }
1.56 www 930: }
1.917 albertel 931: my $opened = open(my $env_file,'+<',$env{'user.environment'});
932: if ($opened
1.915 albertel 933: && &timed_flock($env_file,LOCK_EX)
1.830 albertel 934: &&
935: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
936: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 937: foreach my $key (keys(%disk_env)) {
1.987 raeburn 938: if ($regexp) {
939: if ($key=~/^$delthis/) {
940: delete($env{$key});
941: delete($disk_env{$key});
942: }
943: } else {
944: if ($key=~/^\Q$delthis\E/) {
945: delete($env{$key});
946: delete($disk_env{$key});
947: }
948: }
1.448 albertel 949: }
1.783 albertel 950: untie(%disk_env);
1.5 www 951: }
952: return 'ok';
1.369 albertel 953: }
954:
1.790 albertel 955: sub get_env_multiple {
956: my ($name) = @_;
957: my @values;
958: if (defined($env{$name})) {
959: # exists is it an array
960: if (ref($env{$name})) {
961: @values=@{ $env{$name} };
962: } else {
963: $values[0]=$env{$name};
964: }
965: }
966: return(@values);
967: }
968:
1.958 www 969: # ------------------------------------------------------------------- Locking
970:
971: sub set_lock {
972: my ($text)=@_;
973: $locknum++;
974: my $id=$$.'-'.$locknum;
975: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
976: 'session.lock.'.$id => $text});
977: return $id;
978: }
979:
980: sub get_locks {
981: my $num=0;
982: my %texts=();
983: foreach my $lock (split(/\,/,$env{'session.locks'})) {
984: if ($lock=~/\w/) {
985: $num++;
986: $texts{$lock}=$env{'session.lock.'.$lock};
987: }
988: }
989: return ($num,%texts);
990: }
991:
992: sub remove_lock {
993: my ($id)=@_;
994: my $newlocks='';
995: foreach my $lock (split(/\,/,$env{'session.locks'})) {
996: if (($lock=~/\w/) && ($lock ne $id)) {
997: $newlocks.=','.$lock;
998: }
999: }
1000: &appenv({'session.locks' => $newlocks});
1001: &delenv('session.lock.'.$id);
1002: }
1003:
1004: sub remove_all_locks {
1005: my $activelocks=$env{'session.locks'};
1006: foreach my $lock (split(/\,/,$env{'session.locks'})) {
1007: if ($lock=~/\w/) {
1008: &remove_lock($lock);
1009: }
1010: }
1011: }
1012:
1013:
1.369 albertel 1014: # ------------------------------------------ Find out current server userload
1015: sub userload {
1016: my $numusers=0;
1017: {
1018: opendir(LONIDS,$perlvar{'lonIDsDir'});
1019: my $filename;
1020: my $curtime=time;
1021: while ($filename=readdir(LONIDS)) {
1.925 albertel 1022: next if ($filename eq '.' || $filename eq '..');
1023: next if ($filename =~ /publicuser_\d+\.id/);
1.1390 raeburn 1024: next if ($filename =~ /^[a-f0-9]+_linked\.id$/);
1.404 albertel 1025: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437 albertel 1026: if ($curtime-$mtime < 1800) { $numusers++; }
1.369 albertel 1027: }
1028: closedir(LONIDS);
1029: }
1030: my $userloadpercent=0;
1031: my $maxuserload=$perlvar{'lonUserLoadLim'};
1032: if ($maxuserload) {
1.371 albertel 1033: $userloadpercent=100*$numusers/$maxuserload;
1.369 albertel 1034: }
1.372 albertel 1035: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369 albertel 1036: return $userloadpercent;
1.283 www 1037: }
1038:
1.1 albertel 1039: # ------------------------------ Find server with least workload from spare.tab
1.11 www 1040:
1.1 albertel 1041: sub spareserver {
1.1451 raeburn 1042: my ($r,$loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784 albertel 1043: my $spare_server;
1.370 albertel 1044: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784 albertel 1045: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
1046: : $userloadpercent;
1.1083 raeburn 1047: my ($uint_dom,$remotesessions);
1048: if (($udom ne '') && (&domain($udom) ne '')) {
1.1494 raeburn 1049: my $uprimary_id = &domain($udom,'primary');
1050: $uint_dom = &internet_dom($uprimary_id);
1051: my %udomdefaults = &get_domain_defaults($udom);
1.1083 raeburn 1052: $remotesessions = $udomdefaults{'remotesessions'};
1053: }
1.1123 raeburn 1054: my $spareshash = &this_host_spares($udom);
1055: if (ref($spareshash) eq 'HASH') {
1056: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
1057: foreach my $try_server (@{ $spareshash->{'primary'} }) {
1.1279 raeburn 1058: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
1059: $try_server));
1.1123 raeburn 1060: ($spare_server, $lowest_load) =
1061: &compare_server_load($try_server, $spare_server, $lowest_load);
1062: }
1.1083 raeburn 1063: }
1.784 albertel 1064:
1.1123 raeburn 1065: my $found_server = ($spare_server ne '' && $lowest_load < 100);
1066:
1067: if (!$found_server) {
1068: if (ref($spareshash->{'default'}) eq 'ARRAY') {
1069: foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1279 raeburn 1070: next unless (&spare_can_host($udom,$uint_dom,
1071: $remotesessions,$try_server));
1.1123 raeburn 1072: ($spare_server, $lowest_load) =
1073: &compare_server_load($try_server, $spare_server, $lowest_load);
1074: }
1075: }
1076: }
1.784 albertel 1077: }
1078:
1079: if (!$want_server_name) {
1.1001 raeburn 1080: if (defined($spare_server)) {
1081: my $hostname = &hostname($spare_server);
1.1083 raeburn 1082: if (defined($hostname)) {
1.1397 raeburn 1083: my $protocol = 'http';
1084: if ($protocol{$spare_server} eq 'https') {
1085: $protocol = $protocol{$spare_server};
1086: }
1.1494 raeburn 1087: my $alias = &use_proxy_alias($r,$spare_server);
1.1451 raeburn 1088: $hostname = $alias if ($alias ne '');
1.1001 raeburn 1089: $spare_server = $protocol.'://'.$hostname;
1090: }
1091: }
1.784 albertel 1092: }
1093: return $spare_server;
1094: }
1095:
1096: sub compare_server_load {
1.1253 raeburn 1097: my ($try_server, $spare_server, $lowest_load, $required) = @_;
1098:
1099: if ($required) {
1100: my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
1101: my $remoterev = &get_server_loncaparev(undef,$try_server);
1102: my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
1103: if (($major eq '' && $minor eq '') ||
1104: (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
1105: return ($spare_server,$lowest_load);
1106: }
1107: }
1.784 albertel 1108:
1109: my $loadans = &reply('load', $try_server);
1110: my $userloadans = &reply('userload',$try_server);
1111:
1112: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114 raeburn 1113: return ($spare_server, $lowest_load); #didn't get a number from the server
1.784 albertel 1114: }
1115:
1116: my $load;
1117: if ($loadans =~ /\d/) {
1118: if ($userloadans =~ /\d/) {
1119: #both are numbers, pick the bigger one
1120: $load = ($loadans > $userloadans) ? $loadans
1121: : $userloadans;
1.411 albertel 1122: } else {
1.784 albertel 1123: $load = $loadans;
1.411 albertel 1124: }
1.784 albertel 1125: } else {
1126: $load = $userloadans;
1127: }
1128:
1129: if (($load =~ /\d/) && ($load < $lowest_load)) {
1130: $spare_server = $try_server;
1131: $lowest_load = $load;
1.370 albertel 1132: }
1.784 albertel 1133: return ($spare_server,$lowest_load);
1.202 matthew 1134: }
1.914 albertel 1135:
1136: # --------------------------- ask offload servers if user already has a session
1137: sub find_existing_session {
1138: my ($udom,$uname) = @_;
1.1123 raeburn 1139: my $spareshash = &this_host_spares($udom);
1140: if (ref($spareshash) eq 'HASH') {
1141: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
1142: foreach my $try_server (@{ $spareshash->{'primary'} }) {
1143: return $try_server if (&has_user_session($try_server, $udom, $uname));
1144: }
1145: }
1146: if (ref($spareshash->{'default'}) eq 'ARRAY') {
1147: foreach my $try_server (@{ $spareshash->{'default'} }) {
1148: return $try_server if (&has_user_session($try_server, $udom, $uname));
1149: }
1150: }
1.914 albertel 1151: }
1152: return;
1153: }
1154:
1.1411 raeburn 1155: sub delusersession {
1156: my ($lonid,$udom,$uname) = @_;
1157: my $uprimary_id = &domain($udom,'primary');
1158: my $uintdom = &internet_dom($uprimary_id);
1159: my $intdom = &internet_dom($lonid);
1160: my $serverhomedom = &host_domain($lonid);
1161: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1162: return &reply(join(':','delusersession',
1163: map {&escape($_)} ($udom,$uname)),$lonid);
1164: }
1165: return;
1166: }
1167:
1.1389 raeburn 1168: # check if user's browser sent load balancer cookie and server still has session
1169: # and is not overloaded.
1170: sub check_for_balancer_cookie {
1171: my ($r,$update_mtime) = @_;
1172: my ($otherserver,$cookie);
1173: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1174: if (exists($cookies{'balanceID'})) {
1175: my $balid = $cookies{'balanceID'};
1176: $cookie=&LONCAPA::clean_handle($balid->value);
1177: my $balancedir=$r->dir_config('lonBalanceDir');
1178: if ((-d $balancedir) && (-e "$balancedir/$cookie.id")) {
1179: if ($cookie =~ /^($match_domain)_($match_username)_[a-f0-9]+$/) {
1180: my ($possudom,$possuname) = ($1,$2);
1181: my $has_session = 0;
1182: if ((&domain($possudom) ne '') &&
1183: (&homeserver($possuname,$possudom) ne 'no_host')) {
1184: my $try_server;
1185: my $opened = open(my $idf,'+<',"$balancedir/$cookie.id");
1186: if ($opened) {
1187: flock($idf,LOCK_SH);
1188: while (my $line = <$idf>) {
1189: chomp($line);
1190: if (&hostname($line) ne '') {
1191: $try_server = $line;
1192: last;
1193: }
1194: }
1195: close($idf);
1196: if (($try_server) &&
1197: (&has_user_session($try_server,$possudom,$possuname))) {
1198: my $lowest_load = 30000;
1199: ($otherserver,$lowest_load) =
1200: &compare_server_load($try_server,undef,$lowest_load);
1201: if ($otherserver ne '' && $lowest_load < 100) {
1202: $has_session = 1;
1203: } else {
1204: undef($otherserver);
1205: }
1206: }
1207: }
1208: }
1209: if ($has_session) {
1210: if ($update_mtime) {
1211: my $atime = my $mtime = time;
1212: utime($atime,$mtime,"$balancedir/$cookie.id");
1213: }
1214: } else {
1215: unlink("$balancedir/$cookie.id");
1216: }
1217: }
1218: }
1219: }
1220: return ($otherserver,$cookie);
1221: }
1222:
1.1431 raeburn 1223: sub updatebalcookie {
1224: my ($cookie,$balancer,$lastentry)=@_;
1225: if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
1226: my ($udom,$uname) = ($1,$2);
1227: my $uprimary_id = &domain($udom,'primary');
1228: my $uintdom = &internet_dom($uprimary_id);
1229: my $intdom = &internet_dom($balancer);
1230: my $serverhomedom = &host_domain($balancer);
1231: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1232: return &reply('updatebalcookie:'.&escape($cookie).':'.&escape($lastentry),$balancer);
1233: }
1234: }
1235: return;
1236: }
1237:
1.1389 raeburn 1238: sub delbalcookie {
1239: my ($cookie,$balancer) =@_;
1240: if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
1241: my ($udom,$uname) = ($1,$2);
1242: my $uprimary_id = &domain($udom,'primary');
1243: my $uintdom = &internet_dom($uprimary_id);
1244: my $intdom = &internet_dom($balancer);
1245: my $serverhomedom = &host_domain($balancer);
1246: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1.1431 raeburn 1247: return &reply('delbalcookie:'.&escape($cookie),$balancer);
1.1389 raeburn 1248: }
1249: }
1250: }
1251:
1.914 albertel 1252: # -------------------------------- ask if server already has a session for user
1253: sub has_user_session {
1254: my ($lonid,$udom,$uname) = @_;
1255: my $result = &reply(join(':','userhassession',
1256: map {&escape($_)} ($udom,$uname)),$lonid);
1257: return 1 if ($result eq 'ok');
1258:
1259: return 0;
1260: }
1261:
1.1076 raeburn 1262: # --------- determine least loaded server in a user's domain which allows login
1263:
1264: sub choose_server {
1.1259 raeburn 1265: my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076 raeburn 1266: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077 raeburn 1267: my %servers = &get_servers($udom);
1.1076 raeburn 1268: my $lowest_load = 30000;
1.1259 raeburn 1269: my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
1270: if ($skiploadbal) {
1271: ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
1272: unless (defined($cached)) {
1273: my $cachetime = 60*60*24;
1274: my %domconfig =
1.1494 raeburn 1275: &get_dom('configuration',['loadbalancing'],$udom);
1.1259 raeburn 1276: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1277: $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
1278: $cachetime);
1279: }
1280: }
1281: }
1.1076 raeburn 1282: foreach my $lonhost (keys(%servers)) {
1.1259 raeburn 1283: if ($skiploadbal) {
1284: if (ref($balancers) eq 'HASH') {
1285: next if (exists($balancers->{$lonhost}));
1286: }
1.1389 raeburn 1287: }
1.1115 raeburn 1288: my $loginvia;
1289: if ($checkloginvia) {
1290: $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116 raeburn 1291: if ($loginvia) {
1292: my ($server,$path) = split(/:/,$loginvia);
1293: ($login_host, $lowest_load) =
1.1253 raeburn 1294: &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116 raeburn 1295: if ($login_host eq $server) {
1296: $portal_path = $path;
1.1151 raeburn 1297: $isredirect = 1;
1.1116 raeburn 1298: }
1299: } else {
1300: ($login_host, $lowest_load) =
1.1253 raeburn 1301: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116 raeburn 1302: if ($login_host eq $lonhost) {
1303: $portal_path = '';
1.1151 raeburn 1304: $isredirect = '';
1.1116 raeburn 1305: }
1306: }
1307: } else {
1.1076 raeburn 1308: ($login_host, $lowest_load) =
1.1253 raeburn 1309: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076 raeburn 1310: }
1311: }
1312: if ($login_host ne '') {
1.1116 raeburn 1313: $hostname = &hostname($login_host);
1.1076 raeburn 1314: }
1.1331 raeburn 1315: return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
1.1076 raeburn 1316: }
1317:
1.1420 raeburn 1318: sub get_course_sessions {
1319: my ($cnum,$cdom,$lastactivity) = @_;
1320: my %servers = &internet_dom_servers($cdom);
1321: my %returnhash;
1322: foreach my $server (sort(keys(%servers))) {
1323: my $rep = &reply("coursesessions:$cdom:$cnum:$lastactivity",$server);
1324: my @pairs=split(/\&/,$rep);
1325: unless (($rep eq 'unknown_cmd') || ($rep =~ /^error/)) {
1326: foreach my $item (@pairs) {
1327: my ($key,$value)=split(/=/,$item,2);
1328: $key = &unescape($key);
1329: next if ($key =~ /^error: 2 /);
1330: if (exists($returnhash{$key})) {
1331: next if ($value < $returnhash{$key});
1332: }
1333: $returnhash{$key}=$value;
1334: }
1335: }
1336: }
1337: return %returnhash;
1338: }
1339:
1.202 matthew 1340: # --------------------------------------------- Try to change a user's password
1341:
1342: sub changepass {
1.799 raeburn 1343: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 1344: $currentpass = &escape($currentpass);
1345: $newpass = &escape($newpass);
1.1030 raeburn 1346: my $lonhost = $perlvar{'lonHostID'};
1347: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202 matthew 1348: $server);
1349: if (! $answer) {
1350: &logthis("No reply on password change request to $server ".
1351: "by $uname in domain $udom.");
1352: } elsif ($answer =~ "^ok") {
1353: &logthis("$uname in $udom successfully changed their password ".
1354: "on $server.");
1355: } elsif ($answer =~ "^pwchange_failure") {
1356: &logthis("$uname in $udom was unable to change their password ".
1357: "on $server. The action was blocked by either lcpasswd ".
1358: "or pwchange");
1359: } elsif ($answer =~ "^non_authorized") {
1360: &logthis("$uname in $udom did not get their password correct when ".
1361: "attempting to change it on $server.");
1362: } elsif ($answer =~ "^auth_mode_error") {
1363: &logthis("$uname in $udom attempted to change their password despite ".
1364: "not being locally or internally authenticated on $server.");
1365: } elsif ($answer =~ "^unknown_user") {
1366: &logthis("$uname in $udom attempted to change their password ".
1367: "on $server but were unable to because $server is not ".
1368: "their home server.");
1369: } elsif ($answer =~ "^refused") {
1370: &logthis("$server refused to change $uname in $udom password because ".
1371: "it was sent an unencrypted request to change the password.");
1.1030 raeburn 1372: } elsif ($answer =~ "invalid_client") {
1373: &logthis("$server refused to change $uname in $udom password because ".
1374: "it was a reset by e-mail originating from an invalid server.");
1.1408 raeburn 1375: } elsif ($answer =~ "^prioruse") {
1376: &logthis("$server refused to change $uname in $udom password because ".
1377: "the password had been used before");
1.202 matthew 1378: }
1379: return $answer;
1.1 albertel 1380: }
1381:
1.169 harris41 1382: # ----------------------- Try to determine user's current authentication scheme
1383:
1384: sub queryauthenticate {
1385: my ($uname,$udom)=@_;
1.456 albertel 1386: my $uhome=&homeserver($uname,$udom);
1.1484 raeburn 1387: if ((!$uhome) || ($uhome eq 'no_host')) {
1.456 albertel 1388: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
1389: return 'no_host';
1390: }
1391: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
1392: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
1393: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 1394: }
1.456 albertel 1395: return $answer;
1.169 harris41 1396: }
1397:
1.1 albertel 1398: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 1399:
1.1 albertel 1400: sub authenticate {
1.1073 raeburn 1401: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807 albertel 1402: $upass=&escape($upass);
1403: $uname= &LONCAPA::clean_username($uname);
1.836 www 1404: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 1405: my $newhome;
1.836 www 1406: if ((!$uhome) || ($uhome eq 'no_host')) {
1407: # Maybe the machine was offline and only re-appeared again recently?
1408: &reconlonc();
1409: # One more
1.952 raeburn 1410: $uhome=&homeserver($uname,$udom,1);
1411: if (($uhome eq 'no_host') && $checkdefauth) {
1412: if (defined(&domain($udom,'primary'))) {
1413: $newhome=&domain($udom,'primary');
1414: }
1415: if ($newhome ne '') {
1416: $uhome = $newhome;
1417: }
1418: }
1.836 www 1419: if ((!$uhome) || ($uhome eq 'no_host')) {
1420: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 1421: return 'no_host';
1422: }
1.1 albertel 1423: }
1.1073 raeburn 1424: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471 albertel 1425: if ($answer eq 'authorized') {
1.952 raeburn 1426: if ($newhome) {
1427: &logthis("User $uname at $udom authorized by $uhome, but needs account");
1428: return 'no_account_on_host';
1429: } else {
1430: &logthis("User $uname at $udom authorized by $uhome");
1431: return $uhome;
1432: }
1.471 albertel 1433: }
1434: if ($answer eq 'non_authorized') {
1435: &logthis("User $uname at $udom rejected by $uhome");
1.1484 raeburn 1436: return 'no_host';
1.9 www 1437: }
1.471 albertel 1438: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 1439: return 'no_host';
1440: }
1441:
1.1491 raeburn 1442: sub can_switchserver {
1443: my ($udom,$home) = @_;
1444: my ($canswitch,@intdoms);
1445: my $internet_names = &get_internet_names($home);
1446: if (ref($internet_names) eq 'ARRAY') {
1447: @intdoms = @{$internet_names};
1448: }
1449: my $uint_dom = &internet_dom(&domain($udom,'primary'));
1450: if ($uint_dom ne '' && grep(/^\Q$uint_dom\E$/,@intdoms)) {
1451: $canswitch = 1;
1452: } else {
1453: my $serverhomeID = &get_server_homeID(&hostname($home));
1454: my $serverhomedom = &host_domain($serverhomeID);
1455: my %defdomdefaults = &get_domain_defaults($serverhomedom);
1456: my %udomdefaults = &get_domain_defaults($udom);
1457: my $remoterev = &get_server_loncaparev('',$home);
1458: $canswitch = &can_host_session($udom,$home,$remoterev,
1459: $udomdefaults{'remotesessions'},
1460: $defdomdefaults{'hostedsessions'});
1461: }
1462: return $canswitch;
1463: }
1464:
1.1073 raeburn 1465: sub can_host_session {
1.1074 raeburn 1466: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073 raeburn 1467: my $canhost = 1;
1.1494 raeburn 1468: my $host_idn = &internet_dom($lonhost);
1.1073 raeburn 1469: if (ref($remotesessions) eq 'HASH') {
1470: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074 raeburn 1471: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073 raeburn 1472: $canhost = 0;
1473: } else {
1474: $canhost = 1;
1475: }
1476: }
1477: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074 raeburn 1478: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073 raeburn 1479: $canhost = 1;
1480: } else {
1481: $canhost = 0;
1482: }
1483: }
1484: if ($canhost) {
1485: if ($remotesessions->{'version'} ne '') {
1486: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1487: if ($reqmajor ne '' && $reqminor ne '') {
1488: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1489: my $major = $1;
1490: my $minor = $2;
1491: if (($major < $reqmajor ) ||
1492: (($major == $reqmajor) && ($minor < $reqminor))) {
1493: $canhost = 0;
1494: }
1495: } else {
1496: $canhost = 0;
1497: }
1498: }
1499: }
1500: }
1501: }
1502: if ($canhost) {
1503: if (ref($hostedsessions) eq 'HASH') {
1.1494 raeburn 1504: my $uprimary_id = &domain($udom,'primary');
1505: my $uint_dom = &internet_dom($uprimary_id);
1.1073 raeburn 1506: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120 raeburn 1507: if (($uint_dom ne '') &&
1508: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073 raeburn 1509: $canhost = 0;
1510: } else {
1511: $canhost = 1;
1512: }
1513: }
1514: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120 raeburn 1515: if (($uint_dom ne '') &&
1516: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073 raeburn 1517: $canhost = 1;
1518: } else {
1519: $canhost = 0;
1520: }
1521: }
1522: }
1523: }
1524: return $canhost;
1525: }
1526:
1.1083 raeburn 1527: sub spare_can_host {
1528: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1529: my $canhost=1;
1.1279 raeburn 1530: my $try_server_hostname = &hostname($try_server);
1531: my $serverhomeID = &get_server_homeID($try_server_hostname);
1532: my $serverhomedom = &host_domain($serverhomeID);
1533: my %defdomdefaults = &get_domain_defaults($serverhomedom);
1534: if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
1535: if ($defdomdefaults{'offloadnow'}{$try_server}) {
1536: $canhost = 0;
1537: }
1538: }
1.1439 raeburn 1539: if ($canhost) {
1540: if (ref($defdomdefaults{'offloadoth'}) eq 'HASH') {
1541: if ($defdomdefaults{'offloadoth'}{$try_server}) {
1542: unless (&shared_institution($udom,$try_server)) {
1543: $canhost = 0;
1544: }
1545: }
1546: }
1547: }
1.1279 raeburn 1548: if (($canhost) && ($uint_dom)) {
1549: my @intdoms;
1550: my $internet_names = &get_internet_names($try_server);
1551: if (ref($internet_names) eq 'ARRAY') {
1552: @intdoms = @{$internet_names};
1553: }
1554: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1555: my $remoterev = &get_server_loncaparev(undef,$try_server);
1556: $canhost = &can_host_session($udom,$try_server,$remoterev,
1557: $remotesessions,
1558: $defdomdefaults{'hostedsessions'});
1559: }
1.1083 raeburn 1560: }
1561: return $canhost;
1562: }
1563:
1.1123 raeburn 1564: sub this_host_spares {
1565: my ($dom) = @_;
1.1126 raeburn 1566: my ($dom_in_use,$lonhost_in_use,$result);
1.1123 raeburn 1567: my @hosts = ¤t_machine_ids();
1568: foreach my $lonhost (@hosts) {
1569: if (&host_domain($lonhost) eq $dom) {
1.1126 raeburn 1570: $dom_in_use = $dom;
1571: $lonhost_in_use = $lonhost;
1.1123 raeburn 1572: last;
1573: }
1574: }
1.1126 raeburn 1575: if ($dom_in_use ne '') {
1576: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1577: }
1578: if (ref($result) ne 'HASH') {
1579: $lonhost_in_use = $perlvar{'lonHostID'};
1580: $dom_in_use = &host_domain($lonhost_in_use);
1581: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1582: if (ref($result) ne 'HASH') {
1583: $result = \%spareid;
1584: }
1585: }
1586: return $result;
1587: }
1588:
1589: sub spares_for_offload {
1590: my ($dom_in_use,$lonhost_in_use) = @_;
1591: my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123 raeburn 1592: if (defined($cached)) {
1593: return $result;
1594: } else {
1.1126 raeburn 1595: my $cachetime = 60*60*24;
1596: my %domconfig =
1.1494 raeburn 1597: &get_dom('configuration',['usersessions'],$dom_in_use);
1.1126 raeburn 1598: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1599: if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
1600: if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
1601: return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123 raeburn 1602: }
1603: }
1604: }
1605: }
1.1126 raeburn 1606: return;
1.1123 raeburn 1607: }
1608:
1.1129 raeburn 1609: sub get_lonbalancer_config {
1610: my ($servers) = @_;
1611: my ($currbalancer,$currtargets);
1612: if (ref($servers) eq 'HASH') {
1613: foreach my $server (keys(%{$servers})) {
1614: my %what = (
1615: spareid => 1,
1616: perlvar => 1,
1617: );
1618: my ($result,$returnhash) = &get_remote_globals($server,\%what);
1619: if ($result eq 'ok') {
1620: if (ref($returnhash) eq 'HASH') {
1621: if (ref($returnhash->{'perlvar'}) eq 'HASH') {
1622: if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
1623: $currbalancer = $server;
1624: $currtargets = {};
1625: if (ref($returnhash->{'spareid'}) eq 'HASH') {
1626: if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
1627: $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
1628: }
1629: if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
1630: $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
1631: }
1632: }
1633: last;
1634: }
1635: }
1636: }
1637: }
1638: }
1639: }
1640: return ($currbalancer,$currtargets);
1641: }
1642:
1643: sub check_loadbalancing {
1.1331 raeburn 1644: my ($uname,$udom,$caller) = @_;
1.1191 raeburn 1645: my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1.1391 raeburn 1646: $rule_in_effect,$offloadto,$otherserver,$setcookie,$dom_balancers);
1.1129 raeburn 1647: my $lonhost = $perlvar{'lonHostID'};
1.1175 raeburn 1648: my @hosts = ¤t_machine_ids();
1.1494 raeburn 1649: my $uprimary_id = &domain($udom,'primary');
1650: my $uintdom = &internet_dom($uprimary_id);
1651: my $intdom = &internet_dom($lonhost);
1.1129 raeburn 1652: my $serverhomedom = &host_domain($lonhost);
1.1307 raeburn 1653: my $domneedscache;
1.1129 raeburn 1654: my $cachetime = 60*60*24;
1655:
1656: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1657: $dom_in_use = $udom;
1658: $homeintdom = 1;
1659: } else {
1660: $dom_in_use = $serverhomedom;
1661: }
1662: my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
1663: unless (defined($cached)) {
1664: my %domconfig =
1.1494 raeburn 1665: &get_dom('configuration',['loadbalancing'],$dom_in_use);
1.1129 raeburn 1666: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1667: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1307 raeburn 1668: } else {
1669: $domneedscache = $dom_in_use;
1.1129 raeburn 1670: }
1671: }
1672: if (ref($result) eq 'HASH') {
1.1391 raeburn 1673: ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
1.1191 raeburn 1674: &check_balancer_result($result,@hosts);
1.1129 raeburn 1675: if ($is_balancer) {
1676: if (ref($currrules) eq 'HASH') {
1677: if ($homeintdom) {
1678: if ($uname ne '') {
1679: if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
1680: my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
1681: if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
1682: $rule_in_effect = $currrules->{'_LC_author'};
1683: } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
1684: $rule_in_effect = $currrules->{'_LC_adv'}
1685: }
1686: }
1687: if ($rule_in_effect eq '') {
1688: my %userenv = &userenvironment($udom,$uname,'inststatus');
1689: if ($userenv{'inststatus'} ne '') {
1690: my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
1691: my ($othertitle,$usertypes,$types) =
1692: &Apache::loncommon::sorted_inst_types($udom);
1693: if (ref($types) eq 'ARRAY') {
1694: foreach my $type (@{$types}) {
1695: if (grep(/^\Q$type\E$/,@statuses)) {
1696: if (exists($currrules->{$type})) {
1697: $rule_in_effect = $currrules->{$type};
1698: }
1699: }
1700: }
1701: }
1702: } else {
1703: if (exists($currrules->{'default'})) {
1704: $rule_in_effect = $currrules->{'default'};
1705: }
1706: }
1707: }
1708: } else {
1709: if (exists($currrules->{'default'})) {
1710: $rule_in_effect = $currrules->{'default'};
1711: }
1712: }
1713: } else {
1714: if ($currrules->{'_LC_external'} ne '') {
1715: $rule_in_effect = $currrules->{'_LC_external'};
1716: }
1717: }
1718: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1719: $uname,$udom);
1720: }
1721: }
1722: } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1239 raeburn 1723: ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129 raeburn 1724: unless (defined($cached)) {
1725: my %domconfig =
1.1494 raeburn 1726: &get_dom('configuration',['loadbalancing'],$serverhomedom);
1.1129 raeburn 1727: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1307 raeburn 1728: $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
1729: } else {
1730: $domneedscache = $serverhomedom;
1.1129 raeburn 1731: }
1732: }
1733: if (ref($result) eq 'HASH') {
1.1391 raeburn 1734: ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
1.1191 raeburn 1735: &check_balancer_result($result,@hosts);
1736: if ($is_balancer) {
1.1129 raeburn 1737: if (ref($currrules) eq 'HASH') {
1738: if ($currrules->{'_LC_internetdom'} ne '') {
1739: $rule_in_effect = $currrules->{'_LC_internetdom'};
1740: }
1741: }
1742: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1743: $uname,$udom);
1744: }
1745: } else {
1746: if ($perlvar{'lonBalancer'} eq 'yes') {
1747: $is_balancer = 1;
1748: $offloadto = &this_host_spares($dom_in_use);
1749: }
1.1307 raeburn 1750: unless (defined($cached)) {
1751: $domneedscache = $serverhomedom;
1752: }
1.1129 raeburn 1753: }
1754: } else {
1755: if ($perlvar{'lonBalancer'} eq 'yes') {
1756: $is_balancer = 1;
1757: $offloadto = &this_host_spares($dom_in_use);
1758: }
1.1307 raeburn 1759: unless (defined($cached)) {
1760: $domneedscache = $serverhomedom;
1761: }
1762: }
1763: if ($domneedscache) {
1764: &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129 raeburn 1765: }
1.1430 raeburn 1766: if (($is_balancer) && ($caller ne 'switchserver')) {
1.1176 raeburn 1767: my $lowest_load = 30000;
1768: if (ref($offloadto) eq 'HASH') {
1769: if (ref($offloadto->{'primary'}) eq 'ARRAY') {
1770: foreach my $try_server (@{$offloadto->{'primary'}}) {
1771: ($otherserver,$lowest_load) =
1772: &compare_server_load($try_server,$otherserver,$lowest_load);
1773: }
1.1129 raeburn 1774: }
1.1176 raeburn 1775: my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129 raeburn 1776:
1.1176 raeburn 1777: if (!$found_server) {
1778: if (ref($offloadto->{'default'}) eq 'ARRAY') {
1779: foreach my $try_server (@{$offloadto->{'default'}}) {
1780: ($otherserver,$lowest_load) =
1781: &compare_server_load($try_server,$otherserver,$lowest_load);
1782: }
1783: }
1784: }
1785: } elsif (ref($offloadto) eq 'ARRAY') {
1786: if (@{$offloadto} == 1) {
1787: $otherserver = $offloadto->[0];
1788: } elsif (@{$offloadto} > 1) {
1789: foreach my $try_server (@{$offloadto}) {
1.1129 raeburn 1790: ($otherserver,$lowest_load) =
1791: &compare_server_load($try_server,$otherserver,$lowest_load);
1792: }
1793: }
1794: }
1.1331 raeburn 1795: unless ($caller eq 'login') {
1796: if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
1797: $is_balancer = 0;
1798: if ($uname ne '' && $udom ne '') {
1799: if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1.1389 raeburn 1800: &appenv({'user.loadbalexempt' => $lonhost,
1.1331 raeburn 1801: 'user.loadbalcheck.time' => time});
1802: }
1.1176 raeburn 1803: }
1.1129 raeburn 1804: }
1805: }
1.1430 raeburn 1806: }
1807: if (($is_balancer) && (!$homeintdom)) {
1808: undef($setcookie);
1.1129 raeburn 1809: }
1.1391 raeburn 1810: return ($is_balancer,$otherserver,$setcookie,$offloadto,$dom_balancers);
1.1129 raeburn 1811: }
1812:
1.1191 raeburn 1813: sub check_balancer_result {
1814: my ($result,@hosts) = @_;
1.1391 raeburn 1815: my ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
1.1191 raeburn 1816: if (ref($result) eq 'HASH') {
1817: if ($result->{'lonhost'} ne '') {
1818: my $currbalancer = $result->{'lonhost'};
1819: if (grep(/^\Q$currbalancer\E$/,@hosts)) {
1820: $is_balancer = 1;
1821: $currtargets = $result->{'targets'};
1822: $currrules = $result->{'rules'};
1823: }
1.1391 raeburn 1824: $dom_balancers = $currbalancer;
1.1191 raeburn 1825: } else {
1.1391 raeburn 1826: if (keys(%{$result})) {
1827: foreach my $key (keys(%{$result})) {
1828: if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
1829: (ref($result->{$key}) eq 'HASH')) {
1830: $is_balancer = 1;
1831: $currrules = $result->{$key}{'rules'};
1832: $currtargets = $result->{$key}{'targets'};
1833: $setcookie = $result->{$key}{'cookie'};
1834: last;
1835: }
1.1191 raeburn 1836: }
1.1391 raeburn 1837: $dom_balancers = join(',',sort(keys(%{$result})));
1.1191 raeburn 1838: }
1839: }
1840: }
1.1391 raeburn 1841: return ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
1.1191 raeburn 1842: }
1843:
1.1129 raeburn 1844: sub get_loadbalancer_targets {
1845: my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
1846: my $offloadto;
1.1175 raeburn 1847: if ($rule_in_effect eq 'none') {
1848: return [$perlvar{'lonHostID'}];
1849: } elsif ($rule_in_effect eq '') {
1.1129 raeburn 1850: $offloadto = $currtargets;
1851: } else {
1852: if ($rule_in_effect eq 'homeserver') {
1853: my $homeserver = &homeserver($uname,$udom);
1854: if ($homeserver ne 'no_host') {
1855: $offloadto = [$homeserver];
1856: }
1857: } elsif ($rule_in_effect eq 'externalbalancer') {
1858: my %domconfig =
1.1494 raeburn 1859: &get_dom('configuration',['loadbalancing'],$udom);
1.1129 raeburn 1860: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1861: if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
1862: if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
1863: $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
1864: }
1865: }
1866: } else {
1.1178 raeburn 1867: my %servers = &internet_dom_servers($udom);
1.1129 raeburn 1868: my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
1869: if (&hostname($remotebalancer) ne '') {
1870: $offloadto = [$remotebalancer];
1871: }
1872: }
1873: } elsif (&hostname($rule_in_effect) ne '') {
1874: $offloadto = [$rule_in_effect];
1875: }
1876: }
1877: return $offloadto;
1878: }
1879:
1.1127 raeburn 1880: sub internet_dom_servers {
1881: my ($dom) = @_;
1882: my (%uniqservers,%servers);
1883: my $primaryserver = &hostname(&domain($dom,'primary'));
1884: my @machinedoms = &machine_domains($primaryserver);
1885: foreach my $mdom (@machinedoms) {
1886: my %currservers = %servers;
1887: my %server = &get_servers($mdom);
1888: %servers = (%currservers,%server);
1889: }
1890: my %by_hostname;
1891: foreach my $id (keys(%servers)) {
1892: push(@{$by_hostname{$servers{$id}}},$id);
1893: }
1894: foreach my $hostname (sort(keys(%by_hostname))) {
1895: if (@{$by_hostname{$hostname}} > 1) {
1896: my $match = 0;
1897: foreach my $id (@{$by_hostname{$hostname}}) {
1898: if (&host_domain($id) eq $dom) {
1899: $uniqservers{$id} = $hostname;
1900: $match = 1;
1901: }
1902: }
1903: unless ($match) {
1904: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1905: }
1906: } else {
1907: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1908: }
1909: }
1910: return %uniqservers;
1911: }
1912:
1.1347 raeburn 1913: sub trusted_domains {
1914: my ($cmdtype,$calldom) = @_;
1.1349 raeburn 1915: my ($trusted,$untrusted);
1.1347 raeburn 1916: if (&domain($calldom) eq '') {
1.1349 raeburn 1917: return ($trusted,$untrusted);
1.1347 raeburn 1918: }
1.1395 raeburn 1919: unless ($cmdtype =~ /^(content|shared|enroll|coaurem|othcoau|domroles|catalog|reqcrs|msg)$/) {
1.1349 raeburn 1920: return ($trusted,$untrusted);
1.1347 raeburn 1921: }
1922: my $callprimary = &domain($calldom,'primary');
1.1494 raeburn 1923: my $intcalldom = &internet_dom($callprimary);
1.1347 raeburn 1924: if ($intcalldom eq '') {
1.1349 raeburn 1925: return ($trusted,$untrusted);
1.1347 raeburn 1926: }
1927:
1.1494 raeburn 1928: my ($trustconfig,$cached)=&is_cached_new('trust',$calldom);
1.1347 raeburn 1929: unless (defined($cached)) {
1.1494 raeburn 1930: my %domconfig = &get_dom('configuration',['trust'],$calldom);
1931: &do_cache_new('trust',$calldom,$domconfig{'trust'},3600);
1.1347 raeburn 1932: $trustconfig = $domconfig{'trust'};
1933: }
1934: if (ref($trustconfig)) {
1935: my (%possexc,%possinc,@allexc,@allinc);
1936: if (ref($trustconfig->{$cmdtype}) eq 'HASH') {
1937: if (ref($trustconfig->{$cmdtype}->{'exc'}) eq 'ARRAY') {
1938: map { $possexc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'exc'}};
1939: }
1940: if (ref($trustconfig->{$cmdtype}->{'inc'}) eq 'ARRAY') {
1.1395 raeburn 1941: $possinc{$intcalldom} = 1;
1.1347 raeburn 1942: map { $possinc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'inc'}};
1943: }
1944: }
1945: if (keys(%possexc)) {
1946: if (keys(%possinc)) {
1947: foreach my $key (sort(keys(%possexc))) {
1948: next if ($key eq $intcalldom);
1949: unless ($possinc{$key}) {
1950: push(@allexc,$key);
1951: }
1952: }
1953: } else {
1954: @allexc = sort(keys(%possexc));
1955: }
1956: }
1957: if (keys(%possinc)) {
1958: $possinc{$intcalldom} = 1;
1959: @allinc = sort(keys(%possinc));
1960: }
1961: if ((@allexc > 0) || (@allinc > 0)) {
1962: my %doms_by_intdom;
1963: my %allintdoms = &all_host_intdom();
1964: my %alldoms = &all_host_domain();
1965: foreach my $key (%allintdoms) {
1966: if (ref($doms_by_intdom{$allintdoms{$key}}) eq 'ARRAY') {
1967: unless (grep(/^\Q$alldoms{$key}\E$/,@{$doms_by_intdom{$allintdoms{$key}}})) {
1968: push(@{$doms_by_intdom{$allintdoms{$key}}},$alldoms{$key});
1969: }
1970: } else {
1971: $doms_by_intdom{$allintdoms{$key}} = [$alldoms{$key}];
1972: }
1973: }
1974: foreach my $exc (@allexc) {
1975: if (ref($doms_by_intdom{$exc}) eq 'ARRAY') {
1.1395 raeburn 1976: push(@{$untrusted},@{$doms_by_intdom{$exc}});
1.1347 raeburn 1977: }
1978: }
1979: foreach my $inc (@allinc) {
1980: if (ref($doms_by_intdom{$inc}) eq 'ARRAY') {
1.1395 raeburn 1981: push(@{$trusted},@{$doms_by_intdom{$inc}});
1.1347 raeburn 1982: }
1983: }
1984: }
1985: }
1.1349 raeburn 1986: return ($trusted,$untrusted);
1.1347 raeburn 1987: }
1988:
1989: sub will_trust {
1990: my ($cmdtype,$domain,$possdom) = @_;
1991: return 1 if ($domain eq $possdom);
1992: my ($trustedref,$untrustedref) = &trusted_domains($cmdtype,$possdom);
1993: my $willtrust;
1994: if ((ref($trustedref) eq 'ARRAY') && (@{$trustedref} > 0)) {
1995: if (grep(/^\Q$domain\E$/,@{$trustedref})) {
1996: $willtrust = 1;
1997: }
1998: } elsif ((ref($untrustedref) eq 'ARRAY') && (@{$untrustedref} > 0)) {
1999: unless (grep(/^\Q$domain\E$/,@{$untrustedref})) {
2000: $willtrust = 1;
2001: }
2002: } else {
2003: $willtrust = 1;
2004: }
2005: return $willtrust;
2006: }
2007:
1.1 albertel 2008: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 2009:
1.599 albertel 2010: my %homecache;
1.1 albertel 2011: sub homeserver {
1.230 stredwic 2012: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 2013: my $index="$uname:$udom";
1.426 albertel 2014:
1.599 albertel 2015: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 2016:
2017: my %servers = &get_servers($udom,'library');
2018: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 2019: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 2020: exists($badServerCache{$tryserver}));
1.841 albertel 2021:
2022: my $answer=reply("home:$udom:$uname",$tryserver);
2023: if ($answer eq 'found') {
2024: delete($badServerCache{$tryserver});
2025: return $homecache{$index}=$tryserver;
2026: } elsif ($answer eq 'no_host') {
2027: $badServerCache{$tryserver}=1;
2028: }
1.1 albertel 2029: }
2030: return 'no_host';
1.70 www 2031: }
2032:
1.1300 raeburn 2033: # ----- Find the usernames behind a list of student/employee IDs or clicker IDs
1.70 www 2034:
2035: sub idget {
1.1300 raeburn 2036: my ($udom,$idsref,$namespace)=@_;
1.70 www 2037: my %returnhash=();
1.1300 raeburn 2038: my @ids=();
2039: if (ref($idsref) eq 'ARRAY') {
2040: @ids = @{$idsref};
2041: } else {
2042: return %returnhash;
2043: }
2044: if ($namespace eq '') {
2045: $namespace = 'ids';
2046: }
1.70 www 2047:
1.841 albertel 2048: my %servers = &get_servers($udom,'library');
2049: foreach my $tryserver (keys(%servers)) {
1.1299 raeburn 2050: my $idlist=join('&', map { &escape($_); } @ids);
1.1300 raeburn 2051: if ($namespace eq 'ids') {
2052: $idlist=~tr/A-Z/a-z/;
2053: }
2054: my $reply;
2055: if ($namespace eq 'ids') {
2056: $reply=&reply("idget:$udom:".$idlist,$tryserver);
2057: } else {
2058: $reply=&reply("getdom:$udom:$namespace:$idlist",$tryserver);
2059: }
1.841 albertel 2060: my @answer=();
2061: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
2062: @answer=split(/\&/,$reply);
2063: } ;
2064: my $i;
2065: for ($i=0;$i<=$#ids;$i++) {
2066: if ($answer[$i]) {
1.1299 raeburn 2067: $returnhash{$ids[$i]}=&unescape($answer[$i]);
1.1300 raeburn 2068: }
1.841 albertel 2069: }
1.1300 raeburn 2070: }
1.70 www 2071: return %returnhash;
2072: }
2073:
2074: # ------------------------------------- Find the IDs behind a list of usernames
2075:
2076: sub idrget {
2077: my ($udom,@unames)=@_;
2078: my %returnhash=();
1.800 albertel 2079: foreach my $uname (@unames) {
2080: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 2081: }
1.70 www 2082: return %returnhash;
2083: }
2084:
1.1300 raeburn 2085: # Store away a list of names and associated student/employee IDs or clicker IDs
1.70 www 2086:
2087: sub idput {
1.1300 raeburn 2088: my ($udom,$idsref,$uhom,$namespace)=@_;
1.70 www 2089: my %servers=();
1.1300 raeburn 2090: my %ids=();
2091: my %byid = ();
2092: if (ref($idsref) eq 'HASH') {
2093: %ids=%{$idsref};
2094: }
2095: if ($namespace eq '') {
2096: $namespace = 'ids';
2097: }
1.800 albertel 2098: foreach my $uname (keys(%ids)) {
2099: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1.1300 raeburn 2100: if ($uhom eq '') {
2101: $uhom=&homeserver($uname,$udom);
2102: }
1.70 www 2103: if ($uhom ne 'no_host') {
1.800 albertel 2104: my $esc_unam=&escape($uname);
1.1300 raeburn 2105: if ($namespace eq 'ids') {
2106: my $id=&escape($ids{$uname});
2107: $id=~tr/A-Z/a-z/;
2108: my $esc_unam=&escape($uname);
2109: $servers{$uhom}.=$id.'='.$esc_unam.'&';
1.70 www 2110: } else {
1.1300 raeburn 2111: my @currids = split(/,/,$ids{$uname});
2112: foreach my $id (@currids) {
2113: $byid{$uhom}{$id} .= $uname.',';
2114: }
2115: }
2116: }
2117: }
2118: if ($namespace eq 'clickers') {
2119: foreach my $server (keys(%byid)) {
2120: if (ref($byid{$server}) eq 'HASH') {
2121: foreach my $id (keys(%{$byid{$server}})) {
2122: $byid{$server} =~ s/,$//;
2123: $servers{$uhom}.=&escape($id).'='.&escape($byid{$server}).'&';
2124: }
1.70 www 2125: }
2126: }
1.191 harris41 2127: }
1.800 albertel 2128: foreach my $server (keys(%servers)) {
1.1300 raeburn 2129: $servers{$server} =~ s/\&$//;
2130: if ($namespace eq 'ids') {
2131: &critical('idput:'.$udom.':'.$servers{$server},$server);
2132: } else {
2133: &critical('updateclickers:'.$udom.':add:'.$servers{$server},$server);
2134: }
1.191 harris41 2135: }
1.344 www 2136: }
2137:
1.1300 raeburn 2138: # ------------- Delete unwanted student/employee IDs or clicker IDs from domain
1.1231 raeburn 2139:
2140: sub iddel {
1.1300 raeburn 2141: my ($udom,$idshashref,$uhome,$namespace)=@_;
1.1231 raeburn 2142: my %result=();
1.1300 raeburn 2143: my %ids=();
2144: my %byid = ();
2145: if (ref($idshashref) eq 'HASH') {
2146: %ids=%{$idshashref};
2147: } else {
1.1231 raeburn 2148: return %result;
2149: }
1.1300 raeburn 2150: if ($namespace eq '') {
2151: $namespace = 'ids';
2152: }
1.1231 raeburn 2153: my %servers=();
1.1300 raeburn 2154: while (my ($id,$unamestr) = each(%ids)) {
2155: if ($namespace eq 'ids') {
2156: my $uhom = $uhome;
2157: if ($uhom eq '') {
2158: $uhom=&homeserver($unamestr,$udom);
2159: }
2160: if ($uhom ne 'no_host') {
2161: $servers{$uhom}.='&'.&escape($id);
2162: }
2163: } else {
2164: my @curritems = split(/,/,$ids{$id});
2165: foreach my $uname (@curritems) {
2166: my $uhom = $uhome;
2167: if ($uhom eq '') {
2168: $uhom=&homeserver($uname,$udom);
2169: }
2170: if ($uhom ne 'no_host') {
2171: $byid{$uhom}{$id} .= $uname.',';
2172: }
2173: }
1.1231 raeburn 2174: }
1.1300 raeburn 2175: }
2176: if ($namespace eq 'clickers') {
2177: foreach my $server (keys(%byid)) {
2178: if (ref($byid{$server}) eq 'HASH') {
2179: foreach my $id (keys(%{$byid{$server}})) {
2180: $byid{$server}{$id} =~ s/,$//;
2181: $servers{$server}.=&escape($id).'='.&escape($byid{$server}{$id}).'&';
2182: }
1.1231 raeburn 2183: }
2184: }
2185: }
2186: foreach my $server (keys(%servers)) {
1.1300 raeburn 2187: $servers{$server} =~ s/\&$//;
2188: if ($namespace eq 'ids') {
2189: $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
2190: } elsif ($namespace eq 'clickers') {
2191: $result{$server} = &critical('updateclickers:'.$udom.':del:'.$servers{$server},$server);
2192: }
1.1231 raeburn 2193: }
2194: return %result;
2195: }
2196:
1.1300 raeburn 2197: # ----- Update clicker ID-to-username look-ups in clickers.db on library server
2198:
2199: sub updateclickers {
2200: my ($udom,$action,$idshashref,$uhome,$critical) = @_;
2201: my %clickers;
2202: if (ref($idshashref) eq 'HASH') {
2203: %clickers=%{$idshashref};
2204: } else {
2205: return;
2206: }
2207: my $items='';
2208: foreach my $item (keys(%clickers)) {
2209: $items.=&escape($item).'='.&escape($clickers{$item}).'&';
2210: }
2211: $items=~s/\&$//;
2212: my $request = "updateclickers:$udom:$action:$items";
2213: if ($critical) {
2214: return &critical($request,$uhome);
2215: } else {
2216: return &reply($request,$uhome);
2217: }
2218: }
2219:
1.1023 raeburn 2220: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 2221: sub dump_dom {
1.1165 droeschl 2222: my ($namespace, $udom, $regexp) = @_;
2223:
2224: $udom ||= $env{'user.domain'};
2225:
2226: return () unless $udom;
2227:
2228: return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012 raeburn 2229: }
2230:
1.1023 raeburn 2231: # ------------------------------------------ get items from domain db files
1.806 raeburn 2232:
2233: sub get_dom {
1.1462 raeburn 2234: my ($namespace,$storearr,$udom,$uhome,$encrypt)=@_;
1.1267 raeburn 2235: return if ($udom eq 'public');
1.806 raeburn 2236: my $items='';
2237: foreach my $item (@$storearr) {
2238: $items.=&escape($item).'&';
2239: }
2240: $items=~s/\&$//;
1.860 raeburn 2241: if (!$udom) {
2242: $udom=$env{'user.domain'};
1.1267 raeburn 2243: return if ($udom eq 'public');
1.860 raeburn 2244: if (defined(&domain($udom,'primary'))) {
2245: $uhome=&domain($udom,'primary');
2246: } else {
1.874 albertel 2247: undef($uhome);
1.860 raeburn 2248: }
2249: } else {
2250: if (!$uhome) {
2251: if (defined(&domain($udom,'primary'))) {
2252: $uhome=&domain($udom,'primary');
2253: }
2254: }
2255: }
2256: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.1344 raeburn 2257: my $rep;
1.1442 raeburn 2258: if (grep { $_ eq $uhome } ¤t_machine_ids()) {
2259: # domain information is hosted on this machine
1.1462 raeburn 2260: $rep = &LONCAPA::Lond::get_dom("getdom:$udom:$namespace:$items");
1.1344 raeburn 2261: } else {
1.1462 raeburn 2262: if ($encrypt) {
1.1442 raeburn 2263: $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
2264: } else {
2265: $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
2266: }
1.1344 raeburn 2267: }
1.866 raeburn 2268: my %returnhash;
1.875 albertel 2269: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 2270: return %returnhash;
2271: }
1.806 raeburn 2272: my @pairs=split(/\&/,$rep);
2273: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
2274: return @pairs;
2275: }
2276: my $i=0;
2277: foreach my $item (@$storearr) {
2278: $returnhash{$item}=&thaw_unescape($pairs[$i]);
2279: $i++;
2280: }
2281: return %returnhash;
2282: } else {
1.880 banghart 2283: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 2284: }
2285: }
2286:
2287: # -------------------------------------------- put items in domain db files
2288:
2289: sub put_dom {
1.1462 raeburn 2290: my ($namespace,$storehash,$udom,$uhome,$encrypt)=@_;
1.860 raeburn 2291: if (!$udom) {
2292: $udom=$env{'user.domain'};
2293: if (defined(&domain($udom,'primary'))) {
2294: $uhome=&domain($udom,'primary');
2295: } else {
1.874 albertel 2296: undef($uhome);
1.860 raeburn 2297: }
2298: } else {
2299: if (!$uhome) {
2300: if (defined(&domain($udom,'primary'))) {
2301: $uhome=&domain($udom,'primary');
2302: }
2303: }
2304: }
2305: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 2306: my $items='';
2307: foreach my $item (keys(%$storehash)) {
2308: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
2309: }
2310: $items=~s/\&$//;
1.1462 raeburn 2311: if ($encrypt) {
1.1344 raeburn 2312: return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
2313: } else {
2314: return &reply("putdom:$udom:$namespace:$items",$uhome);
2315: }
1.806 raeburn 2316: } else {
1.860 raeburn 2317: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 2318: }
2319: }
2320:
1.1023 raeburn 2321: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 2322: sub newput_dom {
1.1023 raeburn 2323: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 2324: my $result;
2325: if (!$udom) {
2326: $udom=$env{'user.domain'};
2327: }
1.1023 raeburn 2328: if ($udom) {
2329: my $uname = &get_domainconfiguser($udom);
2330: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 2331: }
2332: return $result;
2333: }
2334:
1.1023 raeburn 2335: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 2336: sub del_dom {
1.1023 raeburn 2337: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 2338: if (ref($storearr) eq 'ARRAY') {
2339: if (!$udom) {
2340: $udom=$env{'user.domain'};
2341: }
1.1023 raeburn 2342: if ($udom) {
2343: my $uname = &get_domainconfiguser($udom);
2344: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 2345: }
2346: }
2347: }
2348:
1.1481 raeburn 2349: sub store_dom {
1.1482 raeburn 2350: my ($storehash,$id,$namespace,$dom,$home,$encrypt) = @_;
1.1481 raeburn 2351: $$storehash{'ip'}=&get_requestor_ip();
2352: $$storehash{'host'}=$perlvar{'lonHostID'};
2353: my $namevalue='';
2354: foreach my $key (keys(%{$storehash})) {
2355: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
2356: }
2357: $namevalue=~s/\&$//;
2358: if (grep { $_ eq $home } current_machine_ids()) {
2359: return LONCAPA::Lond::store_dom("storedom:$dom:$namespace:$id:$namevalue");
2360: } else {
2361: if ($namespace eq 'private') {
2362: return 'refused';
1.1482 raeburn 2363: } elsif ($encrypt) {
2364: return reply("encrypt:storedom:$dom:$namespace:$id:$namevalue",$home);
1.1481 raeburn 2365: } else {
1.1482 raeburn 2366: return reply("storedom:$dom:$namespace:$id:$namevalue",$home);
1.1481 raeburn 2367: }
2368: }
2369: }
2370:
1.1482 raeburn 2371: sub restore_dom {
2372: my ($id,$namespace,$dom,$home,$encrypt) = @_;
2373: my $answer;
2374: if (grep { $_ eq $home } current_machine_ids()) {
2375: $answer = LONCAPA::Lond::restore_dom("restoredom:$dom:$namespace:$id");
2376: } elsif ($namespace ne 'private') {
2377: if ($encrypt) {
2378: $answer=&reply("encrypt:restoredom:$dom:$namespace:$id",$home);
2379: } else {
2380: $answer=&reply("restoredom:$dom:$namespace:$id",$home);
2381: }
2382: }
2383: my %returnhash=();
2384: unless (($answer eq '') || ($answer eq 'con_lost') || ($answer eq 'refused') ||
2385: ($answer eq 'unknown_cmd') || ($answer eq 'rejected')) {
2386: foreach my $line (split(/\&/,$answer)) {
2387: my ($name,$value)=split(/\=/,$line);
2388: $returnhash{&unescape($name)}=&thaw_unescape($value);
2389: }
2390: my $version;
2391: for ($version=1;$version<=$returnhash{'version'};$version++) {
2392: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
2393: $returnhash{$item}=$returnhash{$version.':'.$item};
2394: }
2395: }
2396: }
2397: return %returnhash;
2398: }
2399:
1.1023 raeburn 2400: # ----------------------------------construct domainconfig user for a domain
2401: sub get_domainconfiguser {
2402: my ($udom) = @_;
2403: return $udom.'-domainconfig';
2404: }
2405:
1.837 raeburn 2406: sub retrieve_inst_usertypes {
2407: my ($udom) = @_;
2408: my (%returnhash,@order);
1.1494 raeburn 2409: my %domdefs = &get_domain_defaults($udom);
1.989 raeburn 2410: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
2411: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1256 raeburn 2412: return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989 raeburn 2413: } else {
2414: if (defined(&domain($udom,'primary'))) {
2415: my $uhome=&domain($udom,'primary');
2416: my $rep=&reply("inst_usertypes:$udom",$uhome);
2417: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1256 raeburn 2418: &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989 raeburn 2419: return (\%returnhash,\@order);
2420: }
2421: my ($hashitems,$orderitems) = split(/:/,$rep);
2422: my @pairs=split(/\&/,$hashitems);
2423: foreach my $item (@pairs) {
2424: my ($key,$value)=split(/=/,$item,2);
2425: $key = &unescape($key);
2426: next if ($key =~ /^error: 2 /);
2427: $returnhash{$key}=&thaw_unescape($value);
2428: }
2429: my @esc_order = split(/\&/,$orderitems);
2430: foreach my $item (@esc_order) {
2431: push(@order,&unescape($item));
2432: }
2433: } else {
1.1256 raeburn 2434: &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837 raeburn 2435: }
1.1256 raeburn 2436: return (\%returnhash,\@order);
1.837 raeburn 2437: }
2438: }
2439:
1.868 raeburn 2440: sub is_domainimage {
2441: my ($url) = @_;
1.1468 raeburn 2442: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo|login)/+[^/]-) {
1.868 raeburn 2443: if (&domain($1) ne '') {
2444: return '1';
2445: }
2446: }
2447: return;
2448: }
2449:
1.899 raeburn 2450: sub inst_directory_query {
2451: my ($srch) = @_;
2452: my $udom = $srch->{'srchdomain'};
2453: my %results;
2454: my $homeserver = &domain($udom,'primary');
1.909 raeburn 2455: my $outcome;
1.899 raeburn 2456: if ($homeserver ne '') {
1.1357 raeburn 2457: unless ($homeserver eq $perlvar{'lonHostID'}) {
2458: if ($srch->{'srchby'} eq 'email') {
1.1417 raeburn 2459: my $lcrev = &get_server_loncaparev($udom,$homeserver);
1.1357 raeburn 2460: my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
2461: if (($major eq '' && $minor eq '') || ($major < 2) ||
2462: (($major == 2) && ($minor < 12))) {
2463: return;
2464: }
2465: }
2466: }
1.904 albertel 2467: my $queryid=&reply("querysend:instdirsearch:".
2468: &escape($srch->{'srchby'}).':'.
2469: &escape($srch->{'srchterm'}).':'.
2470: &escape($srch->{'srchtype'}),$homeserver);
2471: my $host=&hostname($homeserver);
2472: if ($queryid !~/^\Q$host\E\_/) {
1.1343 raeburn 2473: &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
1.904 albertel 2474: return;
2475: }
2476: my $response = &get_query_reply($queryid);
2477: my $maxtries = 5;
2478: my $tries = 1;
2479: while (($response=~/^timeout/) && ($tries < $maxtries)) {
2480: $response = &get_query_reply($queryid);
2481: $tries ++;
2482: }
2483:
2484: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 2485: if ($response eq 'unavailable') {
2486: $outcome = $response;
2487: } else {
2488: $outcome = 'ok';
2489: my @matches = split(/\n/,$response);
2490: foreach my $match (@matches) {
2491: my ($key,$value) = split(/=/,$match);
2492: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
2493: }
1.899 raeburn 2494: }
2495: }
2496: }
1.909 raeburn 2497: return ($outcome,%results);
1.899 raeburn 2498: }
2499:
2500: sub usersearch {
2501: my ($srch) = @_;
2502: my $dom = $srch->{'srchdomain'};
2503: my %results;
2504: my %libserv = &all_library();
2505: my $query = 'usersearch';
2506: foreach my $tryserver (keys(%libserv)) {
2507: if (&host_domain($tryserver) eq $dom) {
1.1357 raeburn 2508: unless ($tryserver eq $perlvar{'lonHostID'}) {
2509: if ($srch->{'srchby'} eq 'email') {
1.1417 raeburn 2510: my $lcrev = &get_server_loncaparev($dom,$tryserver);
1.1357 raeburn 2511: my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
2512: next if (($major eq '' && $minor eq '') || ($major < 2) ||
2513: (($major == 2) && ($minor < 12)));
2514: }
2515: }
1.899 raeburn 2516: my $host=&hostname($tryserver);
2517: my $queryid=
1.911 raeburn 2518: &reply("querysend:".&escape($query).':'.
2519: &escape($srch->{'srchby'}).':'.
1.899 raeburn 2520: &escape($srch->{'srchtype'}).':'.
2521: &escape($srch->{'srchterm'}),$tryserver);
2522: if ($queryid !~/^\Q$host\E\_/) {
2523: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 2524: next;
1.899 raeburn 2525: }
2526: my $reply = &get_query_reply($queryid);
2527: my $maxtries = 1;
2528: my $tries = 1;
2529: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
2530: $reply = &get_query_reply($queryid);
2531: $tries ++;
2532: }
2533: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
2534: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
2535: } else {
1.911 raeburn 2536: my @matches;
2537: if ($reply =~ /\n/) {
2538: @matches = split(/\n/,$reply);
2539: } else {
2540: @matches = split(/\&/,$reply);
2541: }
1.899 raeburn 2542: foreach my $match (@matches) {
2543: my ($uname,$udom,%userhash);
1.911 raeburn 2544: foreach my $entry (split(/:/,$match)) {
2545: my ($key,$value) =
2546: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 2547: $userhash{$key} = $value;
2548: if ($key eq 'username') {
2549: $uname = $value;
2550: } elsif ($key eq 'domain') {
2551: $udom = $value;
1.911 raeburn 2552: }
1.899 raeburn 2553: }
2554: $results{$uname.':'.$udom} = \%userhash;
2555: }
2556: }
2557: }
2558: }
2559: return %results;
2560: }
2561:
1.912 raeburn 2562: sub get_instuser {
2563: my ($udom,$uname,$id) = @_;
2564: my $homeserver = &domain($udom,'primary');
2565: my ($outcome,%results);
2566: if ($homeserver ne '') {
2567: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
2568: &escape($id).':'.&escape($udom),$homeserver);
2569: my $host=&hostname($homeserver);
2570: if ($queryid !~/^\Q$host\E\_/) {
2571: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
2572: return;
2573: }
2574: my $response = &get_query_reply($queryid);
2575: my $maxtries = 5;
2576: my $tries = 1;
2577: while (($response=~/^timeout/) && ($tries < $maxtries)) {
2578: $response = &get_query_reply($queryid);
2579: $tries ++;
2580: }
2581: if (!&error($response) && $response ne 'refused') {
2582: if ($response eq 'unavailable') {
2583: $outcome = $response;
2584: } else {
2585: $outcome = 'ok';
2586: my @matches = split(/\n/,$response);
2587: foreach my $match (@matches) {
2588: my ($key,$value) = split(/=/,$match);
2589: $results{&unescape($key)} = &thaw_unescape($value);
2590: }
2591: }
2592: }
2593: }
2594: my %userinfo;
2595: if (ref($results{$uname}) eq 'HASH') {
2596: %userinfo = %{$results{$uname}};
2597: }
2598: return ($outcome,%userinfo);
2599: }
2600:
1.1290 raeburn 2601: sub get_multiple_instusers {
2602: my ($udom,$users,$caller) = @_;
2603: my ($outcome,$results);
2604: if (ref($users) eq 'HASH') {
2605: my $count = keys(%{$users});
2606: my $requested = &freeze_escape($users);
2607: my $homeserver = &domain($udom,'primary');
2608: if ($homeserver ne '') {
2609: my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
2610: my $host=&hostname($homeserver);
2611: if ($queryid !~/^\Q$host\E\_/) {
2612: &logthis('get_multiple_instusers invalid queryid: '.$queryid.
2613: ' for host: '.$homeserver.'in domain '.$udom);
2614: return ($outcome,$results);
2615: }
2616: my $response = &get_query_reply($queryid);
2617: my $maxtries = 5;
2618: if ($count > 100) {
2619: $maxtries = 1+int($count/20);
2620: }
2621: my $tries = 1;
2622: while (($response=~/^timeout/) && ($tries <= $maxtries)) {
2623: $response = &get_query_reply($queryid);
2624: $tries ++;
2625: }
2626: if ($response eq '') {
2627: $results = {};
2628: foreach my $key (keys(%{$users})) {
2629: my ($uname,$id);
2630: if ($caller eq 'id') {
2631: $id = $key;
2632: } else {
2633: $uname = $key;
2634: }
2635: my ($resp,%info) = &get_instuser($udom,$uname,$id);
1.1291 raeburn 2636: $outcome = $resp;
1.1290 raeburn 2637: if ($resp eq 'ok') {
2638: %{$results} = (%{$results}, %info);
2639: } else {
2640: last;
2641: }
2642: }
2643: } elsif(!&error($response) && ($response ne 'refused')) {
2644: if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
2645: $outcome = $response;
2646: } else {
1.1291 raeburn 2647: ($outcome,my $userdata) = split(/=/,$response,2);
1.1290 raeburn 2648: if ($outcome eq 'ok') {
2649: $results = &thaw_unescape($userdata);
2650: }
2651: }
2652: }
2653: }
2654: }
2655: return ($outcome,$results);
2656: }
2657:
1.912 raeburn 2658: sub inst_rulecheck {
1.923 raeburn 2659: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 2660: my %returnhash;
2661: if ($udom ne '') {
2662: if (ref($rules) eq 'ARRAY') {
2663: @{$rules} = map {&escape($_);} (@{$rules});
2664: my $rulestr = join(':',@{$rules});
2665: my $homeserver=&domain($udom,'primary');
2666: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 2667: my $response;
2668: if ($item eq 'username') {
2669: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
2670: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 2671: $homeserver));
1.923 raeburn 2672: } elsif ($item eq 'id') {
2673: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
2674: ':'.&escape($id).':'.$rulestr,
2675: $homeserver));
1.945 raeburn 2676: } elsif ($item eq 'selfcreate') {
2677: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 2678: &escape($udom).':'.&escape($uname).
2679: ':'.$rulestr,$homeserver));
1.1484 raeburn 2680: } elsif ($item eq 'unamemap') {
2681: $response=&unescape(&reply('instunamemapcheck:'.
2682: &escape($udom).':'.&escape($uname).
2683: ':'.$rulestr,$homeserver));
1.923 raeburn 2684: }
1.912 raeburn 2685: if ($response ne 'refused') {
2686: my @pairs=split(/\&/,$response);
2687: foreach my $item (@pairs) {
2688: my ($key,$value)=split(/=/,$item,2);
2689: $key = &unescape($key);
2690: next if ($key =~ /^error: 2 /);
2691: $returnhash{$key}=&thaw_unescape($value);
2692: }
2693: }
2694: }
2695: }
2696: }
2697: return %returnhash;
2698: }
2699:
2700: sub inst_userrules {
1.923 raeburn 2701: my ($udom,$check) = @_;
1.912 raeburn 2702: my (%ruleshash,@ruleorder);
2703: if ($udom ne '') {
2704: my $homeserver=&domain($udom,'primary');
2705: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 2706: my $response;
2707: if ($check eq 'id') {
2708: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 2709: $homeserver);
1.943 raeburn 2710: } elsif ($check eq 'email') {
2711: $response=&reply('instemailrules:'.&escape($udom),
2712: $homeserver);
1.1484 raeburn 2713: } elsif ($check eq 'unamemap') {
2714: $response=&reply('unamemaprules:'.&escape($udom),
2715: $homeserver);
1.923 raeburn 2716: } else {
2717: $response=&reply('instuserrules:'.&escape($udom),
2718: $homeserver);
2719: }
1.912 raeburn 2720: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 2721: ($response ne 'unknown_cmd') &&
1.912 raeburn 2722: ($response ne 'no_such_host')) {
2723: my ($hashitems,$orderitems) = split(/:/,$response);
2724: my @pairs=split(/\&/,$hashitems);
2725: foreach my $item (@pairs) {
2726: my ($key,$value)=split(/=/,$item,2);
2727: $key = &unescape($key);
2728: next if ($key =~ /^error: 2 /);
2729: $ruleshash{$key}=&thaw_unescape($value);
2730: }
2731: my @esc_order = split(/\&/,$orderitems);
2732: foreach my $item (@esc_order) {
2733: push(@ruleorder,&unescape($item));
2734: }
2735: }
2736: }
2737: }
2738: return (\%ruleshash,\@ruleorder);
2739: }
2740:
1.976 raeburn 2741: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 2742:
2743: sub get_domain_defaults {
1.1240 raeburn 2744: my ($domain,$ignore_cache) = @_;
1.1242 raeburn 2745: return if (($domain eq '') || ($domain eq 'public'));
1.943 raeburn 2746: my $cachetime = 60*60*24;
1.1240 raeburn 2747: unless ($ignore_cache) {
2748: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
2749: if (defined($cached)) {
2750: if (ref($result) eq 'HASH') {
2751: return %{$result};
2752: }
1.943 raeburn 2753: }
2754: }
2755: my %domdefaults;
2756: my %domconfig =
1.1494 raeburn 2757: &get_dom('configuration',['defaults','quotas',
1.1047 raeburn 2758: 'requestcourses','inststatus',
1.1183 raeburn 2759: 'coursedefaults','usersessions',
1.1517 raeburn 2760: 'requestauthor','authordefaults',
2761: 'selfenrollment','coursecategories',
2762: 'ssl','autoenroll','trust',
2763: 'helpsettings','wafproxy',
1.1520 raeburn 2764: 'ltisec','toolsec','privacy'],$domain);
1.1305 raeburn 2765: my @coursetypes = ('official','unofficial','community','textbook','placement');
1.943 raeburn 2766: if (ref($domconfig{'defaults'}) eq 'HASH') {
2767: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
2768: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
2769: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 2770: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 2771: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147 raeburn 2772: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.1492 raeburn 2773: $domdefaults{'portal_def_email'} = $domconfig{'defaults'}{'portal_def_email'};
2774: $domdefaults{'portal_def_web'} = $domconfig{'defaults'}{'portal_def_web'};
1.1340 raeburn 2775: $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
2776: $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
2777: $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
1.1484 raeburn 2778: $domdefaults{'unamemap_rule'} = $domconfig{'defaults'}{'unamemap_rule'};
1.943 raeburn 2779: } else {
2780: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
2781: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
2782: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
2783: }
1.976 raeburn 2784: if (ref($domconfig{'quotas'}) eq 'HASH') {
2785: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
2786: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
2787: } else {
2788: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1229 raeburn 2789: }
1.1521 raeburn 2790: my @usertools = ('aboutme','blog','webdav','portfolio','portaccess');
1.976 raeburn 2791: foreach my $item (@usertools) {
2792: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
2793: $domdefaults{$item} = $domconfig{'quotas'}{$item};
2794: }
2795: }
1.1229 raeburn 2796: if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
2797: $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
2798: }
1.976 raeburn 2799: }
1.985 raeburn 2800: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1305 raeburn 2801: foreach my $item ('official','unofficial','community','textbook','placement') {
1.985 raeburn 2802: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
2803: }
2804: }
1.1183 raeburn 2805: if (ref($domconfig{'requestauthor'}) eq 'HASH') {
2806: $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
2807: }
1.1517 raeburn 2808: if (ref($domconfig{'authordefaults'}) eq 'HASH') {
1.1527 raeburn 2809: foreach my $item ('nocodemirror','copyright','sourceavail','domcoordacc','editors','archive') {
1.1517 raeburn 2810: if ($item eq 'editors') {
2811: if (ref($domconfig{'authordefaults'}{'editors'}) eq 'ARRAY') {
2812: $domdefaults{$item} = join(',',@{$domconfig{'authordefaults'}{'editors'}});
2813: }
2814: } else {
2815: $domdefaults{$item} = $domconfig{'authordefaults'}{$item};
2816: }
2817: }
2818: }
1.989 raeburn 2819: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1256 raeburn 2820: foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989 raeburn 2821: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
2822: }
2823: }
1.1047 raeburn 2824: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1230 raeburn 2825: $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
1.1277 raeburn 2826: $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
1.1476 raeburn 2827: $domdefaults{'inline_chem'} = $domconfig{'coursedefaults'}{'inline_chem'};
1.1277 raeburn 2828: $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
2829: if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
2830: $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
2831: }
1.1529 raeburn 2832: if (ref($domconfig{'coursedefaults'}{'crseditors'}) eq 'ARRAY') {
2833: $domdefaults{'crseditors'}=join(',',@{$domconfig{'coursedefaults'}{'crseditors'}});
2834: }
1.1254 raeburn 2835: foreach my $type (@coursetypes) {
2836: if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
2837: unless ($type eq 'community') {
2838: $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
2839: }
2840: }
2841: if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
2842: $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
2843: }
1.1514 raeburn 2844: if (ref($domconfig{'coursedefaults'}{'coursequota'}) eq 'HASH') {
2845: $domdefaults{$type.'coursequota'} = $domconfig{'coursedefaults'}{'coursequota'}{$type};
2846: }
1.1277 raeburn 2847: if ($domdefaults{'postsubmit'} eq 'on') {
2848: if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
2849: $domdefaults{$type.'postsubtimeout'} =
2850: $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
2851: }
2852: }
1.1508 raeburn 2853: if (ref($domconfig{'coursedefaults'}{'domexttool'}) eq 'HASH') {
2854: $domdefaults{$type.'domexttool'} = $domconfig{'coursedefaults'}{'domexttool'}{$type};
2855: } else {
2856: $domdefaults{$type.'domexttool'} = 1;
2857: }
2858: if (ref($domconfig{'coursedefaults'}{'exttool'}) eq 'HASH') {
2859: $domdefaults{$type.'exttool'} = $domconfig{'coursedefaults'}{'exttool'}{$type};
2860: } else {
2861: $domdefaults{$type.'exttool'} = 0;
2862: }
1.1520 raeburn 2863: if (ref($domconfig{'coursedefaults'}{'crsauthor'}) eq 'HASH') {
2864: $domdefaults{$type.'crsauthor'} = $domconfig{'coursedefaults'}{'crsauthor'}{$type};
2865: } else {
2866: $domdefaults{$type.'crsauthor'} = 1;
2867: }
1.1230 raeburn 2868: }
1.1286 raeburn 2869: if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
2870: if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
2871: my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
2872: if (@clonecodes) {
2873: $domdefaults{'canclone'} = join('+',@clonecodes);
2874: }
2875: }
2876: } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
2877: $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
2878: }
1.1356 raeburn 2879: if ($domconfig{'coursedefaults'}{'texengine'}) {
2880: $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
1.1480 raeburn 2881: }
2882: if (exists($domconfig{'coursedefaults'}{'ltiauth'})) {
2883: $domdefaults{'crsltiauth'} = $domconfig{'coursedefaults'}{'ltiauth'};
2884: }
1.1047 raeburn 2885: }
1.1073 raeburn 2886: if (ref($domconfig{'usersessions'}) eq 'HASH') {
2887: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
2888: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
2889: }
2890: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
2891: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
2892: }
1.1279 raeburn 2893: if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
2894: $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
2895: }
1.1440 raeburn 2896: if (ref($domconfig{'usersessions'}{'offloadoth'}) eq 'HASH') {
1.1439 raeburn 2897: $domdefaults{'offloadoth'} = $domconfig{'usersessions'}{'offloadoth'};
2898: }
1.1073 raeburn 2899: }
1.1254 raeburn 2900: if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
2901: if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
2902: my @settings = ('types','registered','enroll_dates','access_dates','section',
2903: 'approval','limit');
2904: foreach my $type (@coursetypes) {
2905: if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
2906: my @mgrdc = ();
2907: foreach my $item (@settings) {
2908: if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
2909: push(@mgrdc,$item);
2910: }
2911: }
2912: if (@mgrdc) {
2913: $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
2914: }
2915: }
2916: }
2917: }
2918: if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
2919: foreach my $type (@coursetypes) {
2920: if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
2921: foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
2922: $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
2923: }
2924: }
2925: }
2926: }
2927: }
1.1258 raeburn 2928: if (ref($domconfig{'coursecategories'}) eq 'HASH') {
2929: $domdefaults{'catauth'} = 'std';
2930: $domdefaults{'catunauth'} = 'std';
1.1413 raeburn 2931: if ($domconfig{'coursecategories'}{'auth'}) {
1.1258 raeburn 2932: $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
2933: }
2934: if ($domconfig{'coursecategories'}{'unauth'}) {
2935: $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
2936: }
2937: }
1.1315 raeburn 2938: if (ref($domconfig{'ssl'}) eq 'HASH') {
2939: if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
2940: $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
2941: }
1.1338 raeburn 2942: if (ref($domconfig{'ssl'}{'connto'}) eq 'HASH') {
2943: $domdefaults{'connect'} = $domconfig{'ssl'}{'connto'};
2944: }
2945: if (ref($domconfig{'ssl'}{'connfrom'}) eq 'HASH') {
2946: $domdefaults{'connect'} = $domconfig{'ssl'}{'connfrom'};
1.1315 raeburn 2947: }
2948: }
1.1320 raeburn 2949: if (ref($domconfig{'trust'}) eq 'HASH') {
2950: my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
2951: foreach my $prefix (@prefixes) {
2952: if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
2953: $domdefaults{'trust'.$prefix} = $domconfig{'trust'}{$prefix};
2954: }
2955: }
2956: }
1.1314 raeburn 2957: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
2958: $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
1.1477 raeburn 2959: $domdefaults{'failsafe'} = $domconfig{'autoenroll'}{'failsafe'};
1.1314 raeburn 2960: }
1.1332 raeburn 2961: if (ref($domconfig{'helpsettings'}) eq 'HASH') {
2962: $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
2963: if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
2964: $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
2965: }
2966: }
1.1434 raeburn 2967: if (ref($domconfig{'wafproxy'}) eq 'HASH') {
1.1449 raeburn 2968: foreach my $item ('ipheader','trusted','vpnint','vpnext','sslopt') {
1.1434 raeburn 2969: if ($domconfig{'wafproxy'}{$item}) {
2970: $domdefaults{'waf_'.$item} = $domconfig{'wafproxy'}{$item};
2971: }
2972: }
1.1482 raeburn 2973: }
2974: if (ref($domconfig{'ltisec'}) eq 'HASH') {
2975: if (ref($domconfig{'ltisec'}{'encrypt'}) eq 'HASH') {
2976: $domdefaults{'linkprotenc_crs'} = $domconfig{'ltisec'}{'encrypt'}{'crs'};
2977: $domdefaults{'linkprotenc_dom'} = $domconfig{'ltisec'}{'encrypt'}{'dom'};
2978: $domdefaults{'ltienc_consumers'} = $domconfig{'ltisec'}{'encrypt'}{'consumers'};
2979: }
2980: if (ref($domconfig{'ltisec'}{'private'}) eq 'HASH') {
2981: if (ref($domconfig{'ltisec'}{'private'}{'keys'}) eq 'ARRAY') {
1.1504 raeburn 2982: $domdefaults{'ltiprivhosts'} = $domconfig{'ltisec'}{'private'}{'keys'};
2983: }
2984: }
1.1523 raeburn 2985: if (ref($domconfig{'ltisec'}{'suggested'}) eq 'HASH') {
2986: my %suggestions = %{$domconfig{'ltisec'}{'suggested'}};
2987: foreach my $item (keys(%{$domconfig{'ltisec'}{'suggested'}})) {
2988: unless (ref($domconfig{'ltisec'}{'suggested'}{$item}) eq 'HASH') {
2989: delete($suggestions{$item});
2990: }
2991: }
2992: if (keys(%suggestions)) {
2993: $domdefaults{'linkprotsuggested'} = \%suggestions;
2994: }
2995: }
1.1504 raeburn 2996: }
2997: if (ref($domconfig{'toolsec'}) eq 'HASH') {
2998: if (ref($domconfig{'toolsec'}{'encrypt'}) eq 'HASH') {
2999: $domdefaults{'toolenc_crs'} = $domconfig{'toolsec'}{'encrypt'}{'crs'};
3000: $domdefaults{'toolenc_dom'} = $domconfig{'toolsec'}{'encrypt'}{'dom'};
3001: }
3002: if (ref($domconfig{'toolsec'}{'private'}) eq 'HASH') {
3003: if (ref($domconfig{'toolsec'}{'private'}{'keys'}) eq 'ARRAY') {
3004: $domdefaults{'toolprivhosts'} = $domconfig{'toolsec'}{'private'}{'keys'};
1.1482 raeburn 3005: }
3006: }
3007: }
1.1512 raeburn 3008: if (ref($domconfig{'privacy'}) eq 'HASH') {
3009: if (ref($domconfig{'privacy'}{'approval'}) eq 'HASH') {
3010: foreach my $domtype ('instdom','extdom') {
3011: if (ref($domconfig{'privacy'}{'approval'}{$domtype}) eq 'HASH') {
3012: foreach my $roletype ('domain','author','course','community') {
3013: if ($domconfig{'privacy'}{'approval'}{$domtype}{$roletype} eq 'user') {
3014: $domdefaults{'userapprovals'} = 1;
3015: last;
3016: }
3017: }
3018: }
3019: last if ($domdefaults{'userapprovals'});
3020: }
3021: }
3022: }
1.1219 raeburn 3023: &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943 raeburn 3024: return %domdefaults;
3025: }
3026:
1.1412 raeburn 3027: sub get_dom_cats {
3028: my ($dom) = @_;
3029: return unless (&domain($dom));
3030: my ($cats,$cached)=&is_cached_new('cats',$dom);
3031: unless (defined($cached)) {
3032: my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
3033: if (ref($domconfig{'coursecategories'}) eq 'HASH') {
3034: if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
3035: %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
3036: } else {
3037: $cats = {};
3038: }
3039: } else {
3040: $cats = {};
3041: }
1.1494 raeburn 3042: &do_cache_new('cats',$dom,$cats,3600);
1.1412 raeburn 3043: }
1.1413 raeburn 3044: return $cats;
3045: }
3046:
3047: sub get_dom_instcats {
3048: my ($dom) = @_;
3049: return unless (&domain($dom));
3050: my ($instcats,$cached)=&is_cached_new('instcats',$dom);
3051: unless (defined($cached)) {
3052: my (%coursecodes,%codes,@codetitles,%cat_titles,%cat_order);
3053: my $totcodes = &retrieve_instcodes(\%coursecodes,$dom);
3054: if ($totcodes > 0) {
3055: my $caller = 'global';
3056: if (&auto_instcode_format($caller,$dom,\%coursecodes,\%codes,
3057: \@codetitles,\%cat_titles,\%cat_order) eq 'ok') {
3058: $instcats = {
1.1503 raeburn 3059: totcodes => $totcodes,
1.1413 raeburn 3060: codes => \%codes,
3061: codetitles => \@codetitles,
3062: cat_titles => \%cat_titles,
3063: cat_order => \%cat_order,
3064: };
3065: &do_cache_new('instcats',$dom,$instcats,3600);
3066: }
3067: }
3068: }
3069: return $instcats;
3070: }
3071:
3072: sub retrieve_instcodes {
3073: my ($coursecodes,$dom) = @_;
3074: my $totcodes;
3075: my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
3076: foreach my $course (keys(%courses)) {
3077: if (ref($courses{$course}) eq 'HASH') {
3078: if ($courses{$course}{'inst_code'} ne '') {
3079: $$coursecodes{$course} = $courses{$course}{'inst_code'};
3080: $totcodes ++;
3081: }
3082: }
3083: }
3084: return $totcodes;
1.1412 raeburn 3085: }
3086:
1.1311 raeburn 3087: sub course_portal_url {
1.1451 raeburn 3088: my ($cnum,$cdom,$r) = @_;
1.1311 raeburn 3089: my $chome = &homeserver($cnum,$cdom);
3090: my $hostname = &hostname($chome);
3091: my $protocol = $protocol{$chome};
3092: $protocol = 'http' if ($protocol ne 'https');
3093: my %domdefaults = &get_domain_defaults($cdom);
3094: my $firsturl;
3095: if ($domdefaults{'portal_def'}) {
3096: $firsturl = $domdefaults{'portal_def'};
3097: } else {
1.1494 raeburn 3098: my $alias = &use_proxy_alias($r,$chome);
1.1451 raeburn 3099: $hostname = $alias if ($alias ne '');
1.1311 raeburn 3100: $firsturl = $protocol.'://'.$hostname;
3101: }
3102: return $firsturl;
3103: }
3104:
1.1492 raeburn 3105: sub url_prefix {
3106: my ($r,$dom,$home,$context) = @_;
3107: my $prefix;
3108: my %domdefs = &get_domain_defaults($dom);
3109: if ($domdefs{'portal_def'} && $domdefs{'portal_def_'.$context}) {
3110: if ($domdefs{'portal_def'} =~ m{^(https?://[^/]+)}) {
3111: $prefix = $1;
3112: }
3113: }
3114: if ($prefix eq '') {
3115: my $hostname = &hostname($home);
3116: my $protocol = $protocol{$home};
3117: $protocol = 'http' if ($protocol{$home} ne 'https');
3118: my $alias = &use_proxy_alias($r,$home);
3119: $hostname = $alias if ($alias ne '');
3120: $prefix = $protocol.'://'.$hostname;
3121: }
3122: return $prefix;
3123: }
3124:
1.1407 raeburn 3125: # --------------------------------------------- Get domain config for passwords
3126:
3127: sub get_passwdconf {
3128: my ($dom) = @_;
3129: my (%passwdconf,$gotconf,$lookup);
3130: my ($result,$cached)=&is_cached_new('passwdconf',$dom);
3131: if (defined($cached)) {
3132: if (ref($result) eq 'HASH') {
3133: %passwdconf = %{$result};
3134: $gotconf = 1;
3135: }
3136: }
3137: unless ($gotconf) {
3138: my %domconfig = &get_dom('configuration',['passwords'],$dom);
3139: if (ref($domconfig{'passwords'}) eq 'HASH') {
3140: %passwdconf = %{$domconfig{'passwords'}};
3141: }
3142: my $cachetime = 24*60*60;
3143: &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
3144: }
3145: return %passwdconf;
3146: }
3147:
1.344 www 3148: # --------------------------------------------------- Assign a key to a student
3149:
3150: sub assign_access_key {
1.364 www 3151: #
3152: # a valid key looks like uname:udom#comments
3153: # comments are being appended
3154: #
1.498 www 3155: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
3156: $kdom=
1.620 albertel 3157: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 3158: $knum=
1.620 albertel 3159: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 3160: $cdom=
1.620 albertel 3161: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 3162: $cnum=
1.620 albertel 3163: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
3164: $udom=$env{'user.name'} unless (defined($udom));
3165: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 3166: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 3167: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 3168: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 3169: # assigned to this person
3170: # - this should not happen,
1.345 www 3171: # unless something went wrong
3172: # the first time around
3173: # ready to assign
1.364 www 3174: $logentry=$1.'; '.$logentry;
1.496 www 3175: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 3176: $kdom,$knum) eq 'ok') {
1.345 www 3177: # key now belongs to user
1.346 www 3178: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 3179: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 3180: &appenv({'environment.'.$envkey => $ckey});
1.345 www 3181: return 'ok';
3182: } else {
3183: return
3184: 'error: Count not permanently assign key, will need to be re-entered later.';
3185: }
3186: } else {
3187: return 'error: Could not assign key, try again later.';
3188: }
1.364 www 3189: } elsif (!$existing{$ckey}) {
1.345 www 3190: # the key does not exist
3191: return 'error: The key does not exist';
3192: } else {
3193: # the key is somebody else's
3194: return 'error: The key is already in use';
3195: }
1.344 www 3196: }
3197:
1.364 www 3198: # ------------------------------------------ put an additional comment on a key
3199:
3200: sub comment_access_key {
3201: #
3202: # a valid key looks like uname:udom#comments
3203: # comments are being appended
3204: #
3205: my ($ckey,$cdom,$cnum,$logentry)=@_;
3206: $cdom=
1.620 albertel 3207: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 3208: $cnum=
1.620 albertel 3209: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 3210: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
3211: if ($existing{$ckey}) {
3212: $existing{$ckey}.='; '.$logentry;
3213: # ready to assign
1.367 www 3214: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 3215: $cdom,$cnum) eq 'ok') {
3216: return 'ok';
3217: } else {
3218: return 'error: Count not store comment.';
3219: }
3220: } else {
3221: # the key does not exist
3222: return 'error: The key does not exist';
3223: }
3224: }
3225:
1.344 www 3226: # ------------------------------------------------------ Generate a set of keys
3227:
3228: sub generate_access_keys {
1.364 www 3229: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 3230: $cdom=
1.620 albertel 3231: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 3232: $cnum=
1.620 albertel 3233: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 3234: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 3235: unless (($cdom) && ($cnum)) { return 0; }
3236: if ($number>10000) { return 0; }
3237: sleep(2); # make sure don't get same seed twice
3238: srand(time()^($$+($$<<15))); # from "Programming Perl"
3239: my $total=0;
3240: for (my $i=1;$i<=$number;$i++) {
3241: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
3242: sprintf("%lx",int(100000*rand)).'-'.
3243: sprintf("%lx",int(100000*rand));
3244: $newkey=~s/1/g/g; # folks mix up 1 and l
3245: $newkey=~s/0/h/g; # and also 0 and O
3246: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
3247: if ($existing{$newkey}) {
3248: $i--;
3249: } else {
1.364 www 3250: if (&put('accesskeys',
3251: { $newkey => '# generated '.localtime().
1.620 albertel 3252: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 3253: '; '.$logentry },
3254: $cdom,$cnum) eq 'ok') {
1.344 www 3255: $total++;
3256: }
3257: }
3258: }
1.620 albertel 3259: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 3260: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
3261: return $total;
3262: }
3263:
3264: # ------------------------------------------------------- Validate an accesskey
3265:
3266: sub validate_access_key {
3267: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
3268: $cdom=
1.620 albertel 3269: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 3270: $cnum=
1.620 albertel 3271: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
3272: $udom=$env{'user.domain'} unless (defined($udom));
3273: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 3274: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 3275: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 3276: }
3277:
3278: # ------------------------------------- Find the section of student in a course
1.652 albertel 3279: sub devalidate_getsection_cache {
3280: my ($udom,$unam,$courseid)=@_;
3281: my $hashid="$udom:$unam:$courseid";
3282: &devalidate_cache_new('getsection',$hashid);
3283: }
1.298 matthew 3284:
1.815 albertel 3285: sub courseid_to_courseurl {
3286: my ($courseid) = @_;
3287: #already url style courseid
3288: return $courseid if ($courseid =~ m{^/});
3289:
3290: if (exists($env{'course.'.$courseid.'.num'})) {
3291: my $cnum = $env{'course.'.$courseid.'.num'};
3292: my $cdom = $env{'course.'.$courseid.'.domain'};
3293: return "/$cdom/$cnum";
3294: }
3295:
1.1494 raeburn 3296: my %courseinfo=&coursedescription($courseid);
1.815 albertel 3297: if (exists($courseinfo{'num'})) {
3298: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
3299: }
3300:
3301: return undef;
3302: }
3303:
1.298 matthew 3304: sub getsection {
3305: my ($udom,$unam,$courseid)=@_;
1.599 albertel 3306: my $cachetime=1800;
1.551 albertel 3307:
3308: my $hashid="$udom:$unam:$courseid";
1.599 albertel 3309: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 3310: if (defined($cached)) { return $result; }
3311:
1.298 matthew 3312: my %Pending;
3313: my %Expired;
3314: #
3315: # Each role can either have not started yet (pending), be active,
3316: # or have expired.
3317: #
3318: # If there is an active role, we are done.
3319: #
3320: # If there is more than one role which has not started yet,
3321: # choose the one which will start sooner
3322: # If there is one role which has not started yet, return it.
3323: #
3324: # If there is more than one expired role, choose the one which ended last.
3325: # If there is a role which has expired, return it.
3326: #
1.815 albertel 3327: $courseid = &courseid_to_courseurl($courseid);
1.1166 raeburn 3328: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817 raeburn 3329: foreach my $key (keys(%roleshash)) {
1.479 albertel 3330: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 3331: my $section=$1;
3332: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 3333: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 3334: my $now=time;
1.548 albertel 3335: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 3336: $Expired{$end}=$section;
3337: next;
3338: }
1.548 albertel 3339: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 3340: $Pending{$start}=$section;
3341: next;
3342: }
1.599 albertel 3343: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 3344: }
3345: #
3346: # Presumedly there will be few matching roles from the above
3347: # loop and the sorting time will be negligible.
3348: if (scalar(keys(%Pending))) {
3349: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 3350: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 3351: }
3352: if (scalar(keys(%Expired))) {
3353: my @sorted = sort {$a <=> $b} keys(%Expired);
3354: my $time = pop(@sorted);
1.599 albertel 3355: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 3356: }
1.599 albertel 3357: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 3358: }
1.70 www 3359:
1.599 albertel 3360: sub save_cache {
3361: &purge_remembered();
1.722 albertel 3362: #&Apache::loncommon::validate_page();
1.620 albertel 3363: undef(%env);
1.780 albertel 3364: undef($env_loaded);
1.599 albertel 3365: }
1.452 albertel 3366:
1.599 albertel 3367: my $to_remember=-1;
3368: my %remembered;
3369: my %accessed;
3370: my $kicks=0;
3371: my $hits=0;
1.849 albertel 3372: sub make_key {
3373: my ($name,$id) = @_;
1.872 albertel 3374: if (length($id) > 65
3375: && length(&escape($id)) > 200) {
3376: $id=length($id).':'.&Digest::MD5::md5_hex($id);
3377: }
1.849 albertel 3378: return &escape($name.':'.$id);
3379: }
3380:
1.599 albertel 3381: sub devalidate_cache_new {
3382: my ($name,$id,$debug) = @_;
3383: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1319 damieng 3384: my $remembered_id=$name.':'.$id;
1.849 albertel 3385: $id=&make_key($name,$id);
1.599 albertel 3386: $memcache->delete($id);
1.1319 damieng 3387: delete($remembered{$remembered_id});
3388: delete($accessed{$remembered_id});
1.599 albertel 3389: }
3390:
3391: sub is_cached_new {
3392: my ($name,$id,$debug) = @_;
1.1319 damieng 3393: my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
3394: if (exists($remembered{$remembered_id})) {
3395: if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
3396: $accessed{$remembered_id}=[&gettimeofday()];
1.599 albertel 3397: $hits++;
1.1319 damieng 3398: return ($remembered{$remembered_id},1);
1.599 albertel 3399: }
1.1319 damieng 3400: $id=&make_key($name,$id);
1.599 albertel 3401: my $value = $memcache->get($id);
3402: if (!(defined($value))) {
3403: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 3404: return (undef,undef);
1.416 albertel 3405: }
1.599 albertel 3406: if ($value eq '__undef__') {
3407: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
3408: $value=undef;
3409: }
1.1319 damieng 3410: &make_room($remembered_id,$value,$debug);
1.599 albertel 3411: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
3412: return ($value,1);
3413: }
3414:
3415: sub do_cache_new {
3416: my ($name,$id,$value,$time,$debug) = @_;
1.1319 damieng 3417: my $remembered_id=$name.':'.$id;
1.849 albertel 3418: $id=&make_key($name,$id);
1.599 albertel 3419: my $setvalue=$value;
3420: if (!defined($setvalue)) {
3421: $setvalue='__undef__';
3422: }
1.623 albertel 3423: if (!defined($time) ) {
3424: $time=600;
3425: }
1.599 albertel 3426: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 3427: my $result = $memcache->set($id,$setvalue,$time);
3428: if (! $result) {
1.872 albertel 3429: &logthis("caching of id -> $id failed");
1.910 albertel 3430: $memcache->disconnect_all();
1.872 albertel 3431: }
1.600 albertel 3432: # need to make a copy of $value
1.1319 damieng 3433: &make_room($remembered_id,$value,$debug);
1.599 albertel 3434: return $value;
3435: }
3436:
3437: sub make_room {
1.1319 damieng 3438: my ($remembered_id,$value,$debug)=@_;
1.919 albertel 3439:
1.1319 damieng 3440: $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919 albertel 3441: : $value;
1.599 albertel 3442: if ($to_remember<0) { return; }
1.1319 damieng 3443: $accessed{$remembered_id}=[&gettimeofday()];
1.599 albertel 3444: if (scalar(keys(%remembered)) <= $to_remember) { return; }
3445: my $to_kick;
3446: my $max_time=0;
3447: foreach my $other (keys(%accessed)) {
3448: if (&tv_interval($accessed{$other}) > $max_time) {
3449: $to_kick=$other;
3450: $max_time=&tv_interval($accessed{$other});
3451: }
3452: }
3453: delete($remembered{$to_kick});
3454: delete($accessed{$to_kick});
3455: $kicks++;
3456: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 3457: return;
3458: }
3459:
1.599 albertel 3460: sub purge_remembered {
1.604 albertel 3461: #&logthis("Tossing ".scalar(keys(%remembered)));
3462: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 3463: undef(%remembered);
3464: undef(%accessed);
1.428 albertel 3465: }
1.70 www 3466: # ------------------------------------- Read an entry from a user's environment
3467:
3468: sub userenvironment {
3469: my ($udom,$unam,@what)=@_;
1.976 raeburn 3470: my $items;
3471: foreach my $item (@what) {
3472: $items.=&escape($item).'&';
3473: }
3474: $items=~s/\&$//;
1.70 www 3475: my %returnhash=();
1.1009 raeburn 3476: my $uhome = &homeserver($unam,$udom);
3477: unless ($uhome eq 'no_host') {
3478: my @answer=split(/\&/,
3479: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 3480: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
3481: return %returnhash;
3482: }
1.1009 raeburn 3483: my $i;
3484: for ($i=0;$i<=$#what;$i++) {
3485: $returnhash{$what[$i]}=&unescape($answer[$i]);
3486: }
1.70 www 3487: }
3488: return %returnhash;
1.1 albertel 3489: }
3490:
1.617 albertel 3491: # ---------------------------------------------------------- Get a studentphoto
3492: sub studentphoto {
3493: my ($udom,$unam,$ext) = @_;
1.1494 raeburn 3494: my $home=&homeserver($unam,$udom);
1.706 raeburn 3495: if (defined($env{'request.course.id'})) {
1.708 raeburn 3496: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 3497: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
3498: return(&retrievestudentphoto($udom,$unam,$ext));
3499: } else {
3500: my ($result,$perm_reqd)=
1.1494 raeburn 3501: &auto_photo_permission($unam,$udom);
1.706 raeburn 3502: if ($result eq 'ok') {
3503: if (!($perm_reqd eq 'yes')) {
3504: return(&retrievestudentphoto($udom,$unam,$ext));
3505: }
3506: }
3507: }
3508: }
3509: } else {
3510: my ($result,$perm_reqd) =
1.1494 raeburn 3511: &auto_photo_permission($unam,$udom);
1.706 raeburn 3512: if ($result eq 'ok') {
3513: if (!($perm_reqd eq 'yes')) {
3514: return(&retrievestudentphoto($udom,$unam,$ext));
3515: }
3516: }
3517: }
3518: return '/adm/lonKaputt/lonlogo_broken.gif';
3519: }
3520:
3521: sub retrievestudentphoto {
3522: my ($udom,$unam,$ext,$type) = @_;
1.1494 raeburn 3523: my $home=&homeserver($unam,$udom);
3524: my $ret=&reply("studentphoto:$udom:$unam:$ext:$type",$home);
1.706 raeburn 3525: if ($ret eq 'ok') {
3526: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
3527: if ($type eq 'thumbnail') {
3528: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
3529: }
1.1494 raeburn 3530: my $tokenurl=&tokenwrapper($url);
1.706 raeburn 3531: return $tokenurl;
3532: } else {
3533: if ($type eq 'thumbnail') {
3534: return '/adm/lonKaputt/genericstudent_tn.gif';
3535: } else {
3536: return '/adm/lonKaputt/lonlogo_broken.gif';
3537: }
1.617 albertel 3538: }
3539: }
3540:
1.263 www 3541: # -------------------------------------------------------------------- New chat
3542:
3543: sub chatsend {
1.724 raeburn 3544: my ($newentry,$anon,$group)=@_;
1.620 albertel 3545: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
3546: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3547: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 3548: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 3549: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 3550: &escape($newentry)).':'.$group,$chome);
1.292 www 3551: }
3552:
3553: # ------------------------------------------ Find current version of a resource
3554:
3555: sub getversion {
3556: my $fname=&clutter(shift);
1.1189 raeburn 3557: unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292 www 3558: return ¤tversion(&filelocation('',$fname));
3559: }
3560:
3561: sub currentversion {
3562: my $fname=shift;
3563: my $author=$fname;
3564: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3565: my ($udom,$uname)=split(/\//,$author);
1.1112 www 3566: my $home=&homeserver($uname,$udom);
1.292 www 3567: if ($home eq 'no_host') {
3568: return -1;
3569: }
1.1112 www 3570: my $answer=&reply("currentversion:$fname",$home);
1.292 www 3571: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
3572: return -1;
3573: }
1.1112 www 3574: return $answer;
1.263 www 3575: }
3576:
1.1111 www 3577: #
3578: # Return special version number of resource if set by override, empty otherwise
3579: #
3580: sub usedversion {
3581: my $fname=shift;
3582: unless ($fname) { $fname=$env{'request.uri'}; }
3583: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
3584: if ($urlversion) { return $urlversion; }
3585: return '';
3586: }
3587:
1.1 albertel 3588: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 3589:
1.1 albertel 3590: sub subscribe {
3591: my $fname=shift;
1.761 raeburn 3592: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 3593: $fname=~s/[\n\r]//g;
1.1 albertel 3594: my $author=$fname;
3595: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3596: my ($udom,$uname)=split(/\//,$author);
3597: my $home=homeserver($uname,$udom);
1.335 albertel 3598: if ($home eq 'no_host') {
3599: return 'not_found';
1.1 albertel 3600: }
3601: my $answer=reply("sub:$fname",$home);
1.64 www 3602: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
3603: $answer.=' by '.$home;
3604: }
1.1 albertel 3605: return $answer;
3606: }
3607:
1.8 www 3608: # -------------------------------------------------------------- Replicate file
3609:
3610: sub repcopy {
3611: my $filename=shift;
1.23 www 3612: $filename=~s/\/+/\//g;
1.1142 raeburn 3613: my $londocroot = $perlvar{'lonDocRoot'};
3614: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164 raeburn 3615: if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142 raeburn 3616: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
3617: $filename=~m{^/*(uploaded|editupload)/}) {
1.538 albertel 3618: return &repcopy_userfile($filename);
3619: }
1.532 albertel 3620: $filename=~s/[\n\r]//g;
1.8 www 3621: my $transname="$filename.in.transfer";
1.828 www 3622: # FIXME: this should flock
1.607 raeburn 3623: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 3624: my $remoteurl=subscribe($filename);
1.64 www 3625: if ($remoteurl =~ /^con_lost by/) {
3626: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 3627: return 'unavailable';
1.8 www 3628: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 3629: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 3630: return 'not_found';
1.64 www 3631: } elsif ($remoteurl =~ /^rejected by/) {
3632: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 3633: return 'forbidden';
1.20 www 3634: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 3635: return 'ok';
1.8 www 3636: } else {
1.290 www 3637: my $author=$filename;
3638: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3639: my ($udom,$uname)=split(/\//,$author);
3640: my $home=homeserver($uname,$udom);
3641: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 3642: my @parts=split(/\//,$filename);
3643: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142 raeburn 3644: if ($path ne "$londocroot/res") {
1.8 www 3645: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 3646: return 'bad_request';
1.8 www 3647: }
3648: my $count;
3649: for ($count=5;$count<$#parts;$count++) {
3650: $path.="/$parts[$count]";
3651: if ((-e $path)!=1) {
3652: mkdir($path,0777);
3653: }
3654: }
3655: my $request=new HTTP::Request('GET',"$remoteurl");
1.1345 raeburn 3656: my $response;
3657: if ($remoteurl =~ m{/raw/}) {
3658: $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',0,1);
3659: } else {
3660: $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',1);
3661: }
1.8 www 3662: if ($response->is_error()) {
3663: unlink($transname);
3664: my $message=$response->status_line;
1.672 albertel 3665: &logthis("<font color=\"blue\">WARNING:"
1.12 www 3666: ." LWP get: $message: $filename</font>");
1.607 raeburn 3667: return 'unavailable';
1.8 www 3668: } else {
1.16 www 3669: if ($remoteurl!~/\.meta$/) {
3670: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
1.1345 raeburn 3671: my $mresponse;
3672: if ($remoteurl =~ m{/raw/}) {
3673: $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',0,1);
3674: } else {
3675: $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',1);
3676: }
1.16 www 3677: if ($mresponse->is_error()) {
3678: unlink($filename.'.meta');
3679: &logthis(
1.672 albertel 3680: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 3681: }
3682: }
1.8 www 3683: rename($transname,$filename);
1.607 raeburn 3684: return 'ok';
1.8 www 3685: }
1.290 www 3686: }
1.8 www 3687: }
1.330 www 3688: }
3689:
1.1422 raeburn 3690: # ------------------------------------------------- Unsubscribe from a resource
3691:
3692: sub unsubscribe {
3693: my ($fname) = @_;
3694: my $answer;
3695: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return $answer; }
3696: $fname=~s/[\n\r]//g;
3697: my $author=$fname;
3698: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3699: my ($udom,$uname)=split(/\//,$author);
3700: my $home=homeserver($uname,$udom);
3701: if ($home eq 'no_host') {
3702: $answer = 'no_host';
3703: } elsif (grep { $_ eq $home } ¤t_machine_ids()) {
3704: $answer = 'home';
3705: } else {
3706: my $defdom = $perlvar{'lonDefDomain'};
3707: if (&will_trust('content',$defdom,$udom)) {
3708: $answer = reply("unsub:$fname",$home);
3709: } else {
3710: $answer = 'untrusted';
3711: }
3712: }
3713: return $answer;
3714: }
3715:
1.330 www 3716: # ------------------------------------------------ Get server side include body
3717: sub ssi_body {
1.381 albertel 3718: my ($filelink,%form)=@_;
1.606 matthew 3719: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
3720: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
3721: }
1.953 www 3722: my $output='';
3723: my $response;
1.980 raeburn 3724: if ($filelink=~/^https?\:/) {
1.954 raeburn 3725: ($output,$response)=&externalssi($filelink);
1.953 www 3726: } else {
1.1004 droeschl 3727: $filelink .= $filelink=~/\?/ ? '&' : '?';
3728: $filelink .= 'inhibitmenu=yes';
1.953 www 3729: ($output,$response)=&ssi($filelink,%form);
3730: }
1.778 albertel 3731: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 3732: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 3733: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 3734: if (wantarray) {
3735: return ($output, $response);
3736: } else {
3737: return $output;
3738: }
1.8 www 3739: }
3740:
1.15 www 3741: # --------------------------------------------------------- Server Side Include
3742:
1.782 albertel 3743: sub absolute_url {
1.1447 raeburn 3744: my ($host_name,$unalias,$keep_proto) = @_;
1.782 albertel 3745: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
3746: if ($host_name eq '') {
3747: $host_name = $ENV{'SERVER_NAME'};
3748: }
1.1447 raeburn 3749: if ($unalias) {
3750: my $alias = &get_proxy_alias();
3751: if ($alias eq $host_name) {
3752: my $lonhost = $perlvar{'lonHostID'};
3753: my $hostname = &hostname($lonhost);
3754: my $lcproto;
3755: if (($keep_proto) || ($hostname eq '')) {
3756: $lcproto = $protocol;
3757: } else {
3758: $lcproto = $protocol{$lonhost};
3759: $lcproto = 'http' if ($lcproto ne 'https');
3760: $lcproto .= '://';
3761: }
3762: unless ($hostname eq '') {
3763: return $lcproto.$hostname;
3764: }
3765: }
3766: }
1.782 albertel 3767: return $protocol.$host_name;
3768: }
3769:
1.942 foxr 3770: #
3771: # Server side include.
3772: # Parameters:
3773: # fn Possibly encrypted resource name/id.
3774: # form Hash that describes how the rendering should be done
3775: # and other things.
1.944 foxr 3776: # Returns:
1.950 raeburn 3777: # Scalar context: The content of the response.
3778: # Array context: 2 element list of the content and the full response object.
1.942 foxr 3779: #
1.15 www 3780: sub ssi {
3781:
1.944 foxr 3782: my ($fn,%form)=@_;
1.1447 raeburn 3783: my ($host,$request,$response);
3784: $host = &absolute_url('',1);
1.711 albertel 3785:
3786: $form{'no_update_last_known'}=1;
1.895 albertel 3787: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 3788: if (%form) {
1.1447 raeburn 3789: $request=new HTTP::Request('POST',$host.$fn);
1.1272 droeschl 3790: $request->content(join('&',map {
3791: my $name = escape($_);
3792: "$name=" . ( ref($form{$_}) eq 'ARRAY'
3793: ? join("&$name=", map {escape($_) } @{$form{$_}})
3794: : &escape($form{$_}) );
3795: } keys(%form)));
1.23 www 3796: } else {
1.1447 raeburn 3797: $request=new HTTP::Request('GET',$host.$fn);
1.23 www 3798: }
3799:
1.15 www 3800: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1345 raeburn 3801: my $lonhost = $perlvar{'lonHostID'};
1.1385 raeburn 3802: my $islocal;
3803: if (($env{'request.course.id'}) &&
3804: ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
3805: ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
3806: ($form{'grade_symb'} ne '') &&
1.1494 raeburn 3807: (&allowed('mgr',$env{'request.course.id'}.
3808: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
1.1385 raeburn 3809: $islocal = 1;
3810: }
1.1447 raeburn 3811: $response= &LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,
3812: '','','',$islocal);
1.1182 foxr 3813:
1.944 foxr 3814: if (wantarray) {
1.1345 raeburn 3815: return ($response->content, $response);
1.944 foxr 3816: } else {
1.1345 raeburn 3817: return $response->content;
1.942 foxr 3818: }
1.324 www 3819: }
3820:
3821: sub externalssi {
3822: my ($url)=@_;
3823: my $request=new HTTP::Request('GET',$url);
1.1345 raeburn 3824: my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar);
1.954 raeburn 3825: if (wantarray) {
3826: return ($response->content, $response);
3827: } else {
3828: return $response->content;
3829: }
1.15 www 3830: }
1.254 www 3831:
1.1354 raeburn 3832:
3833: # If the local copy of a replicated resource is outdated, trigger a
3834: # connection from the homeserver to flush the delayed queue. If no update
3835: # happens, remove local copies of outdated resource (and corresponding
3836: # metadata file).
3837:
1.1352 raeburn 3838: sub remove_stale_resfile {
3839: my ($url) = @_;
1.1354 raeburn 3840: my $removed;
1.1352 raeburn 3841: if ($url=~m{^/res/($match_domain)/($match_username)/}) {
3842: my $audom = $1;
3843: my $auname = $2;
1.1353 raeburn 3844: unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
1.1352 raeburn 3845: my $homeserver = &homeserver($auname,$audom);
3846: unless (($homeserver eq 'no_host') ||
3847: (grep { $_ eq $homeserver } ¤t_machine_ids())) {
3848: my $fname = &filelocation('',$url);
3849: if (-e $fname) {
3850: my $hostname = &hostname($homeserver);
3851: if ($hostname) {
1.1397 raeburn 3852: my $protocol = $protocol{$homeserver};
3853: $protocol = 'http' if ($protocol ne 'https');
1.1352 raeburn 3854: my $uri = &declutter($url);
3855: my $request=new HTTP::Request('HEAD',$protocol.'://'.$hostname.'/raw/'.$uri);
3856: my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,5,0,1);
3857: if ($response->is_success()) {
3858: my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
3859: my $locmodtime = (stat($fname))[9];
3860: if ($locmodtime < $remmodtime) {
1.1354 raeburn 3861: my $stale;
3862: my $answer = &reply('pong',$homeserver);
3863: if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
3864: sleep(0.2);
3865: $locmodtime = (stat($fname))[9];
3866: if ($locmodtime < $remmodtime) {
3867: my $posstransfer = $fname.'.in.transfer';
3868: if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
3869: $removed = 1;
3870: } else {
3871: $stale = 1;
3872: }
3873: } else {
3874: $removed = 1;
3875: }
3876: } else {
3877: $stale = 1;
3878: }
3879: if ($stale) {
1.1421 raeburn 3880: if (unlink($fname)) {
3881: if ($uri!~/\.meta$/) {
3882: if (-e $fname.'.meta') {
3883: unlink($fname.'.meta');
3884: }
3885: }
1.1422 raeburn 3886: my $unsubresult = &unsubscribe($fname);
3887: unless ($unsubresult eq 'ok') {
3888: &logthis("no unsub of $fname from $homeserver, reason: $unsubresult");
3889: }
1.1421 raeburn 3890: $removed = 1;
1.1354 raeburn 3891: }
1.1352 raeburn 3892: }
3893: }
3894: }
3895: }
3896: }
3897: }
3898: }
3899: }
1.1354 raeburn 3900: return $removed;
1.1352 raeburn 3901: }
3902:
1.492 albertel 3903: # -------------------------------- Allow a /uploaded/ URI to be vouched for
3904:
3905: sub allowuploaded {
3906: my ($srcurl,$url)=@_;
3907: $url=&clutter(&declutter($url));
3908: my $dir=$url;
3909: $dir=~s/\/[^\/]+$//;
3910: my %httpref=();
3911: my $httpurl=&hreflocation('',$url);
3912: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 3913: &Apache::lonnet::appenv(\%httpref);
1.254 www 3914: }
1.477 raeburn 3915:
1.1193 raeburn 3916: #
3917: # Determine if the current user should be able to edit a particular resource,
3918: # when viewing in course context.
3919: # (a) When viewing resource used to determine if "Edit" item is included in
3920: # Functions.
3921: # (b) When displaying folder contents in course editor, used to determine if
3922: # "Edit" link will be displayed alongside resource.
3923: #
1.1196 raeburn 3924: # input: six args -- filename (decluttered), course number, course domain,
3925: # url, symb (if registered) and group (if this is a group
3926: # item -- e.g., bulletin board, group page etc.).
3927: # output: array of five scalars --
1.1193 raeburn 3928: # $cfile -- url for file editing if editable on current server
3929: # $home -- homeserver of resource (i.e., for author if published,
3930: # or course if uploaded.).
3931: # $switchserver -- 1 if server switch will be needed.
1.1196 raeburn 3932: # $forceedit -- 1 if icon/link should be to go to edit mode
3933: # $forceview -- 1 if icon/link should be to go to view mode
1.1193 raeburn 3934: #
3935:
3936: sub can_edit_resource {
1.1194 raeburn 3937: my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
3938: my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
3939: #
3940: # For aboutme pages user can only edit his/her own.
3941: #
1.1199 raeburn 3942: if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
1.1194 raeburn 3943: my ($sdom,$sname) = ($1,$2);
3944: if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
3945: $home = $env{'user.home'};
3946: $cfile = $resurl;
3947: if ($env{'form.forceedit'}) {
3948: $forceview = 1;
3949: } else {
3950: $forceedit = 1;
3951: }
3952: return ($cfile,$home,$switchserver,$forceedit,$forceview);
3953: } else {
3954: return;
3955: }
3956: }
3957:
1.1517 raeburn 3958: #
3959: # For /adm/viewcoauthors can only edit if author or co-author who is manager.
3960: #
3961:
3962: if (($resurl eq '/adm/viewcoauthors') && ($cnum ne '') && ($cdom ne '')) {
3963: if (((&allowed('cca',"$cdom/$cnum")) ||
3964: (&allowed('caa',"$cdom/$cnum"))) ||
3965: ((&allowed('vca',"$cdom/$cnum") ||
3966: &allowed('vaa',"$cdom/$cnum")) &&
3967: ($env{"environment.internal.manager./$cdom/$cnum"}))) {
3968: $home = $env{'user.home'};
3969: $cfile = $resurl;
3970: if ($env{'form.forceedit'}) {
3971: $forceview = 1;
3972: } else {
3973: $forceedit = 1;
3974: }
3975: return ($cfile,$home,$switchserver,$forceedit,$forceview);
3976: } else {
3977: return;
3978: }
3979: }
3980:
1.1194 raeburn 3981: if ($env{'request.course.id'}) {
1.1494 raeburn 3982: my $crsedit = &allowed('mdc',$env{'request.course.id'});
1.1194 raeburn 3983: if ($group ne '') {
3984: # if this is a group homepage or group bulletin board, check group privs
3985: my $allowed = 0;
1.1197 raeburn 3986: if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
3987: if ((&allowed('mdg',$env{'request.course.id'}.
1.1198 raeburn 3988: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
1.1194 raeburn 3989: (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
3990: $allowed = 1;
3991: }
1.1197 raeburn 3992: } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
3993: if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
3994: (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
1.1194 raeburn 3995: $allowed = 1;
3996: }
3997: }
3998: if ($allowed) {
3999: $home=&homeserver($cnum,$cdom);
4000: if ($env{'form.forceedit'}) {
4001: $forceview = 1;
4002: } else {
4003: $forceedit = 1;
4004: }
4005: $cfile = $resurl;
4006: } else {
4007: return;
4008: }
4009: } else {
1.1208 raeburn 4010: if ($resurl =~ m{^/?adm/viewclasslist$}) {
1.1494 raeburn 4011: unless (&allowed('opa',$env{'request.course.id'})) {
1.1208 raeburn 4012: return;
4013: }
4014: } elsif (!$crsedit) {
1.1507 raeburn 4015: if ($env{'request.role'} =~ m{^st\./$cdom/$cnum}) {
1.1194 raeburn 4016: #
4017: # No edit allowed where CC has switched to student role.
4018: #
1.1507 raeburn 4019: return;
4020: } elsif (($resurl !~ m{^/res/$match_domain/$match_username/}) ||
4021: ($resurl =~ m{^/res/lib/templates/})) {
4022: return;
4023: }
1.1194 raeburn 4024: }
4025: }
4026: }
4027:
1.1193 raeburn 4028: if ($file ne '') {
4029: if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
1.1194 raeburn 4030: if (&is_course_upload($file,$cnum,$cdom)) {
4031: $uploaded = 1;
4032: $incourse = 1;
1.1193 raeburn 4033: if ($file =~/\.(htm|html|css|js|txt)$/) {
4034: $cfile = &hreflocation('',$file);
1.1201 raeburn 4035: if ($env{'form.forceedit'}) {
4036: $forceview = 1;
4037: } else {
4038: $forceedit = 1;
4039: }
1.1194 raeburn 4040: }
4041: } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
4042: $incourse = 1;
4043: if ($env{'form.forceedit'}) {
4044: $forceview = 1;
4045: } else {
4046: $forceedit = 1;
4047: }
4048: $cfile = $resurl;
1.1507 raeburn 4049: } elsif (($resurl ne '') && (&is_on_map($resurl))) {
1.1194 raeburn 4050: if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
4051: $incourse = 1;
4052: if ($env{'form.forceedit'}) {
4053: $forceview = 1;
4054: } else {
4055: $forceedit = 1;
4056: }
4057: $cfile = $resurl;
1.1199 raeburn 4058: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
1.1194 raeburn 4059: $incourse = 1;
4060: $cfile = $resurl.'/smpedit';
1.1199 raeburn 4061: } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
1.1194 raeburn 4062: $incourse = 1;
1.1199 raeburn 4063: if ($env{'form.forceedit'}) {
4064: $forceview = 1;
4065: } else {
4066: $forceedit = 1;
4067: }
4068: $cfile = $resurl;
1.1419 raeburn 4069: } elsif (($resurl =~ m{^/ext/}) && ($symb ne '')) {
4070: my ($map,$id,$res) = &decode_symb($symb);
4071: if ($map =~ /\.page$/) {
4072: $incourse = 1;
4073: if ($env{'form.forceedit'}) {
4074: $forceview = 1;
4075: $cfile = $map;
4076: } else {
4077: $forceedit = 1;
4078: $cfile = '/adm/wrapper'.$resurl;
4079: }
4080: }
1.1343 raeburn 4081: } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
1.1298 raeburn 4082: $incourse = 1;
4083: if ($env{'form.forceedit'}) {
4084: $forceview = 1;
4085: } else {
4086: $forceedit = 1;
4087: }
4088: $cfile = $resurl;
1.1208 raeburn 4089: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
4090: $incourse = 1;
4091: if ($env{'form.forceedit'}) {
4092: $forceview = 1;
4093: } else {
4094: $forceedit = 1;
4095: }
4096: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1194 raeburn 4097: }
4098: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
4099: my $template = '/res/lib/templates/simpleproblem.problem';
4100: if (&is_on_map($template)) {
4101: $incourse = 1;
4102: $forceview = 1;
4103: $cfile = $template;
1.1193 raeburn 4104: }
1.1199 raeburn 4105: } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1418 raeburn 4106: $incourse = 1;
4107: if ($env{'form.forceedit'}) {
4108: $forceview = 1;
4109: } else {
4110: $forceedit = 1;
4111: }
4112: $cfile = $resurl;
1.1343 raeburn 4113: } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1298 raeburn 4114: $incourse = 1;
4115: if ($env{'form.forceedit'}) {
4116: $forceview = 1;
4117: } else {
4118: $forceedit = 1;
4119: }
4120: $cfile = $resurl;
1.1199 raeburn 4121: } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
4122: $incourse = 1;
4123: $forceview = 1;
4124: if ($symb) {
4125: my ($map,$id,$res)=&decode_symb($symb);
4126: $env{'request.symb'} = $symb;
4127: $cfile = &clutter($res);
4128: } else {
4129: $cfile = $env{'form.suppurl'};
1.1298 raeburn 4130: my $escfile = &unescape($cfile);
1.1343 raeburn 4131: if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
1.1298 raeburn 4132: $cfile = '/adm/wrapper'.$escfile;
4133: } else {
4134: $escfile =~ s{^http://}{};
4135: $cfile = &escape("/adm/wrapper/ext/$escfile");
4136: }
1.1199 raeburn 4137: }
1.1234 raeburn 4138: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
4139: if ($env{'form.forceedit'}) {
4140: $forceview = 1;
4141: } else {
4142: $forceedit = 1;
4143: }
4144: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1193 raeburn 4145: }
4146: }
1.1194 raeburn 4147: if ($uploaded || $incourse) {
4148: $home=&homeserver($cnum,$cdom);
1.1207 raeburn 4149: } elsif ($file !~ m{/$}) {
1.1193 raeburn 4150: $file=~s{^(priv/$match_domain/$match_username)}{/$1};
4151: $file=~s{^($match_domain/$match_username)}{/priv/$1};
4152: # Check that the user has permission to edit this resource
4153: my $setpriv = 1;
4154: my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
4155: if (defined($cfudom)) {
4156: $home=&homeserver($cfuname,$cfudom);
4157: $cfile=$file;
4158: }
4159: }
1.1194 raeburn 4160: if (($cfile ne '') && (!$incourse || $uploaded) &&
4161: (($home ne '') && ($home ne 'no_host'))) {
1.1193 raeburn 4162: my @ids=¤t_machine_ids();
4163: unless (grep(/^\Q$home\E$/,@ids)) {
4164: $switchserver=1;
4165: }
4166: }
4167: }
1.1194 raeburn 4168: return ($cfile,$home,$switchserver,$forceedit,$forceview);
1.1193 raeburn 4169: }
4170:
4171: sub is_course_upload {
4172: my ($file,$cnum,$cdom) = @_;
4173: my $uploadpath = &LONCAPA::propath($cdom,$cnum);
4174: $uploadpath =~ s{^\/}{};
1.1201 raeburn 4175: if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
4176: ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
1.1193 raeburn 4177: return 1;
4178: }
4179: return;
4180: }
4181:
1.1194 raeburn 4182: sub in_course {
1.1195 raeburn 4183: my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
4184: if ($hideprivileged) {
4185: my $skipuser;
1.1219 raeburn 4186: my %coursehash = &coursedescription($cdom.'_'.$cnum);
4187: my @possdoms = ($cdom);
4188: if ($coursehash{'checkforpriv'}) {
4189: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
4190: }
4191: if (&privileged($uname,$udom,\@possdoms)) {
1.1195 raeburn 4192: $skipuser = 1;
4193: if ($coursehash{'nothideprivileged'}) {
4194: foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
4195: my $user;
4196: if ($item =~ /:/) {
4197: $user = $item;
4198: } else {
4199: $user = join(':',split(/[\@]/,$item));
4200: }
4201: if ($user eq $uname.':'.$udom) {
4202: undef($skipuser);
4203: last;
4204: }
4205: }
4206: }
4207: if ($skipuser) {
4208: return 0;
4209: }
4210: }
4211: }
1.1194 raeburn 4212: $type ||= 'any';
4213: if (!defined($cdom) || !defined($cnum)) {
4214: my $cid = $env{'request.course.id'};
4215: $cdom = $env{'course.'.$cid.'.domain'};
4216: $cnum = $env{'course.'.$cid.'.num'};
4217: }
4218: my $typesref;
1.1195 raeburn 4219: if (($type eq 'any') || ($type eq 'all')) {
1.1194 raeburn 4220: $typesref = ['active','previous','future'];
4221: } elsif ($type eq 'previous' || $type eq 'future') {
4222: $typesref = [$type];
4223: }
4224: my %roles = &get_my_roles($uname,$udom,'userroles',
4225: $typesref,undef,[$cdom]);
4226: my ($tmp) = keys(%roles);
4227: return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
4228: my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
4229: if (@course_roles > 0) {
4230: return 1;
4231: }
4232: return 0;
4233: }
4234:
1.478 albertel 4235: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 4236: # input: action, courseID, current domain, intended
1.637 raeburn 4237: # path to file, source of file, instruction to parse file for objects,
4238: # ref to hash for embedded objects,
4239: # ref to hash for codebase of java objects.
1.1095 raeburn 4240: # reference to scalar to accommodate mime type determined
4241: # from File::MMagic if $parser = parse.
1.637 raeburn 4242: #
1.485 raeburn 4243: # output: url to file (if action was uploaddoc),
4244: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 4245: #
1.478 albertel 4246: # Allows directory structure to be used within lonUsers/../userfiles/ for a
4247: # course.
1.477 raeburn 4248: #
1.478 albertel 4249: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
4250: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
4251: # course's home server.
1.477 raeburn 4252: #
1.478 albertel 4253: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
4254: # be copied from $source (current location) to
4255: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
4256: # and will then be copied to
4257: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
4258: # course's home server.
1.485 raeburn 4259: #
1.481 raeburn 4260: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 4261: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 4262: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
4263: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
4264: # in course's home server.
1.637 raeburn 4265: #
1.477 raeburn 4266:
4267: sub process_coursefile {
1.1095 raeburn 4268: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
4269: $mimetype)=@_;
1.477 raeburn 4270: my $fetchresult;
1.638 albertel 4271: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 4272: if ($action eq 'propagate') {
1.638 albertel 4273: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
4274: $home);
1.481 raeburn 4275: } else {
1.477 raeburn 4276: my $fpath = '';
4277: my $fname = $file;
1.478 albertel 4278: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 4279: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 4280: my $filepath = &build_filepath($fpath);
1.481 raeburn 4281: if ($action eq 'copy') {
4282: if ($source eq '') {
4283: $fetchresult = 'no source file';
4284: return $fetchresult;
4285: } else {
4286: my $destination = $filepath.'/'.$fname;
4287: rename($source,$destination);
4288: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 4289: $home);
1.481 raeburn 4290: }
4291: } elsif ($action eq 'uploaddoc') {
1.1359 raeburn 4292: open(my $fh,'>',$filepath.'/'.$fname);
1.620 albertel 4293: print $fh $env{'form.'.$source};
1.481 raeburn 4294: close($fh);
1.637 raeburn 4295: if ($parser eq 'parse') {
1.1024 raeburn 4296: my $mm = new File::MMagic;
1.1095 raeburn 4297: my $type = $mm->checktype_filename($filepath.'/'.$fname);
4298: if ($type eq 'text/html') {
1.1024 raeburn 4299: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
4300: unless ($parse_result eq 'ok') {
4301: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
4302: }
1.637 raeburn 4303: }
1.1095 raeburn 4304: if (ref($mimetype)) {
4305: $$mimetype = $type;
4306: }
1.637 raeburn 4307: }
1.477 raeburn 4308: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 4309: $home);
1.481 raeburn 4310: if ($fetchresult eq 'ok') {
4311: return '/uploaded/'.$fpath.'/'.$fname;
4312: } else {
4313: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 4314: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 4315: return '/adm/notfound.html';
4316: }
1.477 raeburn 4317: }
4318: }
1.485 raeburn 4319: unless ( $fetchresult eq 'ok') {
1.477 raeburn 4320: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 4321: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 4322: }
4323: return $fetchresult;
4324: }
4325:
1.637 raeburn 4326: sub build_filepath {
4327: my ($fpath) = @_;
4328: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
4329: unless ($fpath eq '') {
4330: my @parts=split('/',$fpath);
4331: foreach my $part (@parts) {
4332: $filepath.= '/'.$part;
4333: if ((-e $filepath)!=1) {
4334: mkdir($filepath,0777);
4335: }
4336: }
4337: }
4338: return $filepath;
4339: }
4340:
4341: sub store_edited_file {
1.638 albertel 4342: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 4343: my $file = $primary_url;
4344: $file =~ s#^/uploaded/$docudom/$docuname/##;
4345: my $fpath = '';
4346: my $fname = $file;
4347: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
4348: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
4349: my $filepath = &build_filepath($fpath);
1.1359 raeburn 4350: open(my $fh,'>',$filepath.'/'.$fname);
1.637 raeburn 4351: print $fh $content;
4352: close($fh);
1.638 albertel 4353: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 4354: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 4355: $home);
1.637 raeburn 4356: if ($$fetchresult eq 'ok') {
4357: return '/uploaded/'.$fpath.'/'.$fname;
4358: } else {
1.638 albertel 4359: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
4360: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 4361: return '/adm/notfound.html';
4362: }
4363: }
4364:
1.531 albertel 4365: sub clean_filename {
1.831 albertel 4366: my ($fname,$args)=@_;
1.315 www 4367: # Replace Windows backslashes by forward slashes
1.257 www 4368: $fname=~s/\\/\//g;
1.831 albertel 4369: if (!$args->{'keep_path'}) {
4370: # Get rid of everything but the actual filename
4371: $fname=~s/^.*\/([^\/]+)$/$1/;
4372: }
1.315 www 4373: # Replace spaces by underscores
4374: $fname=~s/\s+/\_/g;
1.1406 raeburn 4375: # Transliterate non-ascii text to ascii
4376: my $lang = &Apache::lonlocal::current_language();
4377: $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
1.315 www 4378: # Replace all other weird characters by nothing
1.831 albertel 4379: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 4380: # Replace all .\d. sequences with _\d. so they no longer look like version
4381: # numbers
4382: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.1443 raeburn 4383: # Replace three or more adjacent underscores with one for consistency
4384: # with loncfile::filename_check() so complete url can be extracted by
4385: # lonnet::decode_symb()
4386: $fname=~s/_{3,}/_/g;
1.531 albertel 4387: return $fname;
4388: }
1.1406 raeburn 4389:
1.1051 raeburn 4390: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
4391: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
4392: # image with the same aspect ratio as the original, but with dimensions which do
4393: # not exceed $resizewidth and $resizeheight.
4394:
1.984 neumanie 4395: sub resizeImage {
1.1051 raeburn 4396: my ($img_path,$resizewidth,$resizeheight) = @_;
4397: my $ima = Image::Magick->new;
4398: my $resized;
4399: if (-e $img_path) {
4400: $ima->Read($img_path);
4401: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
4402: my $width = $ima->Get('width');
4403: my $height = $ima->Get('height');
4404: if ($width > $resizewidth) {
4405: my $factor = $width/$resizewidth;
4406: my $newheight = $height/$factor;
4407: $ima->Scale(width=>$resizewidth,height=>$newheight);
4408: $resized = 1;
4409: }
4410: }
4411: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
4412: my $width = $ima->Get('width');
4413: my $height = $ima->Get('height');
4414: if ($height > $resizeheight) {
4415: my $factor = $height/$resizeheight;
4416: my $newwidth = $width/$factor;
4417: $ima->Scale(width=>$newwidth,height=>$resizeheight);
4418: $resized = 1;
4419: }
4420: }
4421: if ($resized) {
4422: $ima->Write($img_path);
4423: }
4424: }
4425: return;
1.977 amueller 4426: }
4427:
1.608 albertel 4428: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 4429: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093 raeburn 4430: # the desired filename is in $env{"form.$formname.filename"}
1.1090 raeburn 4431: # $context - possible values: coursedoc, existingfile, overwrite,
1.1504 raeburn 4432: # canceloverwrite, scantron, toollogo or ''.
1.1090 raeburn 4433: # if 'coursedoc': upload to the current course
4434: # if 'existingfile': write file to tmp/overwrites directory
4435: # if 'canceloverwrite': delete file written to tmp/overwrites directory
4436: # $context is passed as argument to &finishuserfileupload
1.686 albertel 4437: # $subdir - directory in userfile to store the file into
1.1401 raeburn 4438: # $parser - instruction to parse file for objects ($parser = parse) or
4439: # if context is 'scantron', $parser is hashref of csv column mapping
4440: # (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3,
4441: # Section => 4, CODE => 5, FirstQuestion => 9 }).
1.858 raeburn 4442: # $allfiles - reference to hash for embedded objects
4443: # $codebase - reference to hash for codebase of java objects
1.1504 raeburn 4444: # $destuname - username for permanent storage of uploaded file
4445: # $destudom - domain for permanaent storage of uploaded file
1.860 raeburn 4446: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
4447: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 4448: # $resizewidth - width (pixels) to which to resize uploaded image
4449: # $resizeheight - height (pixels) to which to resize uploaded image
1.1095 raeburn 4450: # $mimetype - reference to scalar to accommodate mime type determined
1.1152 raeburn 4451: # from File::MMagic.
1.858 raeburn 4452: #
1.686 albertel 4453: # output: url of file in userspace, or error: <message>
4454: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 4455:
1.531 albertel 4456: sub userfileupload {
1.1090 raeburn 4457: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095 raeburn 4458: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531 albertel 4459: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 4460: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 4461: $fname=&clean_filename($fname);
1.1090 raeburn 4462: # See if there is anything left
1.257 www 4463: unless ($fname) { return 'error: no uploaded file'; }
1.1406 raeburn 4464: # If filename now begins with a . prepend unix timestamp _ milliseconds
4465: if ($fname =~ /^\./) {
4466: my ($s,$usec) = &gettimeofday();
4467: while (length($usec) < 6) {
4468: $usec = '0'.$usec;
4469: }
4470: $fname = $s.'_'.substr($usec,0,3).$fname;
4471: }
1.1090 raeburn 4472: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
4473: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
4474: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
4475: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523 raeburn 4476: my $now = time;
1.1090 raeburn 4477: my $filepath;
1.1095 raeburn 4478: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090 raeburn 4479: $filepath = 'tmp/helprequests/'.$now;
4480: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
4481: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
4482: '_'.$env{'user.domain'}.'/pending';
4483: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
4484: my ($docuname,$docudom);
1.1350 raeburn 4485: if ($destudom =~ /^$match_domain$/) {
1.1090 raeburn 4486: $docudom = $destudom;
4487: } else {
4488: $docudom = $env{'user.domain'};
4489: }
1.1350 raeburn 4490: if ($destuname =~ /^$match_username$/) {
1.1090 raeburn 4491: $docuname = $destuname;
4492: } else {
4493: $docuname = $env{'user.name'};
4494: }
4495: if (exists($env{'form.group'})) {
4496: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
4497: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
4498: }
4499: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
4500: if ($context eq 'canceloverwrite') {
4501: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
4502: if (-e $tempfile) {
4503: my @info = stat($tempfile);
4504: if ($info[9] eq $env{'form.timestamp'}) {
4505: unlink($tempfile);
4506: }
4507: }
4508: return;
1.523 raeburn 4509: }
4510: }
1.1090 raeburn 4511: # Create the directory if not present
1.741 raeburn 4512: my @parts=split(/\//,$filepath);
4513: my $fullpath = $perlvar{'lonDaemons'};
4514: for (my $i=0;$i<@parts;$i++) {
4515: $fullpath .= '/'.$parts[$i];
4516: if ((-e $fullpath)!=1) {
4517: mkdir($fullpath,0777);
4518: }
4519: }
1.1359 raeburn 4520: open(my $fh,'>',$fullpath.'/'.$fname);
1.741 raeburn 4521: print $fh $env{'form.'.$formname};
4522: close($fh);
1.1090 raeburn 4523: if ($context eq 'existingfile') {
4524: my @info = stat($fullpath.'/'.$fname);
4525: return ($fullpath.'/'.$fname,$info[9]);
4526: } else {
4527: return $fullpath.'/'.$fname;
4528: }
1.523 raeburn 4529: }
1.995 raeburn 4530: if ($subdir eq 'scantron') {
4531: $fname = 'scantron_orig_'.$fname;
1.1093 raeburn 4532: } else {
1.995 raeburn 4533: $fname="$subdir/$fname";
4534: }
1.1090 raeburn 4535: if ($context eq 'coursedoc') {
1.638 albertel 4536: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
4537: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 4538: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 4539: return &finishuserfileupload($docuname,$docudom,
4540: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 4541: $codebase,$thumbwidth,$thumbheight,
1.1095 raeburn 4542: $resizewidth,$resizeheight,$context,$mimetype);
1.481 raeburn 4543: } else {
1.1218 raeburn 4544: if ($env{'form.folder'}) {
4545: $fname=$env{'form.folder'}.'/'.$fname;
4546: }
1.638 albertel 4547: return &process_coursefile('uploaddoc',$docuname,$docudom,
4548: $fname,$formname,$parser,
1.1095 raeburn 4549: $allfiles,$codebase,$mimetype);
1.481 raeburn 4550: }
1.719 banghart 4551: } elsif (defined($destuname)) {
4552: my $docuname=$destuname;
4553: my $docudom=$destudom;
1.860 raeburn 4554: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
4555: $parser,$allfiles,$codebase,
1.1051 raeburn 4556: $thumbwidth,$thumbheight,
1.1095 raeburn 4557: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 4558: } else {
1.638 albertel 4559: my $docuname=$env{'user.name'};
4560: my $docudom=$env{'user.domain'};
1.1220 raeburn 4561: if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714 raeburn 4562: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
4563: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
4564: }
1.860 raeburn 4565: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
4566: $parser,$allfiles,$codebase,
1.1051 raeburn 4567: $thumbwidth,$thumbheight,
1.1095 raeburn 4568: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 4569: }
1.271 www 4570: }
4571:
4572: sub finishuserfileupload {
1.860 raeburn 4573: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095 raeburn 4574: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477 raeburn 4575: my $path=$docudom.'/'.$docuname.'/';
1.258 www 4576: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 4577:
1.860 raeburn 4578: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 4579: $file=$fname;
4580: if ($fname=~m|/|) {
4581: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
4582: $path.=$fnamepath.'/';
4583: }
1.259 www 4584: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 4585: my $count;
4586: for ($count=4;$count<=$#parts;$count++) {
4587: $filepath.="/$parts[$count]";
4588: if ((-e $filepath)!=1) {
4589: mkdir($filepath,0777);
4590: }
4591: }
1.984 neumanie 4592:
1.258 www 4593: # Save the file
4594: {
1.1359 raeburn 4595: if (!open(FH,'>',$filepath.'/'.$file)) {
1.701 albertel 4596: &logthis('Failed to create '.$filepath.'/'.$file);
4597: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
4598: return '/adm/notfound.html';
4599: }
1.1090 raeburn 4600: if ($context eq 'overwrite') {
1.1117 foxr 4601: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090 raeburn 4602: my $target = $filepath.'/'.$file;
4603: if (-e $source) {
4604: my @info = stat($source);
4605: if ($info[9] eq $env{'form.timestamp'}) {
4606: unless (&File::Copy::move($source,$target)) {
4607: &logthis('Failed to overwrite '.$filepath.'/'.$file);
4608: return "Moving from $source failed";
4609: }
4610: } else {
4611: return "Temporary file: $source had unexpected date/time for last modification";
4612: }
4613: } else {
4614: return "Temporary file: $source missing";
4615: }
4616: } elsif (!print FH ($env{'form.'.$formname})) {
1.701 albertel 4617: &logthis('Failed to write to '.$filepath.'/'.$file);
4618: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
4619: return '/adm/notfound.html';
4620: }
1.570 albertel 4621: close(FH);
1.1051 raeburn 4622: if ($resizewidth && $resizeheight) {
4623: my $mm = new File::MMagic;
4624: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
4625: if ($mime_type =~ m{^image/}) {
4626: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
4627: }
1.977 amueller 4628: }
1.258 www 4629: }
1.1152 raeburn 4630: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
4631: if (ref($mimetype)) {
4632: if ($$mimetype eq '') {
4633: my $mm = new File::MMagic;
4634: my $type = $mm->checktype_filename($filepath.'/'.$file);
4635: $$mimetype = $type;
4636: }
4637: }
4638: }
1.1401 raeburn 4639: if (($context ne 'scantron') && ($parser eq 'parse')) {
1.1152 raeburn 4640: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024 raeburn 4641: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
4642: $allfiles,$codebase);
4643: unless ($parse_result eq 'ok') {
4644: &logthis('Failed to parse '.$filepath.$file.
4645: ' for embedded media: '.$parse_result);
4646: }
1.637 raeburn 4647: }
1.1401 raeburn 4648: } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
4649: my $format = $env{'form.scantron_format'};
4650: &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
1.637 raeburn 4651: }
1.860 raeburn 4652: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
4653: my $input = $filepath.'/'.$file;
4654: my $output = $filepath.'/'.'tn-'.$file;
1.1504 raeburn 4655: my $makethumb;
1.860 raeburn 4656: my $thumbsize = $thumbwidth.'x'.$thumbheight;
1.1504 raeburn 4657: if ($context eq 'toollogo') {
4658: my ($fullwidth,$fullheight) = &check_dimensions($input);
4659: if ($fullwidth ne '' && $fullheight ne '') {
4660: if ($fullwidth > $thumbwidth && $fullheight > $thumbheight) {
4661: $makethumb = 1;
4662: }
4663: }
4664: } else {
4665: $makethumb = 1;
4666: }
4667: if ($makethumb) {
4668: my @args = ('convert','-sample',$thumbsize,$input,$output);
4669: system({$args[0]} @args);
4670: if (-e $filepath.'/'.'tn-'.$file) {
4671: $fetchthumb = 1;
4672: }
1.860 raeburn 4673: }
4674: }
1.858 raeburn 4675:
1.259 www 4676: # Notify homeserver to grep it
4677: #
1.984 neumanie 4678: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 4679: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 4680: if ($fetchresult eq 'ok') {
1.860 raeburn 4681: if ($fetchthumb) {
4682: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
4683: if ($thumbresult ne 'ok') {
4684: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
4685: $docuhome.': '.$thumbresult);
4686: }
4687: }
1.259 www 4688: #
1.258 www 4689: # Return the URL to it
1.494 albertel 4690: return '/uploaded/'.$path.$file;
1.263 www 4691: } else {
1.494 albertel 4692: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
4693: ': '.$fetchresult);
1.263 www 4694: return '/adm/notfound.html';
1.858 raeburn 4695: }
1.493 albertel 4696: }
4697:
1.637 raeburn 4698: sub extract_embedded_items {
1.961 raeburn 4699: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 4700: my @state = ();
1.1164 raeburn 4701: my (%lastids,%related,%shockwave,%flashvars);
1.637 raeburn 4702: my %javafiles = (
4703: codebase => '',
4704: code => '',
4705: archive => ''
4706: );
4707: my %mediafiles = (
4708: src => '',
4709: movie => '',
4710: );
1.648 raeburn 4711: my $p;
4712: if ($content) {
4713: $p = HTML::LCParser->new($content);
4714: } else {
1.961 raeburn 4715: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 4716: }
1.641 albertel 4717: while (my $t=$p->get_token()) {
1.640 albertel 4718: if ($t->[0] eq 'S') {
4719: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 4720: push(@state, $tagname);
1.648 raeburn 4721: if (lc($tagname) eq 'allow') {
4722: &add_filetype($allfiles,$attr->{'src'},'src');
4723: }
1.640 albertel 4724: if (lc($tagname) eq 'img') {
4725: &add_filetype($allfiles,$attr->{'src'},'src');
4726: }
1.886 albertel 4727: if (lc($tagname) eq 'a') {
1.1222 raeburn 4728: unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
1.1221 raeburn 4729: &add_filetype($allfiles,$attr->{'href'},'href');
4730: }
1.886 albertel 4731: }
1.645 raeburn 4732: if (lc($tagname) eq 'script') {
1.1164 raeburn 4733: my $src;
1.645 raeburn 4734: if ($attr->{'archive'} =~ /\.jar$/i) {
4735: &add_filetype($allfiles,$attr->{'archive'},'archive');
4736: } else {
1.1164 raeburn 4737: if ($attr->{'src'} ne '') {
4738: $src = $attr->{'src'};
4739: &add_filetype($allfiles,$src,'src');
4740: }
4741: }
4742: my $text = $p->get_trimmed_text();
4743: if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
4744: my @swfargs = split(/,/,$1);
4745: foreach my $item (@swfargs) {
4746: $item =~ s/["']//g;
4747: $item =~ s/^\s+//;
4748: $item =~ s/\s+$//;
4749: }
4750: if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
4751: if (ref($related{$swfargs[0]}) eq 'ARRAY') {
4752: push(@{$related{$swfargs[0]}},$swfargs[2]);
4753: } else {
4754: $related{$swfargs[0]} = [$swfargs[2]];
4755: }
4756: }
1.645 raeburn 4757: }
4758: }
4759: if (lc($tagname) eq 'link') {
4760: if (lc($attr->{'rel'}) eq 'stylesheet') {
4761: &add_filetype($allfiles,$attr->{'href'},'href');
4762: }
4763: }
1.640 albertel 4764: if (lc($tagname) eq 'object' ||
4765: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
4766: foreach my $item (keys(%javafiles)) {
4767: $javafiles{$item} = '';
4768: }
1.1164 raeburn 4769: if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
4770: $lastids{lc($tagname)} = $attr->{'id'};
4771: }
1.640 albertel 4772: }
4773: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
4774: my $name = lc($attr->{'name'});
4775: foreach my $item (keys(%javafiles)) {
4776: if ($name eq $item) {
4777: $javafiles{$item} = $attr->{'value'};
4778: last;
4779: }
4780: }
1.1164 raeburn 4781: my $pathfrom;
1.640 albertel 4782: foreach my $item (keys(%mediafiles)) {
4783: if ($name eq $item) {
1.1164 raeburn 4784: $pathfrom = $attr->{'value'};
4785: $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
4786: &add_filetype($allfiles,$pathfrom,$name);
1.640 albertel 4787: last;
4788: }
4789: }
1.1164 raeburn 4790: if ($name eq 'flashvars') {
4791: $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
4792: }
4793: if ($pathfrom ne '') {
4794: &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
4795: $pathfrom);
4796: }
1.640 albertel 4797: }
4798: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
4799: foreach my $item (keys(%javafiles)) {
4800: if ($attr->{$item}) {
4801: $javafiles{$item} = $attr->{$item};
4802: last;
4803: }
4804: }
4805: foreach my $item (keys(%mediafiles)) {
4806: if ($attr->{$item}) {
4807: &add_filetype($allfiles,$attr->{$item},$item);
4808: last;
4809: }
4810: }
1.1164 raeburn 4811: if (lc($tagname) eq 'embed') {
4812: if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
4813: &embedded_dependency($allfiles,\%related,$attr->{'name'},
4814: $attr->{'src'});
4815: }
4816: }
1.640 albertel 4817: }
1.1243 raeburn 4818: if (lc($tagname) eq 'iframe') {
4819: my $src = $attr->{'src'} ;
4820: if (($src ne '') && ($src !~ m{^(/|https?://)})) {
4821: &add_filetype($allfiles,$src,'src');
4822: } elsif ($src =~ m{^/}) {
4823: if ($env{'request.course.id'}) {
4824: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
4825: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
4826: my $url = &hreflocation('',$fullpath);
4827: if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
4828: my $relpath = $1;
4829: if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
4830: &add_filetype($allfiles,$1,'src');
4831: }
4832: }
4833: }
4834: }
4835: }
1.1164 raeburn 4836: if ($t->[4] =~ m{/>$}) {
1.1243 raeburn 4837: pop(@state);
1.1164 raeburn 4838: }
1.640 albertel 4839: } elsif ($t->[0] eq 'E') {
4840: my ($tagname) = ($t->[1]);
4841: if ($javafiles{'codebase'} ne '') {
4842: $javafiles{'codebase'} .= '/';
4843: }
4844: if (lc($tagname) eq 'applet' ||
4845: lc($tagname) eq 'object' ||
4846: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
4847: ) {
4848: foreach my $item (keys(%javafiles)) {
4849: if ($item ne 'codebase' && $javafiles{$item} ne '') {
4850: my $file=$javafiles{'codebase'}.$javafiles{$item};
4851: &add_filetype($allfiles,$file,$item);
4852: }
4853: }
4854: }
4855: pop @state;
4856: }
4857: }
1.1164 raeburn 4858: foreach my $id (sort(keys(%flashvars))) {
4859: if ($shockwave{$id} ne '') {
4860: my @pairs = split(/\&/,$flashvars{$id});
4861: foreach my $pair (@pairs) {
4862: my ($key,$value) = split(/\=/,$pair);
4863: if ($key eq 'thumb') {
4864: &add_filetype($allfiles,$value,$key);
4865: } elsif ($key eq 'content') {
4866: my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
4867: my ($ext) = ($value =~ /\.([^.]+)$/);
4868: if ($ext ne '') {
4869: &add_filetype($allfiles,$path.$value,$ext);
4870: }
4871: }
4872: }
4873: }
4874: }
1.637 raeburn 4875: return 'ok';
4876: }
4877:
1.639 albertel 4878: sub add_filetype {
4879: my ($allfiles,$file,$type)=@_;
4880: if (exists($allfiles->{$file})) {
4881: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
4882: push(@{$allfiles->{$file}}, &escape($type));
4883: }
4884: } else {
4885: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 4886: }
4887: }
4888:
1.1164 raeburn 4889: sub embedded_dependency {
4890: my ($allfiles,$related,$identifier,$pathfrom) = @_;
4891: if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
4892: if (($identifier ne '') &&
4893: (ref($related->{$identifier}) eq 'ARRAY') &&
4894: ($pathfrom ne '')) {
4895: my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
4896: foreach my $dep (@{$related->{$identifier}}) {
4897: &add_filetype($allfiles,$path.$dep,'object');
4898: }
4899: }
4900: }
4901: return;
4902: }
4903:
1.1504 raeburn 4904: sub check_dimensions {
4905: my ($inputfile) = @_;
4906: my ($fullwidth,$fullheight);
4907: if (($inputfile =~ m|^[/\w.\-]+$|) && (-e $inputfile)) {
4908: my $mm = new File::MMagic;
4909: my $mime_type = $mm->checktype_filename($inputfile);
4910: if ($mime_type =~ m{^image/}) {
4911: if (open(PIPE,"identify $inputfile 2>&1 |")) {
4912: my $imageinfo = <PIPE>;
4913: if (!close(PIPE)) {
4914: &Apache::lonnet::logthis("Failed to close PIPE opened to retrieve image information for $inputfile");
4915: }
4916: chomp($imageinfo);
4917: my ($fullsize) =
4918: ($imageinfo =~ /^\Q$inputfile\E\s+\w+\s+(\d+x\d+)/);
4919: if ($fullsize) {
4920: ($fullwidth,$fullheight) = split(/x/,$fullsize);
4921: }
4922: }
4923: }
4924: }
4925: return ($fullwidth,$fullheight);
4926: }
4927:
1.1401 raeburn 4928: sub bubblesheet_converter {
4929: my ($cdom,$fullpath,$config,$format) = @_;
4930: if ((&domain($cdom) ne '') &&
1.1403 raeburn 4931: ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
1.1401 raeburn 4932: (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
1.1404 raeburn 4933: my (%csvcols,%csvoptions);
4934: if (ref($config->{'fields'}) eq 'HASH') {
4935: %csvcols = %{$config->{'fields'}};
4936: }
4937: if (ref($config->{'options'}) eq 'HASH') {
4938: %csvoptions = %{$config->{'options'}};
4939: }
1.1401 raeburn 4940: my %csvbynum = reverse(%csvcols);
4941: my %scantronconf = &get_scantron_config($format,$cdom);
4942: if (keys(%scantronconf)) {
4943: my %bynum = (
4944: $scantronconf{CODEstart} => 'CODEstart',
4945: $scantronconf{IDstart} => 'IDstart',
4946: $scantronconf{PaperID} => 'PaperID',
4947: $scantronconf{FirstName} => 'FirstName',
4948: $scantronconf{LastName} => 'LastName',
4949: $scantronconf{Qstart} => 'Qstart',
4950: );
4951: my @ordered;
4952: foreach my $item (sort { $a <=> $b } keys(%bynum)) {
1.1403 raeburn 4953: push(@ordered,$bynum{$item});
1.1401 raeburn 4954: }
4955: my %mapstart = (
4956: CODEstart => 'CODE',
4957: IDstart => 'ID',
4958: PaperID => 'PaperID',
4959: FirstName => 'FirstName',
4960: LastName => 'LastName',
4961: Qstart => 'FirstQuestion',
4962: );
4963: my %maplength = (
4964: CODEstart => 'CODElength',
4965: IDstart => 'IDlength',
4966: PaperID => 'PaperIDlength',
4967: FirstName => 'FirstNamelength',
4968: LastName => 'LastNamelength',
4969: );
4970: if (open(my $fh,'<',$fullpath)) {
4971: my $output;
1.1403 raeburn 4972: my %lettdig = &letter_to_digits();
4973: my %diglett = reverse(%lettdig);
4974: my $numletts = scalar(keys(%lettdig));
1.1404 raeburn 4975: my $num = 0;
1.1401 raeburn 4976: while (my $line=<$fh>) {
1.1404 raeburn 4977: $num ++;
4978: next if (($num == 1) && ($csvoptions{'hdr'} == 1));
1.1401 raeburn 4979: $line =~ s{[\r\n]+$}{};
4980: my %found;
1.1475 raeburn 4981: my @values = split(/,/,$line,-1);
1.1401 raeburn 4982: my ($qstart,$record);
4983: for (my $i=0; $i<@values; $i++) {
1.1403 raeburn 4984: if ((($qstart ne '') && ($i > $qstart)) ||
4985: ($csvbynum{$i} eq 'FirstQuestion')) {
4986: if ($values[$i] eq '') {
4987: $values[$i] = $scantronconf{'Qoff'};
4988: } elsif ($scantronconf{'Qon'} eq 'number') {
4989: if ($values[$i] =~ /^[A-Ja-j]$/) {
4990: $values[$i] = $lettdig{uc($values[$i])};
4991: }
4992: } elsif ($scantronconf{'Qon'} eq 'letter') {
4993: if ($values[$i] =~ /^[0-9]$/) {
4994: $values[$i] = $diglett{$values[$i]};
4995: }
4996: } else {
4997: if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
4998: my $digit;
4999: if ($values[$i] =~ /^[A-Ja-j]$/) {
5000: $digit = $lettdig{uc($values[$i])}-1;
5001: if ($values[$i] eq 'J') {
5002: $digit += $numletts;
5003: }
5004: } elsif ($values[$i] =~ /^[0-9]$/) {
5005: $digit = $values[$i]-1;
5006: if ($values[$i] eq '0') {
5007: $digit += $numletts;
5008: }
5009: }
5010: my $qval='';
5011: for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
5012: if ($j == $digit) {
5013: $qval .= $scantronconf{'Qon'};
5014: } else {
5015: $qval .= $scantronconf{'Qoff'};
5016: }
5017: }
5018: $values[$i] = $qval;
5019: }
5020: }
5021: if (length($values[$i]) > $scantronconf{'Qlength'}) {
5022: $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
5023: }
5024: my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
5025: if ($numblank > 0) {
5026: $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
5027: }
1.1401 raeburn 5028: if ($csvbynum{$i} eq 'FirstQuestion') {
5029: $qstart = $i;
1.1403 raeburn 5030: $found{$csvbynum{$i}} = $values[$i];
1.1401 raeburn 5031: } else {
1.1403 raeburn 5032: $found{'FirstQuestion'} .= $values[$i];
5033: }
5034: } elsif (exists($csvbynum{$i})) {
1.1404 raeburn 5035: if ($csvoptions{'rem'}) {
5036: $values[$i] =~ s/^\s+//;
5037: }
5038: if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
1.1403 raeburn 5039: while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
5040: $values[$i] = '0'.$values[$i];
1.1401 raeburn 5041: }
5042: }
5043: $found{$csvbynum{$i}} = $values[$i];
5044: }
5045: }
5046: foreach my $item (@ordered) {
5047: my $currlength = 1+length($record);
5048: my $numspaces = $scantronconf{$item} - $currlength;
5049: if ($numspaces > 0) {
5050: $record .= (' ' x $numspaces);
5051: }
5052: if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
5053: unless ($item eq 'Qstart') {
5054: if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
5055: $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
5056: }
5057: }
5058: $record .= $found{$mapstart{$item}};
5059: }
5060: }
5061: $output .= "$record\n";
5062: }
5063: close($fh);
5064: if ($output) {
5065: if (open(my $fh,'>',$fullpath)) {
5066: print $fh $output;
5067: close($fh);
5068: }
5069: }
5070: }
5071: }
5072: return;
5073: }
5074: }
5075:
1.1403 raeburn 5076: sub letter_to_digits {
5077: my %lettdig = (
5078: A => 1,
5079: B => 2,
5080: C => 3,
5081: D => 4,
5082: E => 5,
5083: F => 6,
5084: G => 7,
5085: H => 8,
5086: I => 9,
5087: J => 0,
5088: );
5089: return %lettdig;
5090: }
5091:
1.1401 raeburn 5092: sub get_scantron_config {
5093: my ($which,$cdom) = @_;
5094: my @lines = &get_scantronformat_file($cdom);
5095: my %config;
5096: #FIXME probably should move to XML it has already gotten a bit much now
5097: foreach my $line (@lines) {
5098: my ($name,$descrip)=split(/:/,$line);
5099: if ($name ne $which ) { next; }
5100: chomp($line);
5101: my @config=split(/:/,$line);
5102: $config{'name'}=$config[0];
5103: $config{'description'}=$config[1];
5104: $config{'CODElocation'}=$config[2];
5105: $config{'CODEstart'}=$config[3];
5106: $config{'CODElength'}=$config[4];
5107: $config{'IDstart'}=$config[5];
5108: $config{'IDlength'}=$config[6];
5109: $config{'Qstart'}=$config[7];
5110: $config{'Qlength'}=$config[8];
5111: $config{'Qoff'}=$config[9];
5112: $config{'Qon'}=$config[10];
5113: $config{'PaperID'}=$config[11];
5114: $config{'PaperIDlength'}=$config[12];
5115: $config{'FirstName'}=$config[13];
5116: $config{'FirstNamelength'}=$config[14];
5117: $config{'LastName'}=$config[15];
5118: $config{'LastNamelength'}=$config[16];
5119: $config{'BubblesPerRow'}=$config[17];
5120: last;
5121: }
5122: return %config;
5123: }
5124:
5125: sub get_scantronformat_file {
5126: my ($cdom) = @_;
5127: if ($cdom eq '') {
5128: $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
5129: }
5130: my %domconfig = &get_dom('configuration',['scantron'],$cdom);
5131: my $gottab = 0;
5132: my @lines;
5133: if (ref($domconfig{'scantron'}) eq 'HASH') {
5134: if ($domconfig{'scantron'}{'scantronformat'} ne '') {
5135: my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
5136: if ($formatfile ne '-1') {
5137: @lines = split("\n",$formatfile,-1);
5138: $gottab = 1;
5139: }
5140: }
5141: }
5142: if (!$gottab) {
5143: my $confname = $cdom.'-domainconfig';
5144: my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
5145: my $formatfile = &getfile($default);
5146: if ($formatfile ne '-1') {
5147: @lines = split("\n",$formatfile,-1);
5148: $gottab = 1;
5149: }
5150: }
5151: if (!$gottab) {
5152: my @domains = ¤t_machine_domains();
5153: if (grep(/^\Q$cdom\E$/,@domains)) {
5154: if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
5155: @lines = <$fh>;
5156: close($fh);
1.1403 raeburn 5157: }
1.1401 raeburn 5158: } else {
5159: if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
5160: @lines = <$fh>;
5161: close($fh);
5162: }
5163: }
1.1488 raeburn 5164: chomp(@lines);
1.1401 raeburn 5165: }
5166: return @lines;
5167: }
5168:
1.493 albertel 5169: sub removeuploadedurl {
1.984 neumanie 5170: my ($url)=@_;
5171: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 5172: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 5173: }
5174:
5175: sub removeuserfile {
5176: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 5177: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 5178: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 5179: if ($result eq 'ok') {
1.798 raeburn 5180: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
5181: my $metafile = $fname.'.meta';
5182: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 5183: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 5184: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 5185: my $sqlresult =
1.823 albertel 5186: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 5187: 'portfolio_metadata',$group,
5188: 'delete');
1.798 raeburn 5189: }
5190: }
5191: return $result;
1.257 www 5192: }
1.15 www 5193:
1.530 albertel 5194: sub mkdiruserfile {
5195: my ($docuname,$docudom,$dir)=@_;
5196: my $home=&homeserver($docuname,$docudom);
5197: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
5198: }
5199:
1.531 albertel 5200: sub renameuserfile {
5201: my ($docuname,$docudom,$old,$new)=@_;
5202: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 5203: my $result = &reply("renameuserfile:$docudom:$docuname:".
5204: &escape("$old").':'.&escape("$new"),$home);
5205: if ($result eq 'ok') {
5206: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
5207: my $oldmeta = $old.'.meta';
5208: my $newmeta = $new.'.meta';
5209: my $metaresult =
5210: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 5211: my $url = "/uploaded/$docudom/$docuname/$old";
5212: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 5213: my $sqlresult =
1.823 albertel 5214: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 5215: 'portfolio_metadata',$group,
5216: 'delete');
1.798 raeburn 5217: }
5218: }
5219: return $result;
1.531 albertel 5220: }
5221:
1.14 www 5222: # ------------------------------------------------------------------------- Log
5223:
5224: sub log {
5225: my ($dom,$nam,$hom,$what)=@_;
1.47 www 5226: return critical("log:$dom:$nam:$what",$hom);
1.157 www 5227: }
5228:
5229: # ------------------------------------------------------------------ Course Log
1.352 www 5230: #
5231: # This routine flushes several buffers of non-mission-critical nature
5232: #
1.157 www 5233:
5234: sub flushcourselogs {
1.352 www 5235: &logthis('Flushing log buffers');
5236: #
5237: # course logs
5238: # This is a log of all transactions in a course, which can be used
5239: # for data mining purposes
5240: #
5241: # It also collects the courseid database, which lists last transaction
5242: # times and course titles for all courseids
5243: #
5244: my %courseidbuffer=();
1.921 raeburn 5245: foreach my $crsid (keys(%courselogs)) {
1.352 www 5246: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 5247: &escape($courselogs{$crsid}),
5248: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 5249: delete $courselogs{$crsid};
5250: } else {
5251: &logthis('Failed to flush log buffer for '.$crsid);
5252: if (length($courselogs{$crsid})>40000) {
1.672 albertel 5253: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 5254: " exceeded maximum size, deleting.</font>");
5255: delete $courselogs{$crsid};
5256: }
1.352 www 5257: }
1.920 raeburn 5258: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 5259: 'description' => $coursedescrbuf{$crsid},
5260: 'inst_code' => $courseinstcodebuf{$crsid},
5261: 'type' => $coursetypebuf{$crsid},
5262: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 5263: };
1.191 harris41 5264: }
1.352 www 5265: #
5266: # Write course id database (reverse lookup) to homeserver of courses
5267: # Is used in pickcourse
5268: #
1.840 albertel 5269: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 5270: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 5271: $courseidbuffer{$crs_home},
5272: $crs_home,'timeonly');
1.352 www 5273: }
5274: #
5275: # File accesses
5276: # Writes to the dynamic metadata of resources to get hit counts, etc.
5277: #
1.449 matthew 5278: foreach my $entry (keys(%accesshash)) {
1.458 matthew 5279: if ($entry =~ /___count$/) {
5280: my ($dom,$name);
1.807 albertel 5281: ($dom,$name,undef)=
1.811 albertel 5282: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 5283: if (! defined($dom) || $dom eq '' ||
5284: ! defined($name) || $name eq '') {
1.620 albertel 5285: my $cid = $env{'request.course.id'};
1.1472 raeburn 5286: #
5287: # FIXME 11/29/2021
5288: # Typo in rev. 1.458 (2003/12/09)??
5289: # These should likely by $env{'course.'.$cid.'.domain'} and $env{'course.'.$cid.'.num'}
5290: #
1.1509 raeburn 5291: # While these remain as $env{'request.'.$cid.'.domain'} and $env{'request.'.$cid.'.num'}
1.1472 raeburn 5292: # $dom and $name will always be null, so the &inc() call will default to storing this data
5293: # in a nohist_accesscount.db file for the user rather than the course.
5294: #
5295: # That said there is a lot of noise in the data being stored.
5296: # So counts for prtspool/ and adm/ etc. are recorded.
5297: #
5298: # A review of which items ending '___count' are written to %accesshash should likely be
5299: # made before deciding whether to set these to 'course.' instead of 'request.'
5300: #
5301: # Under the current scheme each user receives a nohist_accesscount.db file listing
5302: # accesses for things which are not published resources, regardless of course, and
5303: # there is not a nohist_accesscount.db file in a course, which might log accesses from
5304: # anyone in the course for things which are not published resources.
5305: #
5306: # For an author, nohist_accesscount.db ends up having records for other items
5307: # mixed up with the legitimate access counts for the author's published resources.
5308: #
1.620 albertel 5309: $dom = $env{'request.'.$cid.'.domain'};
5310: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 5311: }
1.450 matthew 5312: my $value = $accesshash{$entry};
5313: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
5314: my %temphash=($url => $value);
1.449 matthew 5315: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
5316: if ($result eq 'ok') {
5317: delete $accesshash{$entry};
5318: }
5319: } else {
1.811 albertel 5320: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159 www 5321: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450 matthew 5322: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 5323: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
5324: delete $accesshash{$entry};
5325: }
1.185 www 5326: }
1.191 harris41 5327: }
1.352 www 5328: #
5329: # Roles
5330: # Reverse lookup of user roles for course faculty/staff and co-authorship
5331: #
1.800 albertel 5332: foreach my $entry (keys(%userrolehash)) {
1.351 www 5333: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 5334: split(/\:/,$entry);
1.1494 raeburn 5335: if (&put('nohist_userroles',
1.351 www 5336: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 5337: $rudom,$runame) eq 'ok') {
5338: delete $userrolehash{$entry};
5339: }
5340: }
1.662 raeburn 5341: #
1.1334 raeburn 5342: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662 raeburn 5343: #
5344: my %domrolebuffer = ();
1.1000 raeburn 5345: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 5346: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 5347: if ($domrolebuffer{$rudom}) {
5348: $domrolebuffer{$rudom}.='&'.&escape($entry).
5349: '='.&escape($domainrolehash{$entry});
5350: } else {
5351: $domrolebuffer{$rudom}.=&escape($entry).
5352: '='.&escape($domainrolehash{$entry});
5353: }
5354: delete $domainrolehash{$entry};
5355: }
5356: foreach my $dom (keys(%domrolebuffer)) {
1.1324 raeburn 5357: my %servers;
5358: if (defined(&domain($dom,'primary'))) {
5359: my $primary=&domain($dom,'primary');
5360: my $hostname=&hostname($primary);
5361: $servers{$primary} = $hostname;
5362: } else {
5363: %servers = &get_servers($dom,'library');
5364: }
1.841 albertel 5365: foreach my $tryserver (keys(%servers)) {
1.1324 raeburn 5366: if (&reply('domroleput:'.$dom.':'.
5367: $domrolebuffer{$dom},$tryserver) eq 'ok') {
5368: last;
5369: } else {
1.841 albertel 5370: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
5371: }
1.662 raeburn 5372: }
5373: }
1.186 www 5374: $dumpcount++;
1.157 www 5375: }
5376:
5377: sub courselog {
5378: my $what=shift;
1.158 www 5379: $what=time.':'.$what;
1.620 albertel 5380: unless ($env{'request.course.id'}) { return ''; }
5381: $coursedombuf{$env{'request.course.id'}}=
5382: $env{'course.'.$env{'request.course.id'}.'.domain'};
5383: $coursenumbuf{$env{'request.course.id'}}=
5384: $env{'course.'.$env{'request.course.id'}.'.num'};
5385: $coursehombuf{$env{'request.course.id'}}=
5386: $env{'course.'.$env{'request.course.id'}.'.home'};
5387: $coursedescrbuf{$env{'request.course.id'}}=
5388: $env{'course.'.$env{'request.course.id'}.'.description'};
5389: $courseinstcodebuf{$env{'request.course.id'}}=
5390: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
5391: $courseownerbuf{$env{'request.course.id'}}=
5392: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 5393: $coursetypebuf{$env{'request.course.id'}}=
5394: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 5395: if (defined $courselogs{$env{'request.course.id'}}) {
5396: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 5397: } else {
1.620 albertel 5398: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 5399: }
1.620 albertel 5400: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 5401: &flushcourselogs();
5402: }
1.158 www 5403: }
5404:
5405: sub courseacclog {
5406: my $fnsymb=shift;
1.620 albertel 5407: unless ($env{'request.course.id'}) { return ''; }
5408: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144 www 5409: if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187 www 5410: $what.=':POST';
1.583 matthew 5411: # FIXME: Probably ought to escape things....
1.800 albertel 5412: foreach my $key (keys(%env)) {
5413: if ($key=~/^form\.(.*)/) {
1.975 raeburn 5414: my $formitem = $1;
5415: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
5416: $what.=':'.$formitem.'='.$env{$key};
5417: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
1.1432 raeburn 5418: if ($formitem eq 'proctorpassword') {
1.1433 raeburn 5419: $what.=':'.$formitem.'=' . '*' x length($env{$key});
1.1432 raeburn 5420: } else {
5421: $what.=':'.$formitem.'='.$env{$key};
5422: }
1.975 raeburn 5423: }
1.158 www 5424: }
1.191 harris41 5425: }
1.583 matthew 5426: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
5427: # FIXME: We should not be depending on a form parameter that someone
5428: # editing lonsearchcat.pm might change in the future.
1.620 albertel 5429: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 5430: $what.= ':POST';
5431: # FIXME: Probably ought to escape things....
5432: foreach my $element ('courseexp','crsfulltext','crsrelated',
5433: 'crsdiscuss') {
1.620 albertel 5434: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 5435: }
5436: }
1.158 www 5437: }
5438: &courselog($what);
1.149 www 5439: }
5440:
1.185 www 5441: sub countacc {
5442: my $url=&declutter(shift);
1.458 matthew 5443: return if (! defined($url) || $url eq '');
1.620 albertel 5444: unless ($env{'request.course.id'}) { return ''; }
1.1158 www 5445: #
5446: # Mark that this url was used in this course
5447: #
1.620 albertel 5448: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158 www 5449: #
5450: # Increase the access count for this resource in this child process
5451: #
1.281 www 5452: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 5453: $accesshash{$key}++;
1.185 www 5454: }
1.349 www 5455:
1.361 www 5456: sub linklog {
5457: my ($from,$to)=@_;
5458: $from=&declutter($from);
5459: $to=&declutter($to);
5460: $accesshash{$from.'___'.$to.'___comefrom'}=1;
5461: $accesshash{$to.'___'.$from.'___goto'}=1;
5462: }
1.1160 www 5463:
5464: sub statslog {
5465: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
5466: if ($users<2) { return; }
5467: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
5468: 'course' => $env{'request.course.id'},
5469: 'sections' => '"all"',
5470: 'num_students' => $users,
5471: 'part' => $part,
5472: 'symb' => $symb,
5473: 'mean_tries' => $av_attempts,
5474: 'deg_of_diff' => $degdiff});
5475: foreach my $key (keys(%dynstore)) {
5476: $accesshash{$key}=$dynstore{$key};
5477: }
5478: }
1.361 www 5479:
1.349 www 5480: sub userrolelog {
5481: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169 droeschl 5482: if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350 www 5483: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
5484: $userrolehash
5485: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 5486: =$tend.':'.$tstart;
1.662 raeburn 5487: }
1.1169 droeschl 5488: if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898 albertel 5489: $userrolehash
5490: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
5491: =$tend.':'.$tstart;
5492: }
1.1334 raeburn 5493: if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662 raeburn 5494: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
5495: $domainrolehash
5496: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
5497: = $tend.':'.$tstart;
5498: }
1.351 www 5499: }
5500:
1.957 raeburn 5501: sub courserolelog {
1.1512 raeburn 5502: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,
5503: $context,$othdomby,$requester)=@_;
1.1184 raeburn 5504: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
5505: my $cdom = $1;
5506: my $cnum = $2;
5507: my $sec = $3;
5508: my $namespace = 'rolelog';
5509: my %storehash = (
5510: role => $trole,
5511: start => $tstart,
5512: end => $tend,
5513: selfenroll => $selfenroll,
5514: context => $context,
5515: );
1.1512 raeburn 5516: if ($othdomby) {
5517: if ($othdomby eq 'othdombydc') {
5518: $storehash{'approval'} = 'domain';
5519: } elsif ($othdomby eq 'othdombyuser') {
5520: $storehash{'approval'} = 'user';
5521: }
5522: if ($requester ne '') {
5523: $storehash{'requester'} = $requester;
5524: }
5525: }
1.1184 raeburn 5526: if ($trole eq 'gr') {
5527: $namespace = 'groupslog';
5528: $storehash{'group'} = $sec;
5529: } else {
5530: $storehash{'section'} = $sec;
1.1516 raeburn 5531: my ($curruserdomstr,$newuserdomstr);
1.1515 raeburn 5532: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.userdomains'})) {
5533: $curruserdomstr = $env{'course.'.$env{'request.course.id'}.'.internal.userdomains'};
1.1516 raeburn 5534: } else {
1.1515 raeburn 5535: my %courseinfo = &coursedescription($cdom.'/'.$cnum);
5536: $curruserdomstr = $courseinfo{'internal.userdomains'};
5537: }
1.1516 raeburn 5538: if ($curruserdomstr ne '') {
5539: my @udoms = split(/,/,$curruserdomstr);
1.1515 raeburn 5540: unless (grep(/^\Q$domain\E/,@udoms)) {
5541: push(@udoms,$domain);
5542: $newuserdomstr = join(',',sort(@udoms));
5543: }
5544: } else {
5545: $newuserdomstr = $domain;
5546: }
5547: if ($newuserdomstr ne '') {
5548: my $putresult = &put('environment',{ 'internal.userdomains' => $newuserdomstr },
5549: $cdom,$cnum);
5550: if ($putresult eq 'ok') {
5551: unless (($selfenroll) || ($context eq 'selfenroll')) {
5552: if (($context eq 'createcourse') || ($context eq 'requestcourses') ||
5553: ($context eq 'automated') || ($context eq 'domain')) {
5554: $env{'course.'.$cdom.'_'.$cnum.'.internal.userdomains'} = $newuserdomstr;
5555: } elsif ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
5556: &appenv({'course.'.$cdom.'_'.$cnum.'.internal.userdomains' => $newuserdomstr});
5557: }
5558: }
5559: }
5560: }
1.1184 raeburn 5561: }
1.1188 raeburn 5562: &write_log('course',$namespace,\%storehash,$delflag,$username,
5563: $domain,$cnum,$cdom);
1.1184 raeburn 5564: if (($trole ne 'st') || ($sec ne '')) {
5565: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957 raeburn 5566: }
5567: }
5568: return;
5569: }
5570:
1.1184 raeburn 5571: sub domainrolelog {
1.1512 raeburn 5572: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,
5573: $context,$othdomby,$requester)=@_;
1.1184 raeburn 5574: if ($area =~ m{^/($match_domain)/$}) {
5575: my $cdom = $1;
1.1494 raeburn 5576: my $domconfiguser = &get_domainconfiguser($cdom);
1.1184 raeburn 5577: my $namespace = 'rolelog';
5578: my %storehash = (
5579: role => $trole,
5580: start => $tstart,
5581: end => $tend,
5582: context => $context,
5583: );
1.1512 raeburn 5584: if ($othdomby) {
5585: if ($othdomby eq 'othdombydc') {
5586: $storehash{'approval'} = 'domain';
5587: } elsif ($othdomby eq 'othdombyuser') {
5588: $storehash{'approval'} = 'user';
5589: }
5590: if ($requester ne '') {
5591: $storehash{'requester'} = $requester;
5592: }
5593: }
1.1188 raeburn 5594: &write_log('domain',$namespace,\%storehash,$delflag,$username,
5595: $domain,$domconfiguser,$cdom);
1.1184 raeburn 5596: }
5597: return;
5598:
5599: }
5600:
5601: sub coauthorrolelog {
1.1512 raeburn 5602: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,
5603: $context,$othdomby,$requester)=@_;
1.1184 raeburn 5604: if ($area =~ m{^/($match_domain)/($match_username)$}) {
5605: my $audom = $1;
5606: my $auname = $2;
5607: my $namespace = 'rolelog';
5608: my %storehash = (
5609: role => $trole,
5610: start => $tstart,
5611: end => $tend,
5612: context => $context,
5613: );
1.1512 raeburn 5614: if ($othdomby) {
5615: if ($othdomby eq 'othdombydc') {
5616: $storehash{'approval'} = 'domain';
5617: } elsif ($othdomby eq 'othdombyuser') {
5618: $storehash{'approval'} = 'user';
5619: }
5620: if ($requester ne '') {
5621: $storehash{'requester'} = $requester;
5622: }
5623: }
1.1188 raeburn 5624: &write_log('author',$namespace,\%storehash,$delflag,$username,
5625: $domain,$auname,$audom);
1.1184 raeburn 5626: }
5627: return;
5628: }
5629:
1.1527 raeburn 5630: sub authorarchivelog {
5631: my ($hashref,$size,$filesdest,$action) = @_;
5632: my $lonprtdir = $Apache::lonnet::perlvar{'lonPrtDir'};
5633: my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
5634: $filesdest =~ s{^\Q$lonprtdir/\E}{};
5635: if ($filesdest =~ m{^($match_username)_($match_domain)_archive_(\d+_\d+_\d+(|[.\w]+))$}) {
5636: my ($auname,$audom,$id) = ($1,$2,$3);
5637: if (ref($hashref) eq 'HASH') {
5638: my $namespace = 'archivelog';
5639: my $dir;
5640: if ($hashref->{dir} =~ m{^\Q$londocroot/priv/$audom/$auname\E(.*)$}) {
5641: $dir = $1;
5642: }
5643: my $delflag = 0;
5644: my %storehash = (
5645: id => $id,
5646: dir => $dir,
5647: files => $hashref->{numfiles},
5648: subdirs => $hashref->{numdirs},
5649: bytes => $hashref->{bytes},
5650: size => $size,
5651: action => $action,
5652: );
5653: if ($action eq 'delete') {
5654: $delflag = 1;
5655: }
5656: &write_log('author',$namespace,\%storehash,$delflag,$auname,
5657: $audom,$auname,$audom);
5658: }
5659: }
5660: return;
5661: }
5662:
1.351 www 5663: sub get_course_adv_roles {
1.948 raeburn 5664: my ($cid,$codes) = @_;
1.620 albertel 5665: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 5666: my %coursehash=&coursedescription($cid);
1.988 raeburn 5667: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 5668: my %nothide=();
1.800 albertel 5669: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 5670: if ($user !~ /:/) {
5671: $nothide{join(':',split(/[\@]/,$user))}=1;
5672: } else {
5673: $nothide{$user}=1;
5674: }
1.470 www 5675: }
1.1219 raeburn 5676: my @possdoms = ($coursehash{'domain'});
5677: if ($coursehash{'checkforpriv'}) {
5678: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
5679: }
1.351 www 5680: my %returnhash=();
5681: my %dumphash=
5682: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
5683: my $now=time;
1.997 raeburn 5684: my %privileged;
1.1000 raeburn 5685: foreach my $entry (keys(%dumphash)) {
1.800 albertel 5686: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 5687: if (($tstart) && ($tstart<0)) { next; }
5688: if (($tend) && ($tend<$now)) { next; }
5689: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 5690: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 5691: if ($username eq '' || $domain eq '') { next; }
1.1219 raeburn 5692: if ((&privileged($username,$domain,\@possdoms)) &&
1.997 raeburn 5693: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 5694: if ($role eq 'cr') { next; }
1.948 raeburn 5695: if ($codes) {
5696: if ($section) { $role .= ':'.$section; }
5697: if ($returnhash{$role}) {
5698: $returnhash{$role}.=','.$username.':'.$domain;
5699: } else {
5700: $returnhash{$role}=$username.':'.$domain;
5701: }
1.351 www 5702: } else {
1.988 raeburn 5703: my $key=&plaintext($role,$crstype);
1.973 bisitz 5704: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 5705: if ($returnhash{$key}) {
5706: $returnhash{$key}.=','.$username.':'.$domain;
5707: } else {
5708: $returnhash{$key}=$username.':'.$domain;
5709: }
1.351 www 5710: }
1.948 raeburn 5711: }
1.400 www 5712: return %returnhash;
5713: }
5714:
5715: sub get_my_roles {
1.937 raeburn 5716: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 5717: unless (defined($uname)) { $uname=$env{'user.name'}; }
5718: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 5719: my (%dumphash,%nothide);
1.1086 raeburn 5720: if ($context eq 'userroles') {
1.1166 raeburn 5721: %dumphash = &dump('roles',$udom,$uname);
1.858 raeburn 5722: } else {
1.1219 raeburn 5723: %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 5724: if ($hidepriv) {
5725: my %coursehash=&coursedescription($udom.'_'.$uname);
5726: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
5727: if ($user !~ /:/) {
5728: $nothide{join(':',split(/[\@]/,$user))} = 1;
5729: } else {
5730: $nothide{$user} = 1;
5731: }
5732: }
5733: }
1.858 raeburn 5734: }
1.400 www 5735: my %returnhash=();
5736: my $now=time;
1.999 raeburn 5737: my %privileged;
1.800 albertel 5738: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 5739: my ($role,$tend,$tstart);
5740: if ($context eq 'userroles') {
1.1149 raeburn 5741: next if ($entry =~ /^rolesdef/);
1.867 raeburn 5742: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
5743: } else {
5744: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
5745: }
1.400 www 5746: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 5747: my $status = 'active';
1.939 raeburn 5748: if (($tend) && ($tend<=$now)) {
1.832 raeburn 5749: $status = 'previous';
5750: }
5751: if (($tstart) && ($now<$tstart)) {
5752: $status = 'future';
5753: }
5754: if (ref($types) eq 'ARRAY') {
5755: if (!grep(/^\Q$status\E$/,@{$types})) {
5756: next;
5757: }
5758: } else {
5759: if ($status ne 'active') {
5760: next;
5761: }
5762: }
1.867 raeburn 5763: my ($rolecode,$username,$domain,$section,$area);
5764: if ($context eq 'userroles') {
1.1186 raeburn 5765: ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867 raeburn 5766: (undef,$domain,$username,$section) = split(/\//,$area);
5767: } else {
5768: ($role,$username,$domain,$section) = split(/\:/,$entry);
5769: }
1.832 raeburn 5770: if (ref($roledoms) eq 'ARRAY') {
5771: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
5772: next;
5773: }
5774: }
5775: if (ref($roles) eq 'ARRAY') {
5776: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 5777: if ($role =~ /^cr\//) {
5778: if (!grep(/^cr$/,@{$roles})) {
5779: next;
5780: }
1.1104 raeburn 5781: } elsif ($role =~ /^gr\//) {
5782: if (!grep(/^gr$/,@{$roles})) {
5783: next;
5784: }
1.922 raeburn 5785: } else {
5786: next;
5787: }
1.832 raeburn 5788: }
1.867 raeburn 5789: }
1.937 raeburn 5790: if ($hidepriv) {
1.1219 raeburn 5791: my @privroles = ('dc','su');
1.999 raeburn 5792: if ($context eq 'userroles') {
1.1219 raeburn 5793: next if (grep(/^\Q$role\E$/,@privroles));
1.999 raeburn 5794: } else {
1.1219 raeburn 5795: my $possdoms = [$domain];
5796: if (ref($roledoms) eq 'ARRAY') {
5797: push(@{$possdoms},@{$roledoms});
1.999 raeburn 5798: }
1.1219 raeburn 5799: if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999 raeburn 5800: if (!$nothide{$username.':'.$domain}) {
5801: next;
5802: }
5803: }
1.937 raeburn 5804: }
5805: }
1.933 raeburn 5806: if ($withsec) {
5807: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
5808: $tstart.':'.$tend;
5809: } else {
5810: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
5811: }
1.832 raeburn 5812: }
1.373 www 5813: return %returnhash;
1.399 www 5814: }
5815:
1.1333 raeburn 5816: sub get_all_adhocroles {
5817: my ($dom) = @_;
5818: my @roles_by_num = ();
5819: my %domdefaults = &get_domain_defaults($dom);
5820: my (%description,%access_in_dom,%access_info);
5821: if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
5822: my $count = 0;
5823: my %domcurrent = %{$domdefaults{'adhocroles'}};
5824: my %ordered;
5825: foreach my $role (sort(keys(%domcurrent))) {
5826: my ($order,$desc,$access_in_dom);
5827: if (ref($domcurrent{$role}) eq 'HASH') {
5828: $order = $domcurrent{$role}{'order'};
5829: $desc = $domcurrent{$role}{'desc'};
5830: $access_in_dom{$role} = $domcurrent{$role}{'access'};
5831: $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
5832: }
5833: if ($order eq '') {
5834: $order = $count;
5835: }
5836: $ordered{$order} = $role;
5837: if ($desc ne '') {
5838: $description{$role} = $desc;
5839: } else {
5840: $description{$role}= $role;
5841: }
5842: $count++;
5843: }
5844: foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
5845: push(@roles_by_num,$ordered{$item});
5846: }
5847: }
5848: return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
5849: }
5850:
1.1332 raeburn 5851: sub get_my_adhocroles {
1.1333 raeburn 5852: my ($cid,$checkreg) = @_;
5853: my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
5854: if ($env{'request.course.id'} eq $cid) {
5855: $cdom = $env{'course.'.$cid.'.domain'};
5856: $cnum = $env{'course.'.$cid.'.num'};
5857: $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
5858: } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
5859: $cdom = $1;
5860: $cnum = $2;
1.1494 raeburn 5861: %info = &get('environment',['internal.coursecode'],
5862: $cdom,$cnum);
1.1333 raeburn 5863: }
5864: if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
5865: my $user = $env{'user.name'}.':'.$env{'user.domain'};
5866: my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
5867: if ($rosterhash{$user} ne '') {
5868: my $type = (split(/:/,$rosterhash{$user}))[5];
5869: return ([],{}) if ($type eq 'auto');
5870: }
5871: }
5872: if (($cdom ne '') && ($cnum ne '')) {
1.1334 raeburn 5873: if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1332 raeburn 5874: my $then=$env{'user.login.time'};
5875: my $update=$env{'user.update.time'};
1.1335 raeburn 5876: if (!$update) {
5877: $update = $then;
5878: }
5879: my @liveroles;
1.1334 raeburn 5880: foreach my $role ('dh','da') {
5881: if ($env{"user.role.$role./$cdom/"}) {
1.1335 raeburn 5882: my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
1.1334 raeburn 5883: my $limit = $update;
5884: if ($env{'request.role'} eq "$role./$cdom/") {
5885: $limit = $then;
5886: }
1.1335 raeburn 5887: my $activerole = 1;
5888: if ($tstart && $tstart>$limit) { $activerole = 0; }
5889: if ($tend && $tend <$limit) { $activerole = 0; }
5890: if ($activerole) {
5891: push(@liveroles,$role);
5892: }
1.1334 raeburn 5893: }
1.1332 raeburn 5894: }
1.1335 raeburn 5895: if (@liveroles) {
1.1332 raeburn 5896: if (&homeserver($cnum,$cdom) ne 'no_host') {
1.1333 raeburn 5897: my ($accessref,$accessinfo,%access_in_dom);
5898: ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
5899: if (ref($roles_by_num) eq 'ARRAY') {
5900: if (@{$roles_by_num}) {
1.1332 raeburn 5901: my %settings;
5902: if ($env{'request.course.id'} eq $cid) {
5903: foreach my $envkey (keys(%env)) {
5904: if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
5905: $settings{$1} = $env{$envkey};
5906: }
5907: }
5908: } else {
5909: %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
5910: }
5911: my %setincrs;
5912: if ($settings{'internal.adhocaccess'}) {
5913: map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
5914: }
5915: my @statuses;
5916: if ($env{'environment.inststatus'}) {
5917: @statuses = split(/,/,$env{'environment.inststatus'});
5918: }
5919: my $user = $env{'user.name'}.':'.$env{'user.domain'};
1.1333 raeburn 5920: if (ref($accessref) eq 'HASH') {
5921: %access_in_dom = %{$accessref};
5922: }
5923: foreach my $role (@{$roles_by_num}) {
1.1332 raeburn 5924: my ($curraccess,@okstatus,@personnel);
5925: if ($setincrs{$role}) {
5926: ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
5927: if ($curraccess eq 'status') {
5928: @okstatus = split(/\&/,$rest);
5929: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
5930: @personnel = split(/\&/,$rest);
5931: }
5932: } else {
5933: $curraccess = $access_in_dom{$role};
1.1333 raeburn 5934: if (ref($accessinfo) eq 'HASH') {
5935: if ($curraccess eq 'status') {
5936: if (ref($accessinfo->{$role}) eq 'ARRAY') {
5937: @okstatus = @{$accessinfo->{$role}};
5938: }
5939: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
5940: if (ref($accessinfo->{$role}) eq 'ARRAY') {
5941: @personnel = @{$accessinfo->{$role}};
5942: }
1.1332 raeburn 5943: }
5944: }
5945: }
5946: if ($curraccess eq 'none') {
5947: next;
5948: } elsif ($curraccess eq 'all') {
5949: push(@possroles,$role);
1.1336 raeburn 5950: } elsif ($curraccess eq 'dh') {
1.1335 raeburn 5951: if (grep(/^dh$/,@liveroles)) {
5952: push(@possroles,$role);
5953: } else {
5954: next;
5955: }
1.1336 raeburn 5956: } elsif ($curraccess eq 'da') {
1.1335 raeburn 5957: if (grep(/^da$/,@liveroles)) {
5958: push(@possroles,$role);
5959: } else {
5960: next;
5961: }
1.1332 raeburn 5962: } elsif ($curraccess eq 'status') {
5963: if (@okstatus) {
5964: if (!@statuses) {
5965: if (grep(/^default$/,@okstatus)) {
5966: push(@possroles,$role);
5967: }
5968: } else {
5969: foreach my $status (@okstatus) {
5970: if (grep(/^\Q$status\E$/,@statuses)) {
5971: push(@possroles,$role);
5972: last;
5973: }
5974: }
5975: }
5976: }
5977: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
5978: if (grep(/^\Q$user\E$/,@personnel)) {
5979: if ($curraccess eq 'exc') {
5980: push(@possroles,$role);
5981: }
5982: } elsif ($curraccess eq 'inc') {
5983: push(@possroles,$role);
5984: }
5985: }
5986: }
5987: }
5988: }
5989: }
5990: }
5991: }
5992: }
1.1333 raeburn 5993: unless (ref($description) eq 'HASH') {
5994: if (ref($roles_by_num) eq 'ARRAY') {
5995: my %desc;
5996: map { $desc{$_} = $_; } (@{$roles_by_num});
5997: $description = \%desc;
5998: } else {
5999: $description = {};
6000: }
6001: }
6002: return (\@possroles,$description);
1.1332 raeburn 6003: }
6004:
1.399 www 6005: # ----------------------------------------------------- Frontpage Announcements
6006: #
6007: #
6008:
6009: sub postannounce {
6010: my ($server,$text)=@_;
1.844 albertel 6011: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 6012: unless ($text=~/\w/) { $text=''; }
6013: return &reply('setannounce:'.&escape($text),$server);
6014: }
6015:
6016: sub getannounce {
1.448 albertel 6017:
1.1359 raeburn 6018: if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 6019: my $announcement='';
1.800 albertel 6020: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 6021: close($fh);
1.399 www 6022: if ($announcement=~/\w/) {
6023: return
6024: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 6025: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 6026: } else {
6027: return '';
6028: }
6029: } else {
6030: return '';
6031: }
1.351 www 6032: }
1.353 www 6033:
6034: # ---------------------------------------------------------- Course ID routines
6035: # Deal with domain's nohist_courseid.db files
6036: #
6037:
6038: sub courseidput {
1.921 raeburn 6039: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 6040: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 6041: my $outcome;
6042: if ($caller eq 'timeonly') {
6043: my $cids = '';
6044: foreach my $item (keys(%$storehash)) {
6045: $cids.=&escape($item).'&';
6046: }
6047: $cids=~s/\&$//;
6048: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
6049: $coursehome);
6050: } else {
6051: my $items = '';
6052: foreach my $item (keys(%$storehash)) {
6053: $items.= &escape($item).'='.
6054: &freeze_escape($$storehash{$item}).'&';
6055: }
6056: $items=~s/\&$//;
6057: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
6058: $coursehome);
1.918 raeburn 6059: }
6060: if ($outcome eq 'unknown_cmd') {
6061: my $what;
6062: foreach my $cid (keys(%$storehash)) {
6063: $what .= &escape($cid).'=';
1.921 raeburn 6064: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 6065: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 6066: }
6067: $what =~ s/\:$/&/;
6068: }
6069: $what =~ s/\&$//;
6070: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
6071: } else {
6072: return $outcome;
6073: }
1.353 www 6074: }
6075:
6076: sub courseiddump {
1.921 raeburn 6077: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 6078: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 6079: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1247 raeburn 6080: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1287 raeburn 6081: $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918 raeburn 6082: my $as_hash = 1;
6083: my %returnhash;
6084: if (!$domfilter) { $domfilter=''; }
1.845 albertel 6085: my %libserv = &all_library();
6086: foreach my $tryserver (keys(%libserv)) {
6087: if ( ( $hostidflag == 1
6088: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
6089: || (!defined($hostidflag)) ) {
6090:
1.918 raeburn 6091: if (($domfilter eq '') ||
6092: (&host_domain($tryserver) eq $domfilter)) {
1.1180 droeschl 6093: my $rep;
6094: if (grep { $_ eq $tryserver } current_machine_ids()) {
6095: $rep = LONCAPA::Lond::dump_course_id_handler(
6096: join(":", (&host_domain($tryserver), $sincefilter,
6097: &escape($descfilter), &escape($instcodefilter),
6098: &escape($ownerfilter), &escape($coursefilter),
6099: &escape($typefilter), &escape($regexp_ok),
6100: $as_hash, &escape($selfenrollonly),
6101: &escape($catfilter), $showhidden, $caller,
6102: &escape($cloner), &escape($cc_clone), $cloneonly,
6103: &escape($createdbefore), &escape($createdafter),
1.1287 raeburn 6104: &escape($creationcontext),$domcloner,$hasuniquecode,
6105: $reqcrsdom,&escape($reqinstcode))));
1.1180 droeschl 6106: } else {
6107: $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
6108: $sincefilter.':'.&escape($descfilter).':'.
6109: &escape($instcodefilter).':'.&escape($ownerfilter).
6110: ':'.&escape($coursefilter).':'.&escape($typefilter).
6111: ':'.&escape($regexp_ok).':'.$as_hash.':'.
6112: &escape($selfenrollonly).':'.&escape($catfilter).':'.
6113: $showhidden.':'.$caller.':'.&escape($cloner).':'.
6114: &escape($cc_clone).':'.$cloneonly.':'.
6115: &escape($createdbefore).':'.&escape($createdafter).':'.
1.1287 raeburn 6116: &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
6117: ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1180 droeschl 6118: }
6119:
1.918 raeburn 6120: my @pairs=split(/\&/,$rep);
6121: foreach my $item (@pairs) {
6122: my ($key,$value)=split(/\=/,$item,2);
6123: $key = &unescape($key);
6124: next if ($key =~ /^error: 2 /);
6125: my $result = &thaw_unescape($value);
6126: if (ref($result) eq 'HASH') {
6127: $returnhash{$key}=$result;
6128: } else {
1.921 raeburn 6129: my @responses = split(/:/,$value);
6130: my @items = ('description','inst_code','owner','type');
1.918 raeburn 6131: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 6132: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 6133: }
1.1008 raeburn 6134: }
1.353 www 6135: }
6136: }
6137: }
6138: }
6139: return %returnhash;
6140: }
6141:
1.1055 raeburn 6142: sub courselastaccess {
6143: my ($cdom,$cnum,$hostidref) = @_;
6144: my %returnhash;
6145: if ($cdom && $cnum) {
6146: my $chome = &homeserver($cnum,$cdom);
6147: if ($chome ne 'no_host') {
6148: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
6149: &extract_lastaccess(\%returnhash,$rep);
6150: }
6151: } else {
6152: if (!$cdom) { $cdom=''; }
6153: my %libserv = &all_library();
6154: foreach my $tryserver (keys(%libserv)) {
6155: if (ref($hostidref) eq 'ARRAY') {
6156: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
6157: }
6158: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
6159: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
6160: &extract_lastaccess(\%returnhash,$rep);
6161: }
6162: }
6163: }
6164: return %returnhash;
6165: }
6166:
6167: sub extract_lastaccess {
6168: my ($returnhash,$rep) = @_;
6169: if (ref($returnhash) eq 'HASH') {
1.1531 raeburn 6170: unless ($rep eq 'unknown_cmd' || $rep eq 'no_such_host' ||
1.1055 raeburn 6171: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
6172: $rep eq '') {
6173: my @pairs=split(/\&/,$rep);
6174: foreach my $item (@pairs) {
6175: my ($key,$value)=split(/\=/,$item,2);
6176: $key = &unescape($key);
6177: next if ($key =~ /^error: 2 /);
6178: $returnhash->{$key} = &thaw_unescape($value);
6179: }
6180: }
6181: }
6182: return;
6183: }
6184:
1.658 raeburn 6185: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 6186:
6187: sub dcmailput {
1.685 raeburn 6188: my ($domain,$msgid,$message,$server)=@_;
1.1494 raeburn 6189: my $status = &critical(
1.740 www 6190: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
6191: &escape($message),$server);
1.662 raeburn 6192: return $status;
6193: }
6194:
1.658 raeburn 6195: sub dcmaildump {
6196: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 6197: my %returnhash=();
1.846 albertel 6198:
6199: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 6200: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
6201: &escape($enddate).':';
6202: my @esc_senders=map { &escape($_)} @$senders;
6203: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 6204: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 6205: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 6206: if (($key) && ($value)) {
6207: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 6208: }
6209: }
6210: }
6211: return %returnhash;
6212: }
1.662 raeburn 6213: # ---------------------------------------------------------- Domain roles
6214:
6215: sub get_domain_roles {
6216: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 6217: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 6218: $startdate = '.';
6219: }
1.1018 raeburn 6220: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 6221: $enddate = '.';
6222: }
1.922 raeburn 6223: my $rolelist;
6224: if (ref($roles) eq 'ARRAY') {
1.1219 raeburn 6225: $rolelist = join('&',@{$roles});
1.922 raeburn 6226: }
1.662 raeburn 6227: my %personnel = ();
1.841 albertel 6228:
6229: my %servers = &get_servers($dom,'library');
6230: foreach my $tryserver (keys(%servers)) {
6231: %{$personnel{$tryserver}}=();
6232: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
6233: &escape($startdate).':'.
6234: &escape($enddate).':'.
6235: &escape($rolelist), $tryserver))) {
6236: my ($key,$value) = split(/\=/,$line,2);
6237: if (($key) && ($value)) {
6238: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
6239: }
6240: }
1.662 raeburn 6241: }
6242: return %personnel;
6243: }
1.658 raeburn 6244:
1.1332 raeburn 6245: sub get_active_domroles {
6246: my ($dom,$roles) = @_;
6247: return () unless (ref($roles) eq 'ARRAY');
6248: my $now = time;
6249: my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
6250: my %domroles;
6251: foreach my $server (keys(%dompersonnel)) {
6252: foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
6253: my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
6254: $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
6255: }
6256: }
6257: return %domroles;
6258: }
6259:
1.1057 www 6260: # ----------------------------------------------------------- Interval timing
1.149 www 6261:
1.1153 www 6262: {
6263: # Caches needed for speedup of navmaps
6264: # We don't want to cache this for very long at all (5 seconds at most)
6265: #
6266: # The user for whom we cache
6267: my $cachedkey='';
6268: # The cached times for this user
6269: my %cachedtimes=();
6270: # When this was last done
1.1282 raeburn 6271: my $cachedtime='';
1.1153 www 6272:
6273: sub load_all_first_access {
1.1308 raeburn 6274: my ($uname,$udom,$ignorecache)=@_;
1.1156 www 6275: if (($cachedkey eq $uname.':'.$udom) &&
1.1308 raeburn 6276: (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
6277: (!$ignorecache)) {
1.1154 raeburn 6278: return;
6279: }
6280: $cachedtime=time;
6281: $cachedkey=$uname.':'.$udom;
6282: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153 www 6283: }
6284:
1.504 albertel 6285: sub get_first_access {
1.1308 raeburn 6286: my ($type,$argsymb,$argmap,$ignorecache)=@_;
1.790 albertel 6287: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 6288: if ($argsymb) { $symb=$argsymb; }
6289: my ($map,$id,$res)=&decode_symb($symb);
1.1162 raeburn 6290: if ($argmap) { $map = $argmap; }
1.926 albertel 6291: if ($type eq 'course') {
6292: $res='course';
6293: } elsif ($type eq 'map') {
1.588 albertel 6294: $res=&symbread($map);
6295: } else {
6296: $res=$symb;
6297: }
1.1308 raeburn 6298: &load_all_first_access($uname,$udom,$ignorecache);
1.1153 www 6299: return $cachedtimes{"$courseid\0$res"};
1.504 albertel 6300: }
6301:
6302: sub set_first_access {
1.1162 raeburn 6303: my ($type,$interval)=@_;
1.790 albertel 6304: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 6305: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 6306: if ($type eq 'course') {
6307: $res='course';
6308: } elsif ($type eq 'map') {
1.588 albertel 6309: $res=&symbread($map);
6310: } else {
6311: $res=$symb;
6312: }
1.1153 www 6313: $cachedkey='';
1.1162 raeburn 6314: my $firstaccess=&get_first_access($type,$symb,$map);
1.1386 raeburn 6315: if ($firstaccess) {
6316: &logthis("First access time already set ($firstaccess) when attempting ".
1.1393 raeburn 6317: "to set new value (type: $type, extent: $res) for $uname:$udom ".
6318: "in $courseid");
1.1386 raeburn 6319: return 'already_set';
6320: } else {
1.1162 raeburn 6321: my $start = time;
6322: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
6323: $udom,$uname);
6324: if ($putres eq 'ok') {
6325: &put('timerinterval',{"$courseid\0$res"=>$interval},
6326: $udom,$uname);
6327: &appenv(
6328: {
6329: 'course.'.$courseid.'.firstaccess.'.$res => $start,
6330: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
6331: }
6332: );
1.1365 raeburn 6333: if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
6334: $cachedtimes{"$courseid\0$res"} = $start;
6335: }
1.1386 raeburn 6336: } elsif ($putres ne 'refused') {
6337: &logthis("Result: $putres when attempting to set first access time ".
6338: "(type: $type, extent: $res) for $uname:$udom in $courseid");
1.1162 raeburn 6339: }
6340: return $putres;
1.505 albertel 6341: }
6342: return 'already_set';
1.504 albertel 6343: }
1.1153 www 6344: }
1.1282 raeburn 6345:
1.110 www 6346: # --------------------------------------------- Set Expire Date for Spreadsheet
6347:
6348: sub expirespread {
6349: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 6350: my $cid=$env{'request.course.id'};
1.110 www 6351: if ($cid) {
6352: my $now=time;
6353: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 6354: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
6355: $env{'course.'.$cid.'.num'}.
1.110 www 6356: ':nohist_expirationdates:'.
6357: &escape($key).'='.$now,
1.620 albertel 6358: $env{'course.'.$cid.'.home'})
1.110 www 6359: }
6360: return 'ok';
1.14 www 6361: }
6362:
1.109 www 6363: # ----------------------------------------------------- Devalidate Spreadsheets
6364:
6365: sub devalidate {
1.325 www 6366: my ($symb,$uname,$udom)=@_;
1.620 albertel 6367: my $cid=$env{'request.course.id'};
1.109 www 6368: if ($cid) {
1.391 matthew 6369: # delete the stored spreadsheets for
6370: # - the student level sheet of this user in course's homespace
6371: # - the assessment level sheet for this resource
6372: # for this user in user's homespace
1.553 albertel 6373: # - current conditional state info
1.325 www 6374: my $key=$uname.':'.$udom.':';
1.109 www 6375: my $status=
1.299 matthew 6376: &del('nohist_calculatedsheets',
1.391 matthew 6377: [$key.'studentcalc:'],
1.620 albertel 6378: $env{'course.'.$cid.'.domain'},
6379: $env{'course.'.$cid.'.num'})
1.133 albertel 6380: .' '.
6381: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 6382: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 6383: unless ($status eq 'ok ok') {
6384: &logthis('Could not devalidate spreadsheet '.
1.325 www 6385: $uname.' at '.$udom.' for '.
1.109 www 6386: $symb.': '.$status);
1.133 albertel 6387: }
1.553 albertel 6388: &delenv('user.state.'.$cid);
1.109 www 6389: }
6390: }
6391:
1.265 albertel 6392: sub get_scalar {
6393: my ($string,$end) = @_;
6394: my $value;
6395: if ($$string =~ s/^([^&]*?)($end)/$2/) {
6396: $value = $1;
6397: } elsif ($$string =~ s/^([^&]*?)&//) {
6398: $value = $1;
6399: }
6400: return &unescape($value);
6401: }
6402:
6403: sub array2str {
6404: my (@array) = @_;
6405: my $result=&arrayref2str(\@array);
6406: $result=~s/^__ARRAY_REF__//;
6407: $result=~s/__END_ARRAY_REF__$//;
6408: return $result;
6409: }
6410:
1.204 albertel 6411: sub arrayref2str {
6412: my ($arrayref) = @_;
1.265 albertel 6413: my $result='__ARRAY_REF__';
1.204 albertel 6414: foreach my $elem (@$arrayref) {
1.265 albertel 6415: if(ref($elem) eq 'ARRAY') {
6416: $result.=&arrayref2str($elem).'&';
6417: } elsif(ref($elem) eq 'HASH') {
6418: $result.=&hashref2str($elem).'&';
6419: } elsif(ref($elem)) {
6420: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 6421: } else {
6422: $result.=&escape($elem).'&';
6423: }
6424: }
6425: $result=~s/\&$//;
1.265 albertel 6426: $result .= '__END_ARRAY_REF__';
1.204 albertel 6427: return $result;
6428: }
6429:
1.168 albertel 6430: sub hash2str {
1.204 albertel 6431: my (%hash) = @_;
6432: my $result=&hashref2str(\%hash);
1.265 albertel 6433: $result=~s/^__HASH_REF__//;
6434: $result=~s/__END_HASH_REF__$//;
1.204 albertel 6435: return $result;
6436: }
6437:
6438: sub hashref2str {
6439: my ($hashref)=@_;
1.265 albertel 6440: my $result='__HASH_REF__';
1.800 albertel 6441: foreach my $key (sort(keys(%$hashref))) {
6442: if (ref($key) eq 'ARRAY') {
6443: $result.=&arrayref2str($key).'=';
6444: } elsif (ref($key) eq 'HASH') {
6445: $result.=&hashref2str($key).'=';
6446: } elsif (ref($key)) {
1.265 albertel 6447: $result.='=';
1.800 albertel 6448: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 6449: } else {
1.1132 raeburn 6450: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 6451: }
6452:
1.800 albertel 6453: if(ref($hashref->{$key}) eq 'ARRAY') {
6454: $result.=&arrayref2str($hashref->{$key}).'&';
6455: } elsif(ref($hashref->{$key}) eq 'HASH') {
6456: $result.=&hashref2str($hashref->{$key}).'&';
6457: } elsif(ref($hashref->{$key})) {
1.265 albertel 6458: $result.='&';
1.800 albertel 6459: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 6460: } else {
1.800 albertel 6461: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 6462: }
6463: }
1.168 albertel 6464: $result=~s/\&$//;
1.265 albertel 6465: $result .= '__END_HASH_REF__';
1.168 albertel 6466: return $result;
6467: }
6468:
6469: sub str2hash {
1.265 albertel 6470: my ($string)=@_;
6471: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
6472: return %$hash;
6473: }
6474:
6475: sub str2hashref {
1.168 albertel 6476: my ($string) = @_;
1.265 albertel 6477:
6478: my %hash;
6479:
6480: if($string !~ /^__HASH_REF__/) {
6481: if (! ($string eq '' || !defined($string))) {
6482: $hash{'error'}='Not hash reference';
6483: }
6484: return (\%hash, $string);
6485: }
6486:
6487: $string =~ s/^__HASH_REF__//;
6488:
6489: while($string !~ /^__END_HASH_REF__/) {
6490: #key
6491: my $key='';
6492: if($string =~ /^__HASH_REF__/) {
6493: ($key, $string)=&str2hashref($string);
6494: if(defined($key->{'error'})) {
6495: $hash{'error'}='Bad data';
6496: return (\%hash, $string);
6497: }
6498: } elsif($string =~ /^__ARRAY_REF__/) {
6499: ($key, $string)=&str2arrayref($string);
6500: if($key->[0] eq 'Array reference error') {
6501: $hash{'error'}='Bad data';
6502: return (\%hash, $string);
6503: }
6504: } else {
6505: $string =~ s/^(.*?)=//;
1.267 albertel 6506: $key=&unescape($1);
1.265 albertel 6507: }
6508: $string =~ s/^=//;
6509:
6510: #value
6511: my $value='';
6512: if($string =~ /^__HASH_REF__/) {
6513: ($value, $string)=&str2hashref($string);
6514: if(defined($value->{'error'})) {
6515: $hash{'error'}='Bad data';
6516: return (\%hash, $string);
6517: }
6518: } elsif($string =~ /^__ARRAY_REF__/) {
6519: ($value, $string)=&str2arrayref($string);
6520: if($value->[0] eq 'Array reference error') {
6521: $hash{'error'}='Bad data';
6522: return (\%hash, $string);
6523: }
6524: } else {
6525: $value=&get_scalar(\$string,'__END_HASH_REF__');
6526: }
6527: $string =~ s/^&//;
6528:
6529: $hash{$key}=$value;
1.204 albertel 6530: }
1.265 albertel 6531:
6532: $string =~ s/^__END_HASH_REF__//;
6533:
6534: return (\%hash, $string);
1.204 albertel 6535: }
6536:
6537: sub str2array {
1.265 albertel 6538: my ($string)=@_;
6539: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
6540: return @$array;
6541: }
6542:
6543: sub str2arrayref {
1.204 albertel 6544: my ($string) = @_;
1.265 albertel 6545: my @array;
6546:
6547: if($string !~ /^__ARRAY_REF__/) {
6548: if (! ($string eq '' || !defined($string))) {
6549: $array[0]='Array reference error';
6550: }
6551: return (\@array, $string);
6552: }
6553:
6554: $string =~ s/^__ARRAY_REF__//;
6555:
6556: while($string !~ /^__END_ARRAY_REF__/) {
6557: my $value='';
6558: if($string =~ /^__HASH_REF__/) {
6559: ($value, $string)=&str2hashref($string);
6560: if(defined($value->{'error'})) {
6561: $array[0] ='Array reference error';
6562: return (\@array, $string);
6563: }
6564: } elsif($string =~ /^__ARRAY_REF__/) {
6565: ($value, $string)=&str2arrayref($string);
6566: if($value->[0] eq 'Array reference error') {
6567: $array[0] ='Array reference error';
6568: return (\@array, $string);
6569: }
6570: } else {
6571: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
6572: }
6573: $string =~ s/^&//;
6574:
6575: push(@array, $value);
1.191 harris41 6576: }
1.265 albertel 6577:
6578: $string =~ s/^__END_ARRAY_REF__//;
6579:
6580: return (\@array, $string);
1.168 albertel 6581: }
6582:
1.167 albertel 6583: # -------------------------------------------------------------------Temp Store
6584:
1.168 albertel 6585: sub tmpreset {
6586: my ($symb,$namespace,$domain,$stuname) = @_;
6587: if (!$symb) {
6588: $symb=&symbread();
1.620 albertel 6589: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 6590: }
6591: $symb=escape($symb);
6592:
1.620 albertel 6593: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 6594: $namespace=~s/\//\_/g;
6595: $namespace=~s/\W//g;
6596:
1.620 albertel 6597: if (!$domain) { $domain=$env{'user.domain'}; }
6598: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 6599: if ($domain eq 'public' && $stuname eq 'public') {
1.1434 raeburn 6600: $stuname=&get_requestor_ip();
1.591 albertel 6601: }
1.1117 foxr 6602: my $path=LONCAPA::tempdir();
1.168 albertel 6603: my %hash;
6604: if (tie(%hash,'GDBM_File',
6605: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 6606: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 6607: foreach my $key (keys(%hash)) {
1.180 albertel 6608: if ($key=~ /:$symb/) {
1.168 albertel 6609: delete($hash{$key});
6610: }
6611: }
6612: }
6613: }
6614:
1.167 albertel 6615: sub tmpstore {
1.168 albertel 6616: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
6617:
6618: if (!$symb) {
6619: $symb=&symbread();
1.620 albertel 6620: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 6621: }
6622: $symb=escape($symb);
6623:
6624: if (!$namespace) {
6625: # I don't think we would ever want to store this for a course.
6626: # it seems this will only be used if we don't have a course.
1.620 albertel 6627: #$namespace=$env{'request.course.id'};
1.168 albertel 6628: #if (!$namespace) {
1.620 albertel 6629: $namespace=$env{'request.state'};
1.168 albertel 6630: #}
6631: }
6632: $namespace=~s/\//\_/g;
6633: $namespace=~s/\W//g;
1.620 albertel 6634: if (!$domain) { $domain=$env{'user.domain'}; }
6635: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 6636: if ($domain eq 'public' && $stuname eq 'public') {
1.1434 raeburn 6637: $stuname=&get_requestor_ip();
1.591 albertel 6638: }
1.168 albertel 6639: my $now=time;
6640: my %hash;
1.1117 foxr 6641: my $path=LONCAPA::tempdir();
1.168 albertel 6642: if (tie(%hash,'GDBM_File',
6643: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 6644: &GDBM_WRCREAT(),0640)) {
1.168 albertel 6645: $hash{"version:$symb"}++;
6646: my $version=$hash{"version:$symb"};
6647: my $allkeys='';
6648: foreach my $key (keys(%$storehash)) {
6649: $allkeys.=$key.':';
1.591 albertel 6650: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 6651: }
6652: $hash{"$version:$symb:timestamp"}=$now;
6653: $allkeys.='timestamp';
6654: $hash{"$version:keys:$symb"}=$allkeys;
6655: if (untie(%hash)) {
6656: return 'ok';
6657: } else {
6658: return "error:$!";
6659: }
6660: } else {
6661: return "error:$!";
6662: }
6663: }
1.167 albertel 6664:
1.168 albertel 6665: # -----------------------------------------------------------------Temp Restore
1.167 albertel 6666:
1.168 albertel 6667: sub tmprestore {
6668: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 6669:
1.168 albertel 6670: if (!$symb) {
6671: $symb=&symbread();
1.620 albertel 6672: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 6673: }
6674: $symb=escape($symb);
6675:
1.620 albertel 6676: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 6677:
1.620 albertel 6678: if (!$domain) { $domain=$env{'user.domain'}; }
6679: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 6680: if ($domain eq 'public' && $stuname eq 'public') {
1.1434 raeburn 6681: $stuname=&get_requestor_ip();
1.591 albertel 6682: }
1.168 albertel 6683: my %returnhash;
6684: $namespace=~s/\//\_/g;
6685: $namespace=~s/\W//g;
6686: my %hash;
1.1117 foxr 6687: my $path=LONCAPA::tempdir();
1.168 albertel 6688: if (tie(%hash,'GDBM_File',
6689: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 6690: &GDBM_READER(),0640)) {
1.168 albertel 6691: my $version=$hash{"version:$symb"};
6692: $returnhash{'version'}=$version;
6693: my $scope;
6694: for ($scope=1;$scope<=$version;$scope++) {
6695: my $vkeys=$hash{"$scope:keys:$symb"};
6696: my @keys=split(/:/,$vkeys);
6697: my $key;
6698: $returnhash{"$scope:keys"}=$vkeys;
6699: foreach $key (@keys) {
1.591 albertel 6700: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
6701: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 6702: }
6703: }
1.168 albertel 6704: if (!(untie(%hash))) {
6705: return "error:$!";
6706: }
6707: } else {
6708: return "error:$!";
6709: }
6710: return %returnhash;
1.167 albertel 6711: }
6712:
1.9 www 6713: # ----------------------------------------------------------------------- Store
6714:
6715: sub store {
1.1269 raeburn 6716: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 6717: my $home='';
6718:
1.168 albertel 6719: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 6720:
1.213 www 6721: $symb=&symbclean($symb);
1.122 albertel 6722: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 6723:
1.620 albertel 6724: if (!$domain) { $domain=$env{'user.domain'}; }
6725: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 6726:
6727: &devalidate($symb,$stuname,$domain);
1.109 www 6728:
6729: $symb=escape($symb);
1.187 www 6730: if (!$namespace) {
1.620 albertel 6731: unless ($namespace=$env{'request.course.id'}) {
1.187 www 6732: return '';
6733: }
6734: }
1.620 albertel 6735: if (!$home) { $home=$env{'user.home'}; }
1.447 www 6736:
1.1434 raeburn 6737: $$storehash{'ip'}=&get_requestor_ip();
1.447 www 6738: $$storehash{'host'}=$perlvar{'lonHostID'};
6739:
1.12 www 6740: my $namevalue='';
1.800 albertel 6741: foreach my $key (keys(%$storehash)) {
6742: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 6743: }
1.12 www 6744: $namevalue=~s/\&$//;
1.187 www 6745: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1269 raeburn 6746: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9 www 6747: }
6748:
1.47 www 6749: # -------------------------------------------------------------- Critical Store
6750:
6751: sub cstore {
1.1533 ! raeburn 6752: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 6753: my $home='';
6754:
1.168 albertel 6755: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 6756:
1.1530 raeburn 6757: unless (($symb eq '_feedback') || ($symb eq '_discussion')) {
6758: $symb=&symbclean($symb);
6759: }
1.122 albertel 6760: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 6761:
1.620 albertel 6762: if (!$domain) { $domain=$env{'user.domain'}; }
6763: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 6764:
1.1530 raeburn 6765: unless (($symb eq '_feedback') || ($symb eq '_discussion')) {
6766: &devalidate($symb,$stuname,$domain);
6767: }
1.109 www 6768:
6769: $symb=escape($symb);
1.187 www 6770: if (!$namespace) {
1.620 albertel 6771: unless ($namespace=$env{'request.course.id'}) {
1.187 www 6772: return '';
6773: }
6774: }
1.620 albertel 6775: if (!$home) { $home=$env{'user.home'}; }
1.447 www 6776:
1.1533 ! raeburn 6777: $$storehash{'ip'} = &get_requestor_ip();
1.447 www 6778: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 6779:
1.47 www 6780: my $namevalue='';
1.800 albertel 6781: foreach my $key (keys(%$storehash)) {
6782: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 6783: }
1.47 www 6784: $namevalue=~s/\&$//;
1.1533 ! raeburn 6785: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 6786: return critical
1.1269 raeburn 6787: ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47 www 6788: }
6789:
1.9 www 6790: # --------------------------------------------------------------------- Restore
6791:
6792: sub restore {
1.124 www 6793: my ($symb,$namespace,$domain,$stuname) = @_;
6794: my $home='';
6795:
1.168 albertel 6796: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 6797:
1.122 albertel 6798: if (!$symb) {
1.1224 raeburn 6799: return if ($namespace eq 'courserequests');
6800: unless ($symb=escape(&symbread())) { return ''; }
1.122 albertel 6801: } else {
1.1224 raeburn 6802: unless ($namespace eq 'courserequests') {
6803: $symb=&escape(&symbclean($symb));
6804: }
1.122 albertel 6805: }
1.188 www 6806: if (!$namespace) {
1.620 albertel 6807: unless ($namespace=$env{'request.course.id'}) {
1.188 www 6808: return '';
6809: }
6810: }
1.620 albertel 6811: if (!$domain) { $domain=$env{'user.domain'}; }
6812: if (!$stuname) { $stuname=$env{'user.name'}; }
6813: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 6814: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
6815:
1.12 www 6816: my %returnhash=();
1.800 albertel 6817: foreach my $line (split(/\&/,$answer)) {
6818: my ($name,$value)=split(/\=/,$line);
1.591 albertel 6819: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 6820: }
1.75 www 6821: my $version;
6822: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 6823: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
6824: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 6825: }
1.75 www 6826: }
1.13 www 6827: return %returnhash;
1.34 www 6828: }
6829:
6830: # ---------------------------------------------------------- Course Description
1.1118 foxr 6831: #
6832: #
1.34 www 6833:
6834: sub coursedescription {
1.731 albertel 6835: my ($courseid,$args)=@_;
1.34 www 6836: $courseid=~s/^\///;
1.49 www 6837: $courseid=~s/\_/\//g;
1.34 www 6838: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 6839: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 6840: my $normalid=$cdomain.'_'.$cnum;
6841: # need to always cache even if we get errors otherwise we keep
6842: # trying and trying and trying to get the course description.
6843: my %envhash=();
6844: my %returnhash=();
1.731 albertel 6845:
6846: my $expiretime=600;
6847: if ($env{'request.course.id'} eq $normalid) {
6848: $expiretime=120;
6849: }
6850:
6851: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
6852: if (!$args->{'freshen_cache'}
6853: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
6854: foreach my $key (keys(%env)) {
6855: next if ($key !~ /^\Q$prefix\E(.*)/);
6856: my ($setting) = $1;
6857: $returnhash{$setting} = $env{$key};
6858: }
6859: return %returnhash;
6860: }
6861:
1.1118 foxr 6862: # get the data again
6863:
1.731 albertel 6864: if (!$args->{'one_time'}) {
6865: $envhash{'course.'.$normalid.'.last_cache'}=time;
6866: }
1.811 albertel 6867:
1.34 www 6868: if ($chome ne 'no_host') {
1.302 albertel 6869: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 6870: if (!exists($returnhash{'con_lost'})) {
1.1118 foxr 6871: my $username = $env{'user.name'}; # Defult username
6872: if(defined $args->{'user'}) {
6873: $username = $args->{'user'};
6874: }
1.129 albertel 6875: $returnhash{'home'}= $chome;
6876: $returnhash{'domain'} = $cdomain;
6877: $returnhash{'num'} = $cnum;
1.741 raeburn 6878: if (!defined($returnhash{'type'})) {
6879: $returnhash{'type'} = 'Course';
6880: }
1.130 albertel 6881: while (my ($name,$value) = each %returnhash) {
1.53 www 6882: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 6883: }
1.270 www 6884: $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117 foxr 6885: $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118 foxr 6886: $username.'_'.$cdomain.'_'.$cnum;
1.60 www 6887: $envhash{'course.'.$normalid.'.home'}=$chome;
6888: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
6889: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 6890: }
6891: }
1.731 albertel 6892: if (!$args->{'one_time'}) {
1.949 raeburn 6893: &appenv(\%envhash);
1.731 albertel 6894: }
1.302 albertel 6895: return %returnhash;
1.461 www 6896: }
6897:
1.1080 raeburn 6898: sub update_released_required {
6899: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
6900: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
6901: $cid = $env{'request.course.id'};
6902: $cdom = $env{'course.'.$cid.'.domain'};
6903: $cnum = $env{'course.'.$cid.'.num'};
6904: $chome = $env{'course.'.$cid.'.home'};
6905: }
6906: if ($needsrelease) {
6907: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
6908: my $needsupdate;
6909: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
6910: $needsupdate = 1;
6911: } else {
6912: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
6913: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
6914: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
6915: $needsupdate = 1;
6916: }
6917: }
6918: if ($needsupdate) {
6919: my %needshash = (
6920: 'internal.releaserequired' => $needsrelease,
6921: );
6922: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
6923: if ($putresult eq 'ok') {
6924: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
6925: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
6926: if (ref($crsinfo{$cid}) eq 'HASH') {
6927: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
6928: &courseidput($cdom,\%crsinfo,$chome,'notime');
6929: }
6930: }
6931: }
6932: }
6933: return;
6934: }
6935:
1.461 www 6936: # -------------------------------------------------See if a user is privileged
6937:
6938: sub privileged {
1.1219 raeburn 6939: my ($username,$domain,$possdomains,$possroles)=@_;
1.1170 droeschl 6940: my $now = time;
1.1219 raeburn 6941: my $roles;
6942: if (ref($possroles) eq 'ARRAY') {
6943: $roles = $possroles;
6944: } else {
6945: $roles = ['dc','su'];
6946: }
6947: if (ref($possdomains) eq 'ARRAY') {
6948: my %privileged = &privileged_by_domain($possdomains,$roles);
6949: foreach my $dom (@{$possdomains}) {
6950: if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
6951: (ref($privileged{$dom}) eq 'HASH')) {
6952: foreach my $role (@{$roles}) {
6953: if (ref($privileged{$dom}{$role}) eq 'HASH') {
6954: if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
6955: my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
6956: return 1 unless (($end && $end < $now) ||
6957: ($start && $start > $now));
6958: }
6959: }
6960: }
6961: }
6962: }
6963: } else {
6964: my %rolesdump = &dump("roles", $domain, $username) or return 0;
6965: my $now = time;
1.1170 droeschl 6966:
1.1275 musolffc 6967: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170 droeschl 6968: my ($trole, $tend, $tstart) = split(/_/, $role);
1.1219 raeburn 6969: if (grep(/^\Q$trole\E$/,@{$roles})) {
1.1170 droeschl 6970: return 1 unless ($tend && $tend < $now)
1.1219 raeburn 6971: or ($tstart && $tstart > $now);
1.1170 droeschl 6972: }
1.1219 raeburn 6973: }
6974: }
6975: return 0;
6976: }
1.1170 droeschl 6977:
1.1219 raeburn 6978: sub privileged_by_domain {
6979: my ($domains,$roles) = @_;
6980: my %privileged = ();
6981: my $cachetime = 60*60*24;
6982: my $now = time;
6983: unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
6984: return %privileged;
6985: }
6986: foreach my $dom (@{$domains}) {
6987: next if (ref($privileged{$dom}) eq 'HASH');
6988: my $needroles;
6989: foreach my $role (@{$roles}) {
6990: my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
6991: if (defined($cached)) {
6992: if (ref($result) eq 'HASH') {
6993: $privileged{$dom}{$role} = $result;
6994: }
6995: } else {
6996: $needroles = 1;
6997: }
6998: }
6999: if ($needroles) {
7000: my %dompersonnel = &get_domain_roles($dom,$roles);
7001: $privileged{$dom} = {};
7002: foreach my $server (keys(%dompersonnel)) {
7003: if (ref($dompersonnel{$server}) eq 'HASH') {
7004: foreach my $item (keys(%{$dompersonnel{$server}})) {
7005: my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
7006: my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
7007: next if ($end && $end < $now);
7008: $privileged{$dom}{$trole}{$uname.':'.$udom} =
7009: $dompersonnel{$server}{$item};
7010: }
7011: }
7012: }
7013: if (ref($privileged{$dom}) eq 'HASH') {
7014: foreach my $role (@{$roles}) {
7015: if (ref($privileged{$dom}{$role}) eq 'HASH') {
7016: &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
7017: } else {
7018: my %hash = ();
7019: &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
7020: }
7021: }
7022: }
7023: }
7024: }
7025: return %privileged;
1.9 www 7026: }
1.1 albertel 7027:
1.103 harris41 7028: # -------------------------------------------------------- Get user privileges
1.11 www 7029:
7030: sub rolesinit {
1.1169 droeschl 7031: my ($domain, $username) = @_;
7032: my %userroles = ('user.login.time' => time);
7033: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
7034:
7035: # firstaccess and timerinterval are related to timed maps/resources.
7036: # also, blocking can be triggered by an activating timer
7037: # it's saved in the user's %env.
7038: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
7039: my %timerinterval = &dump('timerinterval', $domain, $username);
7040: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
1.1517 raeburn 7041: %timerintchk, %timerintenv, %coauthorenv);
1.1169 droeschl 7042:
1.1162 raeburn 7043: foreach my $key (keys(%firstaccess)) {
1.1169 droeschl 7044: my ($cid, $rest) = split(/\0/, $key);
1.1162 raeburn 7045: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
7046: }
1.1169 droeschl 7047:
1.1162 raeburn 7048: foreach my $key (keys(%timerinterval)) {
7049: my ($cid,$rest) = split(/\0/,$key);
7050: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
7051: }
1.1169 droeschl 7052:
1.11 www 7053: my %allroles=();
1.1162 raeburn 7054: my %allgroups=();
1.1517 raeburn 7055: my %gotcoauconfig=();
1.1524 raeburn 7056: my %domdefaults=();
1.11 www 7057:
1.1274 raeburn 7058: for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169 droeschl 7059: my $role = $rolesdump{$area};
7060: $area =~ s/\_\w\w$//;
7061:
7062: my ($trole, $tend, $tstart, $group_privs);
7063:
7064: if ($role =~ /^cr/) {
7065: # Custom role, defined by a user
7066: # e.g., user.role.cr/msu/smith/mynewrole
7067: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
7068: $trole = $1;
7069: ($tend, $tstart) = split('_', $2);
7070: } else {
7071: $trole = $role;
7072: }
7073: } elsif ($role =~ m|^gr/|) {
7074: # Role of member in a group, defined within a course/community
7075: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
7076: ($trole, $tend, $tstart) = split(/_/, $role);
7077: next if $tstart eq '-1';
7078: ($trole, $group_privs) = split(/\//, $trole);
7079: $group_privs = &unescape($group_privs);
7080: } else {
7081: # Just a normal role, defined in roles.tab
7082: ($trole, $tend, $tstart) = split(/_/,$role);
7083: }
7084:
7085: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
7086: $username);
7087: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
7088:
7089: # role expired or not available yet?
7090: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
7091: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
7092:
7093: next if $area eq '' or $trole eq '';
7094:
7095: my $spec = "$trole.$area";
7096: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
7097:
7098: if ($trole =~ /^cr\//) {
7099: # Custom role, defined by a user
7100: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
7101: } elsif ($trole eq 'gr') {
7102: # Role of a member in a group, defined within a course/community
7103: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
7104: next;
7105: } else {
7106: # Normal role, defined in roles.tab
7107: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.1517 raeburn 7108: if (($trole eq 'ca') || ($trole eq 'aa')) {
7109: (undef,my ($audom,$auname)) = split(/\//,$area);
7110: unless ($gotcoauconfig{$area}) {
7111: my @ca_settings = ('authoreditors','coauthorlist','coauthoroptin');
7112: my %info = &userenvironment($audom,$auname,@ca_settings);
7113: $gotcoauconfig{$area} = 1;
7114: foreach my $item (@ca_settings) {
7115: if (exists($info{$item})) {
1.1519 raeburn 7116: my $name = $item;
7117: if ($item eq 'authoreditors') {
7118: $name = 'editors';
1.1524 raeburn 7119: unless ($info{'authoreditors'}) {
7120: my %domdefs;
7121: if (ref($domdefaults{$audom}) eq 'HASH') {
7122: %domdefs = %{$domdefaults{$audom}};
7123: } else {
7124: %domdefs = &get_domain_defaults($audom);
7125: $domdefaults{$audom} = \%domdefs;
7126: }
7127: if ($domdefs{$name} ne '') {
7128: $info{'authoreditors'} = $domdefs{$name};
7129: } else {
7130: $info{'authoreditors'} = 'edit,xml';
7131: }
7132: }
1.1519 raeburn 7133: }
7134: $coauthorenv{"environment.internal.$name.$area"} = $info{$item};
1.1517 raeburn 7135: }
7136: }
7137: }
7138: }
1.1169 droeschl 7139: }
7140:
7141: my $cid = $tdomain.'_'.$trest;
7142: unless ($firstaccchk{$cid}) {
7143: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
7144: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
7145: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
7146: $coursetimerstarts{$cid}{$item};
7147: }
7148: }
7149: $firstaccchk{$cid} = 1;
7150: }
7151: unless ($timerintchk{$cid}) {
7152: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
7153: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
7154: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
7155: $coursetimerintervals{$cid}{$item};
1.1162 raeburn 7156: }
1.12 www 7157: }
1.1169 droeschl 7158: $timerintchk{$cid} = 1;
1.191 harris41 7159: }
1.11 www 7160: }
1.1169 droeschl 7161:
1.1341 raeburn 7162: @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
7163: \%allroles, \%allgroups);
1.1169 droeschl 7164: $env{'user.adv'} = $userroles{'user.adv'};
1.1341 raeburn 7165: $env{'user.rar'} = $userroles{'user.rar'};
1.1169 droeschl 7166:
1.1517 raeburn 7167: return (\%userroles,\%firstaccenv,\%timerintenv,\%coauthorenv);
1.11 www 7168: }
7169:
1.567 raeburn 7170: sub set_arearole {
1.1215 raeburn 7171: my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
7172: unless ($nolog) {
1.567 raeburn 7173: # log the associated role with the area
1.1215 raeburn 7174: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
7175: }
1.743 albertel 7176: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 7177: }
7178:
7179: sub custom_roleprivs {
7180: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
7181: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1250 raeburn 7182: my $homsvr = &homeserver($rauthor,$rdomain);
1.838 albertel 7183: if (&hostname($homsvr) ne '') {
1.567 raeburn 7184: my ($rdummy,$roledef)=
7185: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
7186: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
7187: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
7188: if (defined($syspriv)) {
1.1043 raeburn 7189: if ($trest =~ /^$match_community$/) {
7190: $syspriv =~ s/bre\&S//;
7191: }
1.567 raeburn 7192: $$allroles{'cm./'}.=':'.$syspriv;
7193: $$allroles{$spec.'./'}.=':'.$syspriv;
7194: }
7195: if ($tdomain ne '') {
7196: if (defined($dompriv)) {
7197: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
7198: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
7199: }
7200: if (($trest ne '') && (defined($coursepriv))) {
1.1332 raeburn 7201: if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
7202: my $rolename = $1;
7203: $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
7204: }
1.567 raeburn 7205: $$allroles{'cm.'.$area}.=':'.$coursepriv;
7206: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
7207: }
7208: }
7209: }
7210: }
7211: }
7212:
1.1332 raeburn 7213: sub course_adhocrole_privs {
7214: my ($rolename,$cdom,$cnum,$coursepriv) = @_;
7215: my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
7216: if ($overrides{"internal.adhocpriv.$rolename"}) {
7217: my (%currprivs,%storeprivs);
7218: foreach my $item (split(/:/,$coursepriv)) {
7219: my ($priv,$restrict) = split(/\&/,$item);
7220: $currprivs{$priv} = $restrict;
7221: }
7222: my (%possadd,%possremove,%full);
7223: foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
7224: my ($priv,$restrict)=split(/\&/,$item);
7225: $full{$priv} = $restrict;
7226: }
7227: foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
1.1490 raeburn 7228: next if ($item eq '');
7229: my ($rule,$rest) = split(/=/,$item);
7230: next unless (($rule eq 'off') || ($rule eq 'on'));
7231: foreach my $priv (split(/:/,$rest)) {
7232: if ($priv ne '') {
7233: if ($rule eq 'off') {
7234: $possremove{$priv} = 1;
7235: } else {
7236: $possadd{$priv} = 1;
7237: }
7238: }
7239: }
7240: }
7241: foreach my $priv (sort(keys(%full))) {
7242: if (exists($currprivs{$priv})) {
7243: unless (exists($possremove{$priv})) {
7244: $storeprivs{$priv} = $currprivs{$priv};
7245: }
7246: } elsif (exists($possadd{$priv})) {
7247: $storeprivs{$priv} = $full{$priv};
7248: }
7249: }
7250: $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
7251: }
7252: return $coursepriv;
1.1332 raeburn 7253: }
7254:
1.678 raeburn 7255: sub group_roleprivs {
7256: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
7257: my $access = 1;
7258: my $now = time;
7259: if (($tend!=0) && ($tend<$now)) { $access = 0; }
7260: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
7261: if ($access) {
1.811 albertel 7262: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 7263: $$allgroups{$course}{$group} .=':'.$group_privs;
7264: }
7265: }
1.567 raeburn 7266:
7267: sub standard_roleprivs {
7268: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
7269: if (defined($pr{$trole.':s'})) {
7270: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
7271: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
7272: }
7273: if ($tdomain ne '') {
7274: if (defined($pr{$trole.':d'})) {
7275: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
7276: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
7277: }
7278: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
7279: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
7280: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
7281: }
7282: }
7283: }
7284:
7285: sub set_userprivs {
1.1064 raeburn 7286: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 7287: my $author=0;
7288: my $adv=0;
1.1341 raeburn 7289: my $rar=0;
1.678 raeburn 7290: my %grouproles = ();
7291: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 7292: my @groupkeys;
1.1000 raeburn 7293: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 7294: push(@groupkeys,$role);
7295: }
7296: if (ref($groups_roles) eq 'HASH') {
7297: foreach my $key (keys(%{$groups_roles})) {
7298: unless (grep(/^\Q$key\E$/,@groupkeys)) {
7299: push(@groupkeys,$key);
7300: }
7301: }
7302: }
7303: if (@groupkeys > 0) {
7304: foreach my $role (@groupkeys) {
7305: my ($trole,$area,$sec,$extendedarea);
7306: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
7307: $trole = $1;
7308: $area = $2;
7309: $sec = $3;
7310: $extendedarea = $area.$sec;
7311: if (exists($$allgroups{$area})) {
7312: foreach my $group (keys(%{$$allgroups{$area}})) {
7313: my $spec = $trole.'.'.$extendedarea;
7314: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 7315: $$allgroups{$area}{$group};
1.1064 raeburn 7316: }
1.678 raeburn 7317: }
7318: }
7319: }
7320: }
7321: }
1.800 albertel 7322: foreach my $group (keys(%grouproles)) {
7323: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 7324: }
1.800 albertel 7325: foreach my $role (keys(%{$allroles})) {
7326: my %thesepriv;
1.941 raeburn 7327: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 7328: foreach my $item (split(/:/,$$allroles{$role})) {
7329: if ($item ne '') {
7330: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 7331: if ($restrictions eq '') {
7332: $thesepriv{$privilege}='F';
7333: } elsif ($thesepriv{$privilege} ne 'F') {
7334: $thesepriv{$privilege}.=$restrictions;
7335: }
7336: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1341 raeburn 7337: if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567 raeburn 7338: }
7339: }
7340: my $thesestr='';
1.1104 raeburn 7341: foreach my $priv (sort(keys(%thesepriv))) {
1.800 albertel 7342: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
7343: }
7344: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 7345: }
1.1341 raeburn 7346: return ($author,$adv,$rar);
1.567 raeburn 7347: }
7348:
1.994 raeburn 7349: sub role_status {
1.1104 raeburn 7350: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 7351: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1250 raeburn 7352: my ($one,$two) = split(m{\./},$rolekey,2);
7353: (undef,undef,$$role) = split(/\./,$one,3);
1.994 raeburn 7354: unless (!defined($$role) || $$role eq '') {
1.1251 raeburn 7355: $$where = '/'.$two;
1.994 raeburn 7356: $$trolecode=$$role.'.'.$$where;
7357: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
7358: $$tstatus='is';
1.1104 raeburn 7359: if ($$tstart && $$tstart>$update) {
1.994 raeburn 7360: $$tstatus='future';
1.1034 raeburn 7361: if ($$tstart<$now) {
7362: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 7363: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 7364: my (%allroles,%allgroups,$group_privs,
7365: %groups_roles,@rolecodes);
1.1002 raeburn 7366: my %userroles = (
7367: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
7368: );
1.1064 raeburn 7369: @rolecodes = ('cm');
1.1002 raeburn 7370: my $spec=$$role.'.'.$$where;
7371: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
7372: if ($$role =~ /^cr\//) {
7373: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 7374: push(@rolecodes,'cr');
1.1002 raeburn 7375: } elsif ($$role eq 'gr') {
1.1064 raeburn 7376: push(@rolecodes,$$role);
1.1002 raeburn 7377: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
7378: $env{'user.name'});
1.1064 raeburn 7379: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 7380: (undef,my $group_privs) = split(/\//,$trole);
7381: $group_privs = &unescape($group_privs);
7382: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 7383: 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 7384: &get_groups_roles($tdomain,$trest,
7385: \%course_roles,\@rolecodes,
7386: \%groups_roles);
1.1002 raeburn 7387: } else {
1.1064 raeburn 7388: push(@rolecodes,$$role);
1.1002 raeburn 7389: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
7390: }
1.1341 raeburn 7391: my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
7392: \%groups_roles);
1.1064 raeburn 7393: &appenv(\%userroles,\@rolecodes);
1.1342 raeburn 7394: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002 raeburn 7395: }
7396: }
1.1034 raeburn 7397: $$tstatus = 'is';
1.1002 raeburn 7398: }
1.994 raeburn 7399: }
7400: if ($$tend) {
1.1104 raeburn 7401: if ($$tend<$update) {
1.994 raeburn 7402: $$tstatus='expired';
7403: } elsif ($$tend<$now) {
7404: $$tstatus='will_not';
7405: }
7406: }
7407: }
7408: }
7409: }
7410:
1.1104 raeburn 7411: sub get_groups_roles {
7412: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
7413: return unless((ref($cdom_courseroles) eq 'HASH') &&
7414: (ref($rolecodes) eq 'ARRAY') &&
7415: (ref($groups_roles) eq 'HASH'));
7416: if (keys(%{$cdom_courseroles}) > 0) {
7417: my ($cnum) = ($rest =~ /^($match_courseid)/);
7418: if ($cdom ne '' && $cnum ne '') {
7419: foreach my $key (keys(%{$cdom_courseroles})) {
7420: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
7421: my $crsrole = $1;
7422: my $crssec = $2;
7423: if ($crsrole =~ /^cr/) {
7424: unless (grep(/^cr$/,@{$rolecodes})) {
7425: push(@{$rolecodes},'cr');
7426: }
7427: } else {
7428: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
7429: push(@{$rolecodes},$crsrole);
7430: }
7431: }
7432: my $rolekey = "$crsrole./$cdom/$cnum";
7433: if ($crssec ne '') {
7434: $rolekey .= "/$crssec";
7435: }
7436: $rolekey .= './';
7437: $groups_roles->{$rolekey} = $rolecodes;
7438: }
7439: }
7440: }
7441: }
7442: return;
7443: }
7444:
7445: sub delete_env_groupprivs {
7446: my ($where,$courseroles,$possroles) = @_;
7447: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
7448: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
7449: unless (ref($courseroles->{$udom}) eq 'HASH') {
7450: %{$courseroles->{$udom}} =
7451: &get_my_roles('','','userroles',['active'],
7452: $possroles,[$udom],1);
7453: }
7454: if (ref($courseroles->{$udom}) eq 'HASH') {
7455: foreach my $item (keys(%{$courseroles->{$udom}})) {
7456: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
7457: my $area = '/'.$cdom.'/'.$cnum;
7458: my $privkey = "user.priv.$crsrole.$area";
7459: if ($crssec ne '') {
7460: $privkey .= '/'.$crssec;
7461: }
7462: $privkey .= ".$area/$group";
7463: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
7464: }
7465: }
7466: return;
7467: }
7468:
1.994 raeburn 7469: sub check_adhoc_privs {
1.1329 raeburn 7470: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994 raeburn 7471: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1329 raeburn 7472: if ($sec) {
7473: $cckey .= '/'.$sec;
7474: }
1.1185 raeburn 7475: my $setprivs;
1.994 raeburn 7476: if ($env{$cckey}) {
7477: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104 raeburn 7478: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 7479: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1329 raeburn 7480: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185 raeburn 7481: $setprivs = 1;
1.994 raeburn 7482: }
7483: } else {
1.1330 raeburn 7484: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185 raeburn 7485: $setprivs = 1;
1.994 raeburn 7486: }
1.1185 raeburn 7487: return $setprivs;
1.994 raeburn 7488: }
7489:
7490: sub set_adhoc_privileges {
1.1326 raeburn 7491: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1329 raeburn 7492: my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994 raeburn 7493: my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1329 raeburn 7494: if ($sec ne '') {
7495: $area .= '/'.$sec;
7496: }
1.994 raeburn 7497: my $spec = $role.'.'.$area;
7498: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1215 raeburn 7499: $env{'user.name'},1);
1.1326 raeburn 7500: my %rolehash = ();
1.1332 raeburn 7501: if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
7502: my $rolename = $1;
1.1326 raeburn 7503: &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1332 raeburn 7504: my %domdef = &get_domain_defaults($dcdom);
7505: if (ref($domdef{'adhocroles'}) eq 'HASH') {
7506: if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
7507: &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
7508: }
7509: }
1.1326 raeburn 7510: } else {
7511: &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
7512: }
1.1341 raeburn 7513: my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994 raeburn 7514: &appenv(\%userroles,[$role,'cm']);
1.1342 raeburn 7515: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1402 raeburn 7516: unless (($caller eq 'constructaccess' && $env{'request.course.id'}) ||
7517: ($caller eq 'tiny')) {
1.1088 raeburn 7518: &appenv( {'request.role' => $spec,
7519: 'request.role.domain' => $dcdom,
1.1332 raeburn 7520: 'request.course.sec' => $sec,
1.1088 raeburn 7521: }
7522: );
7523: my $tadv=0;
7524: if (&allowed('adv') eq 'F') { $tadv=1; }
7525: &appenv({'request.role.adv' => $tadv});
7526: }
1.994 raeburn 7527: }
7528:
1.12 www 7529: # --------------------------------------------------------------- get interface
7530:
7531: sub get {
1.131 albertel 7532: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 7533: my $items='';
1.800 albertel 7534: foreach my $item (@$storearr) {
7535: $items.=&escape($item).'&';
1.191 harris41 7536: }
1.12 www 7537: $items=~s/\&$//;
1.620 albertel 7538: if (!$udomain) { $udomain=$env{'user.domain'}; }
7539: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 7540: my $uhome=&homeserver($uname,$udomain);
7541:
1.133 albertel 7542: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 7543: my @pairs=split(/\&/,$rep);
1.273 albertel 7544: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
7545: return @pairs;
7546: }
1.15 www 7547: my %returnhash=();
1.42 www 7548: my $i=0;
1.800 albertel 7549: foreach my $item (@$storearr) {
7550: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 7551: $i++;
1.191 harris41 7552: }
1.15 www 7553: return %returnhash;
1.27 www 7554: }
7555:
7556: # --------------------------------------------------------------- del interface
7557:
7558: sub del {
1.133 albertel 7559: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 7560: my $items='';
1.800 albertel 7561: foreach my $item (@$storearr) {
7562: $items.=&escape($item).'&';
1.191 harris41 7563: }
1.984 neumanie 7564:
1.27 www 7565: $items=~s/\&$//;
1.620 albertel 7566: if (!$udomain) { $udomain=$env{'user.domain'}; }
7567: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 7568: my $uhome=&homeserver($uname,$udomain);
7569: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 7570: }
7571:
7572: # -------------------------------------------------------------- dump interface
7573:
1.1180 droeschl 7574: sub unserialize {
7575: my ($rep, $escapedkeys) = @_;
7576:
7577: return {} if $rep =~ /^error/;
7578:
7579: my %returnhash=();
1.1252 raeburn 7580: foreach my $item (split(/\&/,$rep)) {
1.1180 droeschl 7581: my ($key, $value) = split(/=/, $item, 2);
7582: $key = unescape($key) unless $escapedkeys;
7583: next if $key =~ /^error: 2 /;
1.1252 raeburn 7584: $returnhash{$key} = &thaw_unescape($value);
1.1180 droeschl 7585: }
7586: #return %returnhash;
7587: return \%returnhash;
7588: }
7589:
7590: # see Lond::dump_with_regexp
7591: # if $escapedkeys hash keys won't get unescaped.
1.15 www 7592: sub dump {
1.1462 raeburn 7593: my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys,$encrypt)=@_;
1.755 albertel 7594: if (!$udomain) { $udomain=$env{'user.domain'}; }
7595: if (!$uname) { $uname=$env{'user.name'}; }
7596: my $uhome=&homeserver($uname,$udomain);
1.1167 droeschl 7597:
1.1266 raeburn 7598: if ($regexp) {
7599: $regexp=&escape($regexp);
7600: } else {
7601: $regexp='.';
7602: }
1.1180 droeschl 7603: if (grep { $_ eq $uhome } current_machine_ids()) {
7604: # user is hosted on this machine
1.1266 raeburn 7605: my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
1.1226 raeburn 7606: $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1180 droeschl 7607: return %{unserialize($reply, $escapedkeys)};
7608: }
1.1462 raeburn 7609: my $rep;
7610: if ($encrypt) {
7611: $rep=&reply("encrypt:edump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.1463 raeburn 7612: } else {
1.1462 raeburn 7613: $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
7614: }
1.755 albertel 7615: my @pairs=split(/\&/,$rep);
7616: my %returnhash=();
1.1098 foxr 7617: if (!($rep =~ /^error/ )) {
7618: foreach my $item (@pairs) {
7619: my ($key,$value)=split(/=/,$item,2);
1.1180 droeschl 7620: $key = unescape($key) unless $escapedkeys;
7621: #$key = &unescape($key);
1.1098 foxr 7622: next if ($key =~ /^error: 2 /);
7623: $returnhash{$key}=&thaw_unescape($value);
7624: }
1.755 albertel 7625: }
7626: return %returnhash;
1.407 www 7627: }
7628:
1.1098 foxr 7629:
1.717 albertel 7630: # --------------------------------------------------------- dumpstore interface
7631:
7632: sub dumpstore {
7633: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180 droeschl 7634: # same as dump but keys must be escaped. They may contain colon separated
7635: # lists of values that may themself contain colons (e.g. symbs).
7636: return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717 albertel 7637: }
7638:
1.407 www 7639: # -------------------------------------------------------------- keys interface
7640:
7641: sub getkeys {
7642: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 7643: if (!$udomain) { $udomain=$env{'user.domain'}; }
7644: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 7645: my $uhome=&homeserver($uname,$udomain);
7646: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
7647: my @keyarray=();
1.800 albertel 7648: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 7649: next if ($key =~ /^error: 2 /);
1.800 albertel 7650: push(@keyarray,&unescape($key));
1.407 www 7651: }
7652: return @keyarray;
1.318 matthew 7653: }
7654:
1.319 matthew 7655: # --------------------------------------------------------------- currentdump
7656: sub currentdump {
1.328 matthew 7657: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 7658: $courseid = $env{'request.course.id'} if (! defined($courseid));
7659: $sdom = $env{'user.domain'} if (! defined($sdom));
7660: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 7661: my $uhome = &homeserver($sname,$sdom);
1.1180 droeschl 7662: my $rep;
7663:
7664: if (grep { $_ eq $uhome } current_machine_ids()) {
7665: $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
7666: $courseid)));
7667: } else {
7668: $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
7669: }
7670:
1.318 matthew 7671: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 7672: #
1.318 matthew 7673: my %returnhash=();
1.319 matthew 7674: #
1.1343 raeburn 7675: if ($rep eq 'unknown_cmd') {
1.319 matthew 7676: # an old lond will not know currentdump
7677: # Do a dump and make it look like a currentdump
1.822 albertel 7678: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 7679: return if ($tmp[0] =~ /^(error:|no_such_host)/);
7680: my %hash = @tmp;
7681: @tmp=();
1.424 matthew 7682: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 7683: } else {
7684: my @pairs=split(/\&/,$rep);
1.800 albertel 7685: foreach my $pair (@pairs) {
7686: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 7687: my ($symb,$param) = split(/:/,$key);
7688: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 7689: &thaw_unescape($value);
1.319 matthew 7690: }
1.191 harris41 7691: }
1.12 www 7692: return %returnhash;
1.424 matthew 7693: }
7694:
7695: sub convert_dump_to_currentdump{
7696: my %hash = %{shift()};
7697: my %returnhash;
7698: # Code ripped from lond, essentially. The only difference
7699: # here is the unescaping done by lonnet::dump(). Conceivably
7700: # we might run in to problems with parameter names =~ /^v\./
7701: while (my ($key,$value) = each(%hash)) {
7702: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 7703: $symb = &unescape($symb);
7704: $param = &unescape($param);
1.424 matthew 7705: next if ($v eq 'version' || $symb eq 'keys');
7706: next if (exists($returnhash{$symb}) &&
7707: exists($returnhash{$symb}->{$param}) &&
7708: $returnhash{$symb}->{'v.'.$param} > $v);
7709: $returnhash{$symb}->{$param}=$value;
7710: $returnhash{$symb}->{'v.'.$param}=$v;
7711: }
7712: #
7713: # Remove all of the keys in the hashes which keep track of
7714: # the version of the parameter.
7715: while (my ($symb,$param_hash) = each(%returnhash)) {
7716: # use a foreach because we are going to delete from the hash.
7717: foreach my $key (keys(%$param_hash)) {
7718: delete($param_hash->{$key}) if ($key =~ /^v\./);
7719: }
7720: }
7721: return \%returnhash;
1.12 www 7722: }
7723:
1.627 albertel 7724: # ------------------------------------------------------ critical inc interface
7725:
7726: sub cinc {
7727: return &inc(@_,'critical');
7728: }
7729:
1.449 matthew 7730: # --------------------------------------------------------------- inc interface
7731:
7732: sub inc {
1.627 albertel 7733: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 7734: if (!$udomain) { $udomain=$env{'user.domain'}; }
7735: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 7736: my $uhome=&homeserver($uname,$udomain);
7737: my $items='';
7738: if (! ref($store)) {
7739: # got a single value, so use that instead
7740: $items = &escape($store).'=&';
7741: } elsif (ref($store) eq 'SCALAR') {
7742: $items = &escape($$store).'=&';
7743: } elsif (ref($store) eq 'ARRAY') {
7744: $items = join('=&',map {&escape($_);} @{$store});
7745: } elsif (ref($store) eq 'HASH') {
7746: while (my($key,$value) = each(%{$store})) {
7747: $items.= &escape($key).'='.&escape($value).'&';
7748: }
7749: }
7750: $items=~s/\&$//;
1.627 albertel 7751: if ($critical) {
7752: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
7753: } else {
7754: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
7755: }
1.449 matthew 7756: }
7757:
1.12 www 7758: # --------------------------------------------------------------- put interface
7759:
7760: sub put {
1.1462 raeburn 7761: my ($namespace,$storehash,$udomain,$uname,$encrypt)=@_;
1.620 albertel 7762: if (!$udomain) { $udomain=$env{'user.domain'}; }
7763: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 7764: my $uhome=&homeserver($uname,$udomain);
1.12 www 7765: my $items='';
1.800 albertel 7766: foreach my $item (keys(%$storehash)) {
7767: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 7768: }
1.12 www 7769: $items=~s/\&$//;
1.1462 raeburn 7770: if ($encrypt) {
7771: return &reply("encrypt:put:$udomain:$uname:$namespace:$items",$uhome);
7772: } else {
7773: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
7774: }
1.47 www 7775: }
7776:
1.631 albertel 7777: # ------------------------------------------------------------ newput interface
7778:
7779: sub newput {
7780: my ($namespace,$storehash,$udomain,$uname)=@_;
7781: if (!$udomain) { $udomain=$env{'user.domain'}; }
7782: if (!$uname) { $uname=$env{'user.name'}; }
7783: my $uhome=&homeserver($uname,$udomain);
7784: my $items='';
7785: foreach my $key (keys(%$storehash)) {
7786: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
7787: }
7788: $items=~s/\&$//;
7789: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
7790: }
7791:
7792: # --------------------------------------------------------- putstore interface
7793:
1.524 raeburn 7794: sub putstore {
1.1269 raeburn 7795: my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620 albertel 7796: if (!$udomain) { $udomain=$env{'user.domain'}; }
7797: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 7798: my $uhome=&homeserver($uname,$udomain);
7799: my $items='';
1.715 albertel 7800: foreach my $key (keys(%$storehash)) {
7801: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 7802: }
1.715 albertel 7803: $items=~s/\&$//;
1.716 albertel 7804: my $esc_symb=&escape($symb);
7805: my $esc_v=&escape($version);
1.715 albertel 7806: my $reply =
1.716 albertel 7807: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 7808: $uhome);
1.1269 raeburn 7809: if (($tolog) && ($reply eq 'ok')) {
7810: my $namevalue='';
7811: foreach my $key (keys(%{$storehash})) {
7812: $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
7813: }
1.1434 raeburn 7814: my $ip = &get_requestor_ip();
7815: $namevalue .= 'ip='.&escape($ip).
1.1269 raeburn 7816: '&host='.&escape($perlvar{'lonHostID'}).
7817: '&version='.$esc_v.
7818: '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
1.1494 raeburn 7819: &courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
1.1269 raeburn 7820: }
1.715 albertel 7821: if ($reply eq 'unknown_cmd') {
1.716 albertel 7822: # gfall back to way things use to be done
1.715 albertel 7823: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
7824: $uname);
1.524 raeburn 7825: }
1.715 albertel 7826: return $reply;
7827: }
7828:
7829: sub old_putstore {
1.716 albertel 7830: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
7831: if (!$udomain) { $udomain=$env{'user.domain'}; }
7832: if (!$uname) { $uname=$env{'user.name'}; }
7833: my $uhome=&homeserver($uname,$udomain);
7834: my %newstorehash;
1.800 albertel 7835: foreach my $item (keys(%$storehash)) {
7836: my $key = $version.':'.&escape($symb).':'.$item;
7837: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 7838: }
7839: my $items='';
7840: my %allitems = ();
1.800 albertel 7841: foreach my $item (keys(%newstorehash)) {
7842: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 7843: my $key = $1.':keys:'.$2;
7844: $allitems{$key} .= $3.':';
7845: }
1.800 albertel 7846: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 7847: }
1.800 albertel 7848: foreach my $item (keys(%allitems)) {
7849: $allitems{$item} =~ s/\:$//;
7850: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 7851: }
7852: $items=~s/\&$//;
7853: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 7854: }
7855:
1.47 www 7856: # ------------------------------------------------------ critical put interface
7857:
7858: sub cput {
1.134 albertel 7859: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 7860: if (!$udomain) { $udomain=$env{'user.domain'}; }
7861: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 7862: my $uhome=&homeserver($uname,$udomain);
1.47 www 7863: my $items='';
1.800 albertel 7864: foreach my $item (keys(%$storehash)) {
7865: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 7866: }
1.47 www 7867: $items=~s/\&$//;
1.134 albertel 7868: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 7869: }
7870:
7871: # -------------------------------------------------------------- eget interface
7872:
7873: sub eget {
1.133 albertel 7874: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 7875: my $items='';
1.800 albertel 7876: foreach my $item (@$storearr) {
7877: $items.=&escape($item).'&';
1.191 harris41 7878: }
1.12 www 7879: $items=~s/\&$//;
1.620 albertel 7880: if (!$udomain) { $udomain=$env{'user.domain'}; }
7881: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 7882: my $uhome=&homeserver($uname,$udomain);
7883: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 7884: my @pairs=split(/\&/,$rep);
7885: my %returnhash=();
1.42 www 7886: my $i=0;
1.800 albertel 7887: foreach my $item (@$storearr) {
7888: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 7889: $i++;
1.191 harris41 7890: }
1.12 www 7891: return %returnhash;
7892: }
7893:
1.667 albertel 7894: # ------------------------------------------------------------ tmpput interface
7895: sub tmpput {
1.802 raeburn 7896: my ($storehash,$server,$context)=@_;
1.667 albertel 7897: my $items='';
1.800 albertel 7898: foreach my $item (keys(%$storehash)) {
7899: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 7900: }
7901: $items=~s/\&$//;
1.802 raeburn 7902: if (defined($context)) {
7903: $items .= ':'.&escape($context);
7904: }
1.667 albertel 7905: return &reply("tmpput:$items",$server);
7906: }
7907:
7908: # ------------------------------------------------------------ tmpget interface
7909: sub tmpget {
1.688 albertel 7910: my ($token,$server)=@_;
7911: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
7912: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 7913: my %returnhash;
1.1328 raeburn 7914: if ($rep =~ /^(con_lost|error|no_such_host)/i) {
7915: return %returnhash;
7916: }
1.667 albertel 7917: foreach my $item (split(/\&/,$rep)) {
7918: my ($key,$value)=split(/=/,$item);
7919: $returnhash{&unescape($key)}=&thaw_unescape($value);
7920: }
7921: return %returnhash;
7922: }
7923:
1.1113 raeburn 7924: # ------------------------------------------------------------ tmpdel interface
1.688 albertel 7925: sub tmpdel {
7926: my ($token,$server)=@_;
7927: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
7928: return &reply("tmpdel:$token",$server);
7929: }
7930:
1.1198 raeburn 7931: # ------------------------------------------------------------ get_timebased_id
7932:
7933: sub get_timebased_id {
7934: my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
7935: $maxtries) = @_;
7936: my ($newid,$error,$dellock);
7937: unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
7938: return ('','ok','invalid call to get suffix');
7939: }
7940:
7941: # set defaults for any optional args for which values were not supplied
7942: if ($who eq '') {
7943: $who = $env{'user.name'}.':'.$env{'user.domain'};
7944: }
7945: if (!$locktries) {
7946: $locktries = 3;
7947: }
7948: if (!$maxtries) {
7949: $maxtries = 10;
7950: }
7951:
7952: if (($cdom eq '') || ($cnum eq '')) {
7953: if ($env{'request.course.id'}) {
7954: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7955: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7956: }
7957: if (($cdom eq '') || ($cnum eq '')) {
7958: return ('','ok','call to get suffix not in course context');
7959: }
7960: }
7961:
7962: # construct locking item
7963: my $lockhash = {
7964: $prefix."\0".'locked_'.$keyid => $who,
7965: };
7966: my $tries = 0;
7967:
7968: # attempt to get lock on nohist_$namespace file
1.1494 raeburn 7969: my $gotlock = &newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
1.1198 raeburn 7970: while (($gotlock ne 'ok') && $tries <$locktries) {
7971: $tries ++;
7972: sleep 1;
1.1494 raeburn 7973: $gotlock = &newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
1.1198 raeburn 7974: }
7975:
7976: # attempt to get unique identifier, based on current timestamp
7977: if ($gotlock eq 'ok') {
1.1494 raeburn 7978: my %inuse = &dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
1.1198 raeburn 7979: my $id = time;
7980: $newid = $id;
1.1268 raeburn 7981: if ($idtype eq 'addcode') {
7982: $newid .= &sixnum_code();
7983: }
1.1198 raeburn 7984: my $idtries = 0;
7985: while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
7986: if ($idtype eq 'concat') {
7987: $newid = $id.$idtries;
1.1268 raeburn 7988: } elsif ($idtype eq 'addcode') {
7989: $newid = $newid.&sixnum_code();
1.1198 raeburn 7990: } else {
7991: $newid ++;
7992: }
7993: $idtries ++;
7994: }
7995: if (!exists($inuse{$prefix."\0".$newid})) {
7996: my %new_item = (
7997: $prefix."\0".$newid => $who,
7998: );
1.1494 raeburn 7999: my $putresult = &put('nohist_'.$namespace,\%new_item,
1.1198 raeburn 8000: $cdom,$cnum);
8001: if ($putresult ne 'ok') {
8002: undef($newid);
8003: $error = 'error saving new item: '.$putresult;
8004: }
8005: } else {
1.1268 raeburn 8006: undef($newid);
1.1198 raeburn 8007: $error = ('error: no unique suffix available for the new item ');
8008: }
8009: # remove lock
8010: my @del_lock = ($prefix."\0".'locked_'.$keyid);
8011: $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
8012: } else {
8013: $error = "error: could not obtain lockfile\n";
8014: $dellock = 'ok';
1.1276 raeburn 8015: if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
8016: $dellock = 'nolock';
8017: }
1.1198 raeburn 8018: }
8019: return ($newid,$dellock,$error);
8020: }
8021:
1.1268 raeburn 8022: sub sixnum_code {
8023: my $code;
8024: for (0..6) {
8025: $code .= int( rand(9) );
8026: }
8027: return $code;
8028: }
8029:
1.765 albertel 8030: # -------------------------------------------------- portfolio access checking
8031:
8032: sub portfolio_access {
1.1270 raeburn 8033: my ($requrl,$clientip) = @_;
1.765 albertel 8034: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1270 raeburn 8035: my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814 raeburn 8036: if ($result) {
8037: my %setters;
8038: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
1.1473 raeburn 8039: my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
8040: &Apache::loncommon::blockcheck(\%setters,'port',$clientip,$unum,$udom);
8041: if (($startblock && $endblock) || ($by_ip)) {
1.814 raeburn 8042: return 'B';
8043: }
8044: } else {
1.1473 raeburn 8045: my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
8046: &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
8047: if (($startblock && $endblock) || ($by_ip)) {
1.814 raeburn 8048: return 'B';
8049: }
8050: }
8051: }
1.765 albertel 8052: if ($result eq 'ok') {
1.766 albertel 8053: return 'F';
1.765 albertel 8054: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 8055: return 'A';
1.765 albertel 8056: }
1.766 albertel 8057: return '';
1.765 albertel 8058: }
8059:
8060: sub get_portfolio_access {
1.1521 raeburn 8061: my ($udom,$unum,$file_name,$group,$clientip,$access_hash,$portaccessref) = @_;
1.767 albertel 8062:
8063: if (!ref($access_hash)) {
8064: my $current_perms = &get_portfile_permissions($udom,$unum);
8065: my %access_controls = &get_access_controls($current_perms,$group,
8066: $file_name);
8067: $access_hash = $access_controls{$file_name};
8068: }
8069:
1.1521 raeburn 8070: my $portaccess;
8071: if (ref($portaccess) eq 'SCALAR') {
8072: $portaccess = $$portaccessref;
8073: } else {
8074: $portaccess = &usertools_access($unum,$udom,'portaccess',undef,'tools');
8075: }
8076:
1.1522 raeburn 8077: my ($public,$guest,@domains,@users,@courses,@groups,@ips,@userips);
1.765 albertel 8078: my $now = time;
8079: if (ref($access_hash) eq 'HASH') {
8080: foreach my $key (keys(%{$access_hash})) {
8081: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
1.1521 raeburn 8082: next if (($scope ne 'ip') && ($portaccess == 0));
1.765 albertel 8083: if ($start > $now) {
8084: next;
8085: }
8086: if ($end && $end<$now) {
8087: next;
8088: }
8089: if ($scope eq 'public') {
8090: $public = $key;
8091: last;
8092: } elsif ($scope eq 'guest') {
8093: $guest = $key;
8094: } elsif ($scope eq 'domains') {
8095: push(@domains,$key);
8096: } elsif ($scope eq 'users') {
8097: push(@users,$key);
8098: } elsif ($scope eq 'course') {
8099: push(@courses,$key);
8100: } elsif ($scope eq 'group') {
8101: push(@groups,$key);
1.1270 raeburn 8102: } elsif ($scope eq 'ip') {
8103: push(@ips,$key);
1.1522 raeburn 8104: } elsif ($scope eq 'userip') {
8105: push(@userips,$key);
1.765 albertel 8106: }
8107: }
8108: if ($public) {
8109: return 'ok';
1.1270 raeburn 8110: } elsif (@ips > 0) {
8111: my $allowed;
8112: foreach my $ipkey (@ips) {
8113: if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
8114: if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
8115: $allowed = 1;
8116: last;
8117: }
8118: }
8119: }
8120: if ($allowed) {
8121: return 'ok';
8122: }
1.1522 raeburn 8123: } elsif (@userips > 0) {
8124: my $allowed;
8125: foreach my $useripkey (@userips) {
8126: if (ref($access_hash->{$useripkey}{'ip'}) eq 'ARRAY') {
8127: if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$useripkey}{'ip'}}),$clientip)) {
8128: $allowed = 1;
8129: last;
8130: }
8131: }
8132: }
8133: if ($allowed) {
8134: return 'ok';
8135: }
1.765 albertel 8136: }
8137: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
8138: if ($guest) {
8139: return $guest;
8140: }
8141: } else {
8142: if (@domains > 0) {
8143: foreach my $domkey (@domains) {
8144: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
8145: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
8146: return 'ok';
8147: }
8148: }
8149: }
8150: }
8151: if (@users > 0) {
8152: foreach my $userkey (@users) {
1.865 raeburn 8153: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
8154: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
8155: if (ref($item) eq 'HASH') {
8156: if (($item->{'uname'} eq $env{'user.name'}) &&
8157: ($item->{'udom'} eq $env{'user.domain'})) {
8158: return 'ok';
8159: }
8160: }
8161: }
8162: }
1.765 albertel 8163: }
8164: }
8165: my %roleshash;
8166: my @courses_and_groups = @courses;
8167: push(@courses_and_groups,@groups);
8168: if (@courses_and_groups > 0) {
8169: my (%allgroups,%allroles);
8170: my ($start,$end,$role,$sec,$group);
8171: foreach my $envkey (%env) {
1.1060 raeburn 8172: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 8173: my $cid = $2.'_'.$3;
8174: if ($1 eq 'gr') {
8175: $group = $4;
8176: $allgroups{$cid}{$group} = $env{$envkey};
8177: } else {
8178: if ($4 eq '') {
8179: $sec = 'none';
8180: } else {
8181: $sec = $4;
8182: }
8183: $allroles{$cid}{$1}{$sec} = $env{$envkey};
8184: }
1.811 albertel 8185: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 8186: my $cid = $2.'_'.$3;
8187: if ($4 eq '') {
8188: $sec = 'none';
8189: } else {
8190: $sec = $4;
8191: }
8192: $allroles{$cid}{$1}{$sec} = $env{$envkey};
8193: }
8194: }
8195: if (keys(%allroles) == 0) {
8196: return;
8197: }
8198: foreach my $key (@courses_and_groups) {
8199: my %content = %{$$access_hash{$key}};
8200: my $cnum = $content{'number'};
8201: my $cdom = $content{'domain'};
8202: my $cid = $cdom.'_'.$cnum;
8203: if (!exists($allroles{$cid})) {
8204: next;
8205: }
8206: foreach my $role_id (keys(%{$content{'roles'}})) {
8207: my @sections = @{$content{'roles'}{$role_id}{'section'}};
8208: my @groups = @{$content{'roles'}{$role_id}{'group'}};
8209: my @status = @{$content{'roles'}{$role_id}{'access'}};
8210: my @roles = @{$content{'roles'}{$role_id}{'role'}};
8211: foreach my $role (keys(%{$allroles{$cid}})) {
8212: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
8213: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
8214: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
8215: if (grep/^all$/,@sections) {
8216: return 'ok';
8217: } else {
8218: if (grep/^$sec$/,@sections) {
8219: return 'ok';
8220: }
8221: }
8222: }
8223: }
8224: if (keys(%{$allgroups{$cid}}) == 0) {
8225: if (grep/^none$/,@groups) {
8226: return 'ok';
8227: }
8228: } else {
8229: if (grep/^all$/,@groups) {
8230: return 'ok';
8231: }
8232: foreach my $group (keys(%{$allgroups{$cid}})) {
8233: if (grep/^$group$/,@groups) {
8234: return 'ok';
8235: }
8236: }
8237: }
8238: }
8239: }
8240: }
8241: }
8242: }
8243: if ($guest) {
8244: return $guest;
8245: }
8246: }
8247: }
8248: return;
8249: }
8250:
8251: sub course_group_datechecker {
8252: my ($dates,$now,$status) = @_;
8253: my ($start,$end) = split(/\./,$dates);
8254: if (!$start && !$end) {
8255: return 'ok';
8256: }
8257: if (grep/^active$/,@{$status}) {
8258: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
8259: return 'ok';
8260: }
8261: }
8262: if (grep/^previous$/,@{$status}) {
8263: if ($end > $now ) {
8264: return 'ok';
8265: }
8266: }
8267: if (grep/^future$/,@{$status}) {
8268: if ($start > $now) {
8269: return 'ok';
8270: }
8271: }
8272: return;
8273: }
8274:
8275: sub parse_portfolio_url {
8276: my ($url) = @_;
8277:
8278: my ($type,$udom,$unum,$group,$file_name);
8279:
1.823 albertel 8280: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 8281: $type = 1;
8282: $udom = $1;
8283: $unum = $2;
8284: $file_name = $3;
1.823 albertel 8285: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 8286: $type = 2;
8287: $udom = $1;
8288: $unum = $2;
8289: $group = $3;
8290: $file_name = $3.'/'.$4;
8291: }
8292: if (wantarray) {
8293: return ($type,$udom,$unum,$file_name,$group);
8294: }
8295: return $type;
8296: }
8297:
8298: sub is_portfolio_url {
8299: my ($url) = @_;
8300: return scalar(&parse_portfolio_url($url));
8301: }
8302:
1.798 raeburn 8303: sub is_portfolio_file {
8304: my ($file) = @_;
1.820 raeburn 8305: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 8306: return 1;
8307: }
8308: return;
8309: }
8310:
1.1504 raeburn 8311: sub is_coursetool_logo {
8312: my ($uri) = @_;
8313: if ($env{'request.course.id'}) {
8314: my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
8315: if ($uri =~ m{^/*uploaded\Q$courseurl\E/toollogo/\d+/[^/]+$}) {
8316: return 1;
8317: }
8318: }
8319: return;
8320: }
8321:
1.976 raeburn 8322: sub usertools_access {
1.1084 raeburn 8323: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 8324: my ($access,%tools);
8325: if ($context eq '') {
8326: $context = 'tools';
8327: }
8328: if ($context eq 'requestcourses') {
8329: %tools = (
8330: official => 1,
8331: unofficial => 1,
1.1006 raeburn 8332: community => 1,
1.1246 raeburn 8333: textbook => 1,
1.1305 raeburn 8334: placement => 1,
1.1368 raeburn 8335: lti => 1,
1.985 raeburn 8336: );
1.1183 raeburn 8337: } elsif ($context eq 'requestauthor') {
8338: %tools = (
8339: requestauthor => 1,
8340: );
1.1517 raeburn 8341: } elsif ($context eq 'authordefaults') {
8342: %tools = (
8343: webdav => 1,
8344: );
1.985 raeburn 8345: } else {
8346: %tools = (
8347: aboutme => 1,
8348: blog => 1,
1.1526 raeburn 8349: webdav => 1,
1.985 raeburn 8350: portfolio => 1,
1.1517 raeburn 8351: portaccess => 1,
1.1489 raeburn 8352: timezone => 1,
1.985 raeburn 8353: );
8354: }
1.976 raeburn 8355: return if (!defined($tools{$tool}));
8356:
1.1242 raeburn 8357: if (($udom eq '') || ($uname eq '')) {
1.976 raeburn 8358: $udom = $env{'user.domain'};
8359: $uname = $env{'user.name'};
8360: }
8361:
1.978 raeburn 8362: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
8363: if ($action ne 'reload') {
1.985 raeburn 8364: if ($context eq 'requestcourses') {
8365: return $env{'environment.canrequest.'.$tool};
1.1183 raeburn 8366: } elsif ($context eq 'requestauthor') {
8367: return $env{'environment.canrequest.author'};
1.1517 raeburn 8368: } elsif ($context eq 'authordefaults') {
8369: if ($tool eq 'webdav') {
8370: return $env{'environment.availabletools.'.$tool};
8371: }
1.985 raeburn 8372: } else {
8373: return $env{'environment.availabletools.'.$tool};
8374: }
8375: }
1.976 raeburn 8376: }
8377:
1.1183 raeburn 8378: my ($toolstatus,$inststatus,$envkey);
8379: if ($context eq 'requestauthor') {
1.1517 raeburn 8380: $envkey = $context;
8381: } elsif ($context eq 'authordefaults') {
8382: if ($tool eq 'webdav') {
8383: $envkey = 'tools.'.$tool;
8384: }
1.1183 raeburn 8385: } else {
8386: $envkey = $context.'.'.$tool;
8387: }
1.976 raeburn 8388:
1.985 raeburn 8389: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
8390: ($action ne 'reload')) {
1.1183 raeburn 8391: $toolstatus = $env{'environment.'.$envkey};
1.976 raeburn 8392: $inststatus = $env{'environment.inststatus'};
8393: } else {
1.1084 raeburn 8394: if (ref($userenvref) eq 'HASH') {
1.1183 raeburn 8395: $toolstatus = $userenvref->{$envkey};
1.1084 raeburn 8396: $inststatus = $userenvref->{'inststatus'};
8397: } else {
1.1183 raeburn 8398: my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
8399: $toolstatus = $userenv{$envkey};
1.1084 raeburn 8400: $inststatus = $userenv{'inststatus'};
8401: }
1.976 raeburn 8402: }
8403:
8404: if ($toolstatus ne '') {
8405: if ($toolstatus) {
8406: $access = 1;
8407: } else {
8408: $access = 0;
8409: }
8410: return $access;
8411: }
8412:
1.1084 raeburn 8413: my ($is_adv,%domdef);
8414: if (ref($is_advref) eq 'HASH') {
8415: $is_adv = $is_advref->{'is_adv'};
8416: } else {
8417: $is_adv = &is_advanced_user($udom,$uname);
8418: }
8419: if (ref($domdefref) eq 'HASH') {
8420: %domdef = %{$domdefref};
8421: } else {
8422: %domdef = &get_domain_defaults($udom);
8423: }
1.976 raeburn 8424: if (ref($domdef{$tool}) eq 'HASH') {
8425: if ($is_adv) {
8426: if ($domdef{$tool}{'_LC_adv'} ne '') {
8427: if ($domdef{$tool}{'_LC_adv'}) {
8428: $access = 1;
8429: } else {
8430: $access = 0;
8431: }
8432: return $access;
8433: }
8434: }
8435: if ($inststatus ne '') {
8436: my ($hasaccess,$hasnoaccess);
8437: foreach my $affiliation (split(/:/,$inststatus)) {
8438: if ($domdef{$tool}{$affiliation} ne '') {
8439: if ($domdef{$tool}{$affiliation}) {
8440: $hasaccess = 1;
8441: } else {
8442: $hasnoaccess = 1;
8443: }
8444: }
8445: }
8446: if ($hasaccess || $hasnoaccess) {
8447: if ($hasaccess) {
8448: $access = 1;
8449: } elsif ($hasnoaccess) {
8450: $access = 0;
8451: }
8452: return $access;
8453: }
8454: } else {
8455: if ($domdef{$tool}{'default'} ne '') {
8456: if ($domdef{$tool}{'default'}) {
8457: $access = 1;
8458: } elsif ($domdef{$tool}{'default'} == 0) {
8459: $access = 0;
8460: }
8461: return $access;
8462: }
8463: }
8464: } else {
1.1177 raeburn 8465: if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985 raeburn 8466: $access = 1;
8467: } else {
8468: $access = 0;
8469: }
1.976 raeburn 8470: return $access;
8471: }
8472: }
8473:
1.1050 raeburn 8474: sub is_course_owner {
8475: my ($cdom,$cnum,$udom,$uname) = @_;
8476: if (($udom eq '') || ($uname eq '')) {
8477: $udom = $env{'user.domain'};
8478: $uname = $env{'user.name'};
8479: }
8480: unless (($udom eq '') || ($uname eq '')) {
8481: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
8482: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
8483: return 1;
8484: } else {
1.1494 raeburn 8485: my %courseinfo = &coursedescription($cdom.'/'.$cnum);
1.1050 raeburn 8486: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
8487: return 1;
8488: }
8489: }
8490: }
8491: }
8492: return;
8493: }
8494:
1.976 raeburn 8495: sub is_advanced_user {
1.1512 raeburn 8496: my ($udom,$uname,$nocache) = @_;
8497: my ($is_adv,$is_author,$use_cache,$hashid);
1.1085 raeburn 8498: if ($udom ne '' && $uname ne '') {
8499: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128 raeburn 8500: if (wantarray) {
8501: return ($env{'user.adv'},$env{'user.author'});
8502: } else {
8503: return $env{'user.adv'};
8504: }
1.1512 raeburn 8505: } elsif (!$nocache) {
8506: $use_cache = 1;
8507: $hashid = "$udom:$uname";
8508: my ($info,$cached)=&is_cached_new('isadvau',$hashid);
8509: if ($cached) {
8510: ($is_adv,$is_author) = split(/:/,$info);
8511: if (wantarray) {
8512: return ($is_adv,$is_author);
8513: }
8514: return $is_adv;
8515: }
1.1085 raeburn 8516: }
8517: }
1.976 raeburn 8518: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
8519: my %allroles;
8520: foreach my $role (keys(%roleshash)) {
8521: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
8522: my $area = '/'.$tdomain.'/'.$trest;
8523: if ($sec ne '') {
8524: $area .= '/'.$sec;
8525: }
8526: if (($area ne '') && ($trole ne '')) {
8527: my $spec=$trole.'.'.$area;
8528: if ($trole =~ /^cr\//) {
8529: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
8530: } elsif ($trole ne 'gr') {
8531: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
8532: }
1.1128 raeburn 8533: if ($trole eq 'au') {
8534: $is_author = 1;
8535: }
1.976 raeburn 8536: }
8537: }
8538: foreach my $role (keys(%allroles)) {
8539: last if ($is_adv);
8540: foreach my $item (split(/:/,$allroles{$role})) {
8541: if ($item ne '') {
8542: my ($privilege,$restrictions)=split(/&/,$item);
8543: if ($privilege eq 'adv') {
8544: $is_adv = 1;
8545: last;
8546: }
8547: }
8548: }
8549: }
1.1512 raeburn 8550: if ($use_cache) {
8551: my $cachetime = 600;
8552: &do_cache_new('isadvau',$hashid,$is_adv.':'.$is_author,$cachetime);
8553: }
1.1128 raeburn 8554: if (wantarray) {
8555: return ($is_adv,$is_author);
8556: }
1.976 raeburn 8557: return $is_adv;
8558: }
1.798 raeburn 8559:
1.1035 raeburn 8560: sub check_can_request {
1.1368 raeburn 8561: my ($dom,$can_request,$request_domains,$uname,$udom) = @_;
1.1035 raeburn 8562: my $canreq = 0;
1.1368 raeburn 8563: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
8564: $uname = $env{'user.name'};
8565: $udom = $env{'user.domain'};
8566: }
1.1035 raeburn 8567: my ($types,$typename) = &Apache::loncommon::course_types();
8568: my @options = ('approval','validate','autolimit');
8569: my $optregex = join('|',@options);
8570: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
1.1486 raeburn 8571: my %willtrust;
1.1035 raeburn 8572: foreach my $type (@{$types}) {
1.1368 raeburn 8573: if (&usertools_access($uname,$udom,$type,undef,
8574: 'requestcourses')) {
1.1035 raeburn 8575: $canreq ++;
1.1036 raeburn 8576: if (ref($request_domains) eq 'HASH') {
1.1368 raeburn 8577: push(@{$request_domains->{$type}},$udom);
1.1036 raeburn 8578: }
1.1368 raeburn 8579: if ($dom eq $udom) {
1.1035 raeburn 8580: $can_request->{$type} = 1;
8581: }
8582: }
1.1368 raeburn 8583: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
8584: ($env{'environment.reqcrsotherdom.'.$type} ne '')) {
1.1035 raeburn 8585: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
8586: if (@curr > 0) {
1.1036 raeburn 8587: foreach my $item (@curr) {
8588: if (ref($request_domains) eq 'HASH') {
8589: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
8590: if ($otherdom ne '') {
1.1486 raeburn 8591: unless (exists($willtrust{$otherdom})) {
8592: $willtrust{$otherdom} = &will_trust('reqcrs',$env{'user.domain'},$otherdom);
8593: }
8594: if ($willtrust{$otherdom}) {
8595: if (ref($request_domains->{$type}) eq 'ARRAY') {
8596: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
8597: push(@{$request_domains->{$type}},$otherdom);
8598: }
8599: } else {
1.1036 raeburn 8600: push(@{$request_domains->{$type}},$otherdom);
8601: }
8602: }
8603: }
8604: }
8605: }
1.1368 raeburn 8606: unless ($dom eq $env{'user.domain'}) {
1.1036 raeburn 8607: $canreq ++;
1.1035 raeburn 8608: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
8609: $can_request->{$type} = 1;
8610: }
8611: }
8612: }
8613: }
8614: }
8615: }
8616: return $canreq;
8617: }
8618:
1.341 www 8619: # ---------------------------------------------- Custom access rule evaluation
8620:
8621: sub customaccess {
8622: my ($priv,$uri)=@_;
1.807 albertel 8623: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 8624: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 8625: $udom = &LONCAPA::clean_domain($udom);
8626: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 8627: my $access=0;
1.800 albertel 8628: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 8629: my ($effect,$realm,$role,$type)=split(/\:/,$right);
8630: if ($type eq 'user') {
8631: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 8632: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 8633: if ($tdom) {
8634: if ($tdom ne $env{'user.domain'}) { next; }
8635: }
1.896 albertel 8636: if ($tuname) {
8637: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 8638: }
8639: $access=($effect eq 'allow');
8640: last;
8641: }
8642: } else {
8643: if ($role) {
8644: if ($role ne $urole) { next; }
8645: }
8646: foreach my $scope (split(/\s*\,\s*/,$realm)) {
8647: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
8648: if ($tdom) {
8649: if ($tdom ne $udom) { next; }
8650: }
8651: if ($tcrs) {
8652: if ($tcrs ne $ucrs) { next; }
8653: }
8654: if ($tsec) {
8655: if ($tsec ne $usec) { next; }
8656: }
8657: $access=($effect eq 'allow');
8658: last;
8659: }
8660: if ($realm eq '' && $role eq '') {
8661: $access=($effect eq 'allow');
8662: }
1.402 bowersj2 8663: }
1.341 www 8664: }
8665: return $access;
8666: }
8667:
1.103 harris41 8668: # ------------------------------------------------- Check for a user privilege
1.12 www 8669:
8670: sub allowed {
1.1461 raeburn 8671: my ($priv,$uri,$symb,$role,$clientip,$noblockcheck,$ignorecache,$nodeeplinkcheck,$nodeeplinkout)=@_;
1.705 albertel 8672: my $ver_orguri=$uri;
1.439 www 8673: $uri=&deversion($uri);
1.152 www 8674: my $orguri=$uri;
1.52 www 8675: $uri=&declutter($uri);
1.809 raeburn 8676:
1.810 raeburn 8677: if ($priv eq 'evb') {
1.1478 raeburn 8678: # Evade communication block restrictions for specified role in a course or domain
1.810 raeburn 8679: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
8680: return $1;
8681: } else {
8682: return;
8683: }
8684: }
8685:
1.620 albertel 8686: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 8687: # Free bre access to adm and meta resources
1.1436 raeburn 8688: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|viewclasslist|aboutme|ext\.tool)$}))
1.769 albertel 8689: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
8690: && ($priv eq 'bre')) {
1.14 www 8691: return 'F';
1.159 www 8692: }
8693:
1.545 banghart 8694: # Free bre access to user's own portfolio contents
1.714 raeburn 8695: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 8696: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 8697: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 8698: my %setters;
1.1473 raeburn 8699: my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
8700: &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
8701: if (($startblock && $endblock) || ($by_ip)) {
1.814 raeburn 8702: return 'B';
8703: } else {
8704: return 'F';
8705: }
1.545 banghart 8706: }
8707:
1.762 raeburn 8708: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 8709: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
8710: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
8711: if (exists($env{'request.course.id'})) {
8712: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
8713: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
8714: if (($domain eq $cdom) && ($name eq $cnum)) {
8715: my $courseprivid=$env{'request.course.id'};
8716: $courseprivid=~s/\_/\//;
8717: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
8718: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
8719: return $1;
1.762 raeburn 8720: } else {
8721: if ($env{'request.course.sec'}) {
8722: $courseprivid.='/'.$env{'request.course.sec'};
8723: }
8724: if ($env{'user.priv.'.$env{'request.role'}.'./'.
8725: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
8726: return $2;
8727: }
1.714 raeburn 8728: }
8729: }
8730: }
8731: }
8732:
1.159 www 8733: # Free bre to public access
8734:
8735: if ($priv eq 'bre') {
1.1362 raeburn 8736: my $copyright;
8737: unless ($uri =~ /ext\.tool/) {
8738: $copyright=&metadata($uri,'copyright');
8739: }
1.620 albertel 8740: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 8741: return 'F';
8742: }
1.238 www 8743: if ($copyright eq 'priv') {
8744: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 8745: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 8746: return '';
8747: }
8748: }
8749: if ($copyright eq 'domain') {
8750: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 8751: unless (($env{'user.domain'} eq $1) ||
8752: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 8753: return '';
8754: }
1.262 matthew 8755: }
1.620 albertel 8756: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 8757: # Library role, so allow browsing of resources in this domain.
8758: return 'F';
1.238 www 8759: }
1.341 www 8760: if ($copyright eq 'custom') {
8761: unless (&customaccess($priv,$uri)) { return ''; }
8762: }
1.14 www 8763: }
1.264 matthew 8764: # Domain coordinator is trying to create a course
1.620 albertel 8765: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 8766: # uri is the requested domain in this case.
8767: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 8768: # a role of dc for the domain in question.
1.620 albertel 8769: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 8770: }
1.29 www 8771:
1.52 www 8772: my $thisallowed='';
8773: my $statecond=0;
8774: my $courseprivid='';
8775:
1.1039 raeburn 8776: my $ownaccess;
1.1043 raeburn 8777: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 8778: if (($priv eq 'bro') && ($env{'user.author'})) {
8779: if ($uri eq '') {
8780: $ownaccess = 1;
8781: } else {
8782: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
8783: my $udom = $env{'user.domain'};
8784: my $uname = $env{'user.name'};
8785: if ($uri =~ m{^\Q$udom\E/?$}) {
8786: $ownaccess = 1;
1.1040 raeburn 8787: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 8788: unless ($uri =~ m{\.\./}) {
8789: $ownaccess = 1;
8790: }
8791: } elsif (($udom ne 'public') && ($uname ne 'public')) {
8792: my $now = time;
8793: if ($uri =~ m{^([^/]+)/?$}) {
8794: my $adom = $1;
8795: foreach my $key (keys(%env)) {
1.1042 raeburn 8796: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1452 raeburn 8797: my ($start,$end) = split(/\./,$env{$key});
8798: if (($now >= $start) && (!$end || $end > $now)) {
1.1039 raeburn 8799: $ownaccess = 1;
8800: last;
8801: }
8802: }
8803: }
8804: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
8805: my $adom = $1;
8806: my $aname = $2;
1.1042 raeburn 8807: foreach my $role ('ca','aa') {
8808: if ($env{"user.role.$role./$adom/$aname"}) {
8809: my ($start,$end) =
1.1452 raeburn 8810: split(/\./,$env{"user.role.$role./$adom/$aname"});
8811: if (($now >= $start) && (!$end || $end > $now)) {
1.1042 raeburn 8812: $ownaccess = 1;
8813: last;
8814: }
1.1039 raeburn 8815: }
8816: }
8817: }
8818: }
8819: }
8820: }
8821: }
8822:
1.52 www 8823: # Course
8824:
1.620 albertel 8825: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 8826: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 8827: $thisallowed.=$1;
8828: }
1.52 www 8829: }
1.29 www 8830:
1.52 www 8831: # Domain
8832:
1.620 albertel 8833: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 8834: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 8835: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 8836: $thisallowed.=$1;
8837: }
1.12 www 8838: }
1.52 www 8839:
1.1141 raeburn 8840: # User who is not author or co-author might still be able to edit
8841: # resource of an author in the domain (e.g., if Domain Coordinator).
8842: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
8843: (&allowed('mdc',$env{'request.course.id'}))) {
8844: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
8845: $thisallowed.=$1;
8846: }
8847: }
8848:
1.52 www 8849: # Course: uri itself is a course
1.66 www 8850: my $courseuri=$uri;
8851: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 8852: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 8853:
1.620 albertel 8854: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 8855: =~/\Q$priv\E\&([^\:]*)/) {
1.1409 raeburn 8856: if ($priv eq 'mip') {
8857: my $rem = $1;
8858: if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
8859: ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
8860: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
8861: if ($cdom ne '') {
1.1410 raeburn 8862: my %passwdconf = &get_passwdconf($cdom);
8863: if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
8864: if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
8865: if (@{$passwdconf{'crsownerchg'}{'by'}}) {
8866: my @inststatuses = split(':',$env{'environment.inststatus'});
8867: unless (@inststatuses) {
8868: @inststatuses = ('default');
8869: }
8870: foreach my $status (@inststatuses) {
8871: if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
8872: $thisallowed.=$rem;
8873: }
8874: }
8875: }
8876: }
1.1409 raeburn 8877: }
8878: }
8879: }
8880: } else {
8881: unless (($priv eq 'bro') && (!$ownaccess)) {
8882: $thisallowed.=$1;
8883: }
1.1039 raeburn 8884: }
1.12 www 8885: }
1.29 www 8886:
1.665 albertel 8887: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 8888: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 8889: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 8890: $thisallowed='';
1.671 raeburn 8891: my ($match)=&is_on_map($uri);
8892: if ($match) {
8893: if ($env{'user.priv.'.$env{'request.role'}.'./'}
8894: =~/\Q$priv\E\&([^\:]*)/) {
1.1281 raeburn 8895: my $value = $1;
1.1461 raeburn 8896: my $deeplinkblock;
8897: unless ($nodeeplinkcheck) {
8898: $deeplinkblock = &deeplink_check($priv,$symb,$uri);
8899: }
1.1402 raeburn 8900: if ($deeplinkblock) {
8901: $thisallowed='D';
8902: } elsif ($noblockcheck) {
1.1281 raeburn 8903: $thisallowed.=$value;
1.1162 raeburn 8904: } else {
1.1424 raeburn 8905: my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1281 raeburn 8906: if (@blockers > 0) {
8907: $thisallowed = 'B';
8908: } else {
8909: $thisallowed.=$value;
8910: }
1.1162 raeburn 8911: }
1.671 raeburn 8912: }
8913: } else {
1.705 albertel 8914: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 8915: if ($refuri) {
8916: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 8917: $thisallowed='F';
1.671 raeburn 8918: } else {
8919: $refuri=&declutter($refuri);
8920: my ($match) = &is_on_map($refuri);
8921: if ($match) {
1.1461 raeburn 8922: my $deeplinkblock;
8923: unless ($nodeeplinkcheck) {
8924: $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
8925: }
1.1402 raeburn 8926: if ($deeplinkblock) {
8927: $thisallowed='D';
8928: } elsif ($noblockcheck) {
1.1281 raeburn 8929: $thisallowed='F';
1.1162 raeburn 8930: } else {
1.1426 raeburn 8931: my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1281 raeburn 8932: if (@blockers > 0) {
8933: $thisallowed = 'B';
8934: } else {
8935: $thisallowed='F';
8936: }
1.1162 raeburn 8937: }
1.671 raeburn 8938: }
1.669 raeburn 8939: }
1.671 raeburn 8940: }
8941: }
1.314 www 8942: }
1.492 albertel 8943:
1.766 albertel 8944: if ($priv eq 'bre'
8945: && $thisallowed ne 'F'
8946: && $thisallowed ne '2'
8947: && &is_portfolio_url($uri)) {
1.1270 raeburn 8948: $thisallowed = &portfolio_access($uri,$clientip);
1.766 albertel 8949: }
1.1250 raeburn 8950:
1.52 www 8951: # Full access at system, domain or course-wide level? Exit.
1.29 www 8952: if ($thisallowed=~/F/) {
8953: return 'F';
8954: }
8955:
1.52 www 8956: # If this is generating or modifying users, exit with special codes
1.29 www 8957:
1.1517 raeburn 8958: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:vca:vaa:'=~/\:\Q$priv\E\:/) {
1.643 www 8959: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 8960: my ($audom,$auname)=split('/',$uri);
1.643 www 8961: # no author name given, so this just checks on the general right to make a co-author in this domain
8962: unless ($auname) { return $thisallowed; }
8963: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 8964: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
8965: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
8966: ($audom ne $env{'request.role.domain'}))) { return ''; }
1.1517 raeburn 8967: } elsif (($priv eq 'vca') || ($priv eq 'vaa')) {
8968: my ($audom,$auname)=split('/',$uri);
8969: unless ($auname) { return $thisallowed; }
8970: unless (($env{'request.role'} eq "dc./$audom") ||
8971: ($env{'request.role'} eq "ca./$uri")) {
8972: return '';
8973: }
1.642 albertel 8974: }
1.52 www 8975: return $thisallowed;
8976: }
8977: #
1.103 harris41 8978: # Gathered so far: system, domain and course wide privileges
1.52 www 8979: #
8980: # Course: See if uri or referer is an individual resource that is part of
8981: # the course
8982:
1.620 albertel 8983: if ($env{'request.course.id'}) {
1.232 www 8984:
1.1504 raeburn 8985: if ($priv eq 'bre') {
8986: if (&is_coursetool_logo($uri)) {
8987: return 'F';
8988: }
8989: }
8990:
1.1409 raeburn 8991: # If this is modifying password (internal auth) domains must match for user and user's role.
8992:
8993: if ($priv eq 'mip') {
8994: if ($env{'user.domain'} eq $env{'request.role.domain'}) {
8995: return $thisallowed;
8996: } else {
8997: return '';
8998: }
8999: }
9000:
1.620 albertel 9001: $courseprivid=$env{'request.course.id'};
9002: if ($env{'request.course.sec'}) {
9003: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 9004: }
9005: $courseprivid=~s/\_/\//;
9006: my $checkreferer=1;
1.232 www 9007: my ($match,$cond)=&is_on_map($uri);
9008: if ($match) {
9009: $statecond=$cond;
1.620 albertel 9010: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 9011: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 9012: my $value = $1;
9013: if ($priv eq 'bre') {
1.1461 raeburn 9014: my $deeplinkblock;
9015: unless ($nodeeplinkcheck) {
9016: $deeplinkblock = &deeplink_check($priv,$symb,$uri);
9017: }
1.1458 raeburn 9018: if ($deeplinkblock) {
9019: $thisallowed = 'D';
9020: } elsif ($noblockcheck) {
1.1281 raeburn 9021: $thisallowed.=$value;
1.1162 raeburn 9022: } else {
1.1424 raeburn 9023: my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1281 raeburn 9024: if (@blockers > 0) {
9025: $thisallowed = 'B';
9026: } else {
9027: $thisallowed.=$value;
9028: }
1.1162 raeburn 9029: }
9030: } else {
9031: $thisallowed.=$value;
9032: }
1.52 www 9033: $checkreferer=0;
9034: }
1.29 www 9035: }
1.1424 raeburn 9036:
1.148 www 9037: if ($checkreferer) {
1.620 albertel 9038: my $refuri=$env{'httpref.'.$orguri};
1.148 www 9039: unless ($refuri) {
1.800 albertel 9040: foreach my $key (keys(%env)) {
9041: if ($key=~/^httpref\..*\*/) {
9042: my $pattern=$key;
1.156 www 9043: $pattern=~s/^httpref\.\/res\///;
1.148 www 9044: $pattern=~s/\*/\[\^\/\]\+/g;
9045: $pattern=~s/\//\\\//g;
1.152 www 9046: if ($orguri=~/$pattern/) {
1.800 albertel 9047: $refuri=$env{$key};
1.148 www 9048: }
9049: }
1.191 harris41 9050: }
1.148 www 9051: }
1.232 www 9052:
1.148 www 9053: if ($refuri) {
1.152 www 9054: $refuri=&declutter($refuri);
1.232 www 9055: my ($match,$cond)=&is_on_map($refuri);
9056: if ($match) {
9057: my $refstatecond=$cond;
1.620 albertel 9058: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 9059: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 9060: my $value = $1;
9061: if ($priv eq 'bre') {
1.1461 raeburn 9062: my $deeplinkblock;
9063: unless ($nodeeplinkcheck) {
9064: $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
9065: }
1.1402 raeburn 9066: if ($deeplinkblock) {
9067: $thisallowed = 'D';
9068: } elsif ($noblockcheck) {
1.1281 raeburn 9069: $thisallowed.=$value;
1.1162 raeburn 9070: } else {
1.1426 raeburn 9071: my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1281 raeburn 9072: if (@blockers > 0) {
9073: $thisallowed = 'B';
9074: } else {
9075: $thisallowed.=$value;
9076: }
1.1162 raeburn 9077: }
9078: } else {
9079: $thisallowed.=$value;
9080: }
1.53 www 9081: $uri=$refuri;
9082: $statecond=$refstatecond;
1.52 www 9083: }
9084: }
1.148 www 9085: }
1.29 www 9086: }
1.52 www 9087: }
1.29 www 9088:
1.52 www 9089: #
1.103 harris41 9090: # Gathered now: all privileges that could apply, and condition number
1.52 www 9091: #
9092: #
9093: # Full or no access?
9094: #
1.29 www 9095:
1.52 www 9096: if ($thisallowed=~/F/) {
9097: return 'F';
9098: }
1.29 www 9099:
1.52 www 9100: unless ($thisallowed) {
9101: return '';
9102: }
1.29 www 9103:
1.52 www 9104: # Restrictions exist, deal with them
9105: #
9106: # C:according to course preferences
9107: # R:according to resource settings
9108: # L:unless locked
9109: # X:according to user session state
9110: #
9111:
9112: # Possibly locked functionality, check all courses
1.1454 raeburn 9113: # In roles.tab, L (unless locked) available for bre, pch, plc, pac and sma.
1.54 www 9114: # Locks might take effect only after 10 minutes cache expiration for other
1.1454 raeburn 9115: # courses, and 2 minutes for current course, in which user has st or ta role
9116: # which is neither expired nor a future role (unless current course).
1.52 www 9117:
1.1454 raeburn 9118: my ($needlockcheck,$now,$crsonly);
1.52 www 9119: if ($thisallowed=~/L/) {
1.1454 raeburn 9120: $now = time;
9121: if ($priv eq 'bre') {
9122: if ($uri ne '') {
9123: if ($orguri =~ m{^/+res/}) {
9124: if ($uri =~ m{^lib/templates/}) {
9125: if ($env{'request.course.id'}) {
9126: $crsonly = 1;
9127: $needlockcheck = 1;
9128: }
9129: } else {
9130: $needlockcheck = 1;
9131: }
9132: } elsif ($env{'request.course.id'}) {
9133: my ($crsdom,$crsnum) = split('_',$env{'request.course.id'});
9134: if (($uri =~ m{^(adm|uploaded|public)/$crsdom/$crsnum/}) ||
9135: ($uri =~ m{^adm/$match_domain/$match_username/\d+/(smppg|bulletinboard)$})) {
9136: $crsonly = 1;
9137: }
9138: $needlockcheck = 1;
9139: }
9140: }
9141: } elsif (($priv eq 'pch') || ($priv eq 'plc') || ($priv eq 'pac') || ($priv eq 'sma')) {
9142: $needlockcheck = 1;
9143: }
9144: }
9145: if ($needlockcheck) {
1.1453 raeburn 9146: foreach my $envkey (keys(%env)) {
1.54 www 9147: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
9148: my $courseid=$2;
9149: my $roleid=$1.'.'.$2;
1.92 www 9150: $courseid=~s/^\///;
1.1453 raeburn 9151: unless ($env{'request.role'} eq $roleid) {
9152: my ($start,$end) = split(/\./,$env{$envkey});
9153: next unless (($now >= $start) && (!$end || $end > $now));
9154: }
1.54 www 9155: my $expiretime=600;
1.620 albertel 9156: if ($env{'request.role'} eq $roleid) {
1.54 www 9157: $expiretime=120;
9158: }
9159: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
9160: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 9161: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 9162: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 9163: }
1.620 albertel 9164: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
9165: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
9166: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
9167: &log($env{'user.domain'},$env{'user.name'},
9168: $env{'user.home'},
1.57 www 9169: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 9170: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 9171: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 9172: return '';
9173: }
9174: }
1.620 albertel 9175: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
9176: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
1.1455 raeburn 9177: if ($env{$prefix.'priv.'.$priv.'.lock.expire'}>time) {
1.620 albertel 9178: &log($env{'user.domain'},$env{'user.name'},
9179: $env{'user.home'},
1.57 www 9180: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 9181: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 9182: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 9183: return '';
9184: }
9185: }
9186: }
1.29 www 9187: }
1.52 www 9188: }
1.1424 raeburn 9189:
1.52 www 9190: #
9191: # Rest of the restrictions depend on selected course
9192: #
9193:
1.620 albertel 9194: unless ($env{'request.course.id'}) {
1.766 albertel 9195: if ($thisallowed eq 'A') {
9196: return 'A';
1.814 raeburn 9197: } elsif ($thisallowed eq 'B') {
9198: return 'B';
1.766 albertel 9199: } else {
9200: return '1';
9201: }
1.52 www 9202: }
1.29 www 9203:
1.52 www 9204: #
9205: # Now user is definitely in a course
9206: #
1.53 www 9207:
9208:
9209: # Course preferences
9210:
9211: if ($thisallowed=~/C/) {
1.620 albertel 9212: my $rolecode=(split(/\./,$env{'request.role'}))[0];
9213: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
9214: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 9215: =~/\Q$rolecode\E/) {
1.1304 raeburn 9216: if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689 albertel 9217: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
9218: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
9219: $env{'request.course.id'});
9220: }
1.237 www 9221: return '';
9222: }
9223:
1.620 albertel 9224: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 9225: =~/\Q$unamedom\E/) {
1.1304 raeburn 9226: if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689 albertel 9227: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
9228: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
9229: $env{'request.course.id'});
9230: }
1.54 www 9231: return '';
9232: }
1.53 www 9233: }
9234:
9235: # Resource preferences
9236:
9237: if ($thisallowed=~/R/) {
1.620 albertel 9238: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 9239: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103 raeburn 9240: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 9241: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
9242: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
9243: }
9244: return '';
1.54 www 9245: }
1.53 www 9246: }
1.30 www 9247:
1.1461 raeburn 9248: # Restricted for deeplinked session?
9249:
9250: if ($env{'request.deeplink.login'}) {
9251: if ($env{'acc.deeplinkout'} && !$nodeeplinkout) {
9252: if (!$symb) { $symb=&symbread($uri,1); }
9253: if (($symb) && ($env{'acc.deeplinkout'}=~/\&\Q$symb\E\&/)) {
9254: return '';
9255: }
9256: }
9257: }
9258:
1.246 www 9259: # Restricted by state or randomout?
1.30 www 9260:
1.52 www 9261: if ($thisallowed=~/X/) {
1.620 albertel 9262: if ($env{'acc.randomout'}) {
1.579 albertel 9263: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 9264: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 9265: return '';
9266: }
1.247 www 9267: }
9268: if (&condval($statecond)) {
1.52 www 9269: return '2';
9270: } else {
9271: return '';
9272: }
9273: }
1.30 www 9274:
1.766 albertel 9275: if ($thisallowed eq 'A') {
9276: return 'A';
1.814 raeburn 9277: } elsif ($thisallowed eq 'B') {
9278: return 'B';
1.1402 raeburn 9279: } elsif ($thisallowed eq 'D') {
9280: return 'D';
1.766 albertel 9281: }
1.52 www 9282: return 'F';
1.232 www 9283: }
1.1162 raeburn 9284:
1.1192 raeburn 9285: # ------------------------------------------- Check construction space access
9286:
9287: sub constructaccess {
9288: my ($url,$setpriv)=@_;
9289:
9290: # We do not allow editing of previous versions of files
9291: if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
9292:
9293: # Get username and domain from URL
9294: my ($ownername,$ownerdomain,$ownerhome);
9295:
9296: ($ownerdomain,$ownername) =
1.1325 raeburn 9297: ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
1.1192 raeburn 9298:
9299: # The URL does not really point to any authorspace, forget it
9300: unless (($ownername) && ($ownerdomain)) { return ''; }
9301:
9302: # Now we need to see if the user has access to the authorspace of
9303: # $ownername at $ownerdomain
9304:
9305: if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
9306: # Real author for this?
9307: $ownerhome = $env{'user.home'};
9308: if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
9309: return ($ownername,$ownerdomain,$ownerhome);
9310: }
1.1506 raeburn 9311: } elsif (&is_course($ownerdomain,$ownername)) {
9312: # Course Authoring Space?
1.1312 raeburn 9313: if ($env{'request.course.id'}) {
9314: if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
9315: ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
9316: if (&allowed('mdc',$env{'request.course.id'})) {
1.1520 raeburn 9317: return if ($env{'course.'.$env{'request.course.id'}.'.internal.crsauthor'} eq '0');
9318: unless ($env{'course.'.$env{'request.course.id'}.'.internal.crsauthor'}) {
9319: my %domdefs = &get_domain_defaults($ownerdomain);
9320: my $type = lc($env{'course.'.$env{'request.course.id'}.'.type'});
9321: unless (($type eq 'community') || ($type eq 'placement')) {
9322: $type = 'unofficial';
9323: if ($env{'course.'.$env{'request.course.id'}.'internal.coursecode'} ne '') {
9324: $type = 'official';
9325: } elsif ($env{'course.'.$env{'request.course.id'}.'internal.textbook'} ne '') {
9326: $type = 'textbook';
9327: } else {
9328: $type = 'unofficial';
9329: }
9330: }
9331: return if ($domdefs{$type.'crsauthor'} eq '0');
9332: }
1.1312 raeburn 9333: $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
9334: return ($ownername,$ownerdomain,$ownerhome);
9335: }
9336: }
9337: }
1.1506 raeburn 9338: return '';
9339: } else {
9340: # Co-author for this?
9341: if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
9342: exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
9343: $ownerhome = &homeserver($ownername,$ownerdomain);
9344: return ($ownername,$ownerdomain,$ownerhome);
9345: }
1.1192 raeburn 9346: }
9347:
9348: # We don't have any access right now. If we are not possibly going to do anything about this,
9349: # we might as well leave
9350: unless ($setpriv) { return ''; }
9351:
9352: # Backdoor access?
9353: my $allowed=&allowed('eco',$ownerdomain);
9354: # Nope
9355: unless ($allowed) { return ''; }
9356: # Looks like we may have access, but could be locked by the owner of the construction space
9357: if ($allowed eq 'U') {
9358: my %blocked=&get('environment',['domcoord.author'],
9359: $ownerdomain,$ownername);
9360: # Is blocked by owner
9361: if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
9362: }
9363: if (($allowed eq 'F') || ($allowed eq 'U')) {
9364: # Grant temporary access
9365: my $then=$env{'user.login.time'};
1.1209 raeburn 9366: my $update=$env{'user.update.time'};
1.1192 raeburn 9367: if (!$update) { $update = $then; }
9368: my $refresh=$env{'user.refresh.time'};
9369: if (!$refresh) { $refresh = $update; }
9370: my $now = time;
9371: &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
9372: $now,'ca','constructaccess');
9373: $ownerhome = &homeserver($ownername,$ownerdomain);
9374: return($ownername,$ownerdomain,$ownerhome);
9375: }
9376: # No business here
9377: return '';
9378: }
9379:
1.1282 raeburn 9380: # ----------------------------------------------------------- Content Blocking
9381:
9382: {
9383: # Caches for faster Course Contents display where content blocking
9384: # is in operation (i.e., interval param set) for timed quiz.
9385: #
9386: # User for whom data are being temporarily cached.
9387: my $cacheduser='';
1.1424 raeburn 9388: # Course for which data are being temporarily cached.
9389: my $cachedcid='';
1.1282 raeburn 9390: # Cached blockers for this user (a hash of blocking items).
9391: my %cachedblockers=();
9392: # When the data were last cached.
9393: my $cachedlast='';
9394:
9395: sub load_all_blockers {
1.1427 raeburn 9396: my ($uname,$udom)=@_;
1.1282 raeburn 9397: if (($uname ne '') && ($udom ne '')) {
9398: if (($cacheduser eq $uname.':'.$udom) &&
1.1424 raeburn 9399: ($cachedcid eq $env{'request.course.id'}) &&
1.1427 raeburn 9400: (abs($cachedlast-time)<5)) {
1.1282 raeburn 9401: return;
9402: }
9403: }
9404: $cachedlast=time;
9405: $cacheduser=$uname.':'.$udom;
1.1424 raeburn 9406: $cachedcid=$env{'request.course.id'};
1.1427 raeburn 9407: %cachedblockers = &get_commblock_resources();
1.1424 raeburn 9408: return;
1.1282 raeburn 9409: }
9410:
1.1162 raeburn 9411: sub get_comm_blocks {
9412: my ($cdom,$cnum) = @_;
9413: if ($cdom eq '' || $cnum eq '') {
9414: return unless ($env{'request.course.id'});
9415: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
9416: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
9417: }
9418: my %commblocks;
9419: my $hashid=$cdom.'_'.$cnum;
9420: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
9421: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
9422: %commblocks = %{$blocksref};
9423: } else {
1.1494 raeburn 9424: %commblocks = &dump('comm_block',$cdom,$cnum);
1.1162 raeburn 9425: my $cachetime = 600;
9426: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
9427: }
9428: return %commblocks;
9429: }
9430:
1.1282 raeburn 9431: sub get_commblock_resources {
9432: my ($blocks) = @_;
9433: my %blockers = ();
9434: return %blockers unless ($env{'request.course.id'});
1.1470 raeburn 9435: my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
9436: if ($env{'request.course.sec'}) {
9437: $courseurl .= '/'.$env{'request.course.sec'};
9438: }
9439: return %blockers if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
1.1162 raeburn 9440: my %commblocks;
9441: if (ref($blocks) eq 'HASH') {
9442: %commblocks = %{$blocks};
9443: } else {
9444: %commblocks = &get_comm_blocks();
9445: }
1.1282 raeburn 9446: return %blockers unless (keys(%commblocks) > 0);
9447: my $navmap = Apache::lonnavmaps::navmap->new();
9448: return %blockers unless (ref($navmap));
1.1162 raeburn 9449: my $now = time;
9450: foreach my $block (keys(%commblocks)) {
9451: if ($block =~ /^(\d+)____(\d+)$/) {
9452: my ($start,$end) = ($1,$2);
9453: if ($start <= $now && $end >= $now) {
9454: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
9455: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
9456: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1282 raeburn 9457: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
9458: $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162 raeburn 9459: }
9460: }
9461: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1282 raeburn 9462: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
9463: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162 raeburn 9464: }
9465: }
9466: }
9467: }
9468: }
9469: } elsif ($block =~ /^firstaccess____(.+)$/) {
9470: my $item = $1;
9471: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
9472: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1471 raeburn 9473: my (@interval,$mapname);
1.1282 raeburn 9474: my $type = 'map';
9475: if ($item eq 'course') {
9476: $type = 'course';
9477: @interval=&EXT("resource.0.interval");
9478: } else {
9479: if ($item =~ /___\d+___/) {
9480: $type = 'resource';
9481: @interval=&EXT("resource.0.interval",$item);
1.1162 raeburn 9482: } else {
1.1471 raeburn 9483: $mapname = &deversion($item);
9484: if (ref($navmap)) {
9485: my $timelimit = $navmap->get_mapparam(undef,$mapname,'0.interval');
9486: @interval = ($timelimit,'map');
1.1162 raeburn 9487: }
9488: }
1.1282 raeburn 9489: }
1.1310 raeburn 9490: if ($interval[0] =~ /^(\d+)/) {
1.1308 raeburn 9491: my $timelimit = $1;
1.1282 raeburn 9492: my $first_access;
9493: if ($type eq 'resource') {
9494: $first_access=&get_first_access($interval[1],$item);
9495: } elsif ($type eq 'map') {
9496: $first_access=&get_first_access($interval[1],undef,$item);
9497: } else {
9498: $first_access=&get_first_access($interval[1]);
9499: }
9500: if ($first_access) {
1.1292 raeburn 9501: my $timesup = $first_access+$timelimit;
1.1282 raeburn 9502: if ($timesup > $now) {
9503: my $activeblock;
1.1471 raeburn 9504: if ($type eq 'resource') {
9505: if (ref($navmap)) {
9506: my $res = $navmap->getBySymb($item);
9507: if ($res->answerable()) {
9508: $activeblock = 1;
9509: }
9510: }
9511: } elsif ($type eq 'map') {
9512: my $mapsymb = &symbread($mapname,1);
9513: if (($mapsymb) && (ref($navmap))) {
9514: my $mapres = $navmap->getBySymb($mapsymb);
9515: if (ref($mapres)) {
9516: my $first = $mapres->map_start();
9517: my $finish = $mapres->map_finish();
9518: my $it = $navmap->getIterator($first,$finish,undef,0,0);
9519: if (ref($it)) {
9520: my $res;
9521: while ($res = $it->next(undef,1)) {
9522: next unless (ref($res));
9523: my $symb = $res->symb();
9524: next if (($symb eq $mapsymb) || ($symb eq ''));
9525: @interval=&EXT("resource.0.interval",$symb);
9526: if ($interval[1] eq 'map') {
9527: if ($res->answerable()) {
9528: $activeblock = 1;
9529: last;
9530: }
9531: }
9532: }
9533: }
9534: }
1.1282 raeburn 9535: }
9536: }
9537: if ($activeblock) {
9538: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
9539: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
9540: $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
9541: }
9542: }
9543: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
9544: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
9545: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163 raeburn 9546: }
1.1162 raeburn 9547: }
9548: }
9549: }
9550: }
9551: }
9552: }
9553: }
9554: }
9555: }
1.1282 raeburn 9556: return %blockers;
1.1162 raeburn 9557: }
9558:
1.1282 raeburn 9559: sub has_comm_blocking {
1.1427 raeburn 9560: my ($priv,$symb,$uri,$ignoresymbdb,$noenccheck,$blocked,$blocks) = @_;
1.1282 raeburn 9561: my @blockers;
9562: return unless ($env{'request.course.id'});
9563: return unless ($priv eq 'bre');
9564: return if ($env{'request.state'} eq 'construct');
1.1470 raeburn 9565: my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
9566: if ($env{'request.course.sec'}) {
9567: $courseurl .= '/'.$env{'request.course.sec'};
9568: }
9569: return if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
1.1427 raeburn 9570: my %blockinfo;
9571: if (ref($blocks) eq 'HASH') {
9572: %blockinfo = &get_commblock_resources($blocks);
9573: } else {
9574: &load_all_blockers($env{'user.name'},$env{'user.domain'});
9575: %blockinfo = %cachedblockers;
9576: }
9577: return unless (keys(%blockinfo) > 0);
1.1282 raeburn 9578: my (%possibles,@symbs);
9579: if (!$symb) {
1.1427 raeburn 9580: $symb = &symbread($uri,1,1,1,\%possibles,$ignoresymbdb,$noenccheck);
1.1162 raeburn 9581: }
1.1282 raeburn 9582: if ($symb) {
9583: @symbs = ($symb);
9584: } elsif (keys(%possibles)) {
9585: @symbs = keys(%possibles);
9586: }
9587: my $noblock;
9588: foreach my $symb (@symbs) {
9589: last if ($noblock);
9590: my ($map,$resid,$resurl)=&decode_symb($symb);
1.1427 raeburn 9591: foreach my $block (keys(%blockinfo)) {
1.1282 raeburn 9592: if ($block =~ /^firstaccess____(.+)$/) {
9593: my $item = $1;
1.1424 raeburn 9594: unless ($blocked) {
9595: if (($item eq $map) || ($item eq $symb)) {
9596: $noblock = 1;
9597: last;
9598: }
1.1282 raeburn 9599: }
9600: }
1.1427 raeburn 9601: if (ref($blockinfo{$block}) eq 'HASH') {
9602: if (ref($blockinfo{$block}{'resources'}) eq 'HASH') {
9603: if ($blockinfo{$block}{'resources'}{$symb}) {
1.1282 raeburn 9604: unless (grep(/^\Q$block\E$/,@blockers)) {
9605: push(@blockers,$block);
9606: }
9607: }
9608: }
1.1427 raeburn 9609: if (ref($blockinfo{$block}{'maps'}) eq 'HASH') {
9610: if ($blockinfo{$block}{'maps'}{$map}) {
1.1424 raeburn 9611: unless (grep(/^\Q$block\E$/,@blockers)) {
9612: push(@blockers,$block);
9613: }
1.1282 raeburn 9614: }
9615: }
1.1162 raeburn 9616: }
9617: }
9618: }
1.1424 raeburn 9619: unless ($noblock) {
9620: return @blockers;
9621: }
9622: return;
1.1282 raeburn 9623: }
1.1162 raeburn 9624: }
9625:
1.1402 raeburn 9626: sub deeplink_check {
9627: my ($priv,$symb,$uri) = @_;
9628: return unless ($env{'request.course.id'});
9629: return unless ($priv eq 'bre');
9630: return if ($env{'request.state'} eq 'construct');
9631: return if ($env{'request.role.adv'});
9632: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
9633: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
9634: my (%possibles,@symbs);
9635: if (!$symb) {
9636: $symb = &symbread($uri,1,1,1,\%possibles);
9637: }
9638: if ($symb) {
9639: @symbs = ($symb);
9640: } elsif (keys(%possibles)) {
9641: @symbs = keys(%possibles);
9642: }
9643:
1.1461 raeburn 9644: my ($deeplink_symb,$allow);
9645: if ($env{'request.deeplink.login'}) {
9646: $deeplink_symb = &Apache::loncommon::deeplink_login_symb($cnum,$cdom);
1.1402 raeburn 9647: }
9648: foreach my $symb (@symbs) {
9649: last if ($allow);
9650: my $deeplink = &EXT("resource.0.deeplink",$symb);
9651: if ($deeplink eq '') {
9652: $allow = 1;
9653: } else {
1.1463 raeburn 9654: my ($state,$others,$listed,$scope,$protect) = split(/,/,$deeplink);
9655: if ($state ne 'only') {
1.1402 raeburn 9656: $allow = 1;
1.1463 raeburn 9657: } else {
9658: my $check_deeplink_entry;
9659: if ($protect ne 'none') {
9660: my ($acctype,$item) = split(/:/,$protect);
9661: if (($acctype eq 'ltic') && ($env{'user.linkprotector'})) {
9662: if (grep(/^\Q$item\Ec$/,split(/,/,$env{'user.linkprotector'}))) {
9663: $check_deeplink_entry = 1
9664: }
9665: } elsif (($acctype eq 'ltid') && ($env{'user.linkprotector'})) {
9666: if (grep(/^\Q$item\Ed$/,split(/,/,$env{'user.linkprotector'}))) {
9667: $check_deeplink_entry = 1;
9668: }
9669: } elsif (($acctype eq 'key') && ($env{'user.deeplinkkey'})) {
9670: if (grep(/^\Q$item\E$/,split(/,/,$env{'user.deeplinkkey'}))) {
9671: $check_deeplink_entry = 1;
9672: }
9673: }
9674: }
9675: if (($protect eq 'none') || ($check_deeplink_entry)) {
1.1402 raeburn 9676: if ($scope eq 'res') {
1.1461 raeburn 9677: if ($symb eq $deeplink_symb) {
1.1402 raeburn 9678: $allow = 1;
9679: }
1.1459 raeburn 9680: } elsif (($scope eq 'map') || ($scope eq 'rec')) {
1.1463 raeburn 9681: my ($map_from_symb,$map_from_login);
1.1461 raeburn 9682: $map_from_symb = &deversion((&decode_symb($symb))[0]);
9683: if ($deeplink_symb =~ /\.(page|sequence)$/) {
9684: $map_from_login = &deversion((&decode_symb($deeplink_symb))[2]);
9685: } else {
9686: $map_from_login = &deversion((&decode_symb($deeplink_symb))[0]);
9687: }
1.1459 raeburn 9688: if (($map_from_symb) && ($map_from_login)) {
9689: if ($map_from_symb eq $map_from_login) {
9690: $allow = 1;
9691: } elsif ($scope eq 'rec') {
9692: my @recurseup = &get_map_hierarchy($map_from_symb,$env{'request.course.id'});
9693: if (grep(/^\Q$map_from_login\E$/,@recurseup)) {
9694: $allow = 1;
9695: }
9696: }
9697: }
1.1402 raeburn 9698: }
9699: }
9700: }
9701: }
9702: }
9703: return if ($allow);
9704: return 1;
9705: }
9706:
1.1282 raeburn 9707: # -------------------------------- Deversion and split uri into path an filename
9708:
1.1133 foxr 9709: #
1.1282 raeburn 9710: # Removes the version from a URI and
1.1133 foxr 9711: # splits it in to its filename and path to the filename.
9712: # Seems like File::Basename could have done this more clearly.
9713: # Parameters:
9714: # $uri - input URI
9715: # Returns:
9716: # Two element list consisting of
9717: # $pathname - the URI up to and excluding the trailing /
9718: # $filename - The part of the URI following the last /
9719: # NOTE:
9720: # Another realization of this is simply:
9721: # use File::Basename;
9722: # ...
9723: # $uri = shift;
9724: # $filename = basename($uri);
9725: # $path = dirname($uri);
9726: # return ($filename, $path);
9727: #
9728: # The implementation below is probably faster however.
9729: #
1.710 albertel 9730: sub split_uri_for_cond {
9731: my $uri=&deversion(&declutter(shift));
9732: my @uriparts=split(/\//,$uri);
9733: my $filename=pop(@uriparts);
9734: my $pathname=join('/',@uriparts);
9735: return ($pathname,$filename);
9736: }
1.232 www 9737: # --------------------------------------------------- Is a resource on the map?
9738:
9739: sub is_on_map {
1.710 albertel 9740: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 9741: #Trying to find the conditional for the file
1.620 albertel 9742: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 9743: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 9744: if ($match) {
1.289 bowersj2 9745: return (1,$1);
9746: } else {
1.434 www 9747: return (0,0);
1.289 bowersj2 9748: }
1.12 www 9749: }
9750:
1.427 www 9751: # --------------------------------------------------------- Get symb from alias
9752:
9753: sub get_symb_from_alias {
9754: my $symb=shift;
9755: my ($map,$resid,$url)=&decode_symb($symb);
9756: # Already is a symb
9757: if ($url) { return $symb; }
9758: # Must be an alias
9759: my $aliassymb='';
9760: my %bighash;
1.620 albertel 9761: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 9762: &GDBM_READER(),0640)) {
9763: my $rid=$bighash{'mapalias_'.$symb};
9764: if ($rid) {
9765: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 9766: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
9767: $resid,$bighash{'src_'.$rid});
1.427 www 9768: }
9769: untie %bighash;
9770: }
9771: return $aliassymb;
9772: }
9773:
1.12 www 9774: # ----------------------------------------------------------------- Define Role
9775:
9776: sub definerole {
9777: if (allowed('mcr','/')) {
1.1326 raeburn 9778: my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800 albertel 9779: foreach my $role (split(':',$sysrole)) {
9780: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 9781: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
9782: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
9783: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 9784: return "refused:s:$crole&$cqual";
9785: }
9786: }
1.191 harris41 9787: }
1.800 albertel 9788: foreach my $role (split(':',$domrole)) {
9789: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 9790: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
9791: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
9792: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 9793: return "refused:d:$crole&$cqual";
9794: }
9795: }
1.191 harris41 9796: }
1.800 albertel 9797: foreach my $role (split(':',$courole)) {
9798: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 9799: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
9800: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
9801: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 9802: return "refused:c:$crole&$cqual";
9803: }
9804: }
1.191 harris41 9805: }
1.1326 raeburn 9806: my $uhome;
9807: if (($uname ne '') && ($udom ne '')) {
9808: $uhome = &homeserver($uname,$udom);
9809: return $uhome if ($uhome eq 'no_host');
9810: } else {
9811: $uname = $env{'user.name'};
9812: $udom = $env{'user.domain'};
9813: $uhome = $env{'user.home'};
9814: }
1.620 albertel 9815: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1326 raeburn 9816: "$udom:$uname:rolesdef_$rolename=".
1.21 www 9817: escape($sysrole.'_'.$domrole.'_'.$courole);
1.1326 raeburn 9818: return reply($command,$uhome);
1.12 www 9819: } else {
9820: return 'refused';
9821: }
1.105 harris41 9822: }
9823:
9824: # ---------------- Make a metadata query against the network of library servers
9825:
9826: sub metadata_query {
1.1237 raeburn 9827: my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120 harris41 9828: my %rhash;
1.845 albertel 9829: my %libserv = &all_library();
1.244 matthew 9830: my @server_list = (defined($server_array) ? @$server_array
9831: : keys(%libserv) );
9832: for my $server (@server_list) {
1.1237 raeburn 9833: my $domains = '';
9834: if (ref($domains_hash) eq 'HASH') {
9835: $domains = $domains_hash->{$server};
9836: }
1.118 harris41 9837: unless ($custom or $customshow) {
1.1237 raeburn 9838: my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118 harris41 9839: $rhash{$server}=$reply;
9840: }
9841: else {
9842: my $reply=&reply("querysend:".&escape($query).':'.
1.1237 raeburn 9843: &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118 harris41 9844: $server);
9845: $rhash{$server}=$reply;
9846: }
1.112 harris41 9847: }
1.118 harris41 9848: return \%rhash;
1.240 www 9849: }
9850:
9851: # ----------------------------------------- Send log queries and wait for reply
9852:
9853: sub log_query {
9854: my ($uname,$udom,$query,%filters)=@_;
9855: my $uhome=&homeserver($uname,$udom);
9856: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 9857: my $uhost=&hostname($uhome);
1.800 albertel 9858: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 9859: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
9860: $uhome);
1.479 albertel 9861: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 9862: return get_query_reply($queryid);
9863: }
9864:
1.818 raeburn 9865: # -------------------------- Update MySQL table for portfolio file
9866:
9867: sub update_portfolio_table {
1.821 raeburn 9868: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 9869: if ($group ne '') {
9870: $file_name =~s /^\Q$group\E//;
9871: }
1.818 raeburn 9872: my $homeserver = &homeserver($uname,$udom);
9873: my $queryid=
1.821 raeburn 9874: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
9875: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 9876: my $reply = &get_query_reply($queryid);
9877: return $reply;
9878: }
9879:
1.899 raeburn 9880: # -------------------------- Update MySQL allusers table
9881:
9882: sub update_allusers_table {
9883: my ($uname,$udom,$names) = @_;
9884: my $homeserver = &homeserver($uname,$udom);
9885: my $queryid=
9886: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
9887: 'lastname='.&escape($names->{'lastname'}).'%%'.
9888: 'firstname='.&escape($names->{'firstname'}).'%%'.
9889: 'middlename='.&escape($names->{'middlename'}).'%%'.
9890: 'generation='.&escape($names->{'generation'}).'%%'.
9891: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
9892: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 9893: return;
1.899 raeburn 9894: }
9895:
1.508 raeburn 9896: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 9897:
9898: sub fetch_enrollment_query {
1.511 raeburn 9899: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1317 raeburn 9900: my ($homeserver,$sleep,$loopmax);
1.547 raeburn 9901: my $maxtries = 1;
1.508 raeburn 9902: if ($context eq 'automated') {
9903: $homeserver = $perlvar{'lonHostID'};
1.1317 raeburn 9904: $sleep = 2;
9905: $loopmax = 100;
1.547 raeburn 9906: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 9907: } else {
9908: $homeserver = &homeserver($cnum,$dom);
9909: }
1.838 albertel 9910: my $host=&hostname($homeserver);
1.506 raeburn 9911: my $cmd = '';
1.1000 raeburn 9912: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 9913: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 9914: }
9915: $cmd =~ s/%%$//;
9916: $cmd = &escape($cmd);
9917: my $query = 'fetchenrollment';
1.620 albertel 9918: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 9919: unless ($queryid=~/^\Q$host\E\_/) {
9920: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
9921: return 'error: '.$queryid;
9922: }
1.1317 raeburn 9923: my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547 raeburn 9924: my $tries = 1;
9925: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1317 raeburn 9926: $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547 raeburn 9927: $tries ++;
9928: }
1.526 raeburn 9929: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 9930: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 9931: } else {
1.901 albertel 9932: my @responses = split(/:/,$reply);
1.1322 raeburn 9933: if (grep { $_ eq $homeserver } ¤t_machine_ids()) {
1.800 albertel 9934: foreach my $line (@responses) {
9935: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 9936: $$replyref{$key} = $value;
9937: }
9938: } else {
1.1117 foxr 9939: my $pathname = LONCAPA::tempdir();
1.800 albertel 9940: foreach my $line (@responses) {
9941: my ($key,$value) = split(/=/,$line);
1.506 raeburn 9942: $$replyref{$key} = $value;
9943: if ($value > 0) {
1.800 albertel 9944: foreach my $item (@{$$affiliatesref{$key}}) {
9945: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 9946: my $destname = $pathname.'/'.$filename;
9947: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 9948: if ($xml_classlist =~ /^error/) {
9949: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
9950: } else {
1.1359 raeburn 9951: if ( open(FILE,">",$destname) ) {
1.506 raeburn 9952: print FILE &unescape($xml_classlist);
9953: close(FILE);
1.526 raeburn 9954: } else {
9955: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 9956: }
9957: }
9958: }
9959: }
9960: }
9961: }
9962: return 'ok';
9963: }
9964: return 'error';
9965: }
9966:
1.242 www 9967: sub get_query_reply {
1.1471 raeburn 9968: my ($queryid,$sleep,$loopmax) = @_;
1.1317 raeburn 9969: if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
9970: $sleep = 0.2;
9971: }
9972: if (($loopmax eq '') || ($loopmax =~ /\D/)) {
9973: $loopmax = 100;
9974: }
1.1117 foxr 9975: my $replyfile=LONCAPA::tempdir().$queryid;
1.240 www 9976: my $reply='';
1.1317 raeburn 9977: for (1..$loopmax) {
9978: sleep($sleep);
1.240 www 9979: if (-e $replyfile.'.end') {
1.1359 raeburn 9980: if (open(my $fh,"<",$replyfile)) {
1.904 albertel 9981: $reply = join('',<$fh>);
9982: close($fh);
1.240 www 9983: } else { return 'error: reply_file_error'; }
1.242 www 9984: return &unescape($reply);
9985: }
1.240 www 9986: }
1.242 www 9987: return 'timeout:'.$queryid;
1.240 www 9988: }
9989:
9990: sub courselog_query {
1.241 www 9991: #
9992: # possible filters:
9993: # url: url or symb
9994: # username
9995: # domain
9996: # action: view, submit, grade
9997: # start: timestamp
9998: # end: timestamp
9999: #
1.240 www 10000: my (%filters)=@_;
1.620 albertel 10001: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 10002: if ($filters{'url'}) {
10003: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
10004: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
10005: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
10006: }
1.620 albertel 10007: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
10008: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 10009: return &log_query($cname,$cdom,'courselog',%filters);
10010: }
10011:
10012: sub userlog_query {
1.858 raeburn 10013: #
10014: # possible filters:
10015: # action: log check role
10016: # start: timestamp
10017: # end: timestamp
10018: #
1.240 www 10019: my ($uname,$udom,%filters)=@_;
10020: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 10021: }
10022:
1.506 raeburn 10023: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
10024:
10025: sub auto_run {
1.508 raeburn 10026: my ($cnum,$cdom) = @_;
1.876 raeburn 10027: my $response = 0;
10028: my $settings;
10029: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
10030: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
10031: $settings = $domconfig{'autoenroll'};
10032: if ($settings->{'run'} eq '1') {
10033: $response = 1;
10034: }
10035: } else {
1.934 raeburn 10036: my $homeserver;
10037: if (&is_course($cdom,$cnum)) {
10038: $homeserver = &homeserver($cnum,$cdom);
10039: } else {
10040: $homeserver = &domain($cdom,'primary');
10041: }
10042: if ($homeserver ne 'no_host') {
10043: $response = &reply('autorun:'.$cdom,$homeserver);
10044: }
1.876 raeburn 10045: }
1.506 raeburn 10046: return $response;
10047: }
1.776 albertel 10048:
1.506 raeburn 10049: sub auto_get_sections {
1.508 raeburn 10050: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 10051: my $homeserver;
10052: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
10053: $homeserver = &homeserver($cnum,$cdom);
10054: }
10055: if (!defined($homeserver)) {
10056: if ($cdom =~ /^$match_domain$/) {
10057: $homeserver = &domain($cdom,'primary');
10058: }
10059: }
10060: my @secs;
10061: if (defined($homeserver)) {
10062: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
10063: unless ($response eq 'refused') {
10064: @secs = split(/:/,$response);
10065: }
1.506 raeburn 10066: }
10067: return @secs;
10068: }
1.776 albertel 10069:
1.506 raeburn 10070: sub auto_new_course {
1.1099 raeburn 10071: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 10072: my $homeserver = &homeserver($cnum,$cdom);
1.1099 raeburn 10073: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 10074: return $response;
10075: }
1.776 albertel 10076:
1.506 raeburn 10077: sub auto_validate_courseID {
1.508 raeburn 10078: my ($cnum,$cdom,$inst_course_id) = @_;
10079: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 10080: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 10081: return $response;
10082: }
1.776 albertel 10083:
1.1007 raeburn 10084: sub auto_validate_instcode {
1.1020 raeburn 10085: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 10086: my ($homeserver,$response);
10087: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
10088: $homeserver = &homeserver($cnum,$cdom);
10089: }
10090: if (!defined($homeserver)) {
10091: if ($cdom =~ /^$match_domain$/) {
10092: $homeserver = &domain($cdom,'primary');
10093: }
10094: }
1.1065 raeburn 10095: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
10096: &escape($instcode).':'.&escape($owner),$homeserver));
1.1216 raeburn 10097: my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
10098: return ($outcome,$description,$defaultcredits);
1.1007 raeburn 10099: }
10100:
1.1444 raeburn 10101: sub auto_validate_inst_crosslist {
10102: my ($cnum,$cdom,$instcode,$inst_xlist,$coowner) = @_;
10103: my ($homeserver,$response);
10104: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
10105: $homeserver = &homeserver($cnum,$cdom);
10106: }
10107: if (!defined($homeserver)) {
10108: if ($cdom =~ /^$match_domain$/) {
10109: $homeserver = &domain($cdom,'primary');
10110: }
10111: }
10112: unless (($homeserver eq '') || ($homeserver eq 'no_host')) {
10113: $response=&reply('autovalidateinstcrosslist:'.$cdom.':'.
10114: &escape($instcode).':'.&escape($inst_xlist).':'.
1.1445 raeburn 10115: &escape($coowner),$homeserver);
1.1444 raeburn 10116: }
10117: return $response;
10118: }
10119:
1.506 raeburn 10120: sub auto_create_password {
1.873 raeburn 10121: my ($cnum,$cdom,$authparam,$udom) = @_;
10122: my ($homeserver,$response);
1.506 raeburn 10123: my $create_passwd = 0;
10124: my $authchk = '';
1.873 raeburn 10125: if ($udom =~ /^$match_domain$/) {
10126: $homeserver = &domain($udom,'primary');
10127: }
10128: if ($homeserver eq '') {
10129: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
10130: $homeserver = &homeserver($cnum,$cdom);
10131: }
10132: }
10133: if ($homeserver eq '') {
10134: $authchk = 'nodomain';
1.506 raeburn 10135: } else {
1.873 raeburn 10136: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
10137: if ($response eq 'refused') {
10138: $authchk = 'refused';
10139: } else {
1.901 albertel 10140: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 10141: }
1.506 raeburn 10142: }
10143: return ($authparam,$create_passwd,$authchk);
10144: }
10145:
1.706 raeburn 10146: sub auto_photo_permission {
10147: my ($cnum,$cdom,$students) = @_;
10148: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 10149: my ($outcome,$perm_reqd,$conditions) =
10150: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 10151: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
10152: return (undef,undef);
10153: }
1.706 raeburn 10154: return ($outcome,$perm_reqd,$conditions);
10155: }
10156:
10157: sub auto_checkphotos {
10158: my ($uname,$udom,$pid) = @_;
10159: my $homeserver = &homeserver($uname,$udom);
10160: my ($result,$resulttype);
10161: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 10162: &escape($uname).':'.&escape($pid),
10163: $homeserver));
1.709 albertel 10164: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
10165: return (undef,undef);
10166: }
1.706 raeburn 10167: if ($outcome) {
10168: ($result,$resulttype) = split(/:/,$outcome);
10169: }
10170: return ($result,$resulttype);
10171: }
10172:
10173: sub auto_photochoice {
10174: my ($cnum,$cdom) = @_;
10175: my $homeserver = &homeserver($cnum,$cdom);
10176: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 10177: &escape($cdom),
10178: $homeserver)));
1.709 albertel 10179: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
10180: return (undef,undef);
10181: }
1.706 raeburn 10182: return ($update,$comment);
10183: }
10184:
10185: sub auto_photoupdate {
10186: my ($affiliatesref,$dom,$cnum,$photo) = @_;
10187: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 10188: my $host=&hostname($homeserver);
1.706 raeburn 10189: my $cmd = '';
10190: my $maxtries = 1;
1.800 albertel 10191: foreach my $affiliate (keys(%{$affiliatesref})) {
10192: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 10193: }
10194: $cmd =~ s/%%$//;
10195: $cmd = &escape($cmd);
10196: my $query = 'institutionalphotos';
10197: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
10198: unless ($queryid=~/^\Q$host\E\_/) {
10199: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
10200: return 'error: '.$queryid;
10201: }
10202: my $reply = &get_query_reply($queryid);
10203: my $tries = 1;
10204: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
10205: $reply = &get_query_reply($queryid);
10206: $tries ++;
10207: }
10208: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
10209: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
10210: } else {
10211: my @responses = split(/:/,$reply);
10212: my $outcome = shift(@responses);
10213: foreach my $item (@responses) {
10214: my ($key,$value) = split(/=/,$item);
10215: $$photo{$key} = $value;
10216: }
10217: return $outcome;
10218: }
10219: return 'error';
10220: }
10221:
1.521 raeburn 10222: sub auto_instcode_format {
1.793 albertel 10223: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
10224: $cat_order) = @_;
1.521 raeburn 10225: my $courses = '';
1.772 raeburn 10226: my @homeservers;
1.521 raeburn 10227: if ($caller eq 'global') {
1.841 albertel 10228: my %servers = &get_servers($codedom,'library');
10229: foreach my $tryserver (keys(%servers)) {
10230: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
10231: push(@homeservers,$tryserver);
10232: }
1.584 raeburn 10233: }
1.1022 raeburn 10234: } elsif ($caller eq 'requests') {
10235: if ($codedom =~ /^$match_domain$/) {
10236: my $chome = &domain($codedom,'primary');
10237: unless ($chome eq 'no_host') {
10238: push(@homeservers,$chome);
10239: }
10240: }
1.521 raeburn 10241: } else {
1.772 raeburn 10242: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 10243: }
1.793 albertel 10244: foreach my $code (keys(%{$instcodes})) {
10245: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 10246: }
10247: chop($courses);
1.772 raeburn 10248: my $ok_response = 0;
10249: my $response;
10250: while (@homeservers > 0 && $ok_response == 0) {
10251: my $server = shift(@homeservers);
10252: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
10253: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
10254: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 10255: split(/:/,$response);
1.772 raeburn 10256: %{$codes} = (%{$codes},&str2hash($codes_str));
10257: push(@{$codetitles},&str2array($codetitles_str));
10258: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
10259: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
10260: $ok_response = 1;
10261: }
10262: }
10263: if ($ok_response) {
1.521 raeburn 10264: return 'ok';
1.772 raeburn 10265: } else {
10266: return $response;
1.521 raeburn 10267: }
10268: }
10269:
1.792 raeburn 10270: sub auto_instcode_defaults {
10271: my ($domain,$returnhash,$code_order) = @_;
10272: my @homeservers;
1.841 albertel 10273:
10274: my %servers = &get_servers($domain,'library');
10275: foreach my $tryserver (keys(%servers)) {
10276: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
10277: push(@homeservers,$tryserver);
10278: }
1.792 raeburn 10279: }
1.841 albertel 10280:
1.792 raeburn 10281: my $response;
1.841 albertel 10282: foreach my $server (@homeservers) {
1.792 raeburn 10283: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 10284: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
10285:
10286: foreach my $pair (split(/\&/,$response)) {
10287: my ($name,$value)=split(/\=/,$pair);
10288: if ($name eq 'code_order') {
10289: @{$code_order} = split(/\&/,&unescape($value));
10290: } else {
10291: $returnhash->{&unescape($name)}=&unescape($value);
10292: }
10293: }
10294: return 'ok';
1.792 raeburn 10295: }
1.841 albertel 10296:
10297: return $response;
1.1003 raeburn 10298: }
10299:
10300: sub auto_possible_instcodes {
1.1007 raeburn 10301: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
10302: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
10303: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
10304: return;
10305: }
1.1003 raeburn 10306: my (@homeservers,$uhome);
10307: if (defined(&domain($domain,'primary'))) {
10308: $uhome=&domain($domain,'primary');
10309: push(@homeservers,&domain($domain,'primary'));
10310: } else {
10311: my %servers = &get_servers($domain,'library');
10312: foreach my $tryserver (keys(%servers)) {
10313: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
10314: push(@homeservers,$tryserver);
10315: }
10316: }
10317: }
10318: my $response;
10319: foreach my $server (@homeservers) {
10320: $response=&reply('autopossibleinstcodes:'.$domain,$server);
10321: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 10322: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
10323: split(':',$response);
10324: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
10325: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 10326: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 10327: my ($name,$value)=split('=',$item);
10328: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 10329: }
10330: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 10331: my ($name,$value)=split('=',$item);
10332: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 10333: }
10334: return 'ok';
10335: }
10336: return $response;
10337: }
1.792 raeburn 10338:
1.1010 raeburn 10339: sub auto_courserequest_checks {
10340: my ($dom) = @_;
1.1020 raeburn 10341: my ($homeserver,%validations);
10342: if ($dom =~ /^$match_domain$/) {
10343: $homeserver = &domain($dom,'primary');
10344: }
10345: unless ($homeserver eq 'no_host') {
10346: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
10347: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
10348: my @items = split(/&/,$response);
10349: foreach my $item (@items) {
10350: my ($key,$value) = split('=',$item);
10351: $validations{&unescape($key)} = &thaw_unescape($value);
10352: }
10353: }
10354: }
1.1010 raeburn 10355: return %validations;
10356: }
10357:
1.1020 raeburn 10358: sub auto_courserequest_validation {
1.1255 raeburn 10359: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020 raeburn 10360: my ($homeserver,$response);
10361: if ($dom =~ /^$match_domain$/) {
10362: $homeserver = &domain($dom,'primary');
10363: }
1.1255 raeburn 10364: unless ($homeserver eq 'no_host') {
10365: my $customdata;
10366: if (ref($custominfo) eq 'HASH') {
10367: $customdata = &freeze_escape($custominfo);
10368: }
1.1020 raeburn 10369: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 10370: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1255 raeburn 10371: ':'.&escape($instcode).':'.&escape($instseclist).':'.
10372: $customdata,$homeserver));
1.1020 raeburn 10373: }
10374: return $response;
10375: }
10376:
1.777 albertel 10377: sub auto_validate_class_sec {
1.918 raeburn 10378: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 10379: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 10380: my $ownerlist;
10381: if (ref($owners) eq 'ARRAY') {
10382: $ownerlist = join(',',@{$owners});
10383: } else {
10384: $ownerlist = $owners;
10385: }
1.773 raeburn 10386: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 10387: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 10388: return $response;
10389: }
10390:
1.1460 raeburn 10391: sub auto_instsec_reformat {
10392: my ($cdom,$action,$instsecref) = @_;
10393: return unless(($action eq 'clutter') || ($action eq 'declutter'));
10394: my @homeservers;
10395: if (defined(&domain($cdom,'primary'))) {
10396: push(@homeservers,&domain($cdom,'primary'));
10397: } else {
10398: my %servers = &get_servers($cdom,'library');
10399: foreach my $tryserver (keys(%servers)) {
10400: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
10401: push(@homeservers,$tryserver);
10402: }
10403: }
10404: }
10405: my $response;
10406: my %reformatted = %{$instsecref};
10407: foreach my $server (@homeservers) {
10408: if (ref($instsecref) eq 'HASH') {
10409: my $info = &freeze_escape($instsecref);
10410: my $response=&reply('autoinstsecreformat:'.$cdom.':'.
10411: $action.':'.$info,$server);
1.1531 raeburn 10412: next if ($response =~ /(con_lost|error|no_such_host|refused|unknown_cmd)/);
1.1460 raeburn 10413: my @items = split(/&/,$response);
10414: foreach my $item (@items) {
10415: my ($key,$value) = split(/=/,$item);
10416: $reformatted{&unescape($key)} = &thaw_unescape($value);
10417: }
10418: }
10419: }
10420: return %reformatted;
10421: }
10422:
1.1367 raeburn 10423: sub auto_validate_instclasses {
10424: my ($cdom,$cnum,$owners,$classesref) = @_;
10425: my ($homeserver,%validations);
10426: $homeserver = &homeserver($cnum,$cdom);
10427: unless ($homeserver eq 'no_host') {
10428: my $ownerlist;
10429: if (ref($owners) eq 'ARRAY') {
10430: $ownerlist = join(',',@{$owners});
10431: } else {
10432: $ownerlist = $owners;
10433: }
10434: if (ref($classesref) eq 'HASH') {
10435: my $classes = &freeze_escape($classesref);
10436: my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
10437: ':'.$cdom.':'.$classes,$homeserver);
10438: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
10439: my @items = split(/&/,$response);
10440: foreach my $item (@items) {
10441: my ($key,$value) = split('=',$item);
10442: $validations{&unescape($key)} = &thaw_unescape($value);
10443: }
10444: }
10445: }
10446: }
10447: return %validations;
10448: }
10449:
1.1248 raeburn 10450: sub auto_crsreq_update {
10451: my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1257 raeburn 10452: $code,$accessstart,$accessend,$inbound) = @_;
1.1248 raeburn 10453: my ($homeserver,%crsreqresponse);
10454: if ($cdom =~ /^$match_domain$/) {
10455: $homeserver = &domain($cdom,'primary');
10456: }
10457: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
10458: my $info;
10459: if (ref($inbound) eq 'HASH') {
10460: $info = &freeze_escape($inbound);
10461: }
10462: my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
10463: ':'.&escape($action).':'.&escape($ownername).':'.
10464: &escape($ownerdomain).':'.&escape($fullname).':'.
1.1257 raeburn 10465: &escape($title).':'.&escape($code).':'.
10466: &escape($accessstart).':'.&escape($accessend).':'.$info,
10467: $homeserver);
1.1248 raeburn 10468: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
10469: my @items = split(/&/,$response);
10470: foreach my $item (@items) {
10471: my ($key,$value) = split('=',$item);
10472: $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
10473: }
10474: }
10475: }
10476: return \%crsreqresponse;
10477: }
10478:
1.1305 raeburn 10479: sub auto_export_grades {
1.1309 raeburn 10480: my ($cdom,$cnum,$inforef,$gradesref) = @_;
10481: my ($homeserver,%exportresponse);
10482: if ($cdom =~ /^$match_domain$/) {
10483: $homeserver = &domain($cdom,'primary');
10484: }
10485: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
10486: my $info;
10487: if (ref($inforef) eq 'HASH') {
10488: $info = &freeze_escape($inforef);
10489: }
10490: if (ref($gradesref) eq 'HASH') {
10491: my $grades = &freeze_escape($gradesref);
10492: my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
10493: $info.':'.$grades,$homeserver);
1.1531 raeburn 10494: unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_cmd)/) {
1.1309 raeburn 10495: my @items = split(/&/,$response);
10496: foreach my $item (@items) {
10497: my ($key,$value) = split('=',$item);
10498: $exportresponse{&unescape($key)} = &thaw_unescape($value);
10499: }
10500: }
10501: }
10502: }
10503: return \%exportresponse;
1.1305 raeburn 10504: }
10505:
1.1287 raeburn 10506: sub check_instcode_cloning {
10507: my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
10508: unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
10509: return;
10510: }
10511: my $canclone;
10512: if (@{$code_order} > 0) {
10513: my $instcoderegexp ='^';
10514: my @clonecodes = split(/\&/,$cloner);
10515: foreach my $item (@{$code_order}) {
10516: if (grep(/^\Q$item\E=/,@clonecodes)) {
10517: foreach my $pair (@clonecodes) {
10518: my ($key,$val) = split(/\=/,$pair,2);
10519: $val = &unescape($val);
10520: if ($key eq $item) {
10521: $instcoderegexp .= '('.$val.')';
10522: last;
10523: }
10524: }
10525: } else {
10526: $instcoderegexp .= $codedefaults->{$item};
10527: }
10528: }
10529: $instcoderegexp .= '$';
10530: my (@from,@to);
10531: eval {
10532: (@from) = ($clonefromcode =~ /$instcoderegexp/);
10533: (@to) = ($clonetocode =~ /$instcoderegexp/);
10534: };
10535: if ((@from > 0) && (@to > 0)) {
10536: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
10537: if (!@diffs) {
10538: $canclone = 1;
10539: }
10540: }
10541: }
10542: return $canclone;
10543: }
10544:
10545: sub default_instcode_cloning {
10546: my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
10547: my (%codedefaults,@code_order,$canclone);
10548: if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
10549: %codedefaults = %{$codedefaultsref};
10550: @code_order = @{$codeorderref};
10551: } elsif ($clonedom) {
10552: &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
10553: }
10554: if (($domdefclone) && (@code_order)) {
10555: my @clonecodes = split(/\+/,$domdefclone);
10556: my $instcoderegexp ='^';
10557: foreach my $item (@code_order) {
10558: if (grep(/^\Q$item\E$/,@clonecodes)) {
10559: $instcoderegexp .= '('.$codedefaults{$item}.')';
10560: } else {
10561: $instcoderegexp .= $codedefaults{$item};
10562: }
10563: }
10564: $instcoderegexp .= '$';
10565: my (@from,@to);
10566: eval {
10567: (@from) = ($clonefromcode =~ /$instcoderegexp/);
10568: (@to) = ($clonetocode =~ /$instcoderegexp/);
10569: };
10570: if ((@from > 0) && (@to > 0)) {
10571: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
10572: if (!@diffs) {
10573: $canclone = 1;
10574: }
10575: }
10576: }
10577: return $canclone;
10578: }
10579:
1.679 raeburn 10580: # ------------------------------------------------------- Course Group routines
10581:
10582: sub get_coursegroups {
1.809 raeburn 10583: my ($cdom,$cnum,$group,$namespace) = @_;
10584: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 10585: }
10586:
1.679 raeburn 10587: sub modify_coursegroup {
10588: my ($cdom,$cnum,$groupsettings) = @_;
10589: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
10590: }
10591:
1.809 raeburn 10592: sub toggle_coursegroup_status {
10593: my ($cdom,$cnum,$group,$action) = @_;
10594: my ($from_namespace,$to_namespace);
10595: if ($action eq 'delete') {
10596: $from_namespace = 'coursegroups';
10597: $to_namespace = 'deleted_groups';
10598: } else {
10599: $from_namespace = 'deleted_groups';
10600: $to_namespace = 'coursegroups';
10601: }
10602: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 10603: if (my $tmp = &error(%curr_group)) {
10604: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
10605: return ('read error',$tmp);
10606: } else {
10607: my %savedsettings = %curr_group;
1.809 raeburn 10608: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 10609: my $deloutcome;
10610: if ($result eq 'ok') {
1.809 raeburn 10611: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 10612: } else {
10613: return ('write error',$result);
10614: }
10615: if ($deloutcome eq 'ok') {
10616: return 'ok';
10617: } else {
10618: return ('delete error',$deloutcome);
10619: }
10620: }
10621: }
10622:
1.679 raeburn 10623: sub modify_group_roles {
1.1512 raeburn 10624: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context,
10625: $othdomby,$requester) = @_;
1.679 raeburn 10626: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
10627: my $role = 'gr/'.&escape($userprivs);
10628: my ($uname,$udom) = split(/:/,$user);
1.1512 raeburn 10629: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context,
10630: $othdomby,$requester);
1.684 raeburn 10631: if ($result eq 'ok') {
10632: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
10633: }
1.679 raeburn 10634: return $result;
10635: }
10636:
10637: sub modify_coursegroup_membership {
10638: my ($cdom,$cnum,$membership) = @_;
10639: my $result = &put('groupmembership',$membership,$cdom,$cnum);
10640: return $result;
10641: }
10642:
1.682 raeburn 10643: sub get_active_groups {
10644: my ($udom,$uname,$cdom,$cnum) = @_;
10645: my $now = time;
10646: my %groups = ();
10647: foreach my $key (keys(%env)) {
1.811 albertel 10648: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 10649: my ($start,$end) = split(/\./,$env{$key});
10650: if (($end!=0) && ($end<$now)) { next; }
10651: if (($start!=0) && ($start>$now)) { next; }
10652: if ($1 eq $cdom && $2 eq $cnum) {
10653: $groups{$3} = $env{$key} ;
10654: }
10655: }
10656: }
10657: return %groups;
10658: }
10659:
1.683 raeburn 10660: sub get_group_membership {
10661: my ($cdom,$cnum,$group) = @_;
10662: return(&dump('groupmembership',$cdom,$cnum,$group));
10663: }
10664:
10665: sub get_users_groups {
10666: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 10667: my @usersgroups;
1.683 raeburn 10668: my $cachetime=1800;
10669:
10670: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 10671: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
10672: if (defined($cached)) {
1.734 albertel 10673: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 10674: } else {
10675: $grouplist = '';
1.816 raeburn 10676: my $courseurl = &courseid_to_courseurl($courseid);
1.1166 raeburn 10677: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 10678: my $access_end = $env{'course.'.$courseid.
10679: '.default_enrollment_end_date'};
10680: my $now = time;
10681: foreach my $key (keys(%roleshash)) {
10682: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
10683: my $group = $1;
10684: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
10685: my $start = $2;
10686: my $end = $1;
10687: if ($start == -1) { next; } # deleted from group
10688: if (($start!=0) && ($start>$now)) { next; }
10689: if (($end!=0) && ($end<$now)) {
10690: if ($access_end && $access_end < $now) {
10691: if ($access_end - $end < 86400) {
10692: push(@usersgroups,$group);
1.733 raeburn 10693: }
10694: }
1.817 raeburn 10695: next;
1.733 raeburn 10696: }
1.817 raeburn 10697: push(@usersgroups,$group);
1.683 raeburn 10698: }
10699: }
10700: }
1.817 raeburn 10701: @usersgroups = &sort_course_groups($courseid,@usersgroups);
10702: $grouplist = join(':',@usersgroups);
10703: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 10704: }
1.733 raeburn 10705: return @usersgroups;
1.683 raeburn 10706: }
10707:
10708: sub devalidate_getgroups_cache {
10709: my ($udom,$uname,$cdom,$cnum)=@_;
10710: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 10711:
1.683 raeburn 10712: my $hashid="$udom:$uname:$courseid";
10713: &devalidate_cache_new('getgroups',$hashid);
10714: }
10715:
1.12 www 10716: # ------------------------------------------------------------------ Plain Text
10717:
10718: sub plaintext {
1.988 raeburn 10719: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 10720: if ($short =~ m{^cr/}) {
1.758 albertel 10721: return (split('/',$short))[-1];
10722: }
1.742 raeburn 10723: if (!defined($cid)) {
10724: $cid = $env{'request.course.id'};
10725: }
10726: my %rolenames = (
1.1008 raeburn 10727: Course => 'std',
10728: Community => 'alt1',
1.1305 raeburn 10729: Placement => 'std',
1.742 raeburn 10730: );
1.1037 raeburn 10731: if ($cid ne '') {
10732: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
10733: unless ($forcedefault) {
10734: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
10735: &Apache::lonlocal::mt_escape(\$roletext);
10736: return &Apache::lonlocal::mt($roletext);
10737: }
10738: }
10739: }
10740: if ((defined($type)) && (defined($rolenames{$type})) &&
10741: (defined($rolenames{$type})) &&
10742: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 10743: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 10744: } elsif ($cid ne '') {
10745: my $crstype = $env{'course.'.$cid.'.type'};
10746: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
10747: (defined($prp{$short}{$rolenames{$crstype}}))) {
10748: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
10749: }
1.742 raeburn 10750: }
1.1037 raeburn 10751: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 10752: }
10753:
10754: # ----------------------------------------------------------------- Assign Role
10755:
10756: sub assignrole {
1.957 raeburn 10757: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
1.1512 raeburn 10758: $context,$othdomby,$requester,$reqsec,$reqrole)=@_;
1.1517 raeburn 10759: my ($mrole,$rolelogcontext);
1.21 www 10760: if ($role =~ /^cr\//) {
1.393 www 10761: my $cwosec=$url;
1.811 albertel 10762: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.1502 raeburn 10763: if ((!&allowed('ccr',$cwosec)) && (!&allowed('ccr',$udom))) {
1.1512 raeburn 10764: my $refused = 1;
10765: if ($context eq 'requestcourses') {
10766: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
10767: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
10768: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
10769: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
10770: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10771: if ($crsenv{'internal.courseowner'} eq
10772: $env{'user.name'}.':'.$env{'user.domain'}) {
10773: $refused = '';
10774: }
10775: }
10776: }
10777: }
10778: } elsif (($context eq 'course') && ($othdomby eq 'othdombyuser')) {
10779: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
10780: my ($sec) = ($url =~ m{^/\Q$cwosec\E/(.*)$});
10781: my $key = "$uname:$udom:$role:$sec";
10782: my %queuedrolereq = &Apache::lonnet::get('nohist_othdomqueued',[$key],$cdom,$cnum);
10783: if ((exists($queuedrolereq{$key})) && (ref($queuedrolereq{$key}) eq 'HASH')) {
10784: if (($queuedrolereq{$key}{'adj'} eq 'user') && ($queuedrolereq{$key}{'requester'} eq $requester)) {
10785: $refused = '';
10786: }
10787: }
10788: }
10789: if ($refused) {
10790: &logthis('Refused custom assignrole: '.
10791: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
10792: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
10793: return 'refused';
10794: }
1.104 www 10795: }
1.21 www 10796: $mrole='cr';
1.678 raeburn 10797: } elsif ($role =~ /^gr\//) {
10798: my $cwogrp=$url;
1.811 albertel 10799: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.1512 raeburn 10800: if (!&allowed('mdg',$cwogrp)) {
10801: my $refused = 1;
10802: if (($refused) && ($othdomby eq 'othdombyuser') && ($requester ne '') && ($reqrole ne '')) {
10803: my ($cdom,$cnum) = ($cwogrp =~ m{^/?($match_domain)/($match_courseid)$});
10804: my $key = "$uname:$udom:$reqrole:$reqsec";
10805: my %queuedrolereq = &Apache::lonnet::get('nohist_othdomqueued',[$key],$cdom,$cnum);
10806: if ((exists($queuedrolereq{$key})) && (ref($queuedrolereq{$key}) eq 'HASH')) {
10807: if (($queuedrolereq{$key}{'adj'} eq 'user') && ($queuedrolereq{$key}{'requester'} eq $requester)) {
10808: $refused = '';
10809: }
10810: }
10811: }
10812: if ($refused) {
10813: &logthis('Refused group assignrole: '.
10814: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
10815: $env{'user.name'}.' at '.$env{'user.domain'});
10816: return 'refused';
10817: }
1.678 raeburn 10818: }
10819: $mrole='gr';
1.21 www 10820: } else {
1.82 www 10821: my $cwosec=$url;
1.811 albertel 10822: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 10823: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
10824: my $refused;
10825: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
10826: if (!(&allowed('c'.$role,$url))) {
10827: $refused = 1;
10828: }
10829: } else {
10830: $refused = 1;
10831: }
1.947 raeburn 10832: if ($refused) {
1.1045 raeburn 10833: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
1.1512 raeburn 10834: if (!$selfenroll && ($othdomby ne 'othdombyuser') &&
10835: (($context eq 'course') || ($context eq 'ltienroll' && $env{'request.lti.login'}))) {
1.1045 raeburn 10836: my %crsenv;
10837: if ($role eq 'cc' || $role eq 'co') {
10838: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10839: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
10840: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
10841: if ($crsenv{'internal.courseowner'} eq
10842: $env{'user.name'}.':'.$env{'user.domain'}) {
10843: $refused = '';
10844: }
10845: }
10846: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
10847: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
10848: if ($crsenv{'internal.courseowner'} eq
10849: $env{'user.name'}.':'.$env{'user.domain'}) {
10850: $refused = '';
10851: }
10852: }
10853: }
10854: }
1.1368 raeburn 10855: } elsif (($selfenroll == 1) && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
10856: if ($role eq 'st') {
10857: $refused = '';
1.1377 raeburn 10858: } elsif (($context eq 'ltienroll') && ($env{'request.lti.login'})) {
1.1368 raeburn 10859: $refused = '';
10860: }
1.1512 raeburn 10861: } elsif ($othdomby eq 'othdombyuser') {
10862: my ($key,%queuedrolereq);
10863: if ($context eq 'course') {
10864: my ($sec) = ($url =~ m{^/\Q$cwosec\E/(.*)$});
10865: $key = "$uname:$udom:$role:$sec";
10866: %queuedrolereq = &Apache::lonnet::get('nohist_othdomqueued',[$key],$cdom,$cnum);
10867: if ((exists($queuedrolereq{$key})) && (ref($queuedrolereq{$key}) eq 'HASH')) {
10868: if (($queuedrolereq{$key}{'adj'} eq 'user') && ($queuedrolereq{$key}{'requester'} eq $requester)) {
10869: if ((($role eq 'cc') && ($cnum !~ /^$match_community$/)) ||
10870: (($role eq 'co') && ($cnum =~ /^$match_community$/))) {
10871: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10872: if ($crsenv{'internal.courseowner'} eq $requester) {
10873: $refused = '';
10874: }
10875: } elsif ($role =~ /^(?:in|ta|ep|st)$/) {
10876: $refused = '';
10877: }
10878: }
10879: }
10880: } elsif (($context eq 'author') && ($role =~ /^ca|aa$/)) {
10881: my $key = "$uname:$udom:$role";
10882: my ($audom,$auname) = ($url =~ m{^/($match_domain)/($match_username)$});
10883: if (($audom ne '') && ($auname ne '')) {
10884: my %queuedrolereq = &Apache::lonnet::get('nohist_othdomqueued',[$key],$audom,$auname);
10885: if ((exists($queuedrolereq{$key})) && (ref($queuedrolereq{$key}) eq 'HASH')) {
10886: if (($queuedrolereq{$key}{'adj'} eq 'user') && ($queuedrolereq{$key}{'requester'} eq $requester)) {
10887: $refused = '';
10888: }
10889: }
10890: }
10891: } elsif (($context eq 'domain') && ($role ne 'dc') && ($role ne 'su')) {
10892: my $key = "$uname:$udom:$role";
10893: my ($roledom) = ($url =~ m{^/($match_domain)/\Q$role\E$});
10894: if ($roledom ne '') {
10895: my $confname = $roledom.'-domainconfig';
10896: my %queuedrolereq = &Apache::lonnet::get('nohist_othdomqueued',[$key],$roledom,$confname);
10897: if ((exists($queuedrolereq{$key})) && (ref($queuedrolereq{$key}) eq 'HASH')) {
10898: if (($queuedrolereq{$key}{'adj'} eq 'user') && ($queuedrolereq{$key}{'requester'} eq $requester)) {
10899: $refused = '';
10900: }
10901: }
10902: }
10903: }
1.1017 raeburn 10904: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 10905: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 10906: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 10907: my $wrongcc;
10908: if ($cnum =~ /^$match_community$/) {
10909: $wrongcc = 1 if ($role eq 'cc');
10910: } else {
10911: $wrongcc = 1 if ($role eq 'co');
10912: }
10913: unless ($wrongcc) {
10914: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10915: if ($crsenv{'internal.courseowner'} eq
10916: $env{'user.name'}.':'.$env{'user.domain'}) {
10917: $refused = '';
10918: }
1.1017 raeburn 10919: }
10920: }
1.1183 raeburn 10921: } elsif ($context eq 'requestauthor') {
10922: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
10923: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
10924: if ($env{'environment.requestauthor'} eq 'automatic') {
10925: $refused = '';
10926: } else {
10927: my %domdefaults = &get_domain_defaults($udom);
10928: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
10929: my $checkbystatus;
10930: if ($env{'user.adv'}) {
10931: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
10932: if ($disposition eq 'automatic') {
10933: $refused = '';
10934: } elsif ($disposition eq '') {
10935: $checkbystatus = 1;
10936: }
10937: } else {
10938: $checkbystatus = 1;
10939: }
10940: if ($checkbystatus) {
10941: if ($env{'environment.inststatus'}) {
10942: my @inststatuses = split(/,/,$env{'environment.inststatus'});
10943: foreach my $type (@inststatuses) {
10944: if (($type ne '') &&
10945: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
10946: $refused = '';
10947: }
10948: }
10949: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
10950: $refused = '';
10951: }
10952: }
10953: }
10954: }
10955: }
1.1517 raeburn 10956: } elsif (($context eq 'author') && (($role eq 'ca' || $role eq 'aa'))) {
10957: if ($url =~ m{^/($match_domain)/($match_username)$}) {
10958: my ($audom,$auname) = ($1,$2);
10959: if ((&Apache::lonnet::allowed('v'.$role,"$audom/$auname")) &&
10960: ($env{"environment.internal.manager.$url"})) {
10961: $refused = '';
10962: $rolelogcontext = 'coauthor';
10963: }
10964: }
1.1017 raeburn 10965: }
10966: if ($refused) {
1.947 raeburn 10967: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
10968: ' '.$role.' '.$end.' '.$start.' by '.
10969: $env{'user.name'}.' at '.$env{'user.domain'});
10970: return 'refused';
10971: }
1.932 raeburn 10972: }
1.1131 raeburn 10973: } elsif ($role eq 'au') {
10974: if ($url ne '/'.$udom.'/') {
10975: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
10976: ' to assign author role for '.$uname.':'.$udom.
10977: ' in domain: '.$url.' refused (wrong domain).');
10978: return 'refused';
10979: }
1.104 www 10980: }
1.21 www 10981: $mrole=$role;
10982: }
1.620 albertel 10983: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 10984: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 10985: if ($end) { $command.='_'.$end; }
1.21 www 10986: if ($start) {
10987: if ($end) {
1.81 www 10988: $command.='_'.$start;
1.21 www 10989: } else {
1.81 www 10990: $command.='_0_'.$start;
1.21 www 10991: }
10992: }
1.739 raeburn 10993: my $origstart = $start;
10994: my $origend = $end;
1.957 raeburn 10995: my $delflag;
1.357 www 10996: # actually delete
10997: if ($deleteflag) {
1.373 www 10998: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 10999: # modify command to delete the role
1.620 albertel 11000: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 11001: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 11002: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 11003: # set start and finish to negative values for userrolelog
11004: $start=-1;
11005: $end=-1;
1.957 raeburn 11006: $delflag = 1;
1.357 www 11007: }
11008: }
11009: # send command
1.349 www 11010: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 11011: # log new user role if status is ok
1.349 www 11012: if ($answer eq 'ok') {
1.663 raeburn 11013: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.1184 raeburn 11014: if (($role eq 'cc') || ($role eq 'in') ||
11015: ($role eq 'ep') || ($role eq 'ad') ||
11016: ($role eq 'ta') || ($role eq 'st') ||
11017: ($role=~/^cr/) || ($role eq 'gr') ||
11018: ($role eq 'co')) {
1.1200 raeburn 11019: # for course roles, perform group memberships changes triggered by role change.
11020: unless ($role =~ /^gr/) {
11021: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
11022: $origstart,$selfenroll,$context);
11023: }
1.1184 raeburn 11024: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
1.1512 raeburn 11025: $selfenroll,$context,$othdomby,$requester);
1.1184 raeburn 11026: } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1334 raeburn 11027: ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
11028: ($role eq 'da')) {
1.1184 raeburn 11029: &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
1.1512 raeburn 11030: $context,$othdomby,$requester);
1.1184 raeburn 11031: } elsif (($role eq 'ca') || ($role eq 'aa')) {
1.1517 raeburn 11032: if ($rolelogcontext eq '') {
11033: $rolelogcontext = $context;
11034: }
1.1184 raeburn 11035: &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
1.1517 raeburn 11036: $rolelogcontext,$othdomby,$requester);
1.1184 raeburn 11037: }
1.1053 raeburn 11038: if ($role eq 'cc') {
11039: &autoupdate_coowners($url,$end,$start,$uname,$udom);
11040: }
1.349 www 11041: }
11042: return $answer;
1.169 harris41 11043: }
11044:
1.1053 raeburn 11045: sub autoupdate_coowners {
11046: my ($url,$end,$start,$uname,$udom) = @_;
11047: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
11048: if (($cdom ne '') && ($cnum ne '')) {
11049: my $now = time;
11050: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
11051: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
11052: my %coursehash = &coursedescription($cdom.'_'.$cnum);
11053: my $instcode = $coursehash{'internal.coursecode'};
1.1444 raeburn 11054: my $xlists = $coursehash{'internal.crosslistings'};
1.1053 raeburn 11055: if ($instcode ne '') {
1.1056 raeburn 11056: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
11057: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 11058: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 11059: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
1.1444 raeburn 11060: unless ($result eq 'valid') {
11061: if ($xlists ne '') {
11062: foreach my $xlist (split(',',$xlists)) {
11063: my ($inst_crosslist,$lcsec) = split(':',$xlist);
11064: $result =
1.1446 raeburn 11065: &auto_validate_inst_crosslist($cnum,$cdom,$instcode,
11066: $inst_crosslist,$uname.':'.$udom);
11067: last if ($result eq 'valid');
1.1444 raeburn 11068: }
11069: }
11070: }
1.1056 raeburn 11071: if ($result eq 'valid') {
11072: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 11073: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
11074: push(@newcoowners,$coowner);
11075: }
11076: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
11077: push(@newcoowners,$uname.':'.$udom);
11078: }
11079: @newcoowners = sort(@newcoowners);
11080: } else {
11081: push(@newcoowners,$uname.':'.$udom);
11082: }
1.1444 raeburn 11083: } elsif ($coursehash{'internal.co-owners'}) {
11084: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
11085: unless ($coowner eq $uname.':'.$udom) {
11086: push(@newcoowners,$coowner);
1.1053 raeburn 11087: }
1.1444 raeburn 11088: }
11089: unless (@newcoowners > 0) {
11090: $delcoowners = 1;
11091: $coowners = '';
1.1053 raeburn 11092: }
11093: }
11094: if (@newcoowners || $delcoowners) {
11095: &store_coowners($cdom,$cnum,$coursehash{'home'},
11096: $delcoowners,@newcoowners);
11097: }
11098: }
11099: }
11100: }
11101: }
11102: }
11103: }
11104:
11105: sub store_coowners {
11106: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
11107: my $cid = $cdom.'_'.$cnum;
11108: my ($coowners,$delresult,$putresult);
11109: if (@newcoowners) {
11110: $coowners = join(',',@newcoowners);
11111: my %coownershash = (
11112: 'internal.co-owners' => $coowners,
11113: );
11114: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
11115: if ($putresult eq 'ok') {
11116: if ($env{'course.'.$cid.'.num'} eq $cnum) {
11117: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
11118: }
11119: }
11120: }
11121: if ($delcoowners) {
11122: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
11123: if ($delresult eq 'ok') {
11124: if ($env{'course.'.$cid.'.internal.co-owners'}) {
11125: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
11126: }
11127: }
11128: }
11129: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
11130: my %crsinfo =
1.1494 raeburn 11131: &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
1.1053 raeburn 11132: if (ref($crsinfo{$cid}) eq 'HASH') {
11133: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
1.1494 raeburn 11134: my $cidput = &courseidput($cdom,\%crsinfo,$chome,'notime');
1.1053 raeburn 11135: }
11136: }
11137: }
11138:
1.169 harris41 11139: # -------------------------------------------------- Modify user authentication
1.197 www 11140: # Overrides without validation
11141:
1.169 harris41 11142: sub modifyuserauth {
11143: my ($udom,$uname,$umode,$upass)=@_;
11144: my $uhome=&homeserver($uname,$udom);
1.1409 raeburn 11145: my $allowed;
11146: if (&allowed('mau',$udom)) {
11147: $allowed = 1;
11148: } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
11149: ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
11150: (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
11151: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
11152: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
11153: if (($cdom ne '') && ($cnum ne '')) {
11154: my $is_owner = &is_course_owner($cdom,$cnum);
11155: if ($is_owner) {
11156: $allowed = 1;
11157: }
11158: }
11159: }
11160: unless ($allowed) { return 'refused'; }
1.197 www 11161: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 11162: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
11163: ' in domain '.$env{'request.role.domain'});
1.169 harris41 11164: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
11165: &escape($upass),$uhome);
1.1434 raeburn 11166: my $ip = &get_requestor_ip();
1.620 albertel 11167: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 11168: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
1.1434 raeburn 11169: '(Remote '.$ip.'): '.$reply);
1.197 www 11170: &log($udom,,$uname,$uhome,
1.620 albertel 11171: 'Authentication changed by '.$env{'user.domain'}.', '.
11172: $env{'user.name'}.', '.$umode.
1.1435 raeburn 11173: '(Remote '.$ip.'): '.$reply);
1.169 harris41 11174: unless ($reply eq 'ok') {
1.197 www 11175: &logthis('Authentication mode error: '.$reply);
1.169 harris41 11176: return 'error: '.$reply;
11177: }
1.170 harris41 11178: return 'ok';
1.80 www 11179: }
11180:
1.81 www 11181: # --------------------------------------------------------------- Modify a user
1.80 www 11182:
1.81 www 11183: sub modifyuser {
1.206 matthew 11184: my ($udom, $uname, $uid,
11185: $umode, $upass, $first,
11186: $middle, $last, $gene,
1.1058 raeburn 11187: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 11188: $udom= &LONCAPA::clean_domain($udom);
11189: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 11190: my $showcandelete = 'none';
11191: if (ref($candelete) eq 'ARRAY') {
11192: if (@{$candelete} > 0) {
11193: $showcandelete = join(', ',@{$candelete});
11194: }
11195: }
1.81 www 11196: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 11197: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 11198: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 11199: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
11200: ' desiredhome not specified').
1.620 albertel 11201: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
11202: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 11203: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 11204: my $newuser;
11205: if ($uhome eq 'no_host') {
11206: $newuser = 1;
1.1368 raeburn 11207: unless (($umode && ($upass ne '')) || ($umode eq 'localauth') ||
11208: ($umode eq 'lti')) {
11209: return 'error: more information needed to create new user';
11210: }
1.1075 raeburn 11211: }
1.80 www 11212: # ----------------------------------------------------------------- Create User
1.406 albertel 11213: if (($uhome eq 'no_host') &&
1.1368 raeburn 11214: (($umode && $upass) || ($umode eq 'localauth') || ($umode eq 'lti'))) {
1.80 www 11215: my $unhome='';
1.844 albertel 11216: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 11217: $unhome = $desiredhome;
1.620 albertel 11218: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
11219: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 11220: } else { # load balancing routine for determining $unhome
1.81 www 11221: my $loadm=10000000;
1.841 albertel 11222: my %servers = &get_servers($udom,'library');
11223: foreach my $tryserver (keys(%servers)) {
11224: my $answer=reply('load',$tryserver);
11225: if (($answer=~/\d+/) && ($answer<$loadm)) {
11226: $loadm=$answer;
11227: $unhome=$tryserver;
11228: }
1.80 www 11229: }
11230: }
11231: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 11232: return 'error: unable to find a home server for '.$uname.
11233: ' in domain '.$udom;
1.80 www 11234: }
11235: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
11236: &escape($upass),$unhome);
11237: unless ($reply eq 'ok') {
11238: return 'error: '.$reply;
11239: }
1.230 stredwic 11240: $uhome=&homeserver($uname,$udom,'true');
1.80 www 11241: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 11242: return 'error: unable verify users home machine.';
1.80 www 11243: }
1.209 matthew 11244: } # End of creation of new user
1.80 www 11245: # ---------------------------------------------------------------------- Add ID
11246: if ($uid) {
11247: $uid=~tr/A-Z/a-z/;
11248: my %uidhash=&idrget($udom,$uname);
1.196 www 11249: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
11250: && (!$forceid)) {
1.80 www 11251: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 11252: return 'error: user id "'.$uid.'" does not match '.
11253: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 11254: }
11255: } else {
1.1300 raeburn 11256: &idput($udom,{$uname => $uid},$uhome,'ids');
1.80 www 11257: }
11258: }
11259: # -------------------------------------------------------------- Add names, etc
1.313 matthew 11260: my @tmp=&get('environment',
1.899 raeburn 11261: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 11262: 'permanentemail','inststatus'],
1.134 albertel 11263: $udom,$uname);
1.1075 raeburn 11264: my (%names,%oldnames);
1.313 matthew 11265: if ($tmp[0] =~ m/^error:.*/) {
11266: %names=();
11267: } else {
11268: %names = @tmp;
1.1075 raeburn 11269: %oldnames = %names;
1.313 matthew 11270: }
1.388 www 11271: #
1.1058 raeburn 11272: # If name, email and/or uid are blank (e.g., because an uploaded file
11273: # of users did not contain them), do not overwrite existing values
11274: # unless field is in $candelete array ref.
11275: #
11276:
11277: my @fields = ('firstname','middlename','lastname','generation',
11278: 'permanentemail','id');
11279: my %newvalues;
11280: if (ref($candelete) eq 'ARRAY') {
11281: foreach my $field (@fields) {
11282: if (grep(/^\Q$field\E$/,@{$candelete})) {
11283: if ($field eq 'firstname') {
11284: $names{$field} = $first;
11285: } elsif ($field eq 'middlename') {
11286: $names{$field} = $middle;
11287: } elsif ($field eq 'lastname') {
11288: $names{$field} = $last;
11289: } elsif ($field eq 'generation') {
11290: $names{$field} = $gene;
11291: } elsif ($field eq 'permanentemail') {
11292: $names{$field} = $email;
11293: } elsif ($field eq 'id') {
11294: $names{$field} = $uid;
11295: }
11296: }
11297: }
11298: }
1.388 www 11299: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 11300: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 11301: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 11302: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 11303: if ($email) {
11304: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 11305: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 11306: }
1.899 raeburn 11307: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 11308: if (defined($inststatus)) {
11309: $names{'inststatus'} = '';
11310: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
11311: if (ref($usertypes) eq 'HASH') {
11312: my @okstatuses;
11313: foreach my $item (split(/:/,$inststatus)) {
11314: if (defined($usertypes->{$item})) {
11315: push(@okstatuses,$item);
11316: }
11317: }
11318: if (@okstatuses) {
11319: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
11320: }
11321: }
11322: }
1.1075 raeburn 11323: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 11324: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 11325: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 11326: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
11327: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
11328: } else {
11329: $logmsg .= ' during self creation';
11330: }
1.1075 raeburn 11331: my $changed;
11332: if ($newuser) {
11333: $changed = 1;
11334: } else {
11335: foreach my $field (@fields) {
11336: if ($names{$field} ne $oldnames{$field}) {
11337: $changed = 1;
11338: last;
11339: }
11340: }
11341: }
11342: unless ($changed) {
11343: $logmsg = 'No changes in user information needed for: '.$logmsg;
11344: &logthis($logmsg);
11345: return 'ok';
11346: }
11347: my $reply = &put('environment', \%names, $udom,$uname);
11348: if ($reply ne 'ok') {
11349: return 'error: '.$reply;
11350: }
1.1087 raeburn 11351: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
1.1494 raeburn 11352: &devalidate_cache_new('emailscache',$uname.':'.$udom);
1.1087 raeburn 11353: }
1.1075 raeburn 11354: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
11355: &devalidate_cache_new('namescache',$uname.':'.$udom);
11356: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 11357: &logthis($logmsg);
1.134 albertel 11358: return 'ok';
1.80 www 11359: }
11360:
1.81 www 11361: # -------------------------------------------------------------- Modify student
1.80 www 11362:
1.81 www 11363: sub modifystudent {
11364: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 11365: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1314 raeburn 11366: $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455 albertel 11367: if (!$cid) {
1.620 albertel 11368: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 11369: return 'not_in_class';
11370: }
1.80 www 11371: }
11372: # --------------------------------------------------------------- Make the user
1.81 www 11373: my $reply=&modifyuser
1.209 matthew 11374: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 11375: $desiredhome,$email,$inststatus);
1.80 www 11376: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 11377: # This will cause &modify_student_enrollment to get the uid from the
1.1235 raeburn 11378: # student's environment
1.297 matthew 11379: $uid = undef if (!$forceid);
1.455 albertel 11380: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1216 raeburn 11381: $gene,$usec,$end,$start,$type,$locktype,
1.1314 raeburn 11382: $cid,$selfenroll,$context,$credits,$instsec);
1.297 matthew 11383: return $reply;
11384: }
11385:
11386: sub modify_student_enrollment {
1.1216 raeburn 11387: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1512 raeburn 11388: $locktype,$cid,$selfenroll,$context,$credits,$instsec,$othdomby,$requester) = @_;
1.455 albertel 11389: my ($cdom,$cnum,$chome);
11390: if (!$cid) {
1.620 albertel 11391: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 11392: return 'not_in_class';
11393: }
1.620 albertel 11394: $cdom=$env{'course.'.$cid.'.domain'};
11395: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 11396: } else {
11397: ($cdom,$cnum)=split(/_/,$cid);
11398: }
1.620 albertel 11399: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 11400: if (!$chome) {
1.457 raeburn 11401: $chome=&homeserver($cnum,$cdom);
1.297 matthew 11402: }
1.455 albertel 11403: if (!$chome) { return 'unknown_course'; }
1.297 matthew 11404: # Make sure the user exists
1.81 www 11405: my $uhome=&homeserver($uname,$udom);
11406: if (($uhome eq '') || ($uhome eq 'no_host')) {
11407: return 'error: no such user';
11408: }
1.297 matthew 11409: # Get student data if we were not given enough information
11410: if (!defined($first) || $first eq '' ||
11411: !defined($last) || $last eq '' ||
11412: !defined($uid) || $uid eq '' ||
11413: !defined($middle) || $middle eq '' ||
11414: !defined($gene) || $gene eq '') {
1.294 matthew 11415: # They did not supply us with enough data to enroll the student, so
11416: # we need to pick up more information.
1.297 matthew 11417: my %tmp = &get('environment',
1.294 matthew 11418: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 11419: ,$udom,$uname);
11420:
1.800 albertel 11421: #foreach my $key (keys(%tmp)) {
11422: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 11423: #}
1.294 matthew 11424: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
11425: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
11426: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 11427: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 11428: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
11429: }
1.556 albertel 11430: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148 raeburn 11431: my $user = "$uname:$udom";
1.1494 raeburn 11432: my %old_entry = &get('classlist',[$user],$cdom,$cnum);
1.487 albertel 11433: my $reply=cput('classlist',
1.1148 raeburn 11434: {$user =>
1.1314 raeburn 11435: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487 albertel 11436: $cdom,$cnum);
1.1148 raeburn 11437: if (($reply eq 'ok') || ($reply eq 'delayed')) {
11438: &devalidate_getsection_cache($udom,$uname,$cid);
11439: } else {
1.81 www 11440: return 'error: '.$reply;
11441: }
1.297 matthew 11442: # Add student role to user
1.83 www 11443: my $uurl='/'.$cid;
1.81 www 11444: $uurl=~s/\_/\//g;
11445: if ($usec) {
11446: $uurl.='/'.$usec;
11447: }
1.1148 raeburn 11448: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
1.1512 raeburn 11449: $selfenroll,$context,$othdomby,$requester);
1.1148 raeburn 11450: if ($result ne 'ok') {
11451: if ($old_entry{$user} ne '') {
11452: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
11453: } else {
11454: $reply = &del('classlist',[$user],$cdom,$cnum);
11455: }
11456: }
11457: return $result;
1.21 www 11458: }
11459:
1.556 albertel 11460: sub format_name {
11461: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
11462: my $name;
11463: if ($first ne 'lastname') {
11464: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
11465: } else {
11466: if ($lastname=~/\S/) {
11467: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
11468: $name=~s/\s+,/,/;
11469: } else {
11470: $name.= $firstname.' '.$middlename.' '.$generation;
11471: }
11472: }
11473: $name=~s/^\s+//;
11474: $name=~s/\s+$//;
11475: $name=~s/\s+/ /g;
11476: return $name;
11477: }
11478:
1.84 www 11479: # ------------------------------------------------- Write to course preferences
11480:
11481: sub writecoursepref {
11482: my ($courseid,%prefs)=@_;
11483: $courseid=~s/^\///;
11484: $courseid=~s/\_/\//g;
11485: my ($cdomain,$cnum)=split(/\//,$courseid);
11486: my $chome=homeserver($cnum,$cdomain);
11487: if (($chome eq '') || ($chome eq 'no_host')) {
11488: return 'error: no such course';
11489: }
11490: my $cstring='';
1.800 albertel 11491: foreach my $pref (keys(%prefs)) {
11492: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 11493: }
1.84 www 11494: $cstring=~s/\&$//;
11495: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
11496: }
11497:
11498: # ---------------------------------------------------------- Make/modify course
11499:
11500: sub createcourse {
1.741 raeburn 11501: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1423 raeburn 11502: $course_owner,$crstype,$cnum,$context,$category,$callercontext)=@_;
1.84 www 11503: $url=&declutter($url);
11504: my $cid='';
1.1028 raeburn 11505: if ($context eq 'requestcourses') {
11506: my $can_create = 0;
11507: my ($ownername,$ownerdom) = split(':',$course_owner);
11508: if ($udom eq $ownerdom) {
1.1423 raeburn 11509: my $reload;
11510: if (($callercontext eq 'auto') &&
11511: ($ownerdom eq $env{'user.domain'}) && ($ownername eq $env{'user.name'})) {
11512: $reload = 'reload';
11513: }
11514: if (&usertools_access($ownername,$ownerdom,$category,$reload,
1.1028 raeburn 11515: $context)) {
11516: $can_create = 1;
11517: }
11518: } else {
11519: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
11520: $category);
11521: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
11522: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
11523: if (@curr > 0) {
11524: my @options = qw(approval validate autolimit);
11525: my $optregex = join('|',@options);
11526: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
11527: $can_create = 1;
11528: }
11529: }
11530: }
11531: }
11532: if ($can_create) {
11533: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
11534: unless (&allowed('ccc',$udom)) {
11535: return 'refused';
11536: }
1.1017 raeburn 11537: }
11538: } else {
11539: return 'refused';
11540: }
1.1028 raeburn 11541: } elsif (!&allowed('ccc',$udom)) {
11542: return 'refused';
1.84 www 11543: }
1.1011 raeburn 11544: # --------------------------------------------------------------- Get Unique ID
11545: my $uname;
11546: if ($cnum =~ /^$match_courseid$/) {
11547: my $chome=&homeserver($cnum,$udom,'true');
11548: if (($chome eq '') || ($chome eq 'no_host')) {
11549: $uname = $cnum;
11550: } else {
1.1038 raeburn 11551: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 11552: }
11553: } else {
1.1038 raeburn 11554: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 11555: }
11556: return $uname if ($uname =~ /^error/);
11557: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 11558: if (!defined($course_server)) {
11559: if (defined(&domain($udom,'primary'))) {
11560: $course_server = &domain($udom,'primary');
11561: } else {
11562: $course_server = $env{'user.home'};
11563: }
11564: }
11565: my %host_servers =
1.1494 raeburn 11566: &get_servers($udom,'library');
1.1052 raeburn 11567: unless ($host_servers{$course_server}) {
11568: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 11569: }
1.84 www 11570: # ------------------------------------------------------------- Make the course
11571: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 11572: $course_server);
1.84 www 11573: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 11574: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 11575: if (($uhome eq '') || ($uhome eq 'no_host')) {
11576: return 'error: no such course';
11577: }
1.271 www 11578: # ----------------------------------------------------------------- Course made
1.516 raeburn 11579: # log existence
1.1029 raeburn 11580: my $now = time;
1.918 raeburn 11581: my $newcourse = {
11582: $udom.'_'.$uname => {
1.921 raeburn 11583: description => $description,
11584: inst_code => $inst_code,
11585: owner => $course_owner,
11586: type => $crstype,
1.1029 raeburn 11587: creator => $env{'user.name'}.':'.
11588: $env{'user.domain'},
11589: created => $now,
11590: context => $context,
1.918 raeburn 11591: },
11592: };
1.921 raeburn 11593: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 11594: # set toplevel url
1.271 www 11595: my $topurl=$url;
11596: unless ($nonstandard) {
11597: # ------------------------------------------ For standard courses, make top url
11598: my $mapurl=&clutter($url);
1.278 www 11599: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 11600: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 11601: <map>
11602: <resource id="1" type="start"></resource>
11603: <resource id="2" src="$mapurl"></resource>
11604: <resource id="3" type="finish"></resource>
11605: <link index="1" from="1" to="2"></link>
11606: <link index="2" from="2" to="3"></link>
11607: </map>
11608: ENDINITMAP
11609: $topurl=&declutter(
1.638 albertel 11610: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 11611: );
11612: }
11613: # ----------------------------------------------------------- Write preferences
1.84 www 11614: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 11615: ('description' => $description,
11616: 'url' => $topurl,
11617: 'internal.creator' => $env{'user.name'}.':'.
11618: $env{'user.domain'},
11619: 'internal.created' => $now,
11620: 'internal.creationcontext' => $context)
11621: );
1.84 www 11622: return '/'.$udom.'/'.$uname;
11623: }
11624:
1.1011 raeburn 11625: # ------------------------------------------------------------------- Create ID
11626: sub generate_coursenum {
1.1038 raeburn 11627: my ($udom,$crstype) = @_;
1.1011 raeburn 11628: my $domdesc = &domain($udom);
11629: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 11630: my $first;
11631: if ($crstype eq 'Community') {
11632: $first = '0';
11633: } else {
11634: $first = int(1+rand(9));
11635: }
11636: my $uname=$first.
1.1011 raeburn 11637: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
11638: substr($$.time,0,5).unpack("H8",pack("I32",time)).
11639: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
11640: # ----------------------------------------------- Make sure that does not exist
11641: my $uhome=&homeserver($uname,$udom,'true');
11642: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 11643: if ($crstype eq 'Community') {
11644: $first = '0';
11645: } else {
11646: $first = int(1+rand(9));
11647: }
11648: $uname=$first.
1.1011 raeburn 11649: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
11650: substr($$.time,0,5).unpack("H8",pack("I32",time)).
11651: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
11652: $uhome=&homeserver($uname,$udom,'true');
11653: unless (($uhome eq '') || ($uhome eq 'no_host')) {
11654: return 'error: unable to generate unique course-ID';
11655: }
11656: }
11657: return $uname;
11658: }
11659:
1.813 albertel 11660: sub is_course {
1.1167 droeschl 11661: my ($cdom, $cnum) = scalar(@_) == 1 ?
11662: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
11663:
1.1381 raeburn 11664: return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
11665: my $uhome=&homeserver($cnum,$cdom);
11666: my $iscourse;
11667: if (grep { $_ eq $uhome } current_machine_ids()) {
1.1382 raeburn 11668: $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
1.1381 raeburn 11669: } else {
11670: my $hashid = $cdom.':'.$cnum;
11671: ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
11672: unless (defined($cached)) {
11673: my %courses = &courseiddump($cdom, '.', 1, '.', '.',
11674: $cnum,undef,undef,'.');
11675: $iscourse = 0;
11676: if (exists($courses{$cdom.'_'.$cnum})) {
11677: $iscourse = 1;
11678: }
11679: &do_cache_new('iscourse',$hashid,$iscourse,3600);
11680: }
11681: }
11682: return unless ($iscourse);
1.1167 droeschl 11683: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813 albertel 11684: }
11685:
1.1015 raeburn 11686: sub store_userdata {
1.1533 ! raeburn 11687: my ($storehash,$datakey,$namespace,$udom,$uname,$ip) = @_;
1.1013 raeburn 11688: my $result;
1.1016 raeburn 11689: if ($datakey ne '') {
1.1013 raeburn 11690: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 11691: if ($udom eq '' || $uname eq '') {
11692: $udom = $env{'user.domain'};
11693: $uname = $env{'user.name'};
11694: }
11695: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 11696: if (($uhome eq '') || ($uhome eq 'no_host')) {
11697: $result = 'error: no_host';
11698: } else {
1.1533 ! raeburn 11699: if ($ip ne '') {
! 11700: $storehash->{'ip'} = $ip;
! 11701: } else {
! 11702: $storehash->{'ip'} = &get_requestor_ip();
! 11703: }
1.1013 raeburn 11704: $storehash->{'host'} = $perlvar{'lonHostID'};
11705:
11706: my $namevalue='';
11707: foreach my $key (keys(%{$storehash})) {
11708: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
11709: }
11710: $namevalue=~s/\&$//;
1.1224 raeburn 11711: unless ($namespace eq 'courserequests') {
11712: $datakey = &escape($datakey);
11713: }
1.1105 raeburn 11714: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
11715: $namevalue,$uhome);
1.1013 raeburn 11716: }
11717: } else {
11718: $result = 'error: data to store was not a hash reference';
11719: }
11720: } else {
11721: $result= 'error: invalid requestkey';
11722: }
11723: return $result;
11724: }
11725:
1.21 www 11726: # ---------------------------------------------------------- Assign Custom Role
11727:
11728: sub assigncustomrole {
1.1512 raeburn 11729: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,
11730: $selfenroll,$context,$othdomby,$requester)=@_;
1.21 www 11731: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.1512 raeburn 11732: $end,$start,$deleteflag,$selfenroll,$context,$othdomby,
11733: $requester);
1.21 www 11734: }
11735:
11736: # ----------------------------------------------------------------- Revoke Role
11737:
11738: sub revokerole {
1.957 raeburn 11739: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 11740: my $now=time;
1.965 raeburn 11741: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 11742: }
11743:
11744: # ---------------------------------------------------------- Revoke Custom Role
11745:
11746: sub revokecustomrole {
1.957 raeburn 11747: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 11748: my $now=time;
1.357 www 11749: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 11750: $deleteflag,$selfenroll,$context);
1.17 www 11751: }
11752:
1.533 banghart 11753: # ------------------------------------------------------------ Disk usage
1.535 albertel 11754: sub diskusage {
1.955 raeburn 11755: my ($udom,$uname,$directorypath,$getpropath)=@_;
11756: $directorypath =~ s/\/$//;
11757: my $listing=&reply('du2:'.&escape($directorypath).':'
11758: .&escape($getpropath).':'.&escape($uname).':'
11759: .&escape($udom),homeserver($uname,$udom));
11760: if ($listing eq 'unknown_cmd') {
11761: if ($getpropath) {
11762: $directorypath = &propath($udom,$uname).'/'.$directorypath;
11763: }
11764: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
11765: }
1.514 albertel 11766: return $listing;
1.512 banghart 11767: }
11768:
1.566 banghart 11769: sub is_locked {
1.1096 raeburn 11770: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 11771: my @check;
11772: my $is_locked;
1.1093 raeburn 11773: push (@check,$file_name);
1.613 albertel 11774: my %locked = &get('file_permissions',\@check,
1.620 albertel 11775: $env{'user.domain'},$env{'user.name'});
1.615 albertel 11776: my ($tmp)=keys(%locked);
11777: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 11778:
1.566 banghart 11779: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 11780: $is_locked = 'false';
11781: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 11782: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 11783: $is_locked = 'true';
1.1096 raeburn 11784: if (ref($which) eq 'ARRAY') {
11785: push(@{$which},$entry);
11786: } else {
11787: last;
11788: }
1.745 raeburn 11789: }
11790: }
1.566 banghart 11791: } else {
11792: $is_locked = 'false';
11793: }
1.1093 raeburn 11794: return $is_locked;
1.566 banghart 11795: }
11796:
1.759 albertel 11797: sub declutter_portfile {
11798: my ($file) = @_;
1.833 albertel 11799: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 11800: return $file;
11801: }
11802:
1.559 banghart 11803: # ------------------------------------------------------------- Mark as Read Only
11804:
11805: sub mark_as_readonly {
11806: my ($domain,$user,$files,$what) = @_;
1.613 albertel 11807: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 11808: my ($tmp)=keys(%current_permissions);
11809: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 11810: foreach my $file (@{$files}) {
1.759 albertel 11811: $file = &declutter_portfile($file);
1.561 banghart 11812: push(@{$current_permissions{$file}},$what);
1.559 banghart 11813: }
1.613 albertel 11814: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 11815: return;
11816: }
11817:
1.572 banghart 11818: # ------------------------------------------------------------Save Selected Files
11819:
11820: sub save_selected_files {
11821: my ($user, $path, @files) = @_;
11822: my $filename = $user."savedfiles";
1.573 banghart 11823: my @other_files = &files_not_in_path($user, $path);
1.1359 raeburn 11824: open (OUT,'>',LONCAPA::tempdir().$filename);
1.573 banghart 11825: foreach my $file (@files) {
1.620 albertel 11826: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 11827: }
11828: foreach my $file (@other_files) {
1.574 banghart 11829: print (OUT $file."\n");
1.572 banghart 11830: }
1.574 banghart 11831: close (OUT);
1.572 banghart 11832: return 'ok';
11833: }
11834:
1.574 banghart 11835: sub clear_selected_files {
11836: my ($user) = @_;
11837: my $filename = $user."savedfiles";
1.1359 raeburn 11838: open (OUT,'>',LONCAPA::tempdir().$filename);
1.574 banghart 11839: print (OUT undef);
11840: close (OUT);
11841: return ("ok");
11842: }
11843:
1.572 banghart 11844: sub files_in_path {
11845: my ($user, $path) = @_;
11846: my $filename = $user."savedfiles";
11847: my %return_files;
1.1359 raeburn 11848: open (IN,'<',LONCAPA::tempdir().$filename);
1.573 banghart 11849: while (my $line_in = <IN>) {
1.574 banghart 11850: chomp ($line_in);
11851: my @paths_and_file = split (m!/!, $line_in);
11852: my $file_part = pop (@paths_and_file);
11853: my $path_part = join ('/', @paths_and_file);
1.573 banghart 11854: $path_part.='/';
11855: my $path_and_file = $path_part.$file_part;
11856: if ($path_part eq $path) {
11857: $return_files{$file_part}= 'selected';
11858: }
11859: }
1.574 banghart 11860: close (IN);
11861: return (\%return_files);
1.572 banghart 11862: }
11863:
11864: # called in portfolio select mode, to show files selected NOT in current directory
11865: sub files_not_in_path {
11866: my ($user, $path) = @_;
11867: my $filename = $user."savedfiles";
11868: my @return_files;
11869: my $path_part;
1.1359 raeburn 11870: open(IN, '<',LONCAPA::tempdir().$filename);
1.800 albertel 11871: while (my $line = <IN>) {
1.572 banghart 11872: #ok, I know it's clunky, but I want it to work
1.800 albertel 11873: my @paths_and_file = split(m|/|, $line);
11874: my $file_part = pop(@paths_and_file);
11875: chomp($file_part);
11876: my $path_part = join('/', @paths_and_file);
1.572 banghart 11877: $path_part .= '/';
11878: my $path_and_file = $path_part.$file_part;
11879: if ($path_part ne $path) {
1.800 albertel 11880: push(@return_files, ($path_and_file));
1.572 banghart 11881: }
11882: }
1.800 albertel 11883: close(OUT);
1.574 banghart 11884: return (@return_files);
1.572 banghart 11885: }
11886:
1.1273 raeburn 11887: #------------------------------Submitted/Handedback Portfolio Files Versioning
11888:
11889: sub portfiles_versioning {
11890: my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
11891: my $portfolio_root = '/userfiles/portfolio';
11892: return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
11893: foreach my $file (@{$portfiles}) {
11894: &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
11895: my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
11896: my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
11897: my $getpropath = 1;
11898: my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
11899: $stu_name,$getpropath);
11900: my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
11901: my $new_answer =
11902: &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
11903: if ($new_answer ne 'problem getting file') {
11904: push(@{$versioned_portfiles}, $directory.$new_answer);
11905: &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
11906: [$symb,$env{'request.course.id'},'graded']);
11907: }
11908: }
11909: }
11910:
11911: sub get_next_version {
11912: my ($answer_name, $answer_ext, $dir_list) = @_;
11913: my $version;
11914: if (ref($dir_list) eq 'ARRAY') {
11915: foreach my $row (@{$dir_list}) {
11916: my ($file) = split(/\&/,$row,2);
11917: my ($file_name,$file_version,$file_ext) =
11918: &file_name_version_ext($file);
11919: if (($file_name eq $answer_name) &&
11920: ($file_ext eq $answer_ext)) {
11921: # gets here if filename and extension match,
11922: # regardless of version
11923: if ($file_version ne '') {
11924: # a versioned file is found so save it for later
11925: if ($file_version > $version) {
11926: $version = $file_version;
11927: }
11928: }
11929: }
11930: }
11931: }
11932: $version ++;
11933: return($version);
11934: }
11935:
11936: sub version_selected_portfile {
11937: my ($domain,$stu_name,$directory,$file_name,$version) = @_;
11938: my ($answer_name,$answer_ver,$answer_ext) =
11939: &file_name_version_ext($file_name);
11940: my $new_answer;
11941: $env{'form.copy'} =
11942: &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
11943: if($env{'form.copy'} eq '-1') {
11944: $new_answer = 'problem getting file';
11945: } else {
11946: $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
11947: my $copy_result =
11948: &finishuserfileupload($stu_name,$domain,'copy',
11949: '/portfolio'.$directory.$new_answer);
11950: }
11951: undef($env{'form.copy'});
11952: return ($new_answer);
11953: }
11954:
11955: sub file_name_version_ext {
11956: my ($file)=@_;
11957: my @file_parts = split(/\./, $file);
11958: my ($name,$version,$ext);
11959: if (@file_parts > 1) {
11960: $ext=pop(@file_parts);
11961: if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
11962: $version=pop(@file_parts);
11963: }
11964: $name=join('.',@file_parts);
11965: } else {
11966: $name=join('.',@file_parts);
11967: }
11968: return($name,$version,$ext);
11969: }
11970:
1.745 raeburn 11971: #----------------------------------------------Get portfolio file permissions
1.629 banghart 11972:
1.745 raeburn 11973: sub get_portfile_permissions {
11974: my ($domain,$user) = @_;
1.613 albertel 11975: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 11976: my ($tmp)=keys(%current_permissions);
11977: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 11978: return \%current_permissions;
11979: }
11980:
11981: #---------------------------------------------Get portfolio file access controls
11982:
1.749 raeburn 11983: sub get_access_controls {
1.745 raeburn 11984: my ($current_permissions,$group,$file) = @_;
1.769 albertel 11985: my %access;
11986: my $real_file = $file;
11987: $file =~ s/\.meta$//;
1.745 raeburn 11988: if (defined($file)) {
1.749 raeburn 11989: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
11990: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 11991: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 11992: }
11993: }
1.745 raeburn 11994: } else {
1.749 raeburn 11995: foreach my $key (keys(%{$current_permissions})) {
11996: if ($key =~ /\0accesscontrol$/) {
11997: if (defined($group)) {
11998: if ($key !~ m-^\Q$group\E/-) {
11999: next;
12000: }
12001: }
12002: my ($fullpath) = split(/\0/,$key);
12003: if (ref($$current_permissions{$key}) eq 'HASH') {
12004: foreach my $control (keys(%{$$current_permissions{$key}})) {
12005: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
12006: }
12007: }
12008: }
12009: }
12010: }
12011: return %access;
12012: }
12013:
12014: sub modify_access_controls {
12015: my ($file_name,$changes,$domain,$user)=@_;
12016: my ($outcome,$deloutcome);
12017: my %store_permissions;
12018: my %new_values;
12019: my %new_control;
12020: my %translation;
12021: my @deletions = ();
12022: my $now = time;
12023: if (exists($$changes{'activate'})) {
12024: if (ref($$changes{'activate'}) eq 'HASH') {
12025: my @newitems = sort(keys(%{$$changes{'activate'}}));
12026: my $numnew = scalar(@newitems);
12027: for (my $i=0; $i<$numnew; $i++) {
12028: my $newkey = $newitems[$i];
12029: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 12030: if ($newkey =~ /^\d+:/) {
12031: $newkey =~ s/^(\d+)/$newid/;
12032: $translation{$1} = $newid;
12033: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
12034: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
12035: $translation{$1} = $newid;
12036: }
1.749 raeburn 12037: $new_values{$file_name."\0".$newkey} =
12038: $$changes{'activate'}{$newitems[$i]};
12039: $new_control{$newkey} = $now;
12040: }
12041: }
12042: }
12043: my %todelete;
12044: my %changed_items;
12045: foreach my $action ('delete','update') {
12046: if (exists($$changes{$action})) {
12047: if (ref($$changes{$action}) eq 'HASH') {
12048: foreach my $key (keys(%{$$changes{$action}})) {
12049: my ($itemnum) = ($key =~ /^([^:]+):/);
12050: if ($action eq 'delete') {
12051: $todelete{$itemnum} = 1;
12052: } else {
12053: $changed_items{$itemnum} = $key;
12054: }
12055: }
1.745 raeburn 12056: }
12057: }
1.749 raeburn 12058: }
12059: # get lock on access controls for file.
12060: my $lockhash = {
12061: $file_name."\0".'locked_access_records' => $env{'user.name'}.
12062: ':'.$env{'user.domain'},
12063: };
12064: my $tries = 0;
12065: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
12066:
1.1288 damieng 12067: while (($gotlock ne 'ok') && $tries < 10) {
1.749 raeburn 12068: $tries ++;
1.1289 damieng 12069: sleep(0.1);
1.749 raeburn 12070: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
12071: }
12072: if ($gotlock eq 'ok') {
12073: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
12074: my ($tmp)=keys(%curr_permissions);
12075: if ($tmp=~/^error:/) { undef(%curr_permissions); }
12076: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
12077: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
12078: if (ref($curr_controls) eq 'HASH') {
12079: foreach my $control_item (keys(%{$curr_controls})) {
12080: my ($itemnum) = ($control_item =~ /^([^:]+):/);
12081: if (defined($todelete{$itemnum})) {
12082: push(@deletions,$file_name."\0".$control_item);
12083: } else {
12084: if (defined($changed_items{$itemnum})) {
12085: $new_control{$changed_items{$itemnum}} = $now;
12086: push(@deletions,$file_name."\0".$control_item);
12087: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
12088: } else {
12089: $new_control{$control_item} = $$curr_controls{$control_item};
12090: }
12091: }
1.745 raeburn 12092: }
12093: }
12094: }
1.970 raeburn 12095: my ($group);
12096: if (&is_course($domain,$user)) {
12097: ($group,my $file) = split(/\//,$file_name,2);
12098: }
1.749 raeburn 12099: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
12100: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
12101: $outcome = &put('file_permissions',\%new_values,$domain,$user);
12102: # remove lock
12103: my @del_lock = ($file_name."\0".'locked_access_records');
12104: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 12105: my $sqlresult =
1.970 raeburn 12106: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 12107: $group);
1.749 raeburn 12108: } else {
12109: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 12110: }
1.749 raeburn 12111: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 12112: }
12113:
1.827 raeburn 12114: sub make_public_indefinitely {
1.1271 raeburn 12115: my (@requrl) = @_;
12116: return &automated_portfile_access('public',\@requrl);
12117: }
12118:
12119: sub automated_portfile_access {
12120: my ($accesstype,$addsref,$delsref,$info) = @_;
1.1273 raeburn 12121: unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
12122: return 'invalid';
12123: }
1.1271 raeburn 12124: my %urls;
12125: if (ref($addsref) eq 'ARRAY') {
12126: foreach my $requrl (@{$addsref}) {
12127: if (&is_portfolio_url($requrl)) {
12128: unless (exists($urls{$requrl})) {
12129: $urls{$requrl} = 'add';
12130: }
12131: }
12132: }
12133: }
12134: if (ref($delsref) eq 'ARRAY') {
12135: foreach my $requrl (@{$delsref}) {
12136: if (&is_portfolio_url($requrl)) {
12137: unless (exists($urls{$requrl})) {
12138: $urls{$requrl} = 'delete';
12139: }
12140: }
12141: }
12142: }
12143: unless (keys(%urls)) {
12144: return 'invalid';
12145: }
12146: my $ip;
12147: if ($accesstype eq 'ip') {
12148: if (ref($info) eq 'HASH') {
12149: if ($info->{'ip'} ne '') {
12150: $ip = $info->{'ip'};
12151: }
12152: }
12153: if ($ip eq '') {
12154: return 'invalid';
12155: }
12156: }
12157: my $errors;
1.827 raeburn 12158: my $now = time;
1.1271 raeburn 12159: my %current_perms;
12160: foreach my $requrl (sort(keys(%urls))) {
12161: my $action;
12162: if ($urls{$requrl} eq 'add') {
12163: $action = 'activate';
12164: } else {
12165: $action = 'none';
12166: }
12167: my $aclnum = 0;
1.827 raeburn 12168: my (undef,$udom,$unum,$file_name,$group) =
12169: &parse_portfolio_url($requrl);
1.1271 raeburn 12170: unless (exists($current_perms{$unum.':'.$udom})) {
12171: $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
12172: }
12173: my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
1.827 raeburn 12174: $group,$file_name);
12175: foreach my $key (keys(%{$access_controls{$file_name}})) {
12176: my ($num,$scope,$end,$start) =
12177: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
1.1271 raeburn 12178: if ($scope eq $accesstype) {
12179: if (($start <= $now) && ($end == 0)) {
12180: if ($accesstype eq 'ip') {
12181: if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
12182: if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
12183: if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
12184: if ($urls{$requrl} eq 'add') {
12185: $action = 'none';
12186: last;
12187: } else {
12188: $action = 'delete';
12189: $aclnum = $num;
12190: last;
12191: }
12192: }
12193: }
12194: }
12195: } elsif ($accesstype eq 'public') {
12196: if ($urls{$requrl} eq 'add') {
12197: $action = 'none';
12198: last;
12199: } else {
12200: $action = 'delete';
12201: $aclnum = $num;
12202: last;
12203: }
12204: }
12205: } elsif ($accesstype eq 'public') {
1.827 raeburn 12206: $action = 'update';
12207: $aclnum = $num;
1.1271 raeburn 12208: last;
1.827 raeburn 12209: }
12210: }
12211: }
12212: if ($action eq 'none') {
1.1271 raeburn 12213: next;
1.827 raeburn 12214: } else {
12215: my %changes;
12216: my $newend = 0;
12217: my $newstart = $now;
1.1271 raeburn 12218: my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
1.827 raeburn 12219: $changes{$action}{$newkey} = {
1.1271 raeburn 12220: type => $accesstype,
1.827 raeburn 12221: time => {
12222: start => $newstart,
12223: end => $newend,
12224: },
12225: };
1.1271 raeburn 12226: if ($accesstype eq 'ip') {
12227: $changes{$action}{$newkey}{'ip'} = [$ip];
12228: }
1.827 raeburn 12229: my ($outcome,$deloutcome,$new_values,$translation) =
12230: &modify_access_controls($file_name,\%changes,$udom,$unum);
1.1271 raeburn 12231: unless ($outcome eq 'ok') {
12232: $errors .= $outcome.' ';
12233: }
1.827 raeburn 12234: }
1.1271 raeburn 12235: }
12236: if ($errors) {
12237: $errors =~ s/\s$//;
12238: return $errors;
1.827 raeburn 12239: } else {
1.1271 raeburn 12240: return 'ok';
1.827 raeburn 12241: }
12242: }
12243:
1.745 raeburn 12244: #------------------------------------------------------Get Marked as Read Only
12245:
12246: sub get_marked_as_readonly {
12247: my ($domain,$user,$what,$group) = @_;
12248: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 12249: my @readonly_files;
1.629 banghart 12250: my $cmp1=$what;
12251: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 12252: while (my ($file_name,$value) = each(%{$current_permissions})) {
12253: if (defined($group)) {
12254: if ($file_name !~ m-^\Q$group\E/-) {
12255: next;
12256: }
12257: }
1.561 banghart 12258: if (ref($value) eq "ARRAY"){
12259: foreach my $stored_what (@{$value}) {
1.629 banghart 12260: my $cmp2=$stored_what;
1.759 albertel 12261: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 12262: $cmp2=join('',@{$stored_what});
1.745 raeburn 12263: }
1.629 banghart 12264: if ($cmp1 eq $cmp2) {
1.561 banghart 12265: push(@readonly_files, $file_name);
1.745 raeburn 12266: last;
1.563 banghart 12267: } elsif (!defined($what)) {
12268: push(@readonly_files, $file_name);
1.745 raeburn 12269: last;
1.561 banghart 12270: }
12271: }
1.745 raeburn 12272: }
1.561 banghart 12273: }
12274: return @readonly_files;
12275: }
1.577 banghart 12276: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 12277:
1.577 banghart 12278: sub get_marked_as_readonly_hash {
1.745 raeburn 12279: my ($current_permissions,$group,$what) = @_;
1.577 banghart 12280: my %readonly_files;
1.745 raeburn 12281: while (my ($file_name,$value) = each(%{$current_permissions})) {
12282: if (defined($group)) {
12283: if ($file_name !~ m-^\Q$group\E/-) {
12284: next;
12285: }
12286: }
1.577 banghart 12287: if (ref($value) eq "ARRAY"){
12288: foreach my $stored_what (@{$value}) {
1.745 raeburn 12289: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 12290: foreach my $lock_descriptor(@{$stored_what}) {
12291: if ($lock_descriptor eq 'graded') {
12292: $readonly_files{$file_name} = 'graded';
12293: } elsif ($lock_descriptor eq 'handback') {
12294: $readonly_files{$file_name} = 'handback';
12295: } else {
12296: if (!exists($readonly_files{$file_name})) {
12297: $readonly_files{$file_name} = 'locked';
12298: }
12299: }
1.745 raeburn 12300: }
1.750 banghart 12301: }
1.577 banghart 12302: }
12303: }
12304: }
12305: return %readonly_files;
12306: }
1.559 banghart 12307: # ------------------------------------------------------------ Unmark as Read Only
12308:
12309: sub unmark_as_readonly {
1.629 banghart 12310: # unmarks $file_name (if $file_name is defined), or all files locked by $what
12311: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 12312: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 12313: $file_name = &declutter_portfile($file_name);
1.634 albertel 12314: my $symb_crs = $what;
12315: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 12316: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 12317: my ($tmp)=keys(%current_permissions);
12318: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 12319: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 12320: foreach my $file (@readonly_files) {
1.759 albertel 12321: my $clean_file = &declutter_portfile($file);
12322: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 12323: my $current_locks = $current_permissions{$file};
1.563 banghart 12324: my @new_locks;
12325: my @del_keys;
12326: if (ref($current_locks) eq "ARRAY"){
12327: foreach my $locker (@{$current_locks}) {
1.632 albertel 12328: my $compare=$locker;
1.749 raeburn 12329: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 12330: $compare=join('',@{$locker});
1.746 raeburn 12331: if ($compare ne $symb_crs) {
12332: push(@new_locks, $locker);
12333: }
1.563 banghart 12334: }
12335: }
1.650 albertel 12336: if (scalar(@new_locks) > 0) {
1.563 banghart 12337: $current_permissions{$file} = \@new_locks;
12338: } else {
12339: push(@del_keys, $file);
1.613 albertel 12340: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 12341: delete($current_permissions{$file});
1.563 banghart 12342: }
12343: }
1.561 banghart 12344: }
1.613 albertel 12345: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 12346: return;
12347: }
1.512 banghart 12348:
1.17 www 12349: # ------------------------------------------------------------ Directory lister
12350:
12351: sub dirlist {
1.955 raeburn 12352: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 12353: $uri=~s/^\///;
12354: $uri=~s/\/$//;
1.253 stredwic 12355: my ($udom, $uname);
1.955 raeburn 12356: if ($getuserdir) {
1.253 stredwic 12357: $udom = $userdomain;
12358: $uname = $username;
1.955 raeburn 12359: } else {
12360: (undef,$udom,$uname)=split(/\//,$uri);
12361: if(defined($userdomain)) {
12362: $udom = $userdomain;
12363: }
12364: if(defined($username)) {
12365: $uname = $username;
12366: }
1.253 stredwic 12367: }
1.955 raeburn 12368: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 12369:
1.955 raeburn 12370: $dirRoot = $perlvar{'lonDocRoot'};
12371: if (defined($getpropath)) {
12372: $dirRoot = &propath($udom,$uname);
1.253 stredwic 12373: $dirRoot =~ s/\/$//;
1.955 raeburn 12374: } elsif (defined($getuserdir)) {
12375: my $subdir=$uname.'__';
12376: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
12377: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
12378: ."/$udom/$subdir/$uname";
12379: } elsif (defined($alternateRoot)) {
12380: $dirRoot = $alternateRoot;
1.751 banghart 12381: }
1.253 stredwic 12382:
12383: if($udom) {
12384: if($uname) {
1.1135 raeburn 12385: my $uhome = &homeserver($uname,$udom);
1.1136 raeburn 12386: if ($uhome eq 'no_host') {
12387: return ([],'no_host');
12388: }
1.955 raeburn 12389: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 12390: .$getuserdir.':'.&escape($dirRoot)
1.1135 raeburn 12391: .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955 raeburn 12392: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 12393: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955 raeburn 12394: } else {
12395: @listing_results = map { &unescape($_); } split(/:/,$listing);
12396: }
1.605 matthew 12397: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 12398: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605 matthew 12399: @listing_results = split(/:/,$listing);
12400: } else {
12401: @listing_results = map { &unescape($_); } split(/:/,$listing);
12402: }
1.1135 raeburn 12403: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
1.1136 raeburn 12404: ($listing eq 'rejected') || ($listing eq 'refused') ||
12405: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
12406: return ([],$listing);
12407: } else {
12408: return (\@listing_results);
1.1135 raeburn 12409: }
1.955 raeburn 12410: } elsif(!$alternateRoot) {
1.1136 raeburn 12411: my (%allusers,%listerror);
1.841 albertel 12412: my %servers = &get_servers($udom,'library');
1.955 raeburn 12413: foreach my $tryserver (keys(%servers)) {
12414: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
12415: &escape($udom),$tryserver);
12416: if ($listing eq 'unknown_cmd') {
12417: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
12418: $udom, $tryserver);
12419: } else {
12420: @listing_results = map { &unescape($_); } split(/:/,$listing);
12421: }
1.841 albertel 12422: if ($listing eq 'unknown_cmd') {
12423: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
12424: $udom, $tryserver);
12425: @listing_results = split(/:/,$listing);
12426: } else {
12427: @listing_results =
12428: map { &unescape($_); } split(/:/,$listing);
12429: }
1.1136 raeburn 12430: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
12431: ($listing eq 'rejected') || ($listing eq 'refused') ||
12432: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
12433: $listerror{$tryserver} = $listing;
12434: } else {
1.841 albertel 12435: foreach my $line (@listing_results) {
12436: my ($entry) = split(/&/,$line,2);
12437: $allusers{$entry} = 1;
12438: }
12439: }
1.253 stredwic 12440: }
1.1136 raeburn 12441: my @alluserslist=();
1.800 albertel 12442: foreach my $user (sort(keys(%allusers))) {
1.1136 raeburn 12443: push(@alluserslist,$user.'&user');
1.253 stredwic 12444: }
1.1318 droeschl 12445:
12446: if (!%listerror) {
12447: # no errors
12448: return (\@alluserslist);
12449: } elsif (scalar(keys(%servers)) == 1) {
12450: # one library server, one error
12451: my ($key) = keys(%listerror);
12452: return (\@alluserslist, $listerror{$key});
12453: } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
12454: # con_lost indicates that we might miss data from at least one
12455: # library server
12456: return (\@alluserslist, 'con_lost');
12457: } else {
12458: # multiple library servers and no con_lost -> data should be
12459: # complete.
12460: return (\@alluserslist);
12461: }
12462:
1.253 stredwic 12463: } else {
1.1136 raeburn 12464: return ([],'missing username');
1.253 stredwic 12465: }
1.955 raeburn 12466: } elsif(!defined($getpropath)) {
1.1136 raeburn 12467: my $path = $perlvar{'lonDocRoot'}.'/res/';
12468: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
12469: return (\@all_domains);
1.955 raeburn 12470: } else {
1.1136 raeburn 12471: return ([],'missing domain');
1.275 stredwic 12472: }
12473: }
12474:
12475: # --------------------------------------------- GetFileTimestamp
12476: # This function utilizes dirlist and returns the date stamp for
12477: # when it was last modified. It will also return an error of -1
12478: # if an error occurs
12479:
12480: sub GetFileTimestamp {
1.955 raeburn 12481: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 12482: $studentDomain = &LONCAPA::clean_domain($studentDomain);
12483: $studentName = &LONCAPA::clean_username($studentName);
1.1136 raeburn 12484: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
12485: undef,$getuserdir);
12486: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
12487: return -1;
12488: }
12489: if (ref($fileref) eq 'ARRAY') {
12490: my @stats = split('&',$fileref->[0]);
1.375 matthew 12491: # @stats contains first the filename, then the stat output
12492: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 12493: } else {
12494: return -1;
1.253 stredwic 12495: }
1.26 www 12496: }
12497:
1.712 albertel 12498: sub stat_file {
12499: my ($uri) = @_;
1.787 albertel 12500: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 12501:
1.955 raeburn 12502: my ($udom,$uname,$file);
1.712 albertel 12503: if ($uri =~ m-^/(uploaded|editupload)/-) {
12504: ($udom,$uname,$file) =
1.811 albertel 12505: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 12506: $file = 'userfiles/'.$file;
12507: }
12508: if ($uri =~ m-^/res/-) {
12509: ($udom,$uname) =
1.807 albertel 12510: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 12511: $file = $uri;
12512: }
12513:
12514: if (!$udom || !$uname || !$file) {
12515: # unable to handle the uri
12516: return ();
12517: }
1.956 raeburn 12518: my $getpropath;
12519: if ($file =~ /^userfiles\//) {
12520: $getpropath = 1;
12521: }
1.1136 raeburn 12522: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
12523: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
12524: return ();
12525: } else {
12526: if (ref($listref) eq 'ARRAY') {
12527: my @stats = split('&',$listref->[0]);
12528: shift(@stats); #filename is first
12529: return @stats;
12530: }
1.712 albertel 12531: }
12532: return ();
12533: }
12534:
1.1313 raeburn 12535: # --------------------------------------------------------- recursedirs
12536: # Recursive function to traverse either a specific user's Authoring Space
12537: # or corresponding Published Resource Space, and populate the hash ref:
12538: # $dirhashref with URLs of all directories, and if $filehashref hash
12539: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
1.1503 raeburn 12540: # or .rights files in resource space, and .meta, .save, .log, .bak and
12541: # .rights files in Authoring Space.
1.1313 raeburn 12542: #
12543: # Inputs:
12544: #
12545: # $is_home - true if current server is home server for user's space
1.1503 raeburn 12546: # $recurse - if true will also traverse subdirectories recursively
12547: # $include - reference to hash containing allowed file extensions. If provided,
12548: # files which do not have a matching extension will be ignored.
12549: # $exclude - reference to hash containing excluded file extensions. If provided,
12550: # files which have a matching extension will be ignored.
12551: # $nonemptydir - if true, will only populate $fileshashref hash entry for a particular
12552: # directory with first file found (with acceptable extension).
1.1505 raeburn 12553: # $addtopdir - if true, set $dirhashref->{'/'} = 1
1.1313 raeburn 12554: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
12555: # $relpath - Current path (relative to top level).
12556: # $dirhashref - reference to hash to populate with URLs of directories (Required)
12557: # $filehashref - reference to hash to populate with URLs of files (Optional)
1.1532 raeburn 12558: # $getlastmod - if true, will set value for each key in innerhash in $filehashref
12559: # to last modification time of file; value set to 1 otherwise.
1.1313 raeburn 12560: #
12561: # Returns: nothing
12562: #
12563: # Side Effects: populates $dirhashref, and $filehashref (if provided).
12564: #
12565: # Currently used by interface/londocs.pm to create linked select boxes for
12566: # directory and filename to import a Course "Author" resource into a course, and
12567: # also to create linked select boxes for Authoring Space and Directory to choose
12568: # save location for creation of a new "standard" problem from the Course Editor.
12569: #
12570:
12571: sub recursedirs {
1.1532 raeburn 12572: my ($is_home,$recurse,$include,$exclude,$nonemptydir,$addtopdir,$toppath,
12573: $relpath,$dirhashref,$filehashref,$getlastmod) = @_;
1.1313 raeburn 12574: return unless (ref($dirhashref) eq 'HASH');
1.1503 raeburn 12575: my $docroot = $perlvar{'lonDocRoot'};
1.1313 raeburn 12576: my $currpath = $docroot.$toppath;
1.1503 raeburn 12577: if ($relpath ne '') {
1.1313 raeburn 12578: $currpath .= "/$relpath";
12579: }
1.1503 raeburn 12580: my ($savefile,$checkinc,$checkexc);
1.1532 raeburn 12581: if (ref($filehashref) eq 'HASH') {
1.1313 raeburn 12582: $savefile = 1;
12583: }
1.1503 raeburn 12584: if (ref($include) eq 'HASH') {
12585: $checkinc = 1;
12586: }
12587: if (ref($exclude) eq 'HASH') {
12588: $checkexc = 1;
12589: }
1.1313 raeburn 12590: if ($is_home) {
1.1505 raeburn 12591: if ((-e $currpath) && (opendir(my $dirh,$currpath))) {
1.1503 raeburn 12592: my $filecount = 0;
1.1313 raeburn 12593: foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
12594: next if ($item eq '');
12595: if (-d "$currpath/$item") {
12596: my $newpath;
1.1503 raeburn 12597: if ($relpath ne '') {
1.1313 raeburn 12598: $newpath = "$relpath/$item";
12599: } else {
12600: $newpath = $item;
12601: }
12602: $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
1.1503 raeburn 12603: if ($recurse) {
1.1532 raeburn 12604: &recursedirs($is_home,$recurse,$include,$exclude,$nonemptydir,$addtopdir,
12605: $toppath,$newpath,$dirhashref,$filehashref,$getlastmod);
1.1503 raeburn 12606: }
12607: } elsif (($savefile) || ($relpath eq '')) {
12608: next if ($nonemptydir && $filecount);
12609: if ($checkinc || $checkexc) {
12610: my ($extension) = ($item =~ /\.(\w+)$/);
12611: if ($checkinc) {
12612: next unless ($extension && $include->{$extension});
12613: }
12614: if ($checkexc) {
12615: next if ($extension && $exclude->{$extension});
12616: }
12617: }
1.1505 raeburn 12618: if (($relpath eq '') && (!exists($dirhashref->{'/'}))) {
1.1503 raeburn 12619: $dirhashref->{'/'} = 1;
12620: }
12621: if ($savefile) {
1.1532 raeburn 12622: my $value;
12623: if ($getlastmod) {
12624: ($value) = (stat("$currpath/$item"))[9];
12625: } else {
12626: $value = 1;
12627: }
1.1503 raeburn 12628: if ($relpath eq '') {
1.1532 raeburn 12629: $filehashref->{'/'}{$item} = $value
1.1503 raeburn 12630: } else {
1.1532 raeburn 12631: $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = $value;
1.1313 raeburn 12632: }
12633: }
1.1503 raeburn 12634: $filecount ++;
1.1313 raeburn 12635: }
12636: }
12637: closedir($dirh);
12638: }
12639: } else {
1.1532 raeburn 12640: my $url = $toppath;
12641: if ($relpath ne '') {
12642: $url = $toppath.'/'.$relpath;
12643: }
12644: my ($dirlistref,$listerror) = &dirlist($url);
1.1313 raeburn 12645: my @dir_lines;
12646: my $dirptr=16384;
12647: if (ref($dirlistref) eq 'ARRAY') {
1.1503 raeburn 12648: my $filecount = 0;
1.1313 raeburn 12649: foreach my $dir_line (sort
12650: {
12651: my ($afile)=split('&',$a,2);
12652: my ($bfile)=split('&',$b,2);
12653: return (lc($afile) cmp lc($bfile));
12654: } (@{$dirlistref})) {
12655: my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
12656: split(/\&/,$dir_line,16);
12657: $item =~ s/\s+$//;
12658: next if (($item =~ /^\.\.?$/) || ($obs));
12659: if ($dirptr&$testdir) {
12660: my $newpath;
12661: if ($relpath) {
12662: $newpath = "$relpath/$item";
12663: } else {
12664: $newpath = $item;
12665: }
12666: $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
1.1503 raeburn 12667: if ($recurse) {
1.1532 raeburn 12668: &recursedirs($is_home,$recurse,$include,$exclude,$nonemptydir,$addtopdir,
12669: $toppath,$newpath,$dirhashref,$filehashref,$getlastmod);
1.1503 raeburn 12670: }
12671: } elsif (($savefile) || ($relpath eq '')) {
12672: next if ($nonemptydir && $filecount);
12673: if ($checkinc || $checkexc) {
1.1532 raeburn 12674: my ($extension) = ($item =~ /\.(\w+)$/);
1.1503 raeburn 12675: if ($checkinc) {
12676: next unless ($extension && $include->{$extension});
12677: }
12678: if ($checkexc) {
12679: next if ($extension && $exclude->{$extension});
12680: }
12681: }
12682: if (($relpath eq '') && (!exists($dirhashref->{'/'}))) {
12683: $dirhashref->{'/'} = 1;
12684: }
12685: if ($savefile) {
1.1532 raeburn 12686: my $value;
12687: if ($getlastmod) {
12688: $value = $mtime;
12689: } else {
12690: $value = 1;
12691: }
1.1503 raeburn 12692: if ($relpath eq '') {
1.1532 raeburn 12693: $filehashref->{'/'}{$item} = $value;
1.1503 raeburn 12694: } else {
1.1532 raeburn 12695: $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = $value;
1.1313 raeburn 12696: }
12697: }
1.1503 raeburn 12698: $filecount ++;
1.1313 raeburn 12699: }
12700: }
12701: }
12702: }
1.1505 raeburn 12703: if ($addtopdir) {
12704: if (($relpath eq '') && (!exists($dirhashref->{'/'}))) {
12705: $dirhashref->{'/'} = 1;
12706: }
12707: }
1.1313 raeburn 12708: return;
12709: }
12710:
1.1503 raeburn 12711: sub priv_exclude {
12712: return {
12713: meta => 1,
12714: save => 1,
12715: log => 1,
12716: bak => 1,
12717: rights => 1,
12718: DS_Store => 1,
12719: };
12720: }
12721:
1.1532 raeburn 12722: sub res_exclude {
12723: return {
12724: meta => 1,
12725: subscription => 1,
12726: rights => 1,
12727: };
12728: }
12729:
1.26 www 12730: # -------------------------------------------------------- Value of a Condition
12731:
1.713 albertel 12732: # gets the value of a specific preevaluated condition
12733: # stored in the string $env{user.state.<cid>}
12734: # or looks up a condition reference in the bighash and if if hasn't
12735: # already been evaluated recurses into docondval to get the value of
12736: # the condition, then memoizing it to
12737: # $env{user.state.<cid>.<condition>}
1.40 www 12738: sub directcondval {
12739: my $number=shift;
1.620 albertel 12740: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 12741: &Apache::lonuserstate::evalstate();
12742: }
1.713 albertel 12743: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
12744: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
12745: } elsif ($number =~ /^_/) {
12746: my $sub_condition;
12747: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12748: &GDBM_READER(),0640)) {
12749: $sub_condition=$bighash{'conditions'.$number};
12750: untie(%bighash);
12751: }
12752: my $value = &docondval($sub_condition);
1.949 raeburn 12753: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 12754: return $value;
12755: }
1.620 albertel 12756: if ($env{'user.state.'.$env{'request.course.id'}}) {
12757: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 12758: } else {
12759: return 2;
12760: }
12761: }
12762:
1.713 albertel 12763: # get the collection of conditions for this resource
1.26 www 12764: sub condval {
12765: my $condidx=shift;
1.54 www 12766: my $allpathcond='';
1.713 albertel 12767: foreach my $cond (split(/\|/,$condidx)) {
12768: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
12769: $allpathcond.=
12770: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
12771: }
1.191 harris41 12772: }
1.54 www 12773: $allpathcond=~s/\|$//;
1.713 albertel 12774: return &docondval($allpathcond);
12775: }
12776:
12777: #evaluates an expression of conditions
12778: sub docondval {
12779: my ($allpathcond) = @_;
12780: my $result=0;
12781: if ($env{'request.course.id'}
12782: && defined($allpathcond)) {
12783: my $operand='|';
12784: my @stack;
12785: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
12786: if ($chunk eq '(') {
12787: push @stack,($operand,$result);
12788: } elsif ($chunk eq ')') {
12789: my $before=pop @stack;
12790: if (pop @stack eq '&') {
12791: $result=$result>$before?$before:$result;
12792: } else {
12793: $result=$result>$before?$result:$before;
12794: }
12795: } elsif (($chunk eq '&') || ($chunk eq '|')) {
12796: $operand=$chunk;
12797: } else {
12798: my $new=directcondval($chunk);
12799: if ($operand eq '&') {
12800: $result=$result>$new?$new:$result;
12801: } else {
12802: $result=$result>$new?$result:$new;
12803: }
12804: }
12805: }
1.26 www 12806: }
12807: return $result;
1.421 albertel 12808: }
12809:
12810: # ---------------------------------------------------- Devalidate courseresdata
12811:
12812: sub devalidatecourseresdata {
12813: my ($coursenum,$coursedomain)=@_;
12814: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 12815: &devalidate_cache_new('courseres',$hashid);
1.28 www 12816: }
12817:
1.763 www 12818:
1.200 www 12819: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 12820: #
12821: # Parameters:
12822: # $coursenum - Number of the course.
12823: # $coursedomain - Domain at which the course was created.
12824: # Returns:
12825: # A hash of the course parameters along (I think) with timestamps
12826: # and version info.
1.877 foxr 12827:
1.624 albertel 12828: sub get_courseresdata {
12829: my ($coursenum,$coursedomain)=@_;
1.200 www 12830: my $coursehom=&homeserver($coursenum,$coursedomain);
12831: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 12832: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 12833: my %dumpreply;
1.417 albertel 12834: unless (defined($cached)) {
1.624 albertel 12835: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 12836: $result=\%dumpreply;
1.251 albertel 12837: my ($tmp) = keys(%dumpreply);
12838: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 12839: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 12840: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
12841: return $tmp;
1.416 albertel 12842: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 12843: $result=undef;
1.599 albertel 12844: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 12845: }
12846: }
1.624 albertel 12847: return $result;
12848: }
12849:
1.633 albertel 12850: sub devalidateuserresdata {
12851: my ($uname,$udom)=@_;
12852: my $hashid="$udom:$uname";
12853: &devalidate_cache_new('userres',$hashid);
12854: }
12855:
1.624 albertel 12856: sub get_userresdata {
12857: my ($uname,$udom)=@_;
12858: #most student don\'t have any data set, check if there is some data
12859: if (&EXT_cache_status($udom,$uname)) { return undef; }
12860:
12861: my $hashid="$udom:$uname";
12862: my ($result,$cached)=&is_cached_new('userres',$hashid);
12863: if (!defined($cached)) {
12864: my %resourcedata=&dump('resourcedata',$udom,$uname);
12865: $result=\%resourcedata;
12866: &do_cache_new('userres',$hashid,$result,600);
12867: }
12868: my ($tmp)=keys(%$result);
12869: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
12870: return $result;
12871: }
12872: #error 2 occurs when the .db doesn't exist
12873: if ($tmp!~/error: 2 /) {
1.1294 raeburn 12874: if ((!defined($cached)) || ($tmp ne 'con_lost')) {
12875: &logthis("<font color=\"blue\">WARNING:".
12876: " Trying to get resource data for ".
12877: $uname." at ".$udom.": ".
12878: $tmp."</font>");
12879: }
1.624 albertel 12880: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 12881: #&EXT_cache_set($udom,$uname);
12882: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 12883: undef($tmp); # not really an error so don't send it back
1.624 albertel 12884: }
12885: return $tmp;
12886: }
1.879 foxr 12887: #----------------------------------------------- resdata - return resource data
12888: # Purpose:
12889: # Return resource data for either users or for a course.
12890: # Parameters:
12891: # $name - Course/user name.
12892: # $domain - Name of the domain the user/course is registered on.
1.1311 raeburn 12893: # $type - Type of thing $name is (must be 'course' or 'user')
1.1301 raeburn 12894: # $mapp - decluttered URL of enclosing map
12895: # $recursed - Ref to scalar -- set to 1, if nested maps have been recursed.
12896: # $recurseup - Ref to array of map URLs, starting with map containing
12897: # $mapp up through hierarchy of nested maps to top level map.
12898: # $courseid - CourseID (first part of param identifier).
12899: # $modifier - Middle part of param identifier.
12900: # $what - Last part of param identifier.
1.879 foxr 12901: # @which - Array of names of resources desired.
12902: # Returns:
12903: # The value of the first reasource in @which that is found in the
12904: # resource hash.
12905: # Exceptional Conditions:
12906: # If the $type passed in is not valid (not the string 'course' or
12907: # 'user', an undefined reference is returned.
12908: # If none of the resources are found, an undef is returned
1.624 albertel 12909: sub resdata {
1.1301 raeburn 12910: my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
12911: $modifier,$what,@which)=@_;
1.624 albertel 12912: my $result;
12913: if ($type eq 'course') {
12914: $result=&get_courseresdata($name,$domain);
12915: } elsif ($type eq 'user') {
12916: $result=&get_userresdata($name,$domain);
12917: }
12918: if (!ref($result)) { return $result; }
1.251 albertel 12919: foreach my $item (@which) {
1.1301 raeburn 12920: if ($item->[1] eq 'course') {
12921: if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
12922: unless ($$recursed) {
1.1302 raeburn 12923: @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
1.1301 raeburn 12924: $$recursed = 1;
12925: }
12926: foreach my $item (@${recurseup}) {
12927: my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
12928: last if (defined($result->{$norecursechk}));
12929: my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
12930: if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
12931: }
12932: }
12933: }
12934: if (defined($result->{$item->[0]})) {
1.927 albertel 12935: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 12936: }
1.250 albertel 12937: }
1.291 albertel 12938: return undef;
1.200 www 12939: }
12940:
1.1360 raeburn 12941: sub get_domain_lti {
12942: my ($cdom,$context) = @_;
1.1483 raeburn 12943: my ($name,$cachename,%lti);
1.1360 raeburn 12944: if ($context eq 'consumer') {
12945: $name = 'ltitools';
12946: } elsif ($context eq 'provider') {
12947: $name = 'lti';
1.1483 raeburn 12948: } elsif ($context eq 'linkprot') {
12949: $name = 'ltisec';
1.1360 raeburn 12950: } else {
12951: return %lti;
12952: }
1.1483 raeburn 12953: if ($context eq 'linkprot') {
12954: $cachename = $context;
12955: } else {
12956: $cachename = $name;
12957: }
12958: my ($result,$cached)=&is_cached_new($cachename,$cdom);
1.1298 raeburn 12959: if (defined($cached)) {
12960: if (ref($result) eq 'HASH') {
1.1360 raeburn 12961: %lti = %{$result};
1.1298 raeburn 12962: }
12963: } else {
1.1360 raeburn 12964: my %domconfig = &get_dom('configuration',[$name],$cdom);
12965: if (ref($domconfig{$name}) eq 'HASH') {
1.1483 raeburn 12966: if ($context eq 'linkprot') {
12967: if (ref($domconfig{$name}{'linkprot'}) eq 'HASH') {
12968: %lti = %{$domconfig{$name}{'linkprot'}};
12969: }
12970: } else {
12971: %lti = %{$domconfig{$name}};
12972: }
1.1298 raeburn 12973: }
12974: my $cachetime = 24*60*60;
1.1483 raeburn 12975: &do_cache_new($cachename,$cdom,\%lti,$cachetime);
1.1298 raeburn 12976: }
1.1360 raeburn 12977: return %lti;
1.1298 raeburn 12978: }
12979:
1.1463 raeburn 12980: sub get_course_lti {
1.1510 raeburn 12981: my ($cnum,$cdom,$context) = @_;
12982: my ($name,$cachename,%lti);
12983: if ($context eq 'consumer') {
12984: $name = 'ltitools';
12985: $cachename = 'courseltitools';
12986: } elsif ($context eq 'provider') {
12987: $name = 'lti';
12988: $cachename = 'courselti';
12989: } else {
12990: return %lti;
12991: }
1.1463 raeburn 12992: my $hashid=$cdom.'_'.$cnum;
1.1510 raeburn 12993: my ($result,$cached)=&is_cached_new($cachename,$hashid);
1.1463 raeburn 12994: if (defined($cached)) {
12995: if (ref($result) eq 'HASH') {
1.1510 raeburn 12996: %lti = %{$result};
1.1463 raeburn 12997: }
12998: } else {
1.1510 raeburn 12999: %lti = &dump($name,$cdom,$cnum,undef,undef,undef,1);
1.1463 raeburn 13000: my $cachetime = 24*60*60;
1.1510 raeburn 13001: &do_cache_new($cachename,$hashid,\%lti,$cachetime);
1.1463 raeburn 13002: }
1.1510 raeburn 13003: return %lti;
1.1463 raeburn 13004: }
13005:
1.1479 raeburn 13006: sub courselti_itemid {
13007: my ($cnum,$cdom,$url,$method,$params,$context) = @_;
13008: my ($chome,$itemid);
13009: $chome = &homeserver($cnum,$cdom);
13010: return if ($chome eq 'no_host');
13011: if (ref($params) eq 'HASH') {
13012: my $rep;
13013: if (grep { $_ eq $chome } current_machine_ids()) {
13014: $rep = LONCAPA::Lond::crslti_itemid($cdom,$cnum,$url,$method,$params,$perlvar{'lonVersion'});
13015: } else {
13016: my $escurl = &escape($url);
13017: my $escmethod = &escape($method);
13018: my $items = &freeze_escape($params);
13019: $rep = &reply("encrypt:lti:$cdom:$cnum:$context:$escurl:$escmethod:$items",$chome);
13020: }
13021: unless (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
13022: ($rep eq 'unknown_cmd')) {
13023: $itemid = $rep;
13024: }
13025: }
13026: return $itemid;
13027: }
13028:
13029: sub domainlti_itemid {
13030: my ($cdom,$url,$method,$params,$context) = @_;
13031: my ($primary_id,$itemid);
13032: $primary_id = &domain($cdom,'primary');
13033: return if ($primary_id eq '');
13034: if (ref($params) eq 'HASH') {
13035: my $rep;
13036: if (grep { $_ eq $primary_id } current_machine_ids()) {
13037: $rep = LONCAPA::Lond::domlti_itemid($cdom,$context,$url,$method,$params,$perlvar{'lonVersion'});
13038: } else {
13039: my $cnum = '';
13040: my $escurl = &escape($url);
13041: my $escmethod = &escape($method);
13042: my $items = &freeze_escape($params);
13043: $rep = &reply("encrypt:lti:$cdom:$cnum:$context:$escurl:$escmethod:$items",$primary_id);
13044: }
13045: unless (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
13046: ($rep eq 'unknown_cmd')) {
13047: $itemid = $rep;
13048: }
13049: }
13050: return $itemid;
13051: }
13052:
1.1513 raeburn 13053: sub get_ltitools_id {
13054: my ($context,$cdom,$cnum,$title) = @_;
13055: my ($lockhash,$tries,$gotlock,$id,$error);
13056:
13057: # get lock on ltitools db
13058: $lockhash = {
13059: lock => $env{'user.name'}.
13060: ':'.$env{'user.domain'},
13061: };
13062: $tries = 0;
13063: if ($context eq 'domain') {
13064: $gotlock = &newput_dom('ltitools',$lockhash,$cdom);
13065: } else {
13066: $gotlock = &newput('ltitools',$lockhash,$cdom,$cnum);
13067: }
13068: while (($gotlock ne 'ok') && ($tries<10)) {
13069: $tries ++;
13070: sleep (0.1);
13071: if ($context eq 'domain') {
13072: $gotlock = &newput_dom('ltitools',$lockhash,$cdom);
13073: } else {
13074: $gotlock = &newput('ltitools',$lockhash,$cdom,$cnum);
13075: }
13076: }
13077: if ($gotlock eq 'ok') {
13078: my %currids;
13079: if ($context eq 'domain') {
13080: %currids = &dump_dom('ltitools',$cdom);
13081: } else {
13082: %currids = &dump('ltitools',$cdom,$cnum);
13083: }
13084: if ($currids{'lock'}) {
13085: delete($currids{'lock'});
13086: if (keys(%currids)) {
13087: my @curr = sort { $a <=> $b } keys(%currids);
13088: if ($curr[-1] =~ /^\d+$/) {
13089: $id = 1 + $curr[-1];
13090: }
13091: } else {
13092: $id = 1;
13093: }
13094: if ($id) {
13095: if ($context eq 'domain') {
13096: unless (&newput_dom('ltitools',{ $id => $title },$cdom) eq 'ok') {
13097: $error = 'nostore';
13098: }
13099: } else {
13100: unless (&newput('ltitools',{ $id => $title },$cdom,$cnum) eq 'ok') {
13101: $error = 'nostore';
13102: }
13103: }
13104: } else {
13105: $error = 'nonumber';
13106: }
13107: }
13108: my $dellockoutcome;
13109: if ($context eq 'domain') {
13110: $dellockoutcome = &del_dom('ltitools',['lock'],$cdom);
13111: } else {
13112: $dellockoutcome = &del('ltitools',['lock'],$cdom,$cnum);
13113: }
13114: } else {
13115: $error = 'nolock';
13116: }
13117: return ($id,$error);
13118: }
13119:
1.1496 raeburn 13120: sub count_supptools {
13121: my ($cnum,$cdom,$ignorecache,$reload)=@_;
13122: my $hashid=$cnum.':'.$cdom;
13123: my ($numexttools,$cached);
13124: unless ($ignorecache) {
13125: ($numexttools,$cached) = &is_cached_new('supptools',$hashid);
13126: }
13127: unless (defined($cached)) {
13128: my $chome=&homeserver($cnum,$cdom);
13129: $numexttools = 0;
13130: unless ($chome eq 'no_host') {
1.1500 raeburn 13131: my ($supplemental) = &Apache::loncommon::get_supplemental($cnum,$cdom,$reload);
1.1496 raeburn 13132: if (ref($supplemental) eq 'HASH') {
13133: if ((ref($supplemental->{'ids'}) eq 'HASH') && (ref($supplemental->{'hidden'}) eq 'HASH')) {
13134: foreach my $key (keys(%{$supplemental->{'ids'}})) {
13135: if ($key =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
13136: $numexttools ++;
13137: }
13138: }
13139: }
13140: }
13141: }
13142: &do_cache_new('supptools',$hashid,$numexttools,600);
13143: }
13144: return $numexttools;
13145: }
13146:
13147: sub has_unhidden_suppfiles {
1.1498 raeburn 13148: my ($cnum,$cdom,$ignorecache,$possdel)=@_;
1.1236 raeburn 13149: my $hashid=$cnum.':'.$cdom;
1.1496 raeburn 13150: my ($showsupp,$cached);
1.1236 raeburn 13151: unless ($ignorecache) {
1.1496 raeburn 13152: ($showsupp,$cached) = &is_cached_new('showsupp',$hashid);
1.1236 raeburn 13153: }
13154: unless (defined($cached)) {
13155: my $chome=&homeserver($cnum,$cdom);
13156: unless ($chome eq 'no_host') {
1.1500 raeburn 13157: my ($supplemental) = &Apache::loncommon::get_supplemental($cnum,$cdom,$ignorecache,$possdel);
1.1496 raeburn 13158: if (ref($supplemental) eq 'HASH') {
13159: if ((ref($supplemental->{'ids'}) eq 'HASH') && (ref($supplemental->{'hidden'}) eq 'HASH')) {
13160: foreach my $key (keys(%{$supplemental->{'ids'}})) {
13161: next if ($key =~ /\.sequence$/);
13162: if (ref($supplemental->{'ids'}->{$key}) eq 'ARRAY') {
13163: foreach my $id (@{$supplemental->{'ids'}->{$key}}) {
13164: unless ($supplemental->{'hidden'}->{$id}) {
13165: $showsupp = 1;
13166: last;
13167: }
13168: }
13169: }
13170: last if ($showsupp);
13171: }
13172: }
13173: }
1.1236 raeburn 13174: }
1.1496 raeburn 13175: &do_cache_new('showsupp',$hashid,$showsupp,600);
1.1236 raeburn 13176: }
1.1496 raeburn 13177: return $showsupp;
13178: }
13179:
1.379 matthew 13180: #
13181: # EXT resource caching routines
13182: #
13183:
1.1302 raeburn 13184: {
13185: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
13186: #
13187: # The course for which we cache
13188: my $cachedmapkey='';
13189: # The cached recursive maps for this course
13190: my %cachedmaps=();
13191: # When this was last done
13192: my $cachedmaptime='';
13193:
1.379 matthew 13194: sub clear_EXT_cache_status {
1.383 albertel 13195: &delenv('cache.EXT.');
1.379 matthew 13196: }
13197:
13198: sub EXT_cache_status {
13199: my ($target_domain,$target_user) = @_;
1.383 albertel 13200: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 13201: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 13202: # We know already the user has no data
13203: return 1;
13204: } else {
13205: return 0;
13206: }
13207: }
13208:
13209: sub EXT_cache_set {
13210: my ($target_domain,$target_user) = @_;
1.383 albertel 13211: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 13212: #&appenv({$cachename => time});
1.379 matthew 13213: }
13214:
1.28 www 13215: # --------------------------------------------------------- Value of a Variable
1.58 www 13216: sub EXT {
1.715 albertel 13217:
1.1461 raeburn 13218: my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid,$recurseupref)=@_;
1.68 www 13219: unless ($varname) { return ''; }
1.218 albertel 13220: #get real user name/domain, courseid and symb
13221: my $courseid;
1.359 albertel 13222: my $publicuser;
1.427 www 13223: if ($symbparm) {
13224: $symbparm=&get_symb_from_alias($symbparm);
13225: }
1.218 albertel 13226: if (!($uname && $udom)) {
1.790 albertel 13227: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 13228: if (!$symbparm) { $symbparm=$cursymb; }
13229: } else {
1.620 albertel 13230: $courseid=$env{'request.course.id'};
1.218 albertel 13231: }
1.48 www 13232: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
13233: my $rest;
1.320 albertel 13234: if (defined($therest[0])) {
1.48 www 13235: $rest=join('.',@therest);
13236: } else {
13237: $rest='';
13238: }
1.320 albertel 13239:
1.57 www 13240: my $qualifierrest=$qualifier;
13241: if ($rest) { $qualifierrest.='.'.$rest; }
13242: my $spacequalifierrest=$space;
13243: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 13244: if ($realm eq 'user') {
1.48 www 13245: # --------------------------------------------------------------- user.resource
13246: if ($space eq 'resource') {
1.651 albertel 13247: if ( (defined($Apache::lonhomework::parsing_a_problem)
13248: || defined($Apache::lonhomework::parsing_a_task))
13249: &&
1.1469 raeburn 13250: ($symbparm eq &symbread()) ) {
1.744 albertel 13251: # if we are in the middle of processing the resource the
13252: # get the value we are planning on committing
13253: if (defined($Apache::lonhomework::results{$qualifierrest})) {
13254: return $Apache::lonhomework::results{$qualifierrest};
13255: } else {
13256: return $Apache::lonhomework::history{$qualifierrest};
13257: }
1.335 albertel 13258: } else {
1.359 albertel 13259: my %restored;
1.620 albertel 13260: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 13261: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
13262: } else {
13263: %restored=&restore($symbparm,$courseid,$udom,$uname);
13264: }
1.335 albertel 13265: return $restored{$qualifierrest};
13266: }
1.48 www 13267: # ----------------------------------------------------------------- user.access
13268: } elsif ($space eq 'access') {
1.218 albertel 13269: # FIXME - not supporting calls for a specific user
1.48 www 13270: return &allowed($qualifier,$rest);
13271: # ------------------------------------------ user.preferences, user.environment
13272: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 13273: if (($uname eq $env{'user.name'}) &&
13274: ($udom eq $env{'user.domain'})) {
13275: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 13276: } else {
1.359 albertel 13277: my %returnhash;
13278: if (!$publicuser) {
13279: %returnhash=&userenvironment($udom,$uname,
13280: $qualifierrest);
13281: }
1.218 albertel 13282: return $returnhash{$qualifierrest};
13283: }
1.48 www 13284: # ----------------------------------------------------------------- user.course
13285: } elsif ($space eq 'course') {
1.218 albertel 13286: # FIXME - not supporting calls for a specific user
1.620 albertel 13287: return $env{join('.',('request.course',$qualifier))};
1.48 www 13288: # ------------------------------------------------------------------- user.role
13289: } elsif ($space eq 'role') {
1.218 albertel 13290: # FIXME - not supporting calls for a specific user
1.620 albertel 13291: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 13292: if ($qualifier eq 'value') {
13293: return $role;
13294: } elsif ($qualifier eq 'extent') {
13295: return $where;
13296: }
13297: # ----------------------------------------------------------------- user.domain
13298: } elsif ($space eq 'domain') {
1.218 albertel 13299: return $udom;
1.48 www 13300: # ------------------------------------------------------------------- user.name
13301: } elsif ($space eq 'name') {
1.218 albertel 13302: return $uname;
1.48 www 13303: # ---------------------------------------------------- Any other user namespace
1.29 www 13304: } else {
1.359 albertel 13305: my %reply;
13306: if (!$publicuser) {
13307: %reply=&get($space,[$qualifierrest],$udom,$uname);
13308: }
13309: return $reply{$qualifierrest};
1.48 www 13310: }
1.236 www 13311: } elsif ($realm eq 'query') {
13312: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 13313: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
13314: [$spacequalifierrest]);
1.620 albertel 13315: return $env{'form.'.$spacequalifierrest};
1.236 www 13316: } elsif ($realm eq 'request') {
1.48 www 13317: # ------------------------------------------------------------- request.browser
13318: if ($space eq 'browser') {
1.1145 bisitz 13319: return $env{'browser.'.$qualifier};
1.57 www 13320: # ------------------------------------------------------------ request.filename
13321: } else {
1.620 albertel 13322: return $env{'request.'.$spacequalifierrest};
1.29 www 13323: }
1.28 www 13324: } elsif ($realm eq 'course') {
1.48 www 13325: # ---------------------------------------------------------- course.description
1.620 albertel 13326: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 13327: } elsif ($realm eq 'resource') {
1.165 www 13328:
1.620 albertel 13329: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 13330: if (!$symbparm) { $symbparm=&symbread(); }
13331: }
1.693 albertel 13332:
1.1232 raeburn 13333: if ($qualifier eq '') {
13334: if ($space eq 'title') {
13335: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
13336: return &gettitle($symbparm);
13337: }
1.693 albertel 13338:
1.1232 raeburn 13339: if ($space eq 'map') {
13340: my ($map) = &decode_symb($symbparm);
13341: return &symbread($map);
13342: }
13343: if ($space eq 'maptitle') {
13344: my ($map) = &decode_symb($symbparm);
13345: return &gettitle($map);
13346: }
13347: if ($space eq 'filename') {
13348: if ($symbparm) {
13349: return &clutter((&decode_symb($symbparm))[2]);
13350: }
13351: return &hreflocation('',$env{'request.filename'});
1.905 albertel 13352: }
1.1232 raeburn 13353:
1.1233 raeburn 13354: if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
13355: if ($space eq 'visibleparts') {
13356: my $navmap = Apache::lonnavmaps::navmap->new();
13357: my $item;
13358: if (ref($navmap)) {
13359: my $res = $navmap->getBySymb($symbparm);
13360: my $parts = $res->parts();
13361: if (ref($parts) eq 'ARRAY') {
13362: $item = join(',',@{$parts});
13363: }
13364: undef($navmap);
1.1232 raeburn 13365: }
1.1233 raeburn 13366: return $item;
1.1232 raeburn 13367: }
13368: }
13369: }
1.693 albertel 13370:
1.1301 raeburn 13371: my ($section, $group, @groups, @recurseup, $recursed);
1.1461 raeburn 13372: if (ref($recurseupref) eq 'ARRAY') {
13373: @recurseup = @{$recurseupref};
13374: $recursed = 1;
13375: }
1.1301 raeburn 13376: my ($courselevelm,$courseleveli,$courselevel,$mapp);
1.1228 raeburn 13377: if (($courseid eq '') && ($cid)) {
13378: $courseid = $cid;
13379: }
13380: if (($symbparm && $courseid) &&
13381: (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165 www 13382:
1.218 albertel 13383: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 13384:
1.60 www 13385: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 13386: my $symbp=$symbparm;
1.1301 raeburn 13387: $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 13388: my $symbparm=$symbp.'.'.$spacequalifierrest;
1.1301 raeburn 13389: my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
1.218 albertel 13390: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
1.620 albertel 13391: if (($env{'user.name'} eq $uname) &&
13392: ($env{'user.domain'} eq $udom)) {
13393: $section=$env{'request.course.sec'};
1.733 raeburn 13394: @groups = split(/:/,$env{'request.course.groups'});
13395: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 13396: } else {
1.539 albertel 13397: if (! defined($usection)) {
1.551 albertel 13398: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 13399: } else {
13400: $section = $usection;
13401: }
1.733 raeburn 13402: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 13403: }
13404:
13405: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
13406: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
1.1301 raeburn 13407: my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
1.218 albertel 13408: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
13409:
1.593 albertel 13410: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 13411: my $courselevelr=$courseid.'.'.$symbparm;
1.1301 raeburn 13412: $courseleveli=$courseid.'.'.$recurseparm;
1.593 albertel 13413: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 13414:
1.60 www 13415: # ----------------------------------------------------------- first, check user
1.624 albertel 13416:
1.1301 raeburn 13417: my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
13418: \@recurseup,$courseid,'.',$spacequalifierrest,
1.927 albertel 13419: ([$courselevelr,'resource'],
13420: [$courselevelm,'map' ],
1.1301 raeburn 13421: [$courseleveli,'map' ],
1.927 albertel 13422: [$courselevel, 'course' ]));
1.931 albertel 13423: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 13424:
1.594 albertel 13425: # ------------------------------------------------ second, check some of course
1.684 raeburn 13426: my $coursereply;
1.691 raeburn 13427: if (@groups > 0) {
13428: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
1.1301 raeburn 13429: $recurseparm,$mapparm,$spacequalifierrest,
13430: $mapp,\$recursed,\@recurseup);
13431: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 13432: }
1.96 www 13433:
1.684 raeburn 13434: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 13435: $env{'course.'.$courseid.'.domain'},
1.1301 raeburn 13436: 'course',$mapp,\$recursed,\@recurseup,
13437: $courseid,'.['.$section.'].',$spacequalifierrest,
1.927 albertel 13438: ([$seclevelr, 'resource'],
13439: [$seclevelm, 'map' ],
1.1301 raeburn 13440: [$secleveli, 'map' ],
1.927 albertel 13441: [$seclevel, 'course' ],
13442: [$courselevelr,'resource']));
13443: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 13444:
1.60 www 13445: # ------------------------------------------------------ third, check map parms
1.218 albertel 13446: my %parmhash=();
13447: my $thisparm='';
13448: if (tie(%parmhash,'GDBM_File',
1.620 albertel 13449: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 13450: &GDBM_READER(),0640)) {
1.218 albertel 13451: $thisparm=$parmhash{$symbparm};
13452: untie(%parmhash);
13453: }
1.927 albertel 13454: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 13455: }
1.594 albertel 13456: # ------------------------------------------ fourth, look in resource metadata
1.1301 raeburn 13457:
13458: my $what = $spacequalifierrest;
13459: $what=~s/\./\_/;
1.282 albertel 13460: my $filename;
13461: if (!$symbparm) { $symbparm=&symbread(); }
13462: if ($symbparm) {
1.409 www 13463: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 13464: } else {
1.620 albertel 13465: $filename=$env{'request.filename'};
1.282 albertel 13466: }
1.1362 raeburn 13467: my $toolsymb;
13468: if (($filename =~ /ext\.tool$/) && ($what ne '0_gradable')) {
13469: $toolsymb = $symbparm;
13470: }
13471: my $metadata=&metadata($filename,$what,$toolsymb);
1.927 albertel 13472: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.1362 raeburn 13473: $metadata=&metadata($filename,'parameter_'.$what,$toolsymb);
1.927 albertel 13474: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 13475:
1.1301 raeburn 13476: # ----------------------------------------------- fifth, look in rest of course
1.593 albertel 13477: if ($symbparm && defined($courseid) &&
1.620 albertel 13478: $courseid eq $env{'request.course.id'}) {
1.624 albertel 13479: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
13480: $env{'course.'.$courseid.'.domain'},
1.1301 raeburn 13481: 'course',$mapp,\$recursed,\@recurseup,
13482: $courseid,'.',$spacequalifierrest,
1.927 albertel 13483: ([$courselevelm,'map' ],
1.1301 raeburn 13484: [$courseleveli,'map' ],
1.927 albertel 13485: [$courselevel, 'course']));
13486: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 13487: }
1.145 www 13488: # ------------------------------------------------------------------ Cascade up
1.218 albertel 13489: unless ($space eq '0') {
1.336 albertel 13490: my @parts=split(/_/,$space);
13491: my $id=pop(@parts);
13492: my $part=join('_',@parts);
13493: if ($part eq '') { $part='0'; }
1.927 albertel 13494: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 13495: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 13496: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 13497: }
1.395 albertel 13498: if ($recurse) { return undef; }
1.1362 raeburn 13499: my $pack_def=&packages_tab_default($filename,$varname,$toolsymb);
1.927 albertel 13500: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 13501: # ---------------------------------------------------- Any other user namespace
13502: } elsif ($realm eq 'environment') {
13503: # ----------------------------------------------------------------- environment
1.620 albertel 13504: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
13505: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 13506: } else {
1.770 albertel 13507: if ($uname eq 'anonymous' && $udom eq '') {
13508: return '';
13509: }
1.219 albertel 13510: my %returnhash=&userenvironment($udom,$uname,
13511: $spacequalifierrest);
13512: return $returnhash{$spacequalifierrest};
13513: }
1.28 www 13514: } elsif ($realm eq 'system') {
1.48 www 13515: # ----------------------------------------------------------------- system.time
13516: if ($space eq 'time') {
13517: return time;
13518: }
1.696 albertel 13519: } elsif ($realm eq 'server') {
13520: # ----------------------------------------------------------------- system.time
13521: if ($space eq 'name') {
13522: return $ENV{'SERVER_NAME'};
13523: }
1.1415 raeburn 13524: } elsif ($realm eq 'client') {
13525: if ($space eq 'remote_addr') {
1.1441 raeburn 13526: return &get_requestor_ip();
1.1415 raeburn 13527: }
1.28 www 13528: }
1.48 www 13529: return '';
1.61 www 13530: }
13531:
1.927 albertel 13532: sub get_reply {
13533: my ($reply_value) = @_;
1.940 raeburn 13534: if (ref($reply_value) eq 'ARRAY') {
13535: if (wantarray) {
13536: return @$reply_value;
13537: }
13538: return $reply_value->[0];
13539: } else {
13540: return $reply_value;
1.927 albertel 13541: }
13542: }
13543:
1.691 raeburn 13544: sub check_group_parms {
1.1301 raeburn 13545: my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
13546: $recursed,$recurseupref) = @_;
13547: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
13548: [$what,'course']);
13549: my $coursereply;
1.691 raeburn 13550: foreach my $group (@{$groups}) {
1.1301 raeburn 13551: my @groupitems = ();
1.691 raeburn 13552: foreach my $level (@levels) {
1.927 albertel 13553: my $item = $courseid.'.['.$group.'].'.$level->[0];
13554: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 13555: }
1.1301 raeburn 13556: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
13557: $env{'course.'.$courseid.'.domain'},
13558: 'course',$mapp,$recursed,$recurseupref,
13559: $courseid,'.['.$group.'].',$what,
13560: @groupitems);
13561: last if (defined($coursereply));
1.691 raeburn 13562: }
13563: return $coursereply;
13564: }
13565:
1.1301 raeburn 13566: sub get_map_hierarchy {
1.1302 raeburn 13567: my ($mapname,$courseid) = @_;
13568: my @recurseup = ();
1.1301 raeburn 13569: if ($mapname) {
1.1302 raeburn 13570: if (($cachedmapkey eq $courseid) &&
13571: (abs($cachedmaptime-time)<5)) {
13572: if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
13573: return @{$cachedmaps{$mapname}};
13574: }
13575: }
1.1301 raeburn 13576: my $navmap = Apache::lonnavmaps::navmap->new();
13577: if (ref($navmap)) {
13578: @recurseup = $navmap->recurseup_maps($mapname);
13579: undef($navmap);
1.1302 raeburn 13580: $cachedmaps{$mapname} = \@recurseup;
13581: $cachedmaptime=time;
13582: $cachedmapkey=$courseid;
1.1301 raeburn 13583: }
13584: }
13585: return @recurseup;
13586: }
13587:
1.1302 raeburn 13588: }
13589:
1.691 raeburn 13590: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 13591: my ($courseid,@groups) = @_;
13592: @groups = sort(@groups);
1.691 raeburn 13593: return @groups;
13594: }
13595:
1.395 albertel 13596: sub packages_tab_default {
1.1362 raeburn 13597: my ($uri,$varname,$toolsymb)=@_;
1.395 albertel 13598: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 13599:
13600: my (@extension,@specifics,$do_default);
1.1362 raeburn 13601: foreach my $package (split(/,/,&metadata($uri,'packages',$toolsymb))) {
1.395 albertel 13602: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 13603: if ($pack_type eq 'default') {
13604: $do_default=1;
13605: } elsif ($pack_type eq 'extension') {
13606: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 13607: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 13608: # only look at packages defaults for packages that this id is
1.738 albertel 13609: push(@specifics,[$package,$pack_type,$pack_part]);
13610: }
13611: }
13612: # first look for a package that matches the requested part id
13613: foreach my $package (@specifics) {
13614: my (undef,$pack_type,$pack_part)=@{$package};
13615: next if ($pack_part ne $part);
13616: if (defined($packagetab{"$pack_type&$name&default"})) {
13617: return $packagetab{"$pack_type&$name&default"};
13618: }
13619: }
13620: # look for any possible matching non extension_ package
13621: foreach my $package (@specifics) {
13622: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 13623: if (defined($packagetab{"$pack_type&$name&default"})) {
13624: return $packagetab{"$pack_type&$name&default"};
13625: }
1.585 albertel 13626: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 13627: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
13628: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 13629: }
13630: }
1.738 albertel 13631: # look for any posible extension_ match
13632: foreach my $package (@extension) {
13633: my ($package,$pack_type)=@{$package};
13634: if (defined($packagetab{"$pack_type&$name&default"})) {
13635: return $packagetab{"$pack_type&$name&default"};
13636: }
13637: if (defined($packagetab{$package."&$name&default"})) {
13638: return $packagetab{$package."&$name&default"};
13639: }
13640: }
13641: # look for a global default setting
13642: if ($do_default && defined($packagetab{"default&$name&default"})) {
13643: return $packagetab{"default&$name&default"};
13644: }
1.395 albertel 13645: return undef;
13646: }
13647:
1.334 albertel 13648: sub add_prefix_and_part {
13649: my ($prefix,$part)=@_;
13650: my $keyroot;
13651: if (defined($prefix) && $prefix !~ /^__/) {
13652: # prefix that has a part already
13653: $keyroot=$prefix;
13654: } elsif (defined($prefix)) {
13655: # prefix that is missing a part
13656: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
13657: } else {
13658: # no prefix at all
13659: if (defined($part)) { $keyroot='_'.$part; }
13660: }
13661: return $keyroot;
13662: }
13663:
1.71 www 13664: # ---------------------------------------------------------------- Get metadata
13665:
1.599 albertel 13666: my %metaentry;
1.1070 www 13667: my %importedpartids;
1.1369 raeburn 13668: my %importedrespids;
1.71 www 13669: sub metadata {
1.1362 raeburn 13670: my ($uri,$what,$toolsymb,$liburi,$prefix,$depthcount)=@_;
1.71 www 13671: $uri=&declutter($uri);
1.288 albertel 13672: # if it is a non metadata possible uri return quickly
1.529 albertel 13673: if (($uri eq '') ||
13674: (($uri =~ m|^/*adm/|) &&
1.1343 raeburn 13675: ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
1.1108 raeburn 13676: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 13677: return undef;
13678: }
1.1261 raeburn 13679: if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv})
1.924 albertel 13680: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 13681: return undef;
1.288 albertel 13682: }
1.73 www 13683: my $filename=$uri;
13684: $uri=~s/\.meta$//;
1.172 www 13685: #
13686: # Is the metadata already cached?
1.177 www 13687: # Look at timestamp of caching
1.172 www 13688: # Everything is cached by the main uri, libraries are never directly cached
13689: #
1.428 albertel 13690: if (!defined($liburi)) {
1.599 albertel 13691: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 13692: if (defined($cached)) { return $result->{':'.$what}; }
13693: }
1.1362 raeburn 13694:
13695: #
13696: # If the uri is for an external tool the file from
13697: # which metadata should be retrieved depends on whether
13698: # the tool had been configured to be gradable (set in the Course
13699: # Editor or Resource Editor).
13700: #
13701: # If a valid symb has been included as the third arg in the call
13702: # to &metadata() that can be used to retrieve the value of
13703: # parameter_0_gradable set for the resource, and included in the
13704: # uploaded map containing the tool. The value is retrieved via
13705: # &EXT(), if a valid symb is available. Otherwise the value of
13706: # gradable in the exttool_$marker.db file for the tool instance
1.1364 raeburn 13707: # is retrieved via &get().
13708: #
13709: # When lonuserstate::traceroute() calls lonnet::EXT() for
13710: # hiddenresource and encrypturl (during course initialization)
13711: # the map-level parameter for resource.0.gradable included in the
13712: # uploaded map containing the tool will not yet have been stored
13713: # in the user_course_parms.db file for the user's session, so in
13714: # this case fall back to retrieving gradable status from the
13715: # exttool_$marker.db file.
1.1362 raeburn 13716: #
13717: # In order to avoid an infinite loop, &metadata() will return
13718: # before a call to &EXT(), if the uri is for an external tool
13719: # and the $what for which metadata is being requested is
13720: # parameter_0_gradable or 0_gradable.
13721: #
13722:
13723: if ($uri =~ /ext\.tool$/) {
13724: if (($what eq 'parameter_0_gradable') || ($what eq '0_gradable')) {
13725: return;
13726: } else {
13727: my ($checked,$use_passback);
13728: if ($toolsymb ne '') {
13729: (undef,undef,my $tooluri) = &decode_symb($toolsymb);
1.1364 raeburn 13730: if (($tooluri eq $uri) && (&EXT('resource.0.gradable',$toolsymb))) {
1.1362 raeburn 13731: $checked = 1;
13732: if (&EXT('resource.0.gradable',$toolsymb) =~ /^yes$/i) {
13733: $use_passback = 1;
13734: }
13735: }
13736: }
13737: unless ($checked) {
13738: my ($ignore,$cdom,$cnum,$marker) = split(m{/},$uri);
13739: $marker=~s/\D//g;
1.1363 raeburn 13740: if ($marker) {
1.1362 raeburn 13741: my %toolsettings=&get('exttool_'.$marker,['gradable'],$cdom,$cnum);
13742: $use_passback = $toolsettings{'gradable'};
13743: }
13744: }
13745: if ($use_passback) {
13746: $filename = '/home/httpd/html/res/lib/templates/LTIpassback.tool';
13747: } else {
13748: $filename = '/home/httpd/html/res/lib/templates/LTIstandard.tool';
13749: }
13750: }
13751: }
13752:
1.428 albertel 13753: {
1.1069 www 13754: # Imported parts would go here
1.1369 raeburn 13755: my @origfiletagids=();
1.1069 www 13756: my $importedparts=0;
1.1369 raeburn 13757:
13758: # Imported responseids would go here
13759: my $importedresponses=0;
1.172 www 13760: #
13761: # Is this a recursive call for a library?
13762: #
1.599 albertel 13763: # if (! exists($metacache{$uri})) {
13764: # $metacache{$uri}={};
13765: # }
1.924 albertel 13766: my $cachetime = 60*60;
1.171 www 13767: if ($liburi) {
13768: $liburi=&declutter($liburi);
13769: $filename=$liburi;
1.401 bowersj2 13770: } else {
1.599 albertel 13771: &devalidate_cache_new('meta',$uri);
13772: undef(%metaentry);
1.401 bowersj2 13773: }
1.140 www 13774: my %metathesekeys=();
1.73 www 13775: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 13776: my $metastring;
1.1140 www 13777: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929 albertel 13778: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 13779: $metastring =
1.929 albertel 13780: &Apache::lonnet::ssi_body($which,
1.924 albertel 13781: ('grade_target' => 'meta'));
13782: $cachetime = 1; # only want this cached in the child not long term
1.1108 raeburn 13783: } elsif (($uri !~ m -^(editupload)/-) &&
13784: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 13785: my $file=&filelocation('',&clutter($filename));
1.599 albertel 13786: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 13787: $metastring=&getfile($file);
1.489 albertel 13788: }
1.208 albertel 13789: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 13790: my $token;
1.140 www 13791: undef %metathesekeys;
1.71 www 13792: while ($token=$parser->get_token) {
1.339 albertel 13793: if ($token->[0] eq 'S') {
13794: if (defined($token->[2]->{'package'})) {
1.172 www 13795: #
13796: # This is a package - get package info
13797: #
1.339 albertel 13798: my $package=$token->[2]->{'package'};
13799: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
13800: if (defined($token->[2]->{'id'})) {
13801: $keyroot.='_'.$token->[2]->{'id'};
13802: }
1.599 albertel 13803: if ($metaentry{':packages'}) {
13804: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 13805: } else {
1.599 albertel 13806: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 13807: }
1.736 albertel 13808: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 13809: my $part=$keyroot;
13810: $part=~s/^\_//;
1.736 albertel 13811: if ($pack_entry=~/^\Q$package\E\&/ ||
13812: $pack_entry=~/^\Q$package\E_0\&/) {
13813: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 13814: # ignore package.tab specified default values
13815: # here &package_tab_default() will fetch those
13816: if ($subp eq 'default') { next; }
1.736 albertel 13817: my $value=$packagetab{$pack_entry};
1.432 albertel 13818: my $unikey;
13819: if ($pack =~ /_0$/) {
13820: $unikey='parameter_0_'.$name;
13821: $part=0;
13822: } else {
13823: $unikey='parameter'.$keyroot.'_'.$name;
13824: }
1.339 albertel 13825: if ($subp eq 'display') {
13826: $value.=' [Part: '.$part.']';
13827: }
1.599 albertel 13828: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 13829: $metathesekeys{$unikey}=1;
1.599 albertel 13830: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
13831: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 13832: }
1.599 albertel 13833: if (defined($metaentry{':'.$unikey.'.default'})) {
13834: $metaentry{':'.$unikey}=
13835: $metaentry{':'.$unikey.'.default'};
1.356 albertel 13836: }
1.339 albertel 13837: }
13838: }
13839: } else {
1.172 www 13840: #
13841: # This is not a package - some other kind of start tag
1.339 albertel 13842: #
13843: my $entry=$token->[1];
1.1068 www 13844: my $unikey='';
1.175 www 13845:
1.339 albertel 13846: if ($entry eq 'import') {
1.175 www 13847: #
13848: # Importing a library here
1.339 albertel 13849: #
1.1067 www 13850: my $location=$parser->get_text('/import');
13851: my $dir=$filename;
13852: $dir=~s|[^/]*$||;
13853: $location=&filelocation($dir,$location);
1.1369 raeburn 13854:
13855: my $importid=$token->[2]->{'id'};
1.1068 www 13856: my $importmode=$token->[2]->{'importmode'};
1.1369 raeburn 13857: #
13858: # Check metadata for imported file to
13859: # see if it contained response items
13860: #
1.1372 raeburn 13861: my ($origfile,@libfilekeys);
1.1370 raeburn 13862: my %currmetaentry = %metaentry;
1.1372 raeburn 13863: @libfilekeys = split(/,/,&metadata($location,'keys',undef,undef,undef,
13864: $depthcount+1));
13865: if (grep(/^responseorder$/,@libfilekeys)) {
13866: my $libresponseorder = &metadata($location,'responseorder',undef,undef,
13867: undef,$depthcount+1);
13868: if ($libresponseorder ne '') {
13869: if ($#origfiletagids<0) {
13870: undef(%importedrespids);
13871: undef(%importedpartids);
13872: }
1.1373 raeburn 13873: my @respids = split(/\s*,\s*/,$libresponseorder);
13874: if (@respids) {
13875: $importedrespids{$importid} = join(',',map { $importid.'_'.$_ } @respids);
13876: }
13877: if ($importedrespids{$importid} ne '') {
1.1372 raeburn 13878: $importedresponses = 1;
1.1369 raeburn 13879: # We need to get the original file and the imported file to get the response order correct
13880: # Load and inspect original file
1.1372 raeburn 13881: if ($#origfiletagids<0) {
13882: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
13883: $origfile=&getfile($origfilelocation);
13884: @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
13885: }
1.1369 raeburn 13886: }
13887: }
13888: }
1.1370 raeburn 13889: # Do not overwrite contents of %metaentry hash for resource itself with
13890: # hash populated for imported library file
13891: %metaentry = %currmetaentry;
13892: undef(%currmetaentry);
1.1374 raeburn 13893: if ($importmode eq 'part') {
1.1068 www 13894: # Import as part(s)
1.1069 www 13895: $importedparts=1;
13896: # We need to get the original file and the imported file to get the part order correct
13897: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1369 raeburn 13898: # Load and inspect original file if we didn't do that already
13899: if ($#origfiletagids<0) {
13900: undef(%importedrespids);
13901: undef(%importedpartids);
13902: if ($origfile eq '') {
13903: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
13904: $origfile=&getfile($origfilelocation);
13905: @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
13906: }
1.1070 www 13907: }
1.1372 raeburn 13908: my @impfilepartids;
13909: # If <partorder> tag is included in metadata for the imported file
13910: # get the parts in the imported file from that.
13911: if (grep(/^partorder$/,@libfilekeys)) {
13912: %currmetaentry = %metaentry;
13913: my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
13914: $depthcount+1);
13915: %metaentry = %currmetaentry;
13916: undef(%currmetaentry);
13917: if ($libpartorder ne '') {
13918: @impfilepartids=split(/\s*,\s*/,$libpartorder);
13919: }
13920: } else {
13921: # If no <partorder> tag available, load and inspect imported file
13922: my $impfile=&getfile($location);
13923: @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
13924: }
1.1069 www 13925: if ($#impfilepartids>=0) {
13926: # This problem had parts
1.1070 www 13927: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 13928: } else {
13929: # Importing by turning a single problem into a problem part
13930: # It gets the import-tags ID as part-ID
13931: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 13932: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 13933: }
1.1068 www 13934: } else {
1.1374 raeburn 13935: # Import as problem or as normal import
13936: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
13937: unless ($importmode eq 'problem') {
1.1068 www 13938: # Normal import
1.1374 raeburn 13939: if (defined($token->[2]->{'id'})) {
13940: $unikey.='_'.$token->[2]->{'id'};
13941: }
13942: }
13943: # Check metadata for imported file to
13944: # see if it contained parts
13945: if (grep(/^partorder$/,@libfilekeys)) {
13946: %currmetaentry = %metaentry;
13947: my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
13948: $depthcount+1);
13949: %metaentry = %currmetaentry;
13950: undef(%currmetaentry);
13951: if ($libpartorder ne '') {
13952: $importedparts = 1;
13953: $importedpartids{$token->[2]->{'id'}}=$libpartorder;
13954: }
13955: }
1.1067 www 13956: }
1.339 albertel 13957: if ($depthcount<20) {
1.736 albertel 13958: my $metadata =
1.1362 raeburn 13959: &metadata($uri,'keys',$toolsymb,$location,$unikey,
1.736 albertel 13960: $depthcount+1);
13961: foreach my $meta (split(',',$metadata)) {
13962: $metaentry{':'.$meta}=$metaentry{':'.$meta};
13963: $metathesekeys{$meta}=1;
1.339 albertel 13964: }
1.1068 www 13965: }
1.1067 www 13966: } else {
13967: #
13968: # Not importing, some other kind of non-package, non-library start tag
13969: #
13970: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
13971: if (defined($token->[2]->{'id'})) {
13972: $unikey.='_'.$token->[2]->{'id'};
13973: }
1.339 albertel 13974: if (defined($token->[2]->{'name'})) {
13975: $unikey.='_'.$token->[2]->{'name'};
13976: }
13977: $metathesekeys{$unikey}=1;
1.736 albertel 13978: foreach my $param (@{$token->[3]}) {
13979: $metaentry{':'.$unikey.'.'.$param} =
13980: $token->[2]->{$param};
1.339 albertel 13981: }
13982: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 13983: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 13984: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
13985: # only ws inside the tag, and not in default, so use default
13986: # as value
1.599 albertel 13987: $metaentry{':'.$unikey}=$default;
1.908 albertel 13988: } elsif ( $internaltext =~ /\S/ ) {
13989: # something interesting inside the tag
13990: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 13991: } else {
1.908 albertel 13992: # no interesting values, don't set a default
1.339 albertel 13993: }
1.172 www 13994: # end of not-a-package not-a-library import
1.339 albertel 13995: }
1.172 www 13996: # end of not-a-package start tag
1.339 albertel 13997: }
1.172 www 13998: # the next is the end of "start tag"
1.339 albertel 13999: }
14000: }
1.483 albertel 14001: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 14002: $extension = lc($extension);
14003: if ($extension eq 'htm') { $extension='html'; }
14004:
1.737 albertel 14005: foreach my $key (keys(%packagetab)) {
1.483 albertel 14006: #no specific packages #how's our extension
14007: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 14008: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 14009: \%metathesekeys);
14010: }
1.883 albertel 14011:
14012: if (!exists($metaentry{':packages'})
14013: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 14014: foreach my $key (keys(%packagetab)) {
1.483 albertel 14015: #no specific packages well let's get default then
14016: if ($key!~/^default&/) { next; }
1.488 albertel 14017: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 14018: \%metathesekeys);
14019: }
14020: }
1.338 www 14021: # are there custom rights to evaluate
1.599 albertel 14022: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 14023:
1.338 www 14024: #
14025: # Importing a rights file here
1.339 albertel 14026: #
14027: unless ($depthcount) {
1.599 albertel 14028: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 14029: my $dir=$filename;
14030: $dir=~s|[^/]*$||;
14031: $location=&filelocation($dir,$location);
1.736 albertel 14032: my $rights_metadata =
1.1362 raeburn 14033: &metadata($uri,'keys',$toolsymb,$location,'_rights',
1.736 albertel 14034: $depthcount+1);
14035: foreach my $rights (split(',',$rights_metadata)) {
14036: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
14037: $metathesekeys{$rights}=1;
1.339 albertel 14038: }
14039: }
14040: }
1.737 albertel 14041: # uniqifiy package listing
14042: my %seen;
14043: my @uniq_packages =
14044: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
14045: $metaentry{':packages'} = join(',',@uniq_packages);
14046:
1.1369 raeburn 14047: if (($importedresponses) || ($importedparts)) {
14048: if ($importedparts) {
1.1070 www 14049: # We had imported parts and need to rebuild partorder
1.1369 raeburn 14050: $metaentry{':partorder'}='';
14051: $metathesekeys{'partorder'}=1;
14052: }
14053: if ($importedresponses) {
14054: # We had imported responses and need to rebuil responseorder
14055: $metaentry{':responseorder'}='';
14056: $metathesekeys{'responseorder'}=1;
14057: }
14058: for (my $index=0;$index<$#origfiletagids;$index+=2) {
14059: my $origid = $origfiletagids[$index+1];
14060: if ($origfiletagids[$index] eq 'part') {
14061: # Original part, part of the problem
14062: if ($importedparts) {
14063: $metaentry{':partorder'}.=','.$origid;
14064: }
14065: } elsif ($origfiletagids[$index] eq 'import') {
14066: if ($importedparts) {
14067: # We have imported parts at this position
1.1373 raeburn 14068: if ($importedpartids{$origid} ne '') {
14069: $metaentry{':partorder'}.=','.$importedpartids{$origid};
14070: }
1.1369 raeburn 14071: }
14072: if ($importedresponses) {
14073: # We have imported responses at this position
1.1373 raeburn 14074: if ($importedrespids{$origid} ne '') {
14075: $metaentry{':responseorder'}.=','.$importedrespids{$origid};
1.1369 raeburn 14076: }
14077: }
14078: } else {
14079: # Original response item, part of the problem
14080: if ($importedresponses) {
14081: $metaentry{':responseorder'}.=','.$origid;
14082: }
14083: }
14084: }
14085: if ($importedparts) {
14086: $metaentry{':partorder'}=~s/^\,//;
14087: }
14088: if ($importedresponses) {
14089: $metaentry{':responseorder'}=~s/^\,//;
14090: }
1.1070 www 14091: }
1.737 albertel 14092: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 14093: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1274 raeburn 14094: $metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.1371 raeburn 14095: unless ($liburi) {
14096: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
14097: }
1.177 www 14098: # this is the end of "was not already recently cached
1.71 www 14099: }
1.599 albertel 14100: return $metaentry{':'.$what};
1.261 albertel 14101: }
14102:
1.488 albertel 14103: sub metadata_create_package_def {
1.483 albertel 14104: my ($uri,$key,$package,$metathesekeys)=@_;
14105: my ($pack,$name,$subp)=split(/\&/,$key);
14106: if ($subp eq 'default') { next; }
14107:
1.599 albertel 14108: if (defined($metaentry{':packages'})) {
14109: $metaentry{':packages'}.=','.$package;
1.483 albertel 14110: } else {
1.599 albertel 14111: $metaentry{':packages'}=$package;
1.483 albertel 14112: }
14113: my $value=$packagetab{$key};
14114: my $unikey;
14115: $unikey='parameter_0_'.$name;
1.599 albertel 14116: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 14117: $$metathesekeys{$unikey}=1;
1.599 albertel 14118: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
14119: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 14120: }
1.599 albertel 14121: if (defined($metaentry{':'.$unikey.'.default'})) {
14122: $metaentry{':'.$unikey}=
14123: $metaentry{':'.$unikey.'.default'};
1.483 albertel 14124: }
14125: }
14126:
1.261 albertel 14127: sub metadata_generate_part0 {
14128: my ($metadata,$metacache,$uri) = @_;
14129: my %allnames;
1.737 albertel 14130: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 14131: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 14132: my $part=$$metacache{':'.$metakey.'.part'};
14133: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 14134: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 14135: $allnames{$name}=$part;
14136: }
14137: }
14138: }
14139: foreach my $name (keys(%allnames)) {
14140: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 14141: my $key=":parameter_0_$name";
1.261 albertel 14142: $$metacache{"$key.part"}='0';
14143: $$metacache{"$key.name"}=$name;
1.428 albertel 14144: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 14145: $allnames{$name}.'_'.$name.
14146: '.type'};
1.428 albertel 14147: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 14148: '.display'};
1.644 www 14149: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 14150: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 14151: $$metacache{"$key.display"}=$olddis;
14152: }
1.71 www 14153: }
14154:
1.764 albertel 14155: # ------------------------------------------------------ Devalidate title cache
14156:
14157: sub devalidate_title_cache {
14158: my ($url)=@_;
14159: if (!$env{'request.course.id'}) { return; }
14160: my $symb=&symbread($url);
14161: if (!$symb) { return; }
14162: my $key=$env{'request.course.id'}."\0".$symb;
14163: &devalidate_cache_new('title',$key);
14164: }
14165:
1.1014 droeschl 14166: # ------------------------------------------------- Get the title of a course
14167:
14168: sub current_course_title {
14169: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
14170: }
1.301 www 14171: # ------------------------------------------------- Get the title of a resource
14172:
14173: sub gettitle {
14174: my $urlsymb=shift;
14175: my $symb=&symbread($urlsymb);
1.534 albertel 14176: if ($symb) {
1.620 albertel 14177: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 14178: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 14179: if (defined($cached)) {
14180: return $result;
14181: }
1.534 albertel 14182: my ($map,$resid,$url)=&decode_symb($symb);
14183: my $title='';
1.907 albertel 14184: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
14185: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
14186: } else {
14187: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
14188: &GDBM_READER(),0640)) {
14189: my $mapid=$bighash{'map_pc_'.&clutter($map)};
14190: $title=$bighash{'title_'.$mapid.'.'.$resid};
14191: untie(%bighash);
14192: }
1.534 albertel 14193: }
14194: $title=~s/\&colon\;/\:/gs;
14195: if ($title) {
1.1159 www 14196: # Remember both $symb and $title for dynamic metadata
14197: $accesshash{$symb.'___crstitle'}=$title;
1.1161 www 14198: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159 www 14199: # Cache this title and then return it
1.599 albertel 14200: return &do_cache_new('title',$key,$title,600);
1.534 albertel 14201: }
14202: $urlsymb=$url;
14203: }
14204: my $title=&metadata($urlsymb,'title');
14205: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
14206: return $title;
1.301 www 14207: }
1.613 albertel 14208:
1.614 albertel 14209: sub get_slot {
14210: my ($which,$cnum,$cdom)=@_;
14211: if (!$cnum || !$cdom) {
1.790 albertel 14212: (undef,my $courseid)=&whichuser();
1.620 albertel 14213: $cdom=$env{'course.'.$courseid.'.domain'};
14214: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 14215: }
1.703 albertel 14216: my $key=join("\0",'slots',$cdom,$cnum,$which);
14217: my %slotinfo;
14218: if (exists($remembered{$key})) {
14219: $slotinfo{$which} = $remembered{$key};
14220: } else {
14221: %slotinfo=&get('slots',[$which],$cdom,$cnum);
14222: &Apache::lonhomework::showhash(%slotinfo);
14223: my ($tmp)=keys(%slotinfo);
14224: if ($tmp=~/^error:/) { return (); }
14225: $remembered{$key} = $slotinfo{$which};
14226: }
1.616 albertel 14227: if (ref($slotinfo{$which}) eq 'HASH') {
14228: return %{$slotinfo{$which}};
14229: }
14230: return $slotinfo{$which};
1.614 albertel 14231: }
1.1150 raeburn 14232:
14233: sub get_reservable_slots {
14234: my ($cnum,$cdom,$uname,$udom) = @_;
14235: my $now = time;
14236: my $reservable_info;
14237: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
14238: if (exists($remembered{$key})) {
14239: $reservable_info = $remembered{$key};
14240: } else {
14241: my %resv;
14242: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
14243: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
14244: $reservable_info = \%resv;
14245: $remembered{$key} = $reservable_info;
14246: }
14247: return $reservable_info;
14248: }
14249:
14250: sub get_course_slots {
14251: my ($cnum,$cdom) = @_;
14252: my $hashid=$cnum.':'.$cdom;
1.1494 raeburn 14253: my ($result,$cached) = &is_cached_new('allslots',$hashid);
1.1150 raeburn 14254: if (defined($cached)) {
14255: if (ref($result) eq 'HASH') {
14256: return %{$result};
14257: }
14258: } else {
1.1494 raeburn 14259: my %slots=&dump('slots',$cdom,$cnum);
1.1150 raeburn 14260: my ($tmp) = keys(%slots);
14261: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1219 raeburn 14262: &do_cache_new('allslots',$hashid,\%slots,600);
1.1150 raeburn 14263: return %slots;
14264: }
14265: }
14266: return;
14267: }
14268:
14269: sub devalidate_slots_cache {
14270: my ($cnum,$cdom)=@_;
14271: my $hashid=$cnum.':'.$cdom;
14272: &devalidate_cache_new('allslots',$hashid);
14273: }
14274:
1.1181 raeburn 14275: sub get_coursechange {
14276: my ($cdom,$cnum) = @_;
14277: if ($cdom eq '' || $cnum eq '') {
14278: return unless ($env{'request.course.id'});
14279: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
14280: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
14281: }
14282: my $hashid=$cdom.'_'.$cnum;
14283: my ($change,$cached)=&is_cached_new('crschange',$hashid);
14284: if ((defined($cached)) && ($change ne '')) {
14285: return $change;
14286: } else {
14287: my %crshash;
14288: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
14289: if ($crshash{'internal.contentchange'} eq '') {
14290: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
14291: if ($change eq '') {
14292: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
14293: $change = $crshash{'internal.created'};
14294: }
14295: } else {
14296: $change = $crshash{'internal.contentchange'};
14297: }
14298: my $cachetime = 600;
14299: &do_cache_new('crschange',$hashid,$change,$cachetime);
14300: }
14301: return $change;
14302: }
14303:
14304: sub devalidate_coursechange_cache {
1.1496 raeburn 14305: my ($cdom,$cnum)=@_;
14306: my $hashid=$cdom.'_'.$cnum;
1.1181 raeburn 14307: &devalidate_cache_new('crschange',$hashid);
14308: }
14309:
1.1496 raeburn 14310: sub get_suppchange {
14311: my ($cdom,$cnum) = @_;
14312: if ($cdom eq '' || $cnum eq '') {
14313: return unless ($env{'request.course.id'});
14314: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
14315: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
14316: }
14317: my $hashid=$cdom.'_'.$cnum;
14318: my ($change,$cached)=&is_cached_new('suppchange',$hashid);
14319: if ((defined($cached)) && ($change ne '')) {
14320: return $change;
14321: } else {
14322: my %crshash = &get('environment',['internal.supplementalchange'],$cdom,$cnum);
14323: if ($crshash{'internal.supplementalchange'} eq '') {
14324: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
14325: if ($change eq '') {
14326: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
14327: $change = $crshash{'internal.created'};
14328: }
14329: } else {
14330: $change = $crshash{'internal.supplementalchange'};
14331: }
14332: my $cachetime = 600;
14333: &do_cache_new('suppchange',$hashid,$change,$cachetime);
14334: }
14335: return $change;
14336: }
14337:
14338: sub devalidate_suppchange_cache {
14339: my ($cdom,$cnum)=@_;
14340: my $hashid=$cdom.'_'.$cnum;
14341: &devalidate_cache_new('suppchange',$hashid);
14342: }
14343:
1.1497 raeburn 14344: sub update_supp_caches {
14345: my ($cdom,$cnum) = @_;
14346: my %servers = &internet_dom_servers($cdom);
14347: my @ids=¤t_machine_ids();
14348: foreach my $server (keys(%servers)) {
14349: next if (grep(/^\Q$server\E$/,@ids));
14350: my $hashid=$cnum.':'.$cdom;
14351: my $cachekey = &escape('showsupp').':'.&escape($hashid);
14352: &remote_devalidate_cache($server,[$cachekey]);
14353: }
14354: &has_unhidden_suppfiles($cnum,$cdom,1,1);
14355: &count_supptools($cnum,$cdom,1);
14356: my $now = time;
14357: if ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
14358: &Apache::lonnet::appenv({'request.course.suppupdated' => $now});
14359: }
14360: &put('environment',{'internal.supplementalchange' => $now},
14361: $cdom,$cnum);
14362: &Apache::lonnet::appenv(
14363: {'course.'.$cdom.'_'.$cnum.'.internal.supplementalchange' => $now});
14364: &do_cache_new('suppchange',$cdom.'_'.$cnum,$now,600);
14365: }
14366:
1.31 www 14367: # ------------------------------------------------- Update symbolic store links
14368:
14369: sub symblist {
14370: my ($mapname,%newhash)=@_;
1.438 www 14371: $mapname=&deversion(&declutter($mapname));
1.31 www 14372: my %hash;
1.620 albertel 14373: if (($env{'request.course.fn'}) && (%newhash)) {
14374: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 14375: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 14376: foreach my $url (keys(%newhash)) {
1.711 albertel 14377: next if ($url eq 'last_known'
14378: && $env{'form.no_update_last_known'});
14379: $hash{declutter($url)}=&encode_symb($mapname,
14380: $newhash{$url}->[1],
14381: $newhash{$url}->[0]);
1.191 harris41 14382: }
1.31 www 14383: if (untie(%hash)) {
14384: return 'ok';
14385: }
14386: }
14387: }
14388: return 'error';
1.212 www 14389: }
14390:
14391: # --------------------------------------------------------------- Verify a symb
14392:
14393: sub symbverify {
1.1190 raeburn 14394: my ($symb,$thisurl,$encstate)=@_;
1.510 www 14395: my $thisfn=$thisurl;
1.439 www 14396: $thisfn=&declutter($thisfn);
1.215 www 14397: # direct jump to resource in page or to a sequence - will construct own symbs
14398: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
14399: # check URL part
1.409 www 14400: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 14401:
1.431 www 14402: unless ($url eq $thisfn) { return 0; }
1.213 www 14403:
1.216 www 14404: $symb=&symbclean($symb);
1.510 www 14405: $thisurl=&deversion($thisurl);
1.439 www 14406: $thisfn=&deversion($thisfn);
1.213 www 14407:
14408: my %bighash;
14409: my $okay=0;
1.431 www 14410:
1.620 albertel 14411: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 14412: &GDBM_READER(),0640)) {
1.1032 raeburn 14413: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
14414: $thisurl =~ s/\?.+$//;
1.1204 raeburn 14415: if ($map =~ m{^uploaded/.+\.page$}) {
14416: $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
14417: $thisurl =~ s{^\Qhttp://https://\E}{https://};
14418: }
14419: }
14420: my $ids;
1.1419 raeburn 14421: if ($map =~ m{^uploaded/.+\.page$}) {
14422: $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
1.1204 raeburn 14423: } else {
14424: $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032 raeburn 14425: }
1.1102 raeburn 14426: unless ($ids) {
14427: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
14428: $ids=$bighash{$idkey};
1.216 www 14429: }
14430: if ($ids) {
14431: # ------------------------------------------------------------------- Has ID(s)
1.1202 raeburn 14432: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
1.1203 raeburn 14433: $symb =~ s/\?.+$//;
1.1202 raeburn 14434: }
1.800 albertel 14435: foreach my $id (split(/\,/,$ids)) {
14436: my ($mapid,$resid)=split(/\./,$id);
1.216 www 14437: if (
14438: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190 raeburn 14439: eq $symb) {
14440: if (ref($encstate)) {
14441: $$encstate = $bighash{'encrypted_'.$id};
14442: }
1.620 albertel 14443: if (($env{'request.role.adv'}) ||
1.1101 raeburn 14444: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
14445: ($thisurl eq '/adm/navmaps')) {
1.1190 raeburn 14446: $okay=1;
1.1202 raeburn 14447: last;
1.582 albertel 14448: }
14449: }
1.216 www 14450: }
14451: }
1.213 www 14452: untie(%bighash);
14453: }
14454: return $okay;
1.31 www 14455: }
14456:
1.210 www 14457: # --------------------------------------------------------------- Clean-up symb
14458:
14459: sub symbclean {
14460: my $symb=shift;
1.568 albertel 14461: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 14462: # remove version from map
14463: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 14464:
1.210 www 14465: # remove version from URL
14466: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 14467:
1.507 www 14468: # remove wrapper
14469:
1.510 www 14470: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 14471: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 14472: return $symb;
1.409 www 14473: }
14474:
14475: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 14476:
14477: sub encode_symb {
14478: my ($map,$resid,$url)=@_;
14479: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
14480: }
1.409 www 14481:
14482: sub decode_symb {
1.568 albertel 14483: my $symb=shift;
14484: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
14485: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 14486: return (&fixversion($map),$resid,&fixversion($url));
14487: }
14488:
14489: sub fixversion {
14490: my $fn=shift;
1.609 banghart 14491: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 14492: my %bighash;
14493: my $uri=&clutter($fn);
1.620 albertel 14494: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 14495: # is this cached?
1.599 albertel 14496: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 14497: if (defined($cached)) { return $result; }
14498: # unfortunately not cached, or expired
1.620 albertel 14499: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 14500: &GDBM_READER(),0640)) {
14501: if ($bighash{'version_'.$uri}) {
14502: my $version=$bighash{'version_'.$uri};
1.444 www 14503: unless (($version eq 'mostrecent') ||
14504: ($version==&getversion($uri))) {
1.440 www 14505: $uri=~s/\.(\w+)$/\.$version\.$1/;
14506: }
14507: }
14508: untie %bighash;
1.413 www 14509: }
1.599 albertel 14510: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 14511: }
14512:
14513: sub deversion {
14514: my $url=shift;
14515: $url=~s/\.\d+\.(\w+)$/\.$1/;
14516: return $url;
1.210 www 14517: }
14518:
1.31 www 14519: # ------------------------------------------------------ Return symb list entry
14520:
14521: sub symbread {
1.1424 raeburn 14522: my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles,
1.1427 raeburn 14523: $ignoresymbdb,$noenccheck)=@_;
1.1265 raeburn 14524: my $cache_str='request.symbread.cached.'.$thisfn;
1.1427 raeburn 14525: if (defined($env{$cache_str})) {
1.1424 raeburn 14526: unless (ref($possibles) eq 'HASH') {
14527: if ($ignorecachednull) {
14528: return $env{$cache_str} unless ($env{$cache_str} eq '');
14529: } else {
14530: return $env{$cache_str};
14531: }
1.1282 raeburn 14532: }
14533: }
1.242 www 14534: # no filename provided? try from environment
1.1265 raeburn 14535: unless ($thisfn) {
1.620 albertel 14536: if ($env{'request.symb'}) {
1.1427 raeburn 14537: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 14538: }
1.620 albertel 14539: $thisfn=$env{'request.filename'};
1.44 www 14540: }
1.569 albertel 14541: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 14542: # is that filename actually a symb? Verify, clean, and return
14543: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 14544: if (&symbverify($thisfn,$1)) {
1.1427 raeburn 14545: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 14546: }
1.242 www 14547: }
1.44 www 14548: $thisfn=declutter($thisfn);
1.31 www 14549: my %hash;
1.37 www 14550: my %bighash;
14551: my $syval='';
1.620 albertel 14552: if (($env{'request.course.fn'}) && ($thisfn)) {
1.1427 raeburn 14553: unless ($ignoresymbdb) {
1.1424 raeburn 14554: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
14555: &GDBM_READER(),0640)) {
1.1487 raeburn 14556: $syval=$hash{$thisfn};
1.1424 raeburn 14557: untie(%hash);
14558: }
1.1427 raeburn 14559: if ($syval && $checkforblock) {
14560: my @blockers = &has_comm_blocking('bre',$syval,$thisfn,$ignoresymbdb,$noenccheck);
1.1424 raeburn 14561: if (@blockers) {
14562: $syval='';
14563: }
14564: }
1.37 www 14565: }
14566: # ---------------------------------------------------------- There was an entry
14567: if ($syval) {
1.601 albertel 14568: #unless ($syval=~/\_\d+$/) {
1.620 albertel 14569: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 14570: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 14571: #return $env{$cache_str}='';
1.601 albertel 14572: #}
14573: #$syval.=$1;
14574: #}
1.37 www 14575: } else {
14576: # ------------------------------------------------------- Was not in symb table
1.620 albertel 14577: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 14578: &GDBM_READER(),0640)) {
1.37 www 14579: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 14580: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 14581: unless ($ids) {
14582: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 14583: }
14584: unless ($ids) {
14585: # alias?
14586: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 14587: }
1.37 www 14588: if ($ids) {
14589: # ------------------------------------------------------------------- Has ID(s)
14590: my @possibilities=split(/\,/,$ids);
1.39 www 14591: if ($#possibilities==0) {
14592: # ----------------------------------------------- There is only one possibility
1.37 www 14593: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 14594: $syval=&encode_symb($bighash{'map_id_'.$mapid},
14595: $resid,$thisfn);
1.1282 raeburn 14596: if (ref($possibles) eq 'HASH') {
1.1424 raeburn 14597: unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
14598: $possibles->{$syval} = 1;
14599: }
1.1282 raeburn 14600: }
14601: if ($checkforblock) {
1.1424 raeburn 14602: unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
1.1426 raeburn 14603: my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids},'',$noenccheck);
1.1424 raeburn 14604: if (@blockers) {
14605: $syval = '';
1.1425 raeburn 14606: untie(%bighash);
14607: return $env{$cache_str}='';
1.1424 raeburn 14608: }
1.1282 raeburn 14609: }
14610: }
14611: } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39 www 14612: # ------------------------------------------ There is more than one possibility
14613: my $realpossible=0;
1.800 albertel 14614: foreach my $id (@possibilities) {
14615: my $file=$bighash{'src_'.$id};
1.1282 raeburn 14616: my $canaccess;
14617: if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
14618: $canaccess = 1;
14619: } else {
14620: $canaccess = &allowed('bre',$file);
14621: }
14622: if ($canaccess) {
14623: my ($mapid,$resid)=split(/\./,$id);
14624: if ($bighash{'map_type_'.$mapid} ne 'page') {
14625: my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
14626: $resid,$thisfn);
1.1424 raeburn 14627: next if ($bighash{'randomout_'.$id} && !$env{'request.role.adv'});
1.1426 raeburn 14628: next unless (($noenccheck) || ($bighash{'encrypted_'.$id} eq $env{'request.enc'}));
1.1282 raeburn 14629: if ($checkforblock) {
1.1426 raeburn 14630: my @blockers = &has_comm_blocking('bre',$poss_syval,$file,'',$noenccheck);
1.1424 raeburn 14631: if (@blockers > 0) {
14632: $syval = '';
14633: } else {
1.1282 raeburn 14634: $syval = $poss_syval;
14635: $realpossible++;
14636: }
14637: } else {
14638: $syval = $poss_syval;
14639: $realpossible++;
14640: }
1.1424 raeburn 14641: if ($syval) {
14642: if (ref($possibles) eq 'HASH') {
14643: $possibles->{$syval} = 1;
14644: }
14645: }
1.1282 raeburn 14646: }
1.39 www 14647: }
1.191 harris41 14648: }
1.39 www 14649: if ($realpossible!=1) { $syval=''; }
1.249 www 14650: } else {
14651: $syval='';
1.37 www 14652: }
14653: }
1.1282 raeburn 14654: untie(%bighash);
1.481 raeburn 14655: }
1.31 www 14656: }
1.62 www 14657: if ($syval) {
1.1427 raeburn 14658: return $env{$cache_str}=$syval;
1.62 www 14659: }
1.31 www 14660: }
1.949 raeburn 14661: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 14662: return $env{$cache_str}='';
1.31 www 14663: }
14664:
14665: # ---------------------------------------------------------- Return random seed
14666:
1.32 www 14667: sub numval {
14668: my $txt=shift;
14669: $txt=~tr/A-J/0-9/;
14670: $txt=~tr/a-j/0-9/;
14671: $txt=~tr/K-T/0-9/;
14672: $txt=~tr/k-t/0-9/;
14673: $txt=~tr/U-Z/0-5/;
14674: $txt=~tr/u-z/0-5/;
14675: $txt=~s/\D//g;
1.564 albertel 14676: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 14677: return int($txt);
1.368 albertel 14678: }
14679:
1.484 albertel 14680: sub numval2 {
14681: my $txt=shift;
14682: $txt=~tr/A-J/0-9/;
14683: $txt=~tr/a-j/0-9/;
14684: $txt=~tr/K-T/0-9/;
14685: $txt=~tr/k-t/0-9/;
14686: $txt=~tr/U-Z/0-5/;
14687: $txt=~tr/u-z/0-5/;
14688: $txt=~s/\D//g;
14689: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
14690: my $total;
14691: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 14692: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 14693: return int($total);
14694: }
14695:
1.575 albertel 14696: sub numval3 {
14697: use integer;
14698: my $txt=shift;
14699: $txt=~tr/A-J/0-9/;
14700: $txt=~tr/a-j/0-9/;
14701: $txt=~tr/K-T/0-9/;
14702: $txt=~tr/k-t/0-9/;
14703: $txt=~tr/U-Z/0-5/;
14704: $txt=~tr/u-z/0-5/;
14705: $txt=~s/\D//g;
14706: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
14707: my $total;
14708: foreach my $val (@txts) { $total+=$val; }
14709: if ($_64bit) { $total=(($total<<32)>>32); }
14710: return $total;
14711: }
14712:
1.675 albertel 14713: sub digest {
14714: my ($data)=@_;
14715: my $digest=&Digest::MD5::md5($data);
14716: my ($a,$b,$c,$d)=unpack("iiii",$digest);
14717: my ($e,$f);
14718: {
14719: use integer;
14720: $e=($a+$b);
14721: $f=($c+$d);
14722: if ($_64bit) {
14723: $e=(($e<<32)>>32);
14724: $f=(($f<<32)>>32);
14725: }
14726: }
14727: if (wantarray) {
14728: return ($e,$f);
14729: } else {
14730: my $g;
14731: {
14732: use integer;
14733: $g=($e+$f);
14734: if ($_64bit) {
14735: $g=(($g<<32)>>32);
14736: }
14737: }
14738: return $g;
14739: }
14740: }
14741:
1.368 albertel 14742: sub latest_rnd_algorithm_id {
1.675 albertel 14743: return '64bit5';
1.366 albertel 14744: }
1.32 www 14745:
1.503 albertel 14746: sub get_rand_alg {
14747: my ($courseid)=@_;
1.790 albertel 14748: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 14749: if ($courseid) {
1.620 albertel 14750: return $env{"course.$courseid.rndseed"};
1.503 albertel 14751: }
14752: return &latest_rnd_algorithm_id();
14753: }
14754:
1.562 albertel 14755: sub validCODE {
14756: my ($CODE)=@_;
14757: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
14758: return 0;
14759: }
14760:
1.491 albertel 14761: sub getCODE {
1.620 albertel 14762: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 14763: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
14764: defined($Apache::lonhomework::parsing_a_task) ) &&
14765: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 14766: return $Apache::lonhomework::history{'resource.CODE'};
14767: }
14768: return undef;
14769: }
1.1133 foxr 14770: #
14771: # Determines the random seed for a specific context:
14772: #
14773: # parameters:
14774: # symb - in course context the symb for the seed.
14775: # course_id - The course id of the form domain_coursenum.
14776: # domain - Domain for the user.
14777: # course - Course for the user.
14778: # cenv - environment of the course.
14779: #
14780: # NOTE:
14781: # All parameters are picked out of the environment if missing
14782: # or not defined.
14783: # If a symb cannot be determined the current time is used instead.
14784: #
14785: # For a given well defined symb, courside, domain, username,
14786: # and course environment, the seed is reproducible.
14787: #
1.31 www 14788: sub rndseed {
1.1133 foxr 14789: my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790 albertel 14790: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 14791: if (!defined($symb)) {
1.366 albertel 14792: unless ($symb=$wsymb) { return time; }
14793: }
1.1146 foxr 14794: if (!defined $courseid) {
14795: $courseid=$wcourseid;
14796: }
14797: if (!defined $domain) { $domain=$wdomain; }
14798: if (!defined $username) { $username=$wusername }
1.1133 foxr 14799:
14800: my $which;
14801: if (defined($cenv->{'rndseed'})) {
14802: $which = $cenv->{'rndseed'};
14803: } else {
14804: $which =&get_rand_alg($courseid);
14805: }
1.491 albertel 14806: if (defined(&getCODE())) {
1.1133 foxr 14807:
1.675 albertel 14808: if ($which eq '64bit5') {
14809: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
14810: } elsif ($which eq '64bit4') {
1.575 albertel 14811: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
14812: } else {
14813: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
14814: }
1.675 albertel 14815: } elsif ($which eq '64bit5') {
14816: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 14817: } elsif ($which eq '64bit4') {
14818: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 14819: } elsif ($which eq '64bit3') {
14820: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 14821: } elsif ($which eq '64bit2') {
14822: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 14823: } elsif ($which eq '64bit') {
14824: return &rndseed_64bit($symb,$courseid,$domain,$username);
14825: }
14826: return &rndseed_32bit($symb,$courseid,$domain,$username);
14827: }
14828:
14829: sub rndseed_32bit {
14830: my ($symb,$courseid,$domain,$username)=@_;
14831: {
14832: use integer;
14833: my $symbchck=unpack("%32C*",$symb) << 27;
14834: my $symbseed=numval($symb) << 22;
14835: my $namechck=unpack("%32C*",$username) << 17;
14836: my $nameseed=numval($username) << 12;
14837: my $domainseed=unpack("%32C*",$domain) << 7;
14838: my $courseseed=unpack("%32C*",$courseid);
14839: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 14840: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14841: #&logthis("rndseed :$num:$symb");
1.564 albertel 14842: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 14843: return $num;
14844: }
14845: }
14846:
14847: sub rndseed_64bit {
14848: my ($symb,$courseid,$domain,$username)=@_;
14849: {
14850: use integer;
14851: my $symbchck=unpack("%32S*",$symb) << 21;
14852: my $symbseed=numval($symb) << 10;
14853: my $namechck=unpack("%32S*",$username);
14854:
14855: my $nameseed=numval($username) << 21;
14856: my $domainseed=unpack("%32S*",$domain) << 10;
14857: my $courseseed=unpack("%32S*",$courseid);
14858:
14859: my $num1=$symbchck+$symbseed+$namechck;
14860: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 14861: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14862: #&logthis("rndseed :$num:$symb");
1.564 albertel 14863: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 14864: return "$num1,$num2";
1.155 albertel 14865: }
1.366 albertel 14866: }
14867:
1.443 albertel 14868: sub rndseed_64bit2 {
14869: my ($symb,$courseid,$domain,$username)=@_;
14870: {
14871: use integer;
14872: # strings need to be an even # of cahracters long, it it is odd the
14873: # last characters gets thrown away
14874: my $symbchck=unpack("%32S*",$symb.' ') << 21;
14875: my $symbseed=numval($symb) << 10;
14876: my $namechck=unpack("%32S*",$username.' ');
14877:
14878: my $nameseed=numval($username) << 21;
1.501 albertel 14879: my $domainseed=unpack("%32S*",$domain.' ') << 10;
14880: my $courseseed=unpack("%32S*",$courseid.' ');
14881:
14882: my $num1=$symbchck+$symbseed+$namechck;
14883: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 14884: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14885: #&logthis("rndseed :$num:$symb");
1.803 albertel 14886: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 14887: return "$num1,$num2";
14888: }
14889: }
14890:
14891: sub rndseed_64bit3 {
14892: my ($symb,$courseid,$domain,$username)=@_;
14893: {
14894: use integer;
14895: # strings need to be an even # of cahracters long, it it is odd the
14896: # last characters gets thrown away
14897: my $symbchck=unpack("%32S*",$symb.' ') << 21;
14898: my $symbseed=numval2($symb) << 10;
14899: my $namechck=unpack("%32S*",$username.' ');
14900:
14901: my $nameseed=numval2($username) << 21;
1.443 albertel 14902: my $domainseed=unpack("%32S*",$domain.' ') << 10;
14903: my $courseseed=unpack("%32S*",$courseid.' ');
14904:
14905: my $num1=$symbchck+$symbseed+$namechck;
14906: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 14907: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14908: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 14909: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 14910:
1.503 albertel 14911: return "$num1:$num2";
1.443 albertel 14912: }
14913: }
14914:
1.575 albertel 14915: sub rndseed_64bit4 {
14916: my ($symb,$courseid,$domain,$username)=@_;
14917: {
14918: use integer;
14919: # strings need to be an even # of cahracters long, it it is odd the
14920: # last characters gets thrown away
14921: my $symbchck=unpack("%32S*",$symb.' ') << 21;
14922: my $symbseed=numval3($symb) << 10;
14923: my $namechck=unpack("%32S*",$username.' ');
14924:
14925: my $nameseed=numval3($username) << 21;
14926: my $domainseed=unpack("%32S*",$domain.' ') << 10;
14927: my $courseseed=unpack("%32S*",$courseid.' ');
14928:
14929: my $num1=$symbchck+$symbseed+$namechck;
14930: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 14931: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14932: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 14933: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 14934:
1.575 albertel 14935: return "$num1:$num2";
14936: }
14937: }
14938:
1.675 albertel 14939: sub rndseed_64bit5 {
14940: my ($symb,$courseid,$domain,$username)=@_;
14941: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
14942: return "$num1:$num2";
14943: }
14944:
1.366 albertel 14945: sub rndseed_CODE_64bit {
14946: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 14947: {
1.366 albertel 14948: use integer;
1.443 albertel 14949: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 14950: my $symbseed=numval2($symb);
1.491 albertel 14951: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
14952: my $CODEseed=numval(&getCODE());
1.443 albertel 14953: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 14954: my $num1=$symbseed+$CODEchck;
14955: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 14956: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
14957: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 14958: if ($_64bit) { $num1=(($num1<<32)>>32); }
14959: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 14960: return "$num1:$num2";
1.366 albertel 14961: }
14962: }
14963:
1.575 albertel 14964: sub rndseed_CODE_64bit4 {
14965: my ($symb,$courseid,$domain,$username)=@_;
14966: {
14967: use integer;
14968: my $symbchck=unpack("%32S*",$symb.' ') << 16;
14969: my $symbseed=numval3($symb);
14970: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
14971: my $CODEseed=numval3(&getCODE());
14972: my $courseseed=unpack("%32S*",$courseid.' ');
14973: my $num1=$symbseed+$CODEchck;
14974: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 14975: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
14976: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 14977: if ($_64bit) { $num1=(($num1<<32)>>32); }
14978: if ($_64bit) { $num2=(($num2<<32)>>32); }
14979: return "$num1:$num2";
14980: }
14981: }
14982:
1.675 albertel 14983: sub rndseed_CODE_64bit5 {
14984: my ($symb,$courseid,$domain,$username)=@_;
14985: my $code = &getCODE();
14986: my ($num1,$num2)=&digest("$symb,$courseid,$code");
14987: return "$num1:$num2";
14988: }
14989:
1.366 albertel 14990: sub setup_random_from_rndseed {
14991: my ($rndseed)=@_;
1.503 albertel 14992: if ($rndseed =~/([,:])/) {
1.1262 raeburn 14993: my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
14994: if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
14995: &Math::Random::random_set_seed_from_phrase($rndseed);
14996: } else {
14997: &Math::Random::random_set_seed($num1,$num2);
14998: }
1.366 albertel 14999: } else {
15000: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 15001: }
1.36 albertel 15002: }
15003:
1.474 albertel 15004: sub latest_receipt_algorithm_id {
1.835 albertel 15005: return 'receipt3';
1.474 albertel 15006: }
15007:
1.480 www 15008: sub recunique {
15009: my $fucourseid=shift;
15010: my $unique;
1.835 albertel 15011: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
15012: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 15013: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 15014: } else {
15015: $unique=$perlvar{'lonReceipt'};
15016: }
15017: return unpack("%32C*",$unique);
15018: }
15019:
15020: sub recprefix {
15021: my $fucourseid=shift;
15022: my $prefix;
1.835 albertel 15023: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
15024: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 15025: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 15026: } else {
15027: $prefix=$perlvar{'lonHostID'};
15028: }
15029: return unpack("%32C*",$prefix);
15030: }
15031:
1.76 www 15032: sub ireceipt {
1.474 albertel 15033: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 15034:
15035: my $return =&recprefix($fucourseid).'-';
15036:
15037: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
15038: $env{'request.state'} eq 'construct') {
15039: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
15040: return $return;
15041: }
15042:
1.76 www 15043: my $cuname=unpack("%32C*",$funame);
15044: my $cudom=unpack("%32C*",$fudom);
15045: my $cucourseid=unpack("%32C*",$fucourseid);
15046: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 15047: my $cunique=&recunique($fucourseid);
1.474 albertel 15048: my $cpart=unpack("%32S*",$part);
1.835 albertel 15049: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
15050:
1.790 albertel 15051: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 15052:
15053: $return.= ($cunique%$cuname+
15054: $cunique%$cudom+
15055: $cusymb%$cuname+
15056: $cusymb%$cudom+
15057: $cucourseid%$cuname+
15058: $cucourseid%$cudom+
15059: $cpart%$cuname+
15060: $cpart%$cudom);
15061: } else {
15062: $return.= ($cunique%$cuname+
15063: $cunique%$cudom+
15064: $cusymb%$cuname+
15065: $cusymb%$cudom+
15066: $cucourseid%$cuname+
15067: $cucourseid%$cudom);
15068: }
15069: return $return;
1.76 www 15070: }
15071:
15072: sub receipt {
1.474 albertel 15073: my ($part)=@_;
1.790 albertel 15074: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 15075: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 15076: }
1.260 ng 15077:
1.790 albertel 15078: sub whichuser {
15079: my ($passedsymb)=@_;
15080: my ($symb,$courseid,$domain,$name,$publicuser);
15081: if (defined($env{'form.grade_symb'})) {
15082: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
15083: my $allowed=&allowed('vgr',$tmp_courseid);
15084: if (!$allowed &&
15085: exists($env{'request.course.sec'}) &&
15086: $env{'request.course.sec'} !~ /^\s*$/) {
15087: $allowed=&allowed('vgr',$tmp_courseid.
15088: '/'.$env{'request.course.sec'});
15089: }
15090: if ($allowed) {
15091: ($symb)=&get_env_multiple('form.grade_symb');
15092: $courseid=$tmp_courseid;
15093: ($domain)=&get_env_multiple('form.grade_domain');
15094: ($name)=&get_env_multiple('form.grade_username');
15095: return ($symb,$courseid,$domain,$name,$publicuser);
15096: }
15097: }
15098: if (!$passedsymb) {
15099: $symb=&symbread();
15100: } else {
15101: $symb=$passedsymb;
15102: }
15103: $courseid=$env{'request.course.id'};
15104: $domain=$env{'user.domain'};
15105: $name=$env{'user.name'};
15106: if ($name eq 'public' && $domain eq 'public') {
15107: if (!defined($env{'form.username'})) {
15108: $env{'form.username'}.=time.rand(10000000);
15109: }
15110: $name.=$env{'form.username'};
15111: }
15112: return ($symb,$courseid,$domain,$name,$publicuser);
15113:
15114: }
15115:
1.36 albertel 15116: # ------------------------------------------------------------ Serves up a file
1.472 albertel 15117: # returns either the contents of the file or
15118: # -1 if the file doesn't exist
1.481 raeburn 15119: #
15120: # if the target is a file that was uploaded via DOCS,
15121: # a check will be made to see if a current copy exists on the local server,
15122: # if it does this will be served, otherwise a copy will be retrieved from
15123: # the home server for the course and stored in /home/httpd/html/userfiles on
15124: # the local server.
1.472 albertel 15125:
1.36 albertel 15126: sub getfile {
1.538 albertel 15127: my ($file) = @_;
1.609 banghart 15128: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 15129: &repcopy($file);
15130: return &readfile($file);
15131: }
15132:
15133: sub repcopy_userfile {
15134: my ($file)=@_;
1.1142 raeburn 15135: my $londocroot = $perlvar{'lonDocRoot'};
15136: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164 raeburn 15137: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538 albertel 15138: my ($cdom,$cnum,$filename) =
1.811 albertel 15139: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 15140: my $uri="/uploaded/$cdom/$cnum/$filename";
15141: if (-e "$file") {
1.828 www 15142: # we already have a local copy, check it out
1.538 albertel 15143: my @fileinfo = stat($file);
1.828 www 15144: my $rtncode;
15145: my $info;
1.538 albertel 15146: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 15147: if ($lwpresp ne 'ok') {
1.828 www 15148: # there is no such file anymore, even though we had a local copy
1.482 albertel 15149: if ($rtncode eq '404') {
1.538 albertel 15150: unlink($file);
1.482 albertel 15151: }
15152: return -1;
15153: }
15154: if ($info < $fileinfo[9]) {
1.828 www 15155: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 15156: return 'ok';
1.828 www 15157: } else {
15158: # the file is outdated, get rid of it
15159: unlink($file);
1.482 albertel 15160: }
1.828 www 15161: }
15162: # one way or the other, at this point, we don't have the file
15163: # construct the correct path for the file
15164: my @parts = ($cdom,$cnum);
15165: if ($filename =~ m|^(.+)/[^/]+$|) {
15166: push @parts, split(/\//,$1);
15167: }
15168: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
15169: foreach my $part (@parts) {
15170: $path .= '/'.$part;
15171: if (!-e $path) {
15172: mkdir($path,0770);
1.482 albertel 15173: }
15174: }
1.828 www 15175: # now the path exists for sure
15176: # get a user agent
15177: my $transferfile=$file.'.in.transfer';
15178: # FIXME: this should flock
15179: if (-e $transferfile) { return 'ok'; }
15180: my $request;
15181: $uri=~s/^\///;
1.980 raeburn 15182: my $homeserver = &homeserver($cnum,$cdom);
1.1398 raeburn 15183: my $hostname = &hostname($homeserver);
1.980 raeburn 15184: my $protocol = $protocol{$homeserver};
15185: $protocol = 'http' if ($protocol ne 'https');
1.1397 raeburn 15186: $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
1.1345 raeburn 15187: my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,$transferfile,\%perlvar,'',0,1);
1.828 www 15188: # did it work?
15189: if ($response->is_error()) {
15190: unlink($transferfile);
15191: &logthis("Userfile repcopy failed for $uri");
15192: return -1;
15193: }
15194: # worked, rename the transfer file
15195: rename($transferfile,$file);
1.607 raeburn 15196: return 'ok';
1.481 raeburn 15197: }
15198:
1.1532 raeburn 15199: sub repcopy_crsprivfile {
15200: my ($src,$dest) = @_;
15201: my $result;
15202: if ($src =~ m{^/priv/($match_domain)/($match_courseid)/(.+)$}) {
15203: my ($cdom,$cnum,$filepath) = ($1,$2,$3);
15204: $filepath =~ s/\.{2,}//g;
15205: my $chome = &homeserver($cnum,$cdom);
15206: unless ($chome eq 'no_host') {
15207: my @ids=¤t_machine_ids();
15208: unless (grep(/^\Q$chome\E$/,@ids)) {
15209: if (&is_course($cdom,$cnum)) {
15210: my $londocroot = $perlvar{'lonDocRoot'};
15211: if ($dest =~ m{^\Q$londocroot/priv/\E$match_domain/$match_username/.*\Q$filepath\E$}) {
15212: my $cmd = 'crsfilefrompriv:'.&escape($filepath).':'.&escape($cnum).':'.&escape($cdom);
15213: $result = &reply($cmd,$chome);
15214: unless (($result eq 'unknown_cmd') || ($result =~ /^error:/)) {
15215: my $url = &unescape($result);
15216: if ($url =~ m{^https?://[^/]+\Q/userfiles/$cdom/$cnum/priv/$filepath\E$}) {
15217: my $request=new HTTP::Request('GET',$url);
15218: my $response=&LONCAPA::LWPReq::makerequest($chome,$request,'',\%perlvar,1200,1);
15219: if ($response->is_error()) {
15220: $result = 'error: '.$response->status_line;
15221: } else {
15222: if (open(my $fh,'>',$dest)) {
15223: print $fh $response->content;
15224: close($fh);
15225: $result = 'ok';
15226: } else {
15227: $result = 'error: nowrite';
15228: }
15229: }
15230: } else {
15231: $result = 'error: invalidurl';
15232: }
15233: }
15234: }
15235: }
15236: }
15237: }
15238: }
15239: return $result;
15240: }
15241:
1.517 albertel 15242: sub tokenwrapper {
15243: my $uri=shift;
1.980 raeburn 15244: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 15245: $uri=~s|^/||;
1.620 albertel 15246: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 15247: my $token=$1;
1.552 albertel 15248: my (undef,$udom,$uname,$file)=split('/',$uri,4);
15249: if ($udom && $uname && $file) {
15250: $file=~s|(\?\.*)*$||;
1.949 raeburn 15251: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 15252: my $homeserver = &homeserver($uname,$udom);
1.1397 raeburn 15253: my $hostname = &hostname($homeserver);
1.980 raeburn 15254: my $protocol = $protocol{$homeserver};
15255: $protocol = 'http' if ($protocol ne 'https');
1.1397 raeburn 15256: return $protocol.'://'.$hostname.'/'.$uri.
1.517 albertel 15257: (($uri=~/\?/)?'&':'?').'token='.$token.
15258: '&tokenissued='.$perlvar{'lonHostID'};
15259: } else {
15260: return '/adm/notfound.html';
15261: }
15262: }
15263:
1.828 www 15264: # call with reqtype HEAD: get last modification time
15265: # call with reqtype GET: get the file contents
15266: # Do not call this with reqtype GET for large files! It loads everything into memory
15267: #
1.481 raeburn 15268: sub getuploaded {
15269: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
15270: $uri=~s/^\///;
1.980 raeburn 15271: my $homeserver = &homeserver($cnum,$cdom);
1.1397 raeburn 15272: my $hostname = &hostname($homeserver);
1.980 raeburn 15273: my $protocol = $protocol{$homeserver};
15274: $protocol = 'http' if ($protocol ne 'https');
1.1397 raeburn 15275: $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
1.481 raeburn 15276: my $request=new HTTP::Request($reqtype,$uri);
1.1345 raeburn 15277: my $response=&LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,'',0,1);
1.481 raeburn 15278: $$rtncode = $response->code;
1.482 albertel 15279: if (! $response->is_success()) {
15280: return 'failed';
15281: }
15282: if ($reqtype eq 'HEAD') {
1.486 www 15283: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 15284: } elsif ($reqtype eq 'GET') {
15285: $$info = $response->content;
1.472 albertel 15286: }
1.482 albertel 15287: return 'ok';
1.36 albertel 15288: }
15289:
1.481 raeburn 15290: sub readfile {
15291: my $file = shift;
15292: if ( (! -e $file ) || ($file eq '') ) { return -1; };
15293: my $fh;
1.1359 raeburn 15294: open($fh,"<",$file);
1.481 raeburn 15295: my $a='';
1.800 albertel 15296: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 15297: return $a;
15298: }
15299:
1.36 albertel 15300: sub filelocation {
1.590 banghart 15301: my ($dir,$file) = @_;
15302: my $location;
15303: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 15304:
15305: if ($file =~ m-^/adm/-) {
15306: $file=~s-^/adm/wrapper/-/-;
15307: $file=~s-^/adm/coursedocs/showdoc/-/-;
15308: }
1.882 albertel 15309:
1.1139 www 15310: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956 raeburn 15311: $location = $file;
1.609 banghart 15312: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 15313: my ($udom,$uname,$filename)=
1.811 albertel 15314: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 15315: my $home=&homeserver($uname,$udom);
15316: my $is_me=0;
15317: my @ids=¤t_machine_ids();
15318: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
15319: if ($is_me) {
1.1117 foxr 15320: $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 15321: } else {
15322: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
15323: $udom.'/'.$uname.'/'.$filename;
15324: }
1.882 albertel 15325: } elsif ($file =~ m-^/adm/-) {
15326: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 15327: } else {
15328: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139 www 15329: $file=~s:^/(res|priv)/:/:;
15330: my $space=$1;
1.590 banghart 15331: if ( !( $file =~ m:^/:) ) {
15332: $location = $dir. '/'.$file;
15333: } else {
1.1142 raeburn 15334: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590 banghart 15335: }
1.59 albertel 15336: }
1.590 banghart 15337: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 15338: while ($location=~m{/\.\./}) {
15339: if ($location =~ m{/[^/]+/\.\./}) {
15340: $location=~ s{/[^/]+/\.\./}{/}g;
15341: } else {
15342: $location=~ s{/\.\./}{/}g;
15343: }
15344: } #remove dir/..
1.590 banghart 15345: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
15346: return $location;
1.46 www 15347: }
1.36 albertel 15348:
1.46 www 15349: sub hreflocation {
15350: my ($dir,$file)=@_;
1.980 raeburn 15351: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 15352: $file=filelocation($dir,$file);
1.700 albertel 15353: } elsif ($file=~m-^/adm/-) {
15354: $file=~s-^/adm/wrapper/-/-;
15355: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 15356: }
15357: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
15358: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
15359: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143 raeburn 15360: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
15361: {/uploaded/$1/$2/}x;
1.46 www 15362: }
1.913 albertel 15363: if ($file=~ m{^/userfiles/}) {
15364: $file =~ s{^/userfiles/}{/uploaded/};
15365: }
1.462 albertel 15366: return $file;
1.465 albertel 15367: }
15368:
1.1139 www 15369:
15370:
15371:
15372:
1.465 albertel 15373: sub current_machine_domains {
1.853 albertel 15374: return &machine_domains(&hostname($perlvar{'lonHostID'}));
15375: }
15376:
15377: sub machine_domains {
15378: my ($hostname) = @_;
1.465 albertel 15379: my @domains;
1.838 albertel 15380: my %hostname = &all_hostnames();
1.465 albertel 15381: while( my($id, $name) = each(%hostname)) {
1.467 matthew 15382: # &logthis("-$id-$name-$hostname-");
1.465 albertel 15383: if ($hostname eq $name) {
1.844 albertel 15384: push(@domains,&host_domain($id));
1.465 albertel 15385: }
15386: }
15387: return @domains;
15388: }
15389:
15390: sub current_machine_ids {
1.853 albertel 15391: return &machine_ids(&hostname($perlvar{'lonHostID'}));
15392: }
15393:
15394: sub machine_ids {
15395: my ($hostname) = @_;
15396: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 15397: my @ids;
1.888 albertel 15398: my %name_to_host = &all_names();
1.889 albertel 15399: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
15400: return @{ $name_to_host{$hostname} };
15401: }
15402: return;
1.31 www 15403: }
15404:
1.824 raeburn 15405: sub additional_machine_domains {
15406: my @domains;
1.1466 raeburn 15407: if (-e "$perlvar{'lonTabDir'}/expected_domains.tab") {
15408: if (open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab")) {
15409: while (my $line = <$fh>) {
15410: chomp($line);
15411: $line =~ s/\s//g;
15412: push(@domains,$line);
15413: }
15414: close($fh);
15415: }
1.824 raeburn 15416: }
15417: return @domains;
15418: }
15419:
15420: sub default_login_domain {
15421: my $domain = $perlvar{'lonDefDomain'};
15422: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
15423: foreach my $posdom (¤t_machine_domains(),
15424: &additional_machine_domains()) {
15425: if (lc($posdom) eq lc($testdomain)) {
15426: $domain=$posdom;
15427: last;
15428: }
15429: }
15430: return $domain;
15431: }
15432:
1.1414 raeburn 15433: sub shared_institution {
1.1439 raeburn 15434: my ($dom,$lonhost) = @_;
15435: if ($lonhost eq '') {
15436: $lonhost = $perlvar{'lonHostID'};
15437: }
1.1414 raeburn 15438: my $same_intdom;
1.1439 raeburn 15439: my $hostintdom = &internet_dom($lonhost);
1.1414 raeburn 15440: if ($hostintdom ne '') {
15441: my %iphost = &get_iphost();
15442: my $primary_id = &domain($dom,'primary');
15443: my $primary_ip = &get_host_ip($primary_id);
15444: if (ref($iphost{$primary_ip}) eq 'ARRAY') {
15445: foreach my $id (@{$iphost{$primary_ip}}) {
15446: my $intdom = &internet_dom($id);
15447: if ($intdom eq $hostintdom) {
15448: $same_intdom = 1;
15449: last;
15450: }
15451: }
15452: }
15453: }
15454: return $same_intdom;
15455: }
15456:
1.1398 raeburn 15457: sub uses_sts {
15458: my ($ignore_cache) = @_;
15459: my $lonhost = $perlvar{'lonHostID'};
15460: my $hostname = &hostname($lonhost);
15461: my $sts_on;
15462: if ($protocol{$lonhost} eq 'https') {
15463: my $cachetime = 12*3600;
15464: if (!$ignore_cache) {
15465: ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
15466: if (defined($cached)) {
15467: return $sts_on;
15468: }
15469: }
15470: my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
15471: my $request=new HTTP::Request('HEAD',$url);
15472: my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,'','','',1);
15473: if ($response->is_success) {
15474: my $has_sts = $response->header('Strict-Transport-Security');
15475: if ($has_sts eq '') {
15476: $sts_on = 0;
15477: } else {
15478: if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
15479: my $maxage = $1;
15480: if ($maxage) {
15481: $sts_on = 1;
15482: } else {
15483: $sts_on = 0;
15484: }
15485: } else {
15486: $sts_on = 0;
15487: }
15488: }
15489: return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
15490: }
15491: }
15492: return;
15493: }
15494:
1.1449 raeburn 15495: sub waf_allssl {
15496: my ($host_name) = @_;
15497: my $alias = &get_proxy_alias();
15498: if ($host_name eq '') {
15499: $host_name = $ENV{'SERVER_NAME'};
15500: }
15501: if (($host_name ne '') && ($alias eq $host_name)) {
15502: my $serverhomedom = &host_domain($perlvar{'lonHostID'});
15503: my %defdomdefaults = &get_domain_defaults($serverhomedom);
15504: if ($defdomdefaults{'waf_sslopt'}) {
15505: return $defdomdefaults{'waf_sslopt'};
15506: }
15507: }
15508: return;
15509: }
15510:
1.1434 raeburn 15511: sub get_requestor_ip {
15512: my ($r,$nolookup,$noproxy) = @_;
15513: my $from_ip;
15514: if (ref($r)) {
1.1447 raeburn 15515: if ($r->can('useragent_ip')) {
15516: if ($noproxy && $r->can('client_ip')) {
15517: $from_ip = $r->client_ip();
15518: } else {
15519: $from_ip = $r->useragent_ip();
15520: }
15521: } elsif ($r->connection->can('remote_ip')) {
15522: $from_ip = $r->connection->remote_ip();
15523: } else {
15524: $from_ip = $r->get_remote_host($nolookup);
15525: }
1.1434 raeburn 15526: } else {
15527: $from_ip = $ENV{'REMOTE_ADDR'};
15528: }
15529: return $from_ip if ($noproxy);
15530: # Who controls proxy settings for server
15531: my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
15532: my $proxyinfo = &get_proxy_settings($dom_in_use);
15533: if ((ref($proxyinfo) eq 'HASH') && ($from_ip)) {
1.1437 raeburn 15534: if ($proxyinfo->{'vpnint'}) {
15535: if (&ip_match($from_ip,$proxyinfo->{'vpnint'})) {
1.1434 raeburn 15536: return $from_ip;
15537: }
15538: }
15539: if ($proxyinfo->{'trusted'}) {
15540: if (&ip_match($from_ip,$proxyinfo->{'trusted'})) {
15541: my $ipheader = $proxyinfo->{'ipheader'};
15542: my ($ip,$xfor);
15543: if (ref($r)) {
15544: if ($ipheader) {
15545: $ip = $r->headers_in->{$ipheader};
15546: }
15547: $xfor = $r->headers_in->{'X-Forwarded-For'};
15548: } else {
15549: if ($ipheader) {
15550: $ip = $ENV{'HTTP_'.uc($ipheader)};
15551: }
15552: $xfor = $ENV{'HTTP_X_FORWARDED_FOR'};
15553: }
15554: if (($ip eq '') && ($xfor ne '')) {
15555: foreach my $poss_ip (reverse(split(/\s*,\s*/,$xfor))) {
15556: unless (&ip_match($poss_ip,$proxyinfo->{'trusted'})) {
15557: $ip = $poss_ip;
1.1435 raeburn 15558: last;
1.1434 raeburn 15559: }
15560: }
15561: }
15562: if ($ip ne '') {
15563: return $ip;
15564: }
15565: }
15566: }
15567: }
15568: return $from_ip;
15569: }
15570:
15571: sub get_proxy_settings {
15572: my ($dom_in_use) = @_;
1.1494 raeburn 15573: my %domdefaults = &get_domain_defaults($dom_in_use);
1.1434 raeburn 15574: my $proxyinfo = {
15575: ipheader => $domdefaults{'waf_ipheader'},
15576: trusted => $domdefaults{'waf_trusted'},
1.1437 raeburn 15577: vpnint => $domdefaults{'waf_vpnint'},
1.1438 raeburn 15578: vpnext => $domdefaults{'waf_vpnext'},
1.1449 raeburn 15579: sslopt => $domdefaults{'waf_sslopt'},
1.1434 raeburn 15580: };
15581: return $proxyinfo;
15582: }
15583:
15584: sub ip_match {
15585: my ($ip,$pattern_str) = @_;
15586: $ip=Net::CIDR::cidrvalidate($ip);
15587: if ($ip) {
15588: return Net::CIDR::cidrlookup($ip,split(/\s*,\s*/,$pattern_str));
15589: }
15590: return;
15591: }
15592:
15593: sub get_proxy_alias {
1.1450 raeburn 15594: my ($lonid) = @_;
15595: if ($lonid eq '') {
15596: $lonid = $perlvar{'lonHostID'};
15597: }
15598: if (!defined(&hostname($lonid))) {
15599: return;
15600: }
15601: if ($lonid ne '') {
15602: my ($alias,$cached) = &is_cached_new('proxyalias',$lonid);
1.1434 raeburn 15603: if ($cached) {
15604: return $alias;
15605: }
1.1494 raeburn 15606: my $dom = &host_domain($lonid);
1.1434 raeburn 15607: if ($dom ne '') {
15608: my $cachetime = 60*60*24;
15609: my %domconfig =
1.1494 raeburn 15610: &get_dom('configuration',['wafproxy'],$dom);
1.1437 raeburn 15611: if (ref($domconfig{'wafproxy'}) eq 'HASH') {
15612: if (ref($domconfig{'wafproxy'}{'alias'}) eq 'HASH') {
1.1450 raeburn 15613: $alias = $domconfig{'wafproxy'}{'alias'}{$lonid};
15614: }
15615: }
15616: return &do_cache_new('proxyalias',$lonid,$alias,$cachetime);
15617: }
15618: }
15619: return;
15620: }
15621:
15622: sub use_proxy_alias {
15623: my ($r,$lonid) = @_;
15624: my $alias = &get_proxy_alias($lonid);
15625: if ($alias) {
15626: my $dom = &host_domain($lonid);
15627: if ($dom ne '') {
1.1467 raeburn 15628: my $proxyinfo = &get_proxy_settings($dom);
1.1450 raeburn 15629: my ($vpnint,$remote_ip);
15630: if (ref($proxyinfo) eq 'HASH') {
15631: $vpnint = $proxyinfo->{'vpnint'};
15632: if ($vpnint) {
15633: $remote_ip = &get_requestor_ip($r,1,1);
1.1434 raeburn 15634: }
15635: }
1.1450 raeburn 15636: unless ($vpnint && &ip_match($remote_ip,$vpnint)) {
15637: return $alias;
15638: }
1.1434 raeburn 15639: }
15640: }
15641: return;
15642: }
15643:
1.1474 raeburn 15644: sub alias_sso {
1.1467 raeburn 15645: my ($lonid) = @_;
15646: if ($lonid eq '') {
15647: $lonid = $perlvar{'lonHostID'};
15648: }
15649: if (!defined(&hostname($lonid))) {
15650: return;
15651: }
15652: if ($lonid ne '') {
15653: my ($use_alias,$cached) = &is_cached_new('proxysaml',$lonid);
15654: if ($cached) {
15655: return $use_alias;
15656: }
1.1494 raeburn 15657: my $dom = &host_domain($lonid);
1.1467 raeburn 15658: if ($dom ne '') {
15659: my $cachetime = 60*60*24;
15660: my %domconfig =
1.1494 raeburn 15661: &get_dom('configuration',['wafproxy'],$dom);
1.1467 raeburn 15662: if (ref($domconfig{'wafproxy'}) eq 'HASH') {
15663: if (ref($domconfig{'wafproxy'}{'saml'}) eq 'HASH') {
15664: $use_alias = $domconfig{'wafproxy'}{'saml'}{$lonid};
15665: }
15666: }
15667: return &do_cache_new('proxysaml',$lonid,$use_alias,$cachetime);
15668: }
15669: }
15670: return;
15671: }
15672:
1.1465 raeburn 15673: sub get_saml_landing {
15674: my ($lonid) = @_;
15675: if ($lonid eq '') {
15676: my $defdom = &default_login_domain();
15677: my @hosts = ¤t_machine_ids();
15678: if (@hosts > 1) {
15679: foreach my $hostid (@hosts) {
15680: if (&host_domain($hostid) eq $defdom) {
15681: $lonid = $hostid;
15682: last;
15683: }
15684: }
15685: } else {
15686: $lonid = $perlvar{'lonHostID'};
15687: }
15688: if ($lonid) {
1.1494 raeburn 15689: unless (&host_domain($lonid) eq $defdom) {
1.1465 raeburn 15690: return;
15691: }
15692: } else {
15693: return;
15694: }
15695: } elsif (!defined(&hostname($lonid))) {
15696: return;
15697: }
15698: my ($landing,$cached) = &is_cached_new('samllanding',$lonid);
15699: if ($cached) {
15700: return $landing;
15701: }
1.1494 raeburn 15702: my $dom = &host_domain($lonid);
1.1465 raeburn 15703: if ($dom ne '') {
15704: my $cachetime = 60*60*24;
15705: my %domconfig =
1.1494 raeburn 15706: &get_dom('configuration',['login'],$dom);
1.1465 raeburn 15707: if (ref($domconfig{'login'}) eq 'HASH') {
15708: if (ref($domconfig{'login'}{'saml'}) eq 'HASH') {
15709: if (ref($domconfig{'login'}{'saml'}{$lonid}) eq 'HASH') {
15710: $landing = 1;
15711: }
15712: }
15713: }
15714: return &do_cache_new('samllanding',$lonid,$landing,$cachetime);
15715: }
15716: return;
15717: }
15718:
1.31 www 15719: # ------------------------------------------------------------- Declutters URLs
15720:
15721: sub declutter {
15722: my $thisfn=shift;
1.569 albertel 15723: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1261 raeburn 15724: unless ($thisfn=~m{^/home/httpd/html/priv/}) {
15725: $thisfn=~s{^/home/httpd/html}{};
15726: }
1.31 www 15727: $thisfn=~s/^\///;
1.697 albertel 15728: $thisfn=~s|^adm/wrapper/||;
15729: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 15730: $thisfn=~s/^res\///;
1.1172 bisitz 15731: $thisfn=~s/^priv\///;
1.1032 raeburn 15732: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
15733: $thisfn=~s/\?.+$//;
15734: }
1.268 www 15735: return $thisfn;
15736: }
15737:
15738: # ------------------------------------------------------------- Clutter up URLs
15739:
15740: sub clutter {
15741: my $thisfn='/'.&declutter(shift);
1.887 albertel 15742: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 15743: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 15744: $thisfn='/res'.$thisfn;
15745: }
1.1031 raeburn 15746: if ($thisfn !~m|^/adm|) {
15747: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 15748: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 15749: } else {
15750: my ($ext) = ($thisfn =~ /\.(\w+)$/);
15751: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 15752: if ($embstyle eq 'ssi'
15753: || ($embstyle eq 'hdn')
15754: || ($embstyle eq 'rat')
15755: || ($embstyle eq 'prv')
15756: || ($embstyle eq 'ign')) {
15757: #do nothing with these
15758: } elsif (($embstyle eq 'img')
1.695 albertel 15759: || ($embstyle eq 'emb')
15760: || ($embstyle eq 'wrp')) {
15761: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 15762: } elsif ($embstyle eq 'unk'
15763: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 15764: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 15765: } else {
1.718 www 15766: # &logthis("Got a blank emb style");
1.695 albertel 15767: }
1.694 albertel 15768: }
1.1343 raeburn 15769: } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
1.1298 raeburn 15770: $thisfn='/adm/wrapper'.$thisfn;
1.694 albertel 15771: }
1.31 www 15772: return $thisfn;
1.12 www 15773: }
15774:
1.787 albertel 15775: sub clutter_with_no_wrapper {
15776: my $uri = &clutter(shift);
15777: if ($uri =~ m-^/adm/-) {
15778: $uri =~ s-^/adm/wrapper/-/-;
15779: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
15780: }
15781: return $uri;
15782: }
15783:
1.557 albertel 15784: sub freeze_escape {
15785: my ($value)=@_;
15786: if (ref($value)) {
15787: $value=&nfreeze($value);
15788: return '__FROZEN__'.&escape($value);
15789: }
15790: return &escape($value);
15791: }
15792:
1.11 www 15793:
1.557 albertel 15794: sub thaw_unescape {
15795: my ($value)=@_;
15796: if ($value =~ /^__FROZEN__/) {
15797: substr($value,0,10,undef);
15798: $value=&unescape($value);
15799: return &thaw($value);
15800: }
15801: return &unescape($value);
15802: }
15803:
1.436 albertel 15804: sub correct_line_ends {
15805: my ($result)=@_;
15806: $$result =~s/\r\n/\n/mg;
15807: $$result =~s/\r/\n/mg;
1.415 albertel 15808: }
1.1 albertel 15809: # ================================================================ Main Program
15810:
1.184 www 15811: sub goodbye {
1.204 albertel 15812: &logthis("Starting Shut down");
1.443 albertel 15813: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 15814: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 15815: #converted
1.599 albertel 15816: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 15817: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
15818: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
15819: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 15820: #1.1 only
1.870 albertel 15821: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
15822: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
15823: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
15824: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
15825: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 15826: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
15827: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 15828: &flushcourselogs();
15829: &logthis("Shutting down");
15830: }
15831:
1.852 albertel 15832: sub get_dns {
1.1210 raeburn 15833: my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869 albertel 15834: if (!$ignore_cache) {
15835: my ($content,$cached)=
1.1494 raeburn 15836: &is_cached_new('dns',$url);
1.869 albertel 15837: if ($cached) {
1.1210 raeburn 15838: &$func($content,$hashref);
1.869 albertel 15839: return;
15840: }
15841: }
15842:
15843: my %alldns;
1.1379 raeburn 15844: if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
15845: foreach my $dns (<$config>) {
15846: next if ($dns !~ /^\^(\S*)/x);
15847: my $line = $1;
15848: my ($host,$protocol) = split(/:/,$line);
15849: if ($protocol ne 'https') {
15850: $protocol = 'http';
15851: }
15852: $alldns{$host} = $protocol;
1.979 raeburn 15853: }
1.1379 raeburn 15854: close($config);
1.869 albertel 15855: }
15856: while (%alldns) {
1.1263 raeburn 15857: my ($dns) = sort { $b cmp $a } keys(%alldns);
1.1456 raeburn 15858: my ($contents,@content);
15859: if ($dns eq Sys::Hostname::FQDN::fqdn()) {
15860: my $command = (split('/',$url))[3];
15861: my ($dir,$file) = &parse_getdns_url($command,$url);
15862: delete($alldns{$dns});
15863: next if (($dir eq '') || ($file eq ''));
15864: if (open(my $config,'<',"$dir/$file")) {
1.1457 raeburn 15865: @content = <$config>;
1.1456 raeburn 15866: close($config);
15867: }
15868: if ($url eq '/adm/dns/loncapaCRL') {
15869: $contents = join('',@content);
15870: }
15871: } else {
15872: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
15873: my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar,30,0);
15874: delete($alldns{$dns});
15875: next if ($response->is_error());
15876: if ($url eq '/adm/dns/loncapaCRL') {
15877: $contents = $response->content;
15878: } else {
15879: @content = split("\n",$response->content);
15880: }
15881: }
1.1379 raeburn 15882: if ($url eq '/adm/dns/loncapaCRL') {
1.1456 raeburn 15883: return &$func($contents);
1.1379 raeburn 15884: } else {
15885: unless ($nocache) {
15886: &do_cache_new('dns',$url,\@content,30*24*60*60);
15887: }
15888: &$func(\@content,$hashref);
15889: return;
15890: }
15891: }
15892: my $which = (split('/',$url,4))[3];
15893: if ($which eq 'loncapaCRL') {
15894: my $diskfile = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
15895: if (-e $diskfile) {
15896: &logthis("unable to contact DNS, on disk file $diskfile not updated");
15897: } else {
15898: &logthis("unable to contact DNS, no on disk file $diskfile available");
15899: }
15900: } else {
15901: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
15902: if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
15903: my @content = <$config>;
15904: close($config);
15905: &$func(\@content,$hashref);
15906: }
1.852 albertel 15907: }
1.1210 raeburn 15908: return;
15909: }
15910:
15911: # ------------------------------------------------------Get DNS checksums file
1.1211 raeburn 15912: sub parse_dns_checksums_tab {
1.1210 raeburn 15913: my ($lines,$hashref) = @_;
1.1264 raeburn 15914: my $lonhost = $perlvar{'lonHostID'};
1.1494 raeburn 15915: my $machine_dom = &host_domain($lonhost);
1.1210 raeburn 15916: my $loncaparev = &get_server_loncaparev($machine_dom);
1.1264 raeburn 15917: my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
15918: my $webconfdir = '/etc/httpd/conf';
15919: if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
15920: $webconfdir = '/etc/apache2';
15921: } elsif ($distro =~ /^sles(\d+)$/) {
15922: if ($1 >= 10) {
15923: $webconfdir = '/etc/apache2';
15924: }
15925: } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
15926: if ($1 >= 10.0) {
15927: $webconfdir = '/etc/apache2';
15928: }
15929: }
1.1210 raeburn 15930: my ($release,$timestamp) = split(/\-/,$loncaparev);
15931: my (%chksum,%revnum);
15932: if (ref($lines) eq 'ARRAY') {
15933: chomp(@{$lines});
1.1238 raeburn 15934: my $version = shift(@{$lines});
15935: if ($version eq $release) {
1.1210 raeburn 15936: foreach my $line (@{$lines}) {
1.1238 raeburn 15937: my ($file,$version,$shasum) = split(/,/,$line);
1.1264 raeburn 15938: if ($file =~ m{^/etc/httpd/conf}) {
15939: if ($webconfdir eq '/etc/apache2') {
15940: $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
15941: }
15942: }
1.1238 raeburn 15943: $chksum{$file} = $shasum;
15944: $revnum{$file} = $version;
1.1210 raeburn 15945: }
15946: if (ref($hashref) eq 'HASH') {
15947: %{$hashref} = (
15948: sums => \%chksum,
15949: versions => \%revnum,
15950: );
15951: }
15952: }
15953: }
1.869 albertel 15954: return;
1.852 albertel 15955: }
1.1210 raeburn 15956:
15957: sub fetch_dns_checksums {
1.1238 raeburn 15958: my %checksums;
1.1494 raeburn 15959: my $machine_dom = &host_domain($perlvar{'lonHostID'});
1.1260 raeburn 15960: my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1238 raeburn 15961: my ($release,$timestamp) = split(/\-/,$loncaparev);
15962: &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1211 raeburn 15963: \%checksums);
1.1210 raeburn 15964: return \%checksums;
15965: }
15966:
1.1379 raeburn 15967: sub fetch_crl_pemfile {
15968: return &get_dns("/adm/dns/loncapaCRL",\&save_crl_pem,1,1);
15969: }
15970:
15971: sub save_crl_pem {
1.1456 raeburn 15972: my ($content) = @_;
1.1380 raeburn 15973: my ($msg,$hadchanges);
1.1456 raeburn 15974: if ($content ne '') {
1.1379 raeburn 15975: my $now = time;
15976: my $lonca = $perlvar{'lonCertificateDirectory'}.'/'.$perlvar{'lonnetCertificateAuthority'};
15977: my $tmpcrl = $tmpdir.'/'.$perlvar{'lonnetCertRevocationList'}.'_'.$now.'.'.$$.'.tmp';
15978: if (open(my $fh,'>',"$tmpcrl")) {
1.1456 raeburn 15979: print $fh $content;
1.1379 raeburn 15980: close($fh);
15981: if (-e $lonca) {
15982: if (open(PIPE,"openssl crl -in $tmpcrl -inform pem -CAfile $lonca -noout 2>&1 |")) {
15983: my $check = <PIPE>;
15984: close(PIPE);
15985: chomp($check);
15986: if ($check eq 'verify OK') {
15987: my $dest = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
1.1380 raeburn 15988: my $backup;
1.1379 raeburn 15989: if (-e $dest) {
1.1380 raeburn 15990: if (&File::Copy::move($dest,"$dest.bak")) {
15991: $backup = 'ok';
15992: }
1.1379 raeburn 15993: }
15994: if (&File::Copy::move($tmpcrl,$dest)) {
15995: $msg = 'ok';
1.1380 raeburn 15996: if ($backup) {
15997: my (%oldnums,%newnums);
15998: if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest.bak |grep 'Serial Number' |")) {
15999: while (<PIPE>) {
16000: $oldnums{(split(/:/))[1]} = 1;
16001: }
16002: close(PIPE);
16003: }
16004: if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest |grep 'Serial Number' |")) {
16005: while(<PIPE>) {
16006: $newnums{(split(/:/))[1]} = 1;
16007: }
16008: close(PIPE);
16009: }
16010: foreach my $key (sort {$b <=> $a } (keys(%newnums))) {
16011: unless (exists($oldnums{$key})) {
16012: $hadchanges = 1;
16013: last;
16014: }
16015: }
16016: unless ($hadchanges) {
16017: foreach my $key (sort {$b <=> $a } (keys(%oldnums))) {
16018: unless (exists($newnums{$key})) {
16019: $hadchanges = 1;
16020: last;
16021: }
16022: }
16023: }
16024: }
1.1379 raeburn 16025: }
16026: } else {
16027: unlink($tmpcrl);
16028: }
16029: } else {
16030: unlink($tmpcrl);
16031: }
16032: } else {
16033: unlink($tmpcrl);
16034: }
16035: }
16036: }
1.1380 raeburn 16037: return ($msg,$hadchanges);
1.1379 raeburn 16038: }
16039:
1.1456 raeburn 16040: sub parse_getdns_url {
16041: my ($command,$url) = @_;
16042: my $dir = $perlvar{'lonTabDir'};
16043: my $file;
16044: if ($command eq 'hosts') {
16045: $file = 'dns_hosts.tab';
16046: } elsif ($command eq 'domain') {
16047: $file = 'dns_domain.tab';
16048: } elsif ($command eq 'checksums') {
16049: my $version = (split('/',$url))[4];
16050: $file = "dns_checksums/$version.tab",
16051: } elsif ($command eq 'loncapaCRL') {
16052: $dir = $perlvar{'lonCertificateDirectory'};
16053: $file = $perlvar{'lonnetCertRevocationList'};
16054: }
16055: return ($dir,$file);
16056: }
16057:
1.327 albertel 16058: # ------------------------------------------------------------ Read domain file
16059: {
1.852 albertel 16060: my $loaded;
1.846 albertel 16061: my %domain;
16062:
1.852 albertel 16063: sub parse_domain_tab {
16064: my ($lines) = @_;
16065: foreach my $line (@$lines) {
16066: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 16067:
1.846 albertel 16068: chomp($line);
1.852 albertel 16069: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 16070: my %this_domain;
16071: foreach my $field ('description', 'auth_def', 'auth_arg_def',
16072: 'lang_def', 'city', 'longi', 'lati',
16073: 'primary') {
16074: $this_domain{$field} = shift(@elements);
16075: }
16076: $domain{$name} = \%this_domain;
1.852 albertel 16077: }
16078: }
1.864 albertel 16079:
16080: sub reset_domain_info {
16081: undef($loaded);
16082: undef(%domain);
16083: }
16084:
1.852 albertel 16085: sub load_domain_tab {
1.1293 raeburn 16086: my ($ignore_cache,$nocache) = @_;
16087: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852 albertel 16088: my $fh;
1.1359 raeburn 16089: if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852 albertel 16090: my @lines = <$fh>;
16091: &parse_domain_tab(\@lines);
1.448 albertel 16092: }
1.852 albertel 16093: close($fh);
16094: $loaded = 1;
1.327 albertel 16095: }
1.846 albertel 16096:
16097: sub domain {
1.852 albertel 16098: &load_domain_tab() if (!$loaded);
16099:
1.846 albertel 16100: my ($name,$what) = @_;
16101: return if ( !exists($domain{$name}) );
16102:
16103: if (!$what) {
16104: return $domain{$name}{'description'};
16105: }
16106: return $domain{$name}{$what};
16107: }
1.974 raeburn 16108:
16109: sub domain_info {
16110: &load_domain_tab() if (!$loaded);
16111: return %domain;
16112: }
16113:
1.327 albertel 16114: }
16115:
16116:
1.1 albertel 16117: # ------------------------------------------------------------- Read hosts file
16118: {
1.838 albertel 16119: my %hostname;
1.844 albertel 16120: my %hostdom;
1.845 albertel 16121: my %libserv;
1.852 albertel 16122: my $loaded;
1.888 albertel 16123: my %name_to_host;
1.1074 raeburn 16124: my %internetdom;
1.1107 raeburn 16125: my %LC_dns_serv;
1.852 albertel 16126:
16127: sub parse_hosts_tab {
16128: my ($file) = @_;
16129: foreach my $configline (@$file) {
16130: next if ($configline =~ /^(\#|\s*$ )/x);
1.1107 raeburn 16131: chomp($configline);
16132: if ($configline =~ /^\^/) {
16133: if ($configline =~ /^\^([\w.\-]+)/) {
16134: $LC_dns_serv{$1} = 1;
16135: }
16136: next;
16137: }
1.1074 raeburn 16138: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 16139: $name=~s/\s//g;
16140: if ($id && $domain && $role && $name) {
1.1351 raeburn 16141: if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
16142: my $curr = $hostname{$id};
16143: my $skip;
16144: if (ref($name_to_host{$curr}) eq 'ARRAY') {
16145: if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
16146: $skip = 1;
16147: } else {
16148: @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
16149: }
16150: }
16151: unless ($skip) {
16152: push(@{$name_to_host{$name}},$id);
16153: }
16154: } else {
16155: push(@{$name_to_host{$name}},$id);
16156: }
1.852 albertel 16157: $hostname{$id}=$name;
16158: $hostdom{$id}=$domain;
16159: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 16160: if (defined($protocol)) {
16161: if ($protocol eq 'https') {
16162: $protocol{$id} = $protocol;
16163: } else {
16164: $protocol{$id} = 'http';
16165: }
1.968 raeburn 16166: } else {
1.969 raeburn 16167: $protocol{$id} = 'http';
1.968 raeburn 16168: }
1.1074 raeburn 16169: if (defined($intdom)) {
16170: $internetdom{$id} = $intdom;
16171: }
1.852 albertel 16172: }
16173: }
16174: }
1.864 albertel 16175:
16176: sub reset_hosts_info {
1.897 albertel 16177: &purge_remembered();
1.864 albertel 16178: &reset_domain_info();
16179: &reset_hosts_ip_info();
1.1339 raeburn 16180: undef(%internetdom);
1.892 albertel 16181: undef(%name_to_host);
1.864 albertel 16182: undef(%hostname);
16183: undef(%hostdom);
16184: undef(%libserv);
16185: undef($loaded);
16186: }
1.1 albertel 16187:
1.852 albertel 16188: sub load_hosts_tab {
1.1293 raeburn 16189: my ($ignore_cache,$nocache) = @_;
16190: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1359 raeburn 16191: open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852 albertel 16192: my @config = <$config>;
16193: &parse_hosts_tab(\@config);
16194: close($config);
16195: $loaded=1;
1.1 albertel 16196: }
1.852 albertel 16197:
1.838 albertel 16198: sub hostname {
1.852 albertel 16199: &load_hosts_tab() if (!$loaded);
16200:
1.838 albertel 16201: my ($lonid) = @_;
16202: return $hostname{$lonid};
16203: }
1.845 albertel 16204:
1.838 albertel 16205: sub all_hostnames {
1.852 albertel 16206: &load_hosts_tab() if (!$loaded);
16207:
1.838 albertel 16208: return %hostname;
16209: }
1.845 albertel 16210:
1.888 albertel 16211: sub all_names {
1.1293 raeburn 16212: my ($ignore_cache,$nocache) = @_;
16213: &load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888 albertel 16214:
16215: return %name_to_host;
16216: }
16217:
1.974 raeburn 16218: sub all_host_domain {
16219: &load_hosts_tab() if (!$loaded);
16220: return %hostdom;
16221: }
16222:
1.1339 raeburn 16223: sub all_host_intdom {
16224: &load_hosts_tab() if (!$loaded);
16225: return %internetdom;
16226: }
16227:
1.845 albertel 16228: sub is_library {
1.852 albertel 16229: &load_hosts_tab() if (!$loaded);
16230:
1.845 albertel 16231: return exists($libserv{$_[0]});
16232: }
16233:
16234: sub all_library {
1.852 albertel 16235: &load_hosts_tab() if (!$loaded);
16236:
1.845 albertel 16237: return %libserv;
16238: }
16239:
1.1062 droeschl 16240: sub unique_library {
16241: #2x reverse removes all hostnames that appear more than once
16242: my %unique = reverse &all_library();
16243: return reverse %unique;
16244: }
16245:
1.841 albertel 16246: sub get_servers {
1.852 albertel 16247: &load_hosts_tab() if (!$loaded);
16248:
1.841 albertel 16249: my ($domain,$type) = @_;
16250: my %possible_hosts = ($type eq 'library') ? %libserv
16251: : %hostname;
16252: my %result;
1.842 albertel 16253: if (ref($domain) eq 'ARRAY') {
16254: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 16255: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 16256: $result{$host} = $hostname;
16257: }
16258: }
16259: } else {
16260: while ( my ($host,$hostname) = each(%possible_hosts)) {
16261: if ($hostdom{$host} eq $domain) {
16262: $result{$host} = $hostname;
16263: }
1.841 albertel 16264: }
16265: }
16266: return %result;
16267: }
1.845 albertel 16268:
1.1062 droeschl 16269: sub get_unique_servers {
16270: my %unique = reverse &get_servers(@_);
16271: return reverse %unique;
16272: }
16273:
1.844 albertel 16274: sub host_domain {
1.852 albertel 16275: &load_hosts_tab() if (!$loaded);
16276:
1.844 albertel 16277: my ($lonid) = @_;
16278: return $hostdom{$lonid};
16279: }
16280:
1.841 albertel 16281: sub all_domains {
1.852 albertel 16282: &load_hosts_tab() if (!$loaded);
16283:
1.841 albertel 16284: my %seen;
16285: my @uniq = grep(!$seen{$_}++, values(%hostdom));
16286: return @uniq;
16287: }
1.1074 raeburn 16288:
16289: sub internet_dom {
16290: &load_hosts_tab() if (!$loaded);
16291:
16292: my ($lonid) = @_;
16293: return $internetdom{$lonid};
16294: }
1.1107 raeburn 16295:
16296: sub is_LC_dns {
16297: &load_hosts_tab() if (!$loaded);
16298:
16299: my ($hostname) = @_;
16300: return exists($LC_dns_serv{$hostname});
16301: }
16302:
1.1 albertel 16303: }
16304:
1.847 albertel 16305: {
16306: my %iphost;
1.856 albertel 16307: my %name_to_ip;
16308: my %lonid_to_ip;
1.869 albertel 16309:
1.847 albertel 16310: sub get_hosts_from_ip {
16311: my ($ip) = @_;
16312: my %iphosts = &get_iphost();
16313: if (ref($iphosts{$ip})) {
16314: return @{$iphosts{$ip}};
16315: }
16316: return;
1.839 albertel 16317: }
1.864 albertel 16318:
16319: sub reset_hosts_ip_info {
16320: undef(%iphost);
16321: undef(%name_to_ip);
16322: undef(%lonid_to_ip);
16323: }
1.856 albertel 16324:
16325: sub get_host_ip {
16326: my ($lonid) = @_;
16327: if (exists($lonid_to_ip{$lonid})) {
16328: return $lonid_to_ip{$lonid};
16329: }
16330: my $name=&hostname($lonid);
16331: my $ip = gethostbyname($name);
16332: return if (!$ip || length($ip) ne 4);
16333: $ip=inet_ntoa($ip);
16334: $name_to_ip{$name} = $ip;
16335: $lonid_to_ip{$lonid} = $ip;
16336: return $ip;
16337: }
1.847 albertel 16338:
16339: sub get_iphost {
1.1293 raeburn 16340: my ($ignore_cache,$nocache) = @_;
1.894 albertel 16341:
1.869 albertel 16342: if (!$ignore_cache) {
16343: if (%iphost) {
16344: return %iphost;
16345: }
16346: my ($ip_info,$cached)=
1.1494 raeburn 16347: &is_cached_new('iphost','iphost');
1.869 albertel 16348: if ($cached) {
16349: %iphost = %{$ip_info->[0]};
16350: %name_to_ip = %{$ip_info->[1]};
16351: %lonid_to_ip = %{$ip_info->[2]};
16352: return %iphost;
16353: }
16354: }
1.894 albertel 16355:
16356: # get yesterday's info for fallback
16357: my %old_name_to_ip;
16358: my ($ip_info,$cached)=
1.1495 raeburn 16359: &is_cached_new('iphost','iphost');
1.894 albertel 16360: if ($cached) {
16361: %old_name_to_ip = %{$ip_info->[1]};
16362: }
16363:
1.1293 raeburn 16364: my %name_to_host = &all_names($ignore_cache,$nocache);
1.888 albertel 16365: foreach my $name (keys(%name_to_host)) {
1.847 albertel 16366: my $ip;
16367: if (!exists($name_to_ip{$name})) {
16368: $ip = gethostbyname($name);
16369: if (!$ip || length($ip) ne 4) {
1.894 albertel 16370: if (defined($old_name_to_ip{$name})) {
16371: $ip = $old_name_to_ip{$name};
16372: &logthis("Can't find $name defaulting to old $ip");
16373: } else {
16374: &logthis("Name $name no IP found");
16375: next;
16376: }
16377: } else {
16378: $ip=inet_ntoa($ip);
1.847 albertel 16379: }
16380: $name_to_ip{$name} = $ip;
16381: } else {
16382: $ip = $name_to_ip{$name};
1.653 albertel 16383: }
1.888 albertel 16384: foreach my $id (@{ $name_to_host{$name} }) {
16385: $lonid_to_ip{$id} = $ip;
16386: }
16387: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 16388: }
1.1293 raeburn 16389: unless ($nocache) {
16390: &do_cache_new('iphost','iphost',
16391: [\%iphost,\%name_to_ip,\%lonid_to_ip],
16392: 48*60*60);
16393: }
1.869 albertel 16394:
1.847 albertel 16395: return %iphost;
1.598 albertel 16396: }
16397:
1.992 raeburn 16398: #
16399: # Given a DNS returns the loncapa host name for that DNS
16400: #
16401: sub host_from_dns {
16402: my ($dns) = @_;
16403: my @hosts;
16404: my $ip;
16405:
1.993 raeburn 16406: if (exists($name_to_ip{$dns})) {
1.992 raeburn 16407: $ip = $name_to_ip{$dns};
16408: }
16409: if (!$ip) {
16410: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
16411: if (length($ip) == 4) {
16412: $ip = &IO::Socket::inet_ntoa($ip);
16413: }
16414: }
16415: if ($ip) {
16416: @hosts = get_hosts_from_ip($ip);
16417: return $hosts[0];
16418: }
16419: return undef;
1.986 foxr 16420: }
1.992 raeburn 16421:
1.1074 raeburn 16422: sub get_internet_names {
16423: my ($lonid) = @_;
16424: return if ($lonid eq '');
16425: my ($idnref,$cached)=
1.1494 raeburn 16426: &is_cached_new('internetnames',$lonid);
1.1074 raeburn 16427: if ($cached) {
16428: return $idnref;
16429: }
16430: my $ip = &get_host_ip($lonid);
16431: my @hosts = &get_hosts_from_ip($ip);
16432: my %iphost = &get_iphost();
16433: my (@idns,%seen);
16434: foreach my $id (@hosts) {
16435: my $dom = &host_domain($id);
16436: my $prim_id = &domain($dom,'primary');
16437: my $prim_ip = &get_host_ip($prim_id);
16438: next if ($seen{$prim_ip});
16439: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
16440: foreach my $id (@{$iphost{$prim_ip}}) {
16441: my $intdom = &internet_dom($id);
16442: unless (grep(/^\Q$intdom\E$/,@idns)) {
16443: push(@idns,$intdom);
16444: }
16445: }
16446: }
16447: $seen{$prim_ip} = 1;
16448: }
1.1219 raeburn 16449: return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074 raeburn 16450: }
16451:
1.986 foxr 16452: }
16453:
1.1079 raeburn 16454: sub all_loncaparevs {
1.1249 raeburn 16455: 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 16456: }
16457:
1.1227 raeburn 16458: # ---------------------------------------------------------- Read loncaparev table
16459: {
16460: sub load_loncaparevs {
16461: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1359 raeburn 16462: if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1227 raeburn 16463: while (my $configline=<$config>) {
16464: chomp($configline);
16465: my ($hostid,$loncaparev)=split(/:/,$configline);
16466: $loncaparevs{$hostid}=$loncaparev;
16467: }
16468: close($config);
16469: }
16470: }
16471: }
16472: }
16473:
16474: # ---------------------------------------------------------- Read serverhostID table
16475: {
16476: sub load_serverhomeIDs {
16477: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1359 raeburn 16478: if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1227 raeburn 16479: while (my $configline=<$config>) {
16480: chomp($configline);
16481: my ($name,$id)=split(/:/,$configline);
16482: $serverhomeIDs{$name}=$id;
16483: }
16484: close($config);
16485: }
16486: }
16487: }
16488: }
16489:
16490:
1.862 albertel 16491: BEGIN {
16492:
16493: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
16494: unless ($readit) {
16495: {
16496: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
16497: %perlvar = (%perlvar,%{$configvars});
16498: }
16499:
16500:
1.1 albertel 16501: # ------------------------------------------------------ Read spare server file
16502: {
1.1359 raeburn 16503: open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 16504:
16505: while (my $configline=<$config>) {
16506: chomp($configline);
1.284 matthew 16507: if ($configline) {
1.784 albertel 16508: my ($host,$type) = split(':',$configline,2);
1.785 albertel 16509: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 16510: push(@{ $spareid{$type} }, $host);
1.1 albertel 16511: }
16512: }
1.448 albertel 16513: close($config);
1.1 albertel 16514: }
1.11 www 16515: # ------------------------------------------------------------ Read permissions
16516: {
1.1359 raeburn 16517: open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11 www 16518:
16519: while (my $configline=<$config>) {
1.448 albertel 16520: chomp($configline);
16521: if ($configline) {
16522: my ($role,$perm)=split(/ /,$configline);
16523: if ($perm ne '') { $pr{$role}=$perm; }
16524: }
1.11 www 16525: }
1.448 albertel 16526: close($config);
1.11 www 16527: }
16528:
16529: # -------------------------------------------- Read plain texts for permissions
16530: {
1.1359 raeburn 16531: open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 16532:
16533: while (my $configline=<$config>) {
1.448 albertel 16534: chomp($configline);
16535: if ($configline) {
1.742 raeburn 16536: my ($short,@plain)=split(/:/,$configline);
16537: %{$prp{$short}} = ();
16538: if (@plain > 0) {
16539: $prp{$short}{'std'} = $plain[0];
16540: for (my $i=1; $i<@plain; $i++) {
16541: $prp{$short}{'alt'.$i} = $plain[$i];
16542: }
16543: }
1.448 albertel 16544: }
1.135 www 16545: }
1.448 albertel 16546: close($config);
1.135 www 16547: }
16548:
16549: # ---------------------------------------------------------- Read package table
16550: {
1.1359 raeburn 16551: open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135 www 16552:
16553: while (my $configline=<$config>) {
1.483 albertel 16554: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 16555: chomp($configline);
16556: my ($short,$plain)=split(/:/,$configline);
16557: my ($pack,$name)=split(/\&/,$short);
16558: if ($plain ne '') {
16559: $packagetab{$pack.'&'.$name.'&name'}=$name;
16560: $packagetab{$short}=$plain;
16561: }
1.11 www 16562: }
1.448 albertel 16563: close($config);
1.329 matthew 16564: }
16565:
1.1073 raeburn 16566: # ---------------------------------------------------------- Read loncaparev table
1.1227 raeburn 16567:
16568: &load_loncaparevs();
1.1073 raeburn 16569:
1.1074 raeburn 16570: # ---------------------------------------------------------- Read serverhostID table
16571:
1.1227 raeburn 16572: &load_serverhomeIDs();
16573:
16574: # ---------------------------------------------------------- Read releaseslist XML
1.1079 raeburn 16575: {
16576: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
16577: if (-e $file) {
16578: my $parser = HTML::LCParser->new($file);
16579: while (my $token = $parser->get_token()) {
16580: if ($token->[0] eq 'S') {
16581: my $item = $token->[1];
16582: my $name = $token->[2]{'name'};
16583: my $value = $token->[2]{'value'};
1.1285 raeburn 16584: my $valuematch = $token->[2]{'valuematch'};
1.1303 raeburn 16585: my $namematch = $token->[2]{'namematch'};
16586: if ($item eq 'parameter') {
16587: if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
16588: my $release = $parser->get_text();
16589: $release =~ s/(^\s*|\s*$ )//gx;
16590: $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
16591: }
16592: } elsif ($item ne '' && $name ne '') {
1.1079 raeburn 16593: my $release = $parser->get_text();
16594: $release =~ s/(^\s*|\s*$ )//gx;
1.1303 raeburn 16595: $needsrelease{$item.':'.$name.':'.$value} = $release;
1.1079 raeburn 16596: }
16597: }
16598: }
16599: }
1.1073 raeburn 16600: }
16601:
1.1138 raeburn 16602: # ---------------------------------------------------------- Read managers table
16603: {
16604: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1359 raeburn 16605: if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138 raeburn 16606: while (my $configline=<$config>) {
16607: chomp($configline);
16608: next if ($configline =~ /^\#/);
16609: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
16610: $managerstab{$configline} = 1;
16611: }
16612: }
16613: close($config);
16614: }
16615: }
16616: }
16617:
1.329 matthew 16618: # ------------- set up temporary directory
16619: {
1.1117 foxr 16620: $tmpdir = LONCAPA::tempdir();
1.329 matthew 16621:
1.11 www 16622: }
16623:
1.1405 raeburn 16624: # ------------- set default texengine (domain default overrides this)
16625: {
16626: $deftex = LONCAPA::texengine();
16627: }
16628:
1.1416 raeburn 16629: # ------------- set default minimum length for passwords for internal auth users
16630: {
16631: $passwdmin = LONCAPA::passwd_min();
16632: }
16633:
1.794 albertel 16634: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
16635: 'compress_threshold'=> 20_000,
16636: });
1.185 www 16637:
1.281 www 16638: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 16639: $dumpcount=0;
1.958 www 16640: $locknum=0;
1.22 www 16641:
1.163 harris41 16642: &logtouch();
1.672 albertel 16643: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 16644: $readit=1;
1.564 albertel 16645: {
16646: use integer;
16647: my $test=(2**32)+1;
1.568 albertel 16648: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 16649: &logthis(" Detected 64bit platform ($_64bit)");
16650: }
1.195 www 16651: }
1.1 albertel 16652: }
1.179 www 16653:
1.1 albertel 16654: 1;
1.191 harris41 16655: __END__
16656:
1.243 albertel 16657: =pod
16658:
1.191 harris41 16659: =head1 NAME
16660:
1.243 albertel 16661: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 16662:
16663: =head1 SYNOPSIS
16664:
1.243 albertel 16665: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 16666:
16667: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
16668:
1.243 albertel 16669: Common parameters:
16670:
16671: =over 4
16672:
16673: =item *
16674:
16675: $uname : an internal username (if $cname expecting a course Id specifically)
16676:
16677: =item *
16678:
16679: $udom : a domain (if $cdom expecting a course's domain specifically)
16680:
16681: =item *
16682:
16683: $symb : a resource instance identifier
16684:
16685: =item *
16686:
16687: $namespace : the name of a .db file that contains the data needed or
16688: being set.
16689:
16690: =back
16691:
1.394 bowersj2 16692: =head1 OVERVIEW
1.191 harris41 16693:
1.394 bowersj2 16694: lonnet provides subroutines which interact with the
16695: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
16696: about classes, users, and resources.
1.243 albertel 16697:
16698: For many of these objects you can also use this to store data about
16699: them or modify them in various ways.
1.191 harris41 16700:
1.394 bowersj2 16701: =head2 Symbs
1.191 harris41 16702:
1.394 bowersj2 16703: To identify a specific instance of a resource, LON-CAPA uses symbols
16704: or "symbs"X<symb>. These identifiers are built from the URL of the
16705: map, the resource number of the resource in the map, and the URL of
16706: the resource itself. The latter is somewhat redundant, but might help
16707: if maps change.
16708:
16709: An example is
16710:
16711: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
16712:
16713: The respective map entry is
16714:
16715: <resource id="19" src="/res/msu/korte/tests/part12.problem"
16716: title="Problem 2">
16717: </resource>
16718:
16719: Symbs are used by the random number generator, as well as to store and
16720: restore data specific to a certain instance of for example a problem.
16721:
16722: =head2 Storing And Retrieving Data
16723:
16724: X<store()>X<cstore()>X<restore()>Three of the most important functions
16725: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
16726: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
16727: is is the non-critical message twin of cstore. These functions are for
16728: handlers to store a perl hash to a user's permanent data space in an
16729: easy manner, and to retrieve it again on another call. It is expected
16730: that a handler would use this once at the beginning to retrieve data,
16731: and then again once at the end to send only the new data back.
16732:
16733: The data is stored in the user's data directory on the user's
16734: homeserver under the ID of the course.
16735:
16736: The hash that is returned by restore will have all of the previous
16737: value for all of the elements of the hash.
16738:
16739: Example:
16740:
16741: #creating a hash
16742: my %hash;
16743: $hash{'foo'}='bar';
16744:
16745: #storing it
16746: &Apache::lonnet::cstore(\%hash);
16747:
16748: #changing a value
16749: $hash{'foo'}='notbar';
16750:
16751: #adding a new value
16752: $hash{'bar'}='foo';
16753: &Apache::lonnet::cstore(\%hash);
16754:
16755: #retrieving the hash
16756: my %history=&Apache::lonnet::restore();
16757:
16758: #print the hash
16759: foreach my $key (sort(keys(%history))) {
16760: print("\%history{$key} = $history{$key}");
16761: }
16762:
16763: Will print out:
1.191 harris41 16764:
1.394 bowersj2 16765: %history{1:foo} = bar
16766: %history{1:keys} = foo:timestamp
16767: %history{1:timestamp} = 990455579
16768: %history{2:bar} = foo
16769: %history{2:foo} = notbar
16770: %history{2:keys} = foo:bar:timestamp
16771: %history{2:timestamp} = 990455580
16772: %history{bar} = foo
16773: %history{foo} = notbar
16774: %history{timestamp} = 990455580
16775: %history{version} = 2
16776:
16777: Note that the special hash entries C<keys>, C<version> and
16778: C<timestamp> were added to the hash. C<version> will be equal to the
16779: total number of versions of the data that have been stored. The
16780: C<timestamp> attribute will be the UNIX time the hash was
16781: stored. C<keys> is available in every historical section to list which
16782: keys were added or changed at a specific historical revision of a
16783: hash.
16784:
16785: B<Warning>: do not store the hash that restore returns directly. This
16786: will cause a mess since it will restore the historical keys as if the
16787: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 16788:
1.394 bowersj2 16789: Calling convention:
1.191 harris41 16790:
1.1225 raeburn 16791: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1269 raeburn 16792: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191 harris41 16793:
1.394 bowersj2 16794: For more detailed information, see lonnet specific documentation.
1.191 harris41 16795:
1.394 bowersj2 16796: =head1 RETURN MESSAGES
1.191 harris41 16797:
1.394 bowersj2 16798: =over 4
1.191 harris41 16799:
1.394 bowersj2 16800: =item * B<con_lost>: unable to contact remote host
1.191 harris41 16801:
1.394 bowersj2 16802: =item * B<con_delayed>: unable to contact remote host, message will be delivered
16803: when the connection is brought back up
1.191 harris41 16804:
1.394 bowersj2 16805: =item * B<con_failed>: unable to contact remote host and unable to save message
16806: for later delivery
1.191 harris41 16807:
1.967 bisitz 16808: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 16809:
1.394 bowersj2 16810: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 16811: that was requested
1.191 harris41 16812:
1.243 albertel 16813: =back
1.191 harris41 16814:
1.243 albertel 16815: =head1 PUBLIC SUBROUTINES
1.191 harris41 16816:
1.243 albertel 16817: =head2 Session Environment Functions
1.191 harris41 16818:
1.243 albertel 16819: =over 4
1.191 harris41 16820:
1.394 bowersj2 16821: =item *
16822: X<appenv()>
1.949 raeburn 16823: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 16824: the user envirnoment file, and will be restored for each access this
1.620 albertel 16825: user makes during this session, also modifies the %env for the current
1.949 raeburn 16826: process. Optional rolesarrayref - if defined contains a reference to an array
16827: of roles which are exempt from the restriction on modifying user.role entries
16828: in the user's environment.db and in %env.
1.191 harris41 16829:
16830: =item *
1.394 bowersj2 16831: X<delenv()>
1.987 raeburn 16832: B<delenv($delthis,$regexp)>: removes all items from the session
16833: environment file that begin with $delthis. If the
16834: optional second arg - $regexp - is true, $delthis is treated as a
16835: regular expression, otherwise \Q$delthis\E is used.
16836: The values are also deleted from the current processes %env.
1.191 harris41 16837:
1.795 albertel 16838: =item * get_env_multiple($name)
16839:
16840: gets $name from the %env hash, it seemlessly handles the cases where multiple
16841: values may be defined and end up as an array ref.
16842:
16843: returns an array of values
16844:
1.243 albertel 16845: =back
16846:
16847: =head2 User Information
1.191 harris41 16848:
1.243 albertel 16849: =over 4
1.191 harris41 16850:
16851: =item *
1.394 bowersj2 16852: X<queryauthenticate()>
16853: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 16854: authentication scheme
16855:
16856: =item *
1.394 bowersj2 16857: X<authenticate()>
1.1073 raeburn 16858: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 16859: authenticate user from domain's lib servers (first use the current
16860: one). C<$upass> should be the users password.
1.1073 raeburn 16861: $checkdefauth is optional (value is 1 if a check should be made to
16862: authenticate user using default authentication method, and allow
16863: account creation if username does not have account in the domain).
16864: $clientcancheckhost is optional (value is 1 if checking whether the
16865: server can host will occur on the client side in lonauth.pm).
1.191 harris41 16866:
16867: =item *
1.394 bowersj2 16868: X<homeserver()>
16869: B<homeserver($uname,$udom)>: find the server which has
16870: the user's directory and files (there must be only one), this caches
16871: the answer, and also caches if there is a borken connection.
1.191 harris41 16872:
16873: =item *
1.394 bowersj2 16874: X<idget()>
1.1300 raeburn 16875: B<idget($udom,$idsref,$namespace)>: find the usernames behind either
16876: a list of student/employee IDs or clicker IDs
16877: (student/employee IDs are a unique resource in a domain, there must be
16878: only 1 ID per username, and only 1 username per ID in a specific domain).
16879: clickerIDs are not necessarily unique, as students might share clickers.
16880: (returns hash: id=>name,id=>name)
1.191 harris41 16881:
16882: =item *
1.394 bowersj2 16883: X<idrget()>
16884: B<idrget($udom,@unames)>: find the IDs behind a list of
16885: usernames (returns hash: name=>id,name=>id)
1.191 harris41 16886:
16887: =item *
1.394 bowersj2 16888: X<idput()>
1.1300 raeburn 16889: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of
16890: names and associated student/employee IDs or clicker IDs.
16891:
16892: =item *
16893: X<iddel()>
16894: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted
16895: student/employee ID or clicker ID username look-ups from domain.
16896: The homeserver ($uhome) and namespace ($namespace) are optional.
16897: If no $uhome is provided, it will be determined usig &homeserver()
16898: for each user. If no $namespace is provided, the default is ids.
16899:
16900: =item *
16901: X<updateclickers()>
16902: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update
16903: clicker ID-to-username look-ups in clickers.db on library server.
16904: Permitted actions are add or del (i.e., add or delete). The
16905: clickers.db contains clickerID as keys (escaped), and each corresponding
16906: value is an escaped comma-separated list of usernames (for whom the
16907: library server is the homeserver), who registered that particular ID.
16908: If $critical is true, the update will be sent via &critical, otherwise
16909: &reply() will be used.
1.191 harris41 16910:
16911: =item *
1.394 bowersj2 16912: X<rolesinit()>
1.1169 droeschl 16913: B<rolesinit($udom,$username)>: get user privileges.
16914: returns user role, first access and timer interval hashes
1.243 albertel 16915:
16916: =item *
1.1171 droeschl 16917: X<privileged()>
16918: B<privileged($username,$domain)>: returns a true if user has a
16919: privileged and active role (i.e. su or dc), false otherwise.
16920:
16921: =item *
1.551 albertel 16922: X<getsection()>
16923: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 16924: course $cname, return section name/number or '' for "not in course"
16925: and '-1' for "no section"
16926:
16927: =item *
1.394 bowersj2 16928: X<userenvironment()>
16929: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 16930: passed in @what from the requested user's environment, returns a hash
16931:
1.858 raeburn 16932: =item *
16933: X<userlog_query()>
1.859 albertel 16934: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
16935: activity.log file. %filters defines filters applied when parsing the
16936: log file. These can be start or end timestamps, or the type of action
16937: - log to look for Login or Logout events, check for Checkin or
16938: Checkout, role for role selection. The response is in the form
16939: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
16940: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 16941:
1.243 albertel 16942: =back
16943:
16944: =head2 User Roles
16945:
16946: =over 4
16947:
16948: =item *
16949:
1.1284 raeburn 16950: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege;
16951: returns codes for allowed actions.
16952:
16953: The first argument is required, all others are optional.
16954:
16955: $priv is the privilege being checked.
16956: $uri contains additional information about what is being checked for access (e.g.,
16957: URL, course ID etc.).
16958: $symb is the unique resource instance identifier in a course; if needed,
16959: but not provided, it will be retrieved via a call to &symbread().
16960: $role is the role for which a priv is being checked (only used if priv is evb).
16961: $clientip is the user's IP address (only used when checking for access to portfolio
16962: files).
16963: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
16964: prevents recursive calls to &allowed.
16965:
1.243 albertel 16966: F: full access
16967: U,I,K: authentication modes (cxx only)
16968: '': forbidden
16969: 1: user needs to choose course
16970: 2: browse allowed
1.766 albertel 16971: A: passphrase authentication needed
1.1284 raeburn 16972: B: access temporarily blocked because of a blocking event in a course.
1.1402 raeburn 16973: D: access blocked because access is required via session initiated via deep-link
1.243 albertel 16974:
16975: =item *
16976:
1.1192 raeburn 16977: constructaccess($url,$setpriv) : check for access to construction space URL
16978:
16979: See if the owner domain and name in the URL match those in the
16980: expected environment. If so, return three element list
16981: ($ownername,$ownerdomain,$ownerhome).
16982:
16983: Otherwise return the null string.
16984:
16985: If second argument 'setpriv' is true, it assigns the privileges,
16986: and returns the same three element list, unless the owner has
16987: blocked "ad hoc" Domain Coordinator access to the Author Space,
16988: in which case the null string is returned.
16989:
16990: =item *
16991:
1.1326 raeburn 16992: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
16993: define a custom role rolename set privileges in format of lonTabs/roles.tab
16994: for system, domain, and course level. $uname and $udom are optional (current
16995: user's username and domain will be used when either of $uname or $udom are absent.
1.243 albertel 16996:
16997: =item *
16998:
1.988 raeburn 16999: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
17000: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 17001: $type is Course (default) or Community.
1.988 raeburn 17002: If $forcedefault evaluates to true, text returned will be default
17003: text for $type. Otherwise, if this is a course, the text returned
17004: will be a custom name for the role (if defined in the course's
17005: environment). If no custom name is defined the default is returned.
17006:
1.832 raeburn 17007: =item *
17008:
1.1219 raeburn 17009: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858 raeburn 17010: All arguments are optional. Returns a hash of a roles, either for
17011: co-author/assistant author roles for a user's Construction Space
1.906 albertel 17012: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 17013: In the hash, keys are set to colon-separated $uname,$udom,$role, and
17014: (optionally) if $withsec is true, a fourth colon-separated item - $section.
17015: For each key, value is set to colon-separated start and end times for
17016: the role. If no username and domain are specified, will default to
1.934 raeburn 17017: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 17018: of role statuses (active, future or previous), roles
17019: (e.g., cc,in, st etc.) and domains of the roles which can be used
17020: to restrict the list of roles reported. If no array ref is
17021: provided for types, will default to return only active roles.
1.834 albertel 17022:
1.1195 raeburn 17023: =item *
17024:
17025: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196 raeburn 17026: user: $uname:$udom has a role in the course: $cdom_$cnum.
17027:
17028: Additional optional arguments are: $type (if role checking is to be restricted
17029: to certain user status types -- previous (expired roles), active (currently
1.1195 raeburn 17030: available roles) or future (roles available in the future), and
17031: $hideprivileged -- if true will not report course roles for users who
1.1219 raeburn 17032: have active Domain Coordinator role in course's domain or in additional
17033: domains (specified in 'Domains to check for privileged users' in course
17034: environment -- set via: Course Settings -> Classlists and staff listing).
17035:
17036: =item *
17037:
17038: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
17039: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
17040: $possdomains and $possroles are optional array refs -- to domains to check and
17041: roles to check. If $possdomains is not specified, a dump will be done of the
17042: users' roles.db to check for a dc or su role in any domain. This can be
17043: time consuming if &privileged is called repeatedly (e.g., when displaying a
17044: classlist), so in such cases, supplying a $possdomains array is preferred, as
17045: this then allows &privileged_by_domain() to be used, which caches the identity
17046: of privileged users, eliminating the need for repeated calls to &dump().
17047:
17048: =item *
17049:
17050: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
17051: where the outer hash keys are domains specified in the $possdomains array ref,
17052: next inner hash keys are privileged roles specified in the $roles array ref,
17053: and the innermost hash contains key = value pairs for username:domain = end:start
17054: for active or future "privileged" users with that role in that domain. To avoid
17055: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
17056: innerhash are cached using priv_$role and $dom as the identifiers.
1.1195 raeburn 17057:
1.243 albertel 17058: =back
17059:
17060: =head2 User Modification
17061:
17062: =over 4
17063:
17064: =item *
17065:
1.957 raeburn 17066: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 17067: user for the level given by URL. Optional start and end dates (leave empty
17068: string or zero for "no date")
1.191 harris41 17069:
17070: =item *
17071:
1.243 albertel 17072: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
17073: change a users, password, possible return values are: ok,
17074: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
17075: refused
1.191 harris41 17076:
17077: =item *
17078:
1.243 albertel 17079: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 17080:
17081: =item *
17082:
1.1058 raeburn 17083: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
17084: $forceid,$desiredhome,$email,$inststatus,$candelete) :
17085:
17086: will update user information (firstname,middlename,lastname,generation,
17087: permanentemail), and if forceid is true, student/employee ID also.
17088: A user's institutional affiliation(s) can also be updated.
17089: User information fields will not be overwritten with empty entries
17090: unless the field is included in the $candelete array reference.
17091: This array is included when a single user is modified via "Manage Users",
17092: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 17093:
17094: =item *
17095:
1.286 matthew 17096: modifystudent
17097:
1.957 raeburn 17098: modify a student's enrollment and identification information.
1.1235 raeburn 17099: The course id is resolved based on the current user's environment.
17100: This means the invoking user must be a course coordinator or otherwise
1.286 matthew 17101: associated with a course.
17102:
1.297 matthew 17103: This call is essentially a wrapper for lonnet::modifyuser and
17104: lonnet::modify_student_enrollment
1.286 matthew 17105:
17106: Inputs:
17107:
17108: =over 4
17109:
1.957 raeburn 17110: =item B<$udom> Student's loncapa domain
1.286 matthew 17111:
1.957 raeburn 17112: =item B<$uname> Student's loncapa login name
1.286 matthew 17113:
1.964 bisitz 17114: =item B<$uid> Student/Employee ID
1.286 matthew 17115:
1.957 raeburn 17116: =item B<$umode> Student's authentication mode
1.286 matthew 17117:
1.957 raeburn 17118: =item B<$upass> Student's password
1.286 matthew 17119:
1.957 raeburn 17120: =item B<$first> Student's first name
1.286 matthew 17121:
1.957 raeburn 17122: =item B<$middle> Student's middle name
1.286 matthew 17123:
1.957 raeburn 17124: =item B<$last> Student's last name
1.286 matthew 17125:
1.957 raeburn 17126: =item B<$gene> Student's generation
1.286 matthew 17127:
1.957 raeburn 17128: =item B<$usec> Student's section in course
1.286 matthew 17129:
17130: =item B<$end> Unix time of the roles expiration
17131:
17132: =item B<$start> Unix time of the roles start date
17133:
17134: =item B<$forceid> If defined, allow $uid to be changed
17135:
17136: =item B<$desiredhome> server to use as home server for student
17137:
1.957 raeburn 17138: =item B<$email> Student's permanent e-mail address
17139:
17140: =item B<$type> Type of enrollment (auto or manual)
17141:
1.963 raeburn 17142: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
17143:
17144: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 17145:
1.963 raeburn 17146: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 17147:
1.963 raeburn 17148: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 17149:
1.1216 raeburn 17150: =item B<$inststatus> institutional status of user - : separated string of escaped status types
17151:
17152: =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 17153:
1.286 matthew 17154: =back
1.297 matthew 17155:
17156: =item *
17157:
17158: modify_student_enrollment
17159:
1.1235 raeburn 17160: Change a student's enrollment status in a class. The environment variable
1.297 matthew 17161: 'role.request.course' must be defined for this function to proceed.
17162:
17163: Inputs:
17164:
17165: =over 4
17166:
1.1235 raeburn 17167: =item $udom, student's domain
1.297 matthew 17168:
1.1235 raeburn 17169: =item $uname, student's name
1.297 matthew 17170:
1.1235 raeburn 17171: =item $uid, student's user id
1.297 matthew 17172:
1.1235 raeburn 17173: =item $first, student's first name
1.297 matthew 17174:
17175: =item $middle
17176:
17177: =item $last
17178:
17179: =item $gene
17180:
17181: =item $usec
17182:
17183: =item $end
17184:
17185: =item $start
17186:
1.957 raeburn 17187: =item $type
17188:
17189: =item $locktype
17190:
17191: =item $cid
17192:
17193: =item $selfenroll
17194:
17195: =item $context
17196:
1.1216 raeburn 17197: =item $credits, number of credits student will earn from this class
17198:
1.1314 raeburn 17199: =item $instsec, institutional course section code for student
17200:
1.297 matthew 17201: =back
17202:
1.191 harris41 17203:
17204: =item *
17205:
1.243 albertel 17206: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
17207: custom role; give a custom role to a user for the level given by URL. Specify
17208: name and domain of role author, and role name
1.191 harris41 17209:
17210: =item *
17211:
1.243 albertel 17212: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 17213:
17214: =item *
17215:
1.243 albertel 17216: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
17217:
17218: =back
17219:
17220: =head2 Course Infomation
17221:
17222: =over 4
1.191 harris41 17223:
17224: =item *
17225:
1.1118 foxr 17226: coursedescription($courseid,$options) : returns a hash of information about the
1.631 albertel 17227: specified course id, including all environment settings for the
17228: course, the description of the course will be in the hash under the
17229: key 'description'
1.191 harris41 17230:
1.1118 foxr 17231: $options is an optional parameter that if supplied is a hash reference that controls
17232: what how this function works. It has the following key/values:
17233:
17234: =over 4
17235:
17236: =item freshen_cache
17237:
17238: If defined, and the environment cache for the course is valid, it is
17239: returned in the returned hash.
17240:
17241: =item one_time
17242:
17243: If defined, the last cache time is set to _now_
17244:
17245: =item user
17246:
17247: If defined, the supplied username is used instead of the current user.
17248:
17249:
17250: =back
17251:
1.191 harris41 17252: =item *
17253:
1.624 albertel 17254: resdata($name,$domain,$type,@which) : request for current parameter
17255: setting for a specific $type, where $type is either 'course' or 'user',
17256: @what should be a list of parameters to ask about. This routine caches
1.1235 raeburn 17257: answers for 10 minutes.
1.243 albertel 17258:
1.877 foxr 17259: =item *
17260:
17261: get_courseresdata($courseid, $domain) : dump the entire course resource
17262: data base, returning a hash that is keyed by the resource name and has
17263: values that are the resource value. I believe that the timestamps and
17264: versions are also returned.
17265:
1.243 albertel 17266: =back
17267:
17268: =head2 Course Modification
17269:
17270: =over 4
1.191 harris41 17271:
17272: =item *
17273:
1.243 albertel 17274: writecoursepref($courseid,%prefs) : write preferences (environment
17275: database) for a course
1.191 harris41 17276:
17277: =item *
17278:
1.1011 raeburn 17279: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
17280:
17281: =item *
17282:
1.1038 raeburn 17283: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 17284:
1.1167 droeschl 17285: =item *
17286:
17287: is_course($courseid), is_course($cdom, $cnum)
17288:
17289: Accepts either a combined $courseid (in the form of domain_courseid) or the
17290: two component version $cdom, $cnum. It checks if the specified course exists.
17291:
17292: Returns:
17293: undef if the course doesn't exist, otherwise
17294: in scalar context the combined courseid.
17295: in list context the two components of the course identifier, domain and
17296: courseid.
17297:
1.243 albertel 17298: =back
17299:
1.1401 raeburn 17300: =head2 Bubblesheet Configuration
17301:
17302: =over 4
17303:
17304: =item *
17305:
17306: get_scantron_config($which)
17307:
17308: $which - the name of the configuration to parse from the file.
17309:
17310: Parses and returns the bubblesheet configuration line selected as a
17311: hash of configuration file fields.
17312:
17313:
17314: Returns:
17315: If the named configuration is not in the file, an empty
17316: hash is returned.
17317:
17318: a hash with the fields
17319: name - internal name for the this configuration setup
17320: description - text to display to operator that describes this config
17321: CODElocation - if 0 or the string 'none'
17322: - no CODE exists for this config
17323: if -1 || the string 'letter'
17324: - a CODE exists for this config and is
17325: a string of letters
17326: Unsupported value (but planned for future support)
17327: if a positive integer
17328: - The CODE exists as the first n items from
17329: the question section of the form
17330: if the string 'number'
17331: - The CODE exists for this config and is
17332: a string of numbers
17333: CODEstart - (only matter if a CODE exists) column in the line where
17334: the CODE starts
17335: CODElength - length of the CODE
17336: IDstart - column where the student/employee ID starts
17337: IDlength - length of the student/employee ID info
17338: Qstart - column where the information from the bubbled
17339: 'questions' start
17340: Qlength - number of columns comprising a single bubble line from
17341: the sheet. (usually either 1 or 10)
17342: Qon - either a single character representing the character used
17343: to signal a bubble was chosen in the positional setup, or
17344: the string 'letter' if the letter of the chosen bubble is
17345: in the final, or 'number' if a number representing the
17346: chosen bubble is in the file (1->A 0->J)
17347: Qoff - the character used to represent that a bubble was
17348: left blank
17349: PaperID - if the scanning process generates a unique number for each
17350: sheet scanned the column that this ID number starts in
17351: PaperIDlength - number of columns that comprise the unique ID number
17352: for the sheet of paper
17353: FirstName - column that the first name starts in
17354: FirstNameLength - number of columns that the first name spans
17355: LastName - column that the last name starts in
17356: LastNameLength - number of columns that the last name spans
17357: BubblesPerRow - number of bubbles available in each row used to
17358: bubble an answer. (If not specified, 10 assumed).
17359:
17360:
17361: =item *
17362:
17363: get_scantronformat_file($cdom)
17364:
17365: $cdom - the course's domain (optional); if not supplied, uses
17366: domain for current $env{'request.course.id'}.
17367:
17368: Returns an array containing lines from the scantron format file for
17369: the domain of the course.
17370:
17371: If a url for a custom.tab file is listed in domain's configuration.db,
17372: lines are from this file.
17373:
17374: Otherwise, if a default.tab has been published in RES space by the
17375: domainconfig user, lines are from this file.
17376:
17377: Otherwise, fall back to getting lines from the legacy file on the
17378: local server: /home/httpd/lonTabs/default_scantronformat.tab
17379:
17380: =back
17381:
1.243 albertel 17382: =head2 Resource Subroutines
17383:
17384: =over 4
1.191 harris41 17385:
17386: =item *
17387:
1.243 albertel 17388: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 17389:
17390: =item *
17391:
1.243 albertel 17392: repcopy($filename) : subscribes to the requested file, and attempts to
17393: replicate from the owning library server, Might return
1.607 raeburn 17394: 'unavailable', 'not_found', 'forbidden', 'ok', or
17395: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 17396: resource. Expects the local filesystem pathname
17397: (/home/httpd/html/res/....)
17398:
17399: =back
17400:
17401: =head2 Resource Information
17402:
17403: =over 4
1.191 harris41 17404:
17405: =item *
17406:
1.1228 raeburn 17407: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates
17408: and returns the value of a variety of different possible values,
17409: $varname should be a request string, and the other parameters can be
17410: used to specify who and what one is asking about. Ordinarily, $cid
17411: does not need to be specified, as it is retrived from
17412: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
17413: within lonuserstate::loadmap() when initializing a course, before
17414: $env{'request.course.id'} has been set, so it needs to be provided
17415: in that one case.
1.243 albertel 17416:
17417: Possible values for $varname are environment.lastname (or other item
17418: from the envirnment hash), user.name (or someother aspect about the
17419: user), resource.0.maxtries (or some other part and parameter of a
17420: resource)
1.204 albertel 17421:
17422: =item *
17423:
1.243 albertel 17424: directcondval($number) : get current value of a condition; reads from a state
17425: string
1.204 albertel 17426:
17427: =item *
17428:
1.243 albertel 17429: condval($condidx) : value of condition index based on state
1.204 albertel 17430:
17431: =item *
17432:
1.1362 raeburn 17433: metadata($uri,$what,$toolsymb,$liburi,$prefix,$depthcount) : request a
1.243 albertel 17434: resource's metadata, $what should be either a specific key, or either
17435: 'keys' (to get a list of possible keys) or 'packages' to get a list of
1.1362 raeburn 17436: packages that this resource currently uses, the last 3 arguments are
17437: only used internally for recursive metadata.
17438:
17439: the toolsymb is only used where the uri is for an external tool (for which
17440: the uri as well as the symb are guaranteed to be unique).
1.243 albertel 17441:
1.1371 raeburn 17442: this function automatically caches all requests except any made recursively
17443: to retrieve a list of metadata keys for an imported library file ($liburi is
17444: defined).
1.191 harris41 17445:
17446: =item *
17447:
1.243 albertel 17448: metadata_query($query,$custom,$customshow) : make a metadata query against the
17449: network of library servers; returns file handle of where SQL and regex results
17450: will be stored for query
1.191 harris41 17451:
17452: =item *
17453:
1.1282 raeburn 17454: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
17455: return symbolic list entry (all arguments optional).
17456:
17457: Args: filename is the filename (including path) for the file for which a symb
17458: is required; donotrecurse, if true will prevent calls to allowed() being made
17459: to check access status if more than one resource was found in the bighash
17460: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
17461: a randompick); ignorecachednull, if true will prevent a symb of '' being
17462: returned if $env{$cache_str} is defined as ''; checkforblock if true will
17463: cause possible symbs to be checked to determine if they are subject to content
17464: blocking, if so they will not be included as possible symbs; possibles is a
17465: ref to a hash, which, as a side effect, will be populated with all possible
17466: symbs (content blocking not tested).
17467:
1.243 albertel 17468: returns the data handle
1.191 harris41 17469:
17470: =item *
17471:
1.1190 raeburn 17472: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
17473: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582 albertel 17474: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190 raeburn 17475: on failure, user must be in a course, as it assumes the existence of
17476: the course initial hash, and uses $env('request.course.id'}. The third
17477: arg is an optional reference to a scalar. If this arg is passed in the
17478: call to symbverify, it will be set to 1 if the symb has been set to be
17479: encrypted; otherwise it will be null.
1.191 harris41 17480:
17481: =item *
17482:
1.243 albertel 17483: symbclean($symb) : removes versions numbers from a symb, returns the
17484: cleaned symb
1.191 harris41 17485:
17486: =item *
17487:
1.243 albertel 17488: is_on_map($uri) : checks if the $uri is somewhere on the current
17489: course map, user must be in a course for it to work.
1.191 harris41 17490:
17491: =item *
17492:
1.243 albertel 17493: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 17494:
17495: =item *
17496:
1.243 albertel 17497: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
17498: a random seed, all arguments are optional, if they aren't sent it uses the
17499: environment to derive them. Note: if symb isn't sent and it can't get one
17500: from &symbread it will use the current time as its return value
1.191 harris41 17501:
17502: =item *
17503:
1.243 albertel 17504: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
17505: unfakeable, receipt
1.191 harris41 17506:
17507: =item *
17508:
1.620 albertel 17509: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 17510:
17511: =item *
17512:
1.243 albertel 17513: countacc($url) : count the number of accesses to a given URL
1.191 harris41 17514:
17515: =item *
17516:
1.243 albertel 17517: 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 17518:
17519: =item *
17520:
1.243 albertel 17521: 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 17522:
17523: =item *
17524:
1.243 albertel 17525: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 17526:
17527: =item *
17528:
1.243 albertel 17529: devalidate($symb) : devalidate temporary spreadsheet calculations,
17530: forcing spreadsheet to reevaluate the resource scores next time.
17531:
1.1195 raeburn 17532: =item *
17533:
1.1196 raeburn 17534: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
17535: when viewing in course context.
1.1195 raeburn 17536:
1.1196 raeburn 17537: input: six args -- filename (decluttered), course number, course domain,
17538: url, symb (if registered) and group (if this is a
17539: group item -- e.g., bulletin board, group page etc.).
1.1195 raeburn 17540:
1.1196 raeburn 17541: output: array of five scalars --
1.1195 raeburn 17542: $cfile -- url for file editing if editable on current server
17543: $home -- homeserver of resource (i.e., for author if published,
17544: or course if uploaded.).
17545: $switchserver -- 1 if server switch will be needed.
1.1196 raeburn 17546: $forceedit -- 1 if icon/link should be to go to edit mode
17547: $forceview -- 1 if icon/link should be to go to view mode
1.1195 raeburn 17548:
17549: =item *
17550:
17551: is_course_upload($file,$cnum,$cdom)
17552:
17553: Used in course context to determine if current file was uploaded to
17554: the course (i.e., would be found in /userfiles/docs on the course's
17555: homeserver.
17556:
17557: input: 3 args -- filename (decluttered), course number and course domain.
17558: output: boolean -- 1 if file was uploaded.
17559:
1.243 albertel 17560: =back
17561:
17562: =head2 Storing/Retreiving Data
17563:
17564: =over 4
1.191 harris41 17565:
17566: =item *
17567:
1.1269 raeburn 17568: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
17569: permanently for this url; hashref needs to be given and should be a \%hashname;
17570: the remaining args aren't required and if they aren't passed or are '' they will
17571: be derived from the env (with the exception of $laststore, which is an
17572: optional arg used when a user's submission is stored in grading).
17573: $laststore is $version=$timestamp, where $version is the most recent version
17574: number retrieved for the corresponding $symb in the $namespace db file, and
17575: $timestamp is the timestamp for that transaction (UNIX time).
17576: $laststore is currently only passed when cstore() is called by
17577: structuretags::finalize_storage().
1.191 harris41 17578:
17579: =item *
17580:
1.1269 raeburn 17581: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
17582: but uses critical subroutine
1.191 harris41 17583:
17584: =item *
17585:
1.243 albertel 17586: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
17587: all args are optional
1.191 harris41 17588:
17589: =item *
17590:
1.717 albertel 17591: dumpstore($namespace,$udom,$uname,$regexp,$range) :
17592: dumps the complete (or key matching regexp) namespace into a hash
17593: ($udom, $uname, $regexp, $range are optional) for a namespace that is
17594: normally &store()ed into
17595:
17596: $range should be either an integer '100' (give me the first 100
17597: matching records)
17598: or be two integers sperated by a - with no spaces
17599: '30-50' (give me the 30th through the 50th matching
17600: records)
17601:
17602:
17603: =item *
17604:
1.1269 raeburn 17605: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717 albertel 17606: replaces a &store() version of data with a replacement set of data
17607: for a particular resource in a namespace passed in the $storehash hash
1.1269 raeburn 17608: reference. If $tolog is true, the transaction is logged in the courselog
17609: with an action=PUTSTORE.
1.717 albertel 17610:
17611: =item *
17612:
1.243 albertel 17613: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
17614: works very similar to store/cstore, but all data is stored in a
17615: temporary location and can be reset using tmpreset, $storehash should
17616: be a hash reference, returns nothing on success
1.191 harris41 17617:
17618: =item *
17619:
1.243 albertel 17620: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
17621: similar to restore, but all data is stored in a temporary location and
17622: can be reset using tmpreset. Returns a hash of values on success,
17623: error string otherwise.
1.191 harris41 17624:
17625: =item *
17626:
1.243 albertel 17627: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
17628: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 17629:
17630: =item *
17631:
1.243 albertel 17632: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
17633: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 17634:
17635: =item *
17636:
1.243 albertel 17637: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
17638: namesp ($udom and $uname are optional)
1.191 harris41 17639:
17640: =item *
17641:
1.702 albertel 17642: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 17643: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 17644: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 17645:
1.702 albertel 17646: $range should be either an integer '100' (give me the first 100
17647: matching records)
17648: or be two integers sperated by a - with no spaces
17649: '30-50' (give me the 30th through the 50th matching
17650: records)
1.449 matthew 17651: =item *
17652:
17653: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
17654: $store can be a scalar, an array reference, or if the amount to be
17655: incremented is > 1, a hash reference.
17656:
17657: ($udom and $uname are optional)
1.191 harris41 17658:
17659: =item *
17660:
1.243 albertel 17661: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
17662: ($udom and $uname are optional)
1.191 harris41 17663:
17664: =item *
17665:
1.243 albertel 17666: cput($namespace,$storehash,$udom,$uname) : critical put
17667: ($udom and $uname are optional)
1.191 harris41 17668:
17669: =item *
17670:
1.748 albertel 17671: newput($namespace,$storehash,$udom,$uname) :
17672:
17673: Attempts to store the items in the $storehash, but only if they don't
17674: currently exist, if this succeeds you can be certain that you have
17675: successfully created a new key value pair in the $namespace db.
17676:
17677:
17678: Args:
17679: $namespace: name of database to store values to
17680: $storehash: hashref to store to the db
17681: $udom: (optional) domain of user containing the db
17682: $uname: (optional) name of user caontaining the db
17683:
17684: Returns:
17685: 'ok' -> succeeded in storing all keys of $storehash
17686: 'key_exists: <key>' -> failed to anything out of $storehash, as at
17687: least <key> already existed in the db (other
17688: requested keys may also already exist)
1.967 bisitz 17689: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 17690: 'con_lost' -> unable to contact request server
17691: 'refused' -> action was not allowed by remote machine
17692:
17693:
17694: =item *
17695:
1.243 albertel 17696: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
17697: reference filled in from namesp (encrypts the return communication)
17698: ($udom and $uname are optional)
1.191 harris41 17699:
17700: =item *
17701:
1.243 albertel 17702: log($udom,$name,$home,$message) : write to permanent log for user; use
17703: critical subroutine
17704:
1.806 raeburn 17705: =item *
17706:
1.860 raeburn 17707: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
17708: array reference filled in from namespace found in domain level on either
17709: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 17710:
17711: =item *
17712:
1.860 raeburn 17713: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
17714: domain level either on specified domain server ($uhome) or primary domain
17715: server ($udom and $uhome are optional)
1.806 raeburn 17716:
1.943 raeburn 17717: =item *
17718:
1.1240 raeburn 17719: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
17720: for: authentication, language, quotas, timezone, date locale, and portal URL in
17721: the target domain.
17722:
17723: May also include additional key => value pairs for the following groups:
17724:
17725: =over
17726:
17727: =item
17728: disk quotas (MB allocated by default to portfolios and authoring spaces).
17729:
17730: =over
17731:
17732: =item defaultquota, authorquota
17733:
17734: =back
17735:
17736: =item
17737: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
17738: portfolio for users).
17739:
17740: =over
17741:
17742: =item
17743: aboutme, blog, webdav, portfolio
17744:
17745: =back
17746:
17747: =item
17748: requestcourses: ability to request courses, and how requests are processed.
17749:
17750: =over
17751:
17752: =item
1.1305 raeburn 17753: official, unofficial, community, textbook, placement
1.1240 raeburn 17754:
17755: =back
17756:
17757: =item
17758: inststatus: types of institutional affiliation, and order in which they are displayed.
17759:
17760: =over
17761:
17762: =item
1.1256 raeburn 17763: inststatustypes, inststatusorder, inststatusguest
1.1240 raeburn 17764:
17765: =back
17766:
17767: =item
17768: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
17769: for course's uploaded content.
17770:
17771: =over
17772:
17773: =item
1.1246 raeburn 17774: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
1.1305 raeburn 17775: communityquota, textbookquota, placementquota
1.1240 raeburn 17776:
17777: =back
17778:
17779: =item
17780: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
17781: on your servers.
17782:
17783: =over
17784:
17785: =item
17786: remotesessions, hostedsessions
17787:
17788: =back
17789:
17790: =back
17791:
17792: In cases where a domain coordinator has never used the "Set Domain Configuration"
17793: utility to create a configuration.db file on a domain's primary library server
17794: only the following domain defaults: auth_def, auth_arg_def, lang_def
17795: -- corresponding values are authentication type (internal, krb4, krb5,
17796: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
17797: will be available. Values are retrieved from cache (if current), unless the
17798: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
17799: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
17800:
17801: Typical usage:
1.943 raeburn 17802:
1.1240 raeburn 17803: %domdefaults = &get_domain_defaults($target_domain);
1.943 raeburn 17804:
1.243 albertel 17805: =back
17806:
17807: =head2 Network Status Functions
17808:
17809: =over 4
1.191 harris41 17810:
17811: =item *
17812:
1.1137 raeburn 17813: dirlist() : return directory list based on URI (first arg).
17814:
17815: Inputs: 1 required, 5 optional.
17816:
17817: =over
17818:
17819: =item
17820: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
17821:
17822: =item
17823: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
17824:
17825: =item
17826: $username - username of user/course to be listed. Extracted from $uri if absent.
17827:
17828: =item
17829: $getpropath - boolean: 1 if prepend path using &propath().
17830:
17831: =item
17832: $getuserdir - boolean: 1 if prepend path for "userfiles".
17833:
17834: =item
17835: $alternateRoot - path to prepend in place of path from $uri.
17836:
17837: =back
17838:
17839: Returns: Array of up to two items.
17840:
17841: =over
17842:
17843: a reference to an array of files/subdirectories
17844:
17845: =over
17846:
17847: Each element in the array of files/subdirectories is a & separated list of
17848: item name and the result of running stat on the item. If dirlist was requested
17849: for a file instead of a directory, the item name will be ''. For a directory
17850: listing, if the item is a metadata file, the element will end &N&M
17851: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
17852: default copyright set (1).
17853:
17854: =back
17855:
17856: a scalar containing error condition (if encountered).
17857:
17858: =over
17859:
17860: =item
17861: no_host (no homeserver identified for $username:$domain).
17862:
17863: =item
17864: no_such_host (server contacted for listing not identified as valid host).
17865:
17866: =item
17867: con_lost (connection to remote server failed).
17868:
17869: =item
17870: refused (invalid $username:$domain received on lond side).
17871:
17872: =item
17873: no_such_dir (directory at specified path on lond side does not exist).
17874:
17875: =item
17876: empty (directory at specified path on lond side is empty).
17877:
17878: =over
17879:
17880: This is currently not encountered because the &ls3, &ls2,
17881: &ls (_handler) routines on the lond side do not filter out
17882: . and .. from a directory listing.
17883:
17884: =back
17885:
17886: =back
17887:
17888: =back
1.191 harris41 17889:
17890: =item *
17891:
1.243 albertel 17892: spareserver() : find server with least workload from spare.tab
17893:
1.986 foxr 17894:
17895: =item *
17896:
17897: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
17898: if there is no corresponding loncapa host.
17899:
1.243 albertel 17900: =back
17901:
1.986 foxr 17902:
1.243 albertel 17903: =head2 Apache Request
17904:
17905: =over 4
1.191 harris41 17906:
17907: =item *
17908:
1.243 albertel 17909: ssi($url,%hash) : server side include, does a complete request cycle on url to
17910: localhost, posts hash
17911:
17912: =back
17913:
17914: =head2 Data to String to Data
17915:
17916: =over 4
1.191 harris41 17917:
17918: =item *
17919:
1.243 albertel 17920: hash2str(%hash) : convert a hash into a string complete with escaping and '='
17921: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 17922:
17923: =item *
17924:
1.243 albertel 17925: hashref2str($hashref) : convert a hashref into a string complete with
17926: escaping and '=' and '&' separators, supports elements that are
17927: arrayrefs and hashrefs
1.191 harris41 17928:
17929: =item *
17930:
1.243 albertel 17931: arrayref2str($arrayref) : convert an arrayref into a string complete
17932: with escaping and '&' separators, supports elements that are arrayrefs
17933: and hashrefs
1.191 harris41 17934:
17935: =item *
17936:
1.243 albertel 17937: str2hash($string) : convert string to hash using unescaping and
17938: splitting on '=' and '&', supports elements that are arrayrefs and
17939: hashrefs
1.191 harris41 17940:
17941: =item *
17942:
1.243 albertel 17943: str2array($string) : convert string to hash using unescaping and
17944: splitting on '&', supports elements that are arrayrefs and hashrefs
17945:
17946: =back
17947:
17948: =head2 Logging Routines
17949:
17950:
17951: These routines allow one to make log messages in the lonnet.log and
17952: lonnet.perm logfiles.
1.191 harris41 17953:
1.1119 foxr 17954: =over 4
17955:
1.191 harris41 17956: =item *
17957:
1.243 albertel 17958: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 17959:
17960: =item *
17961:
1.243 albertel 17962: logthis() : append message to the normal lonnet.log file, it gets
17963: preiodically rolled over and deleted.
1.191 harris41 17964:
17965: =item *
17966:
1.243 albertel 17967: logperm() : append a permanent message to lonnet.perm.log, this log
17968: file never gets deleted by any automated portion of the system, only
17969: messages of critical importance should go in here.
17970:
1.1119 foxr 17971:
1.243 albertel 17972: =back
17973:
17974: =head2 General File Helper Routines
17975:
17976: =over 4
1.191 harris41 17977:
17978: =item *
17979:
1.481 raeburn 17980: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
17981: (a) files in /uploaded
17982: (i) If a local copy of the file exists -
17983: compares modification date of local copy with last-modified date for
17984: definitive version stored on home server for course. If local copy is
17985: stale, requests a new version from the home server and stores it.
17986: If the original has been removed from the home server, then local copy
17987: is unlinked.
17988: (ii) If local copy does not exist -
17989: requests the file from the home server and stores it.
17990:
17991: If $caller is 'uploadrep':
17992: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
17993: for request for files originally uploaded via DOCS.
17994: - returns 'ok' if fresh local copy now available, -1 otherwise.
17995:
17996: Otherwise:
17997: This indicates a call from the content generation phase of the request.
17998: - returns the entire contents of the file or -1.
17999:
18000: (b) files in /res
18001: - returns the entire contents of a file or -1;
18002: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 18003:
1.712 albertel 18004:
18005: =item *
18006:
18007: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
18008: reference
18009:
18010: returns either a stat() list of data about the file or an empty list
18011: if the file doesn't exist or couldn't find out about it (connection
18012: problems or user unknown)
18013:
1.191 harris41 18014: =item *
18015:
1.243 albertel 18016: filelocation($dir,$file) : returns file system location of a file
18017: based on URI; meant to be "fairly clean" absolute reference, $dir is a
18018: directory that relative $file lookups are to looked in ($dir of /a/dir
18019: and a file of ../bob will become /a/bob)
1.191 harris41 18020:
18021: =item *
18022:
18023: hreflocation($dir,$file) : returns file system location or a URL; same as
18024: filelocation except for hrefs
18025:
18026: =item *
18027:
1.1261 raeburn 18028: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
18029: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191 harris41 18030:
1.243 albertel 18031: =back
18032:
1.608 albertel 18033: =head2 Usererfile file routines (/uploaded*)
18034:
18035: =over 4
18036:
18037: =item *
18038:
18039: userfileupload(): main rotine for putting a file in a user or course's
18040: filespace, arguments are,
18041:
1.620 albertel 18042: formname - required - this is the name of the element in $env where the
1.608 albertel 18043: filename, and the contents of the file to create/modifed exist
1.620 albertel 18044: the filename is in $env{'form.'.$formname.'.filename'} and the
18045: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 18046: context - if coursedoc, store the file in the course of the active role
18047: of the current user;
18048: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
18049: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 18050: subdir - required - subdirectory to put the file in under ../userfiles/
18051: if undefined, it will be placed in "unknown"
18052:
18053: (This routine calls clean_filename() to remove any dangerous
18054: characters from the filename, and then calls finuserfileupload() to
18055: complete the transaction)
18056:
18057: returns either the url of the uploaded file (/uploaded/....) if successful
18058: and /adm/notfound.html if unsuccessful
18059:
18060: =item *
18061:
18062: clean_filename(): routine for cleaing a filename up for storage in
18063: userfile space, argument is:
18064:
18065: filename - proposed filename
18066:
18067: returns: the new clean filename
18068:
18069: =item *
18070:
1.1090 raeburn 18071: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 18072: userspace, probably shouldn't be called directly
18073:
18074: docuname: username or courseid of destination for the file
18075: docudom: domain of user/course of destination for the file
18076: formname: same as for userfileupload()
1.1090 raeburn 18077: fname: filename (including subdirectories) for the file
18078: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
1.1401 raeburn 18079: if hashref, and context is scantron, will convert csv format to standard format
1.1090 raeburn 18080: allfiles: reference to hash used to store objects found by parser
18081: codebase: reference to hash used for codebases of java objects found by parser
18082: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
18083: thumbheight: height (pixels) of thumbnail to be created for uploaded image
18084: resizewidth: width to be used to resize image using resizeImage from ImageMagick
18085: resizeheight: height to be used to resize image using resizeImage from ImageMagick
18086: context: if 'overwrite', will move the uploaded file from its temporary location to
18087: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 18088: mimetype: reference to scalar to accommodate mime type determined
18089: from File::MMagic if $parser = parse.
1.608 albertel 18090:
18091: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 18092: and /adm/notfound.html if unsuccessful (or an error message if context
18093: was 'overwrite').
18094:
1.608 albertel 18095:
18096: =item *
18097:
18098: renameuserfile(): renames an existing userfile to a new name
18099:
18100: Args:
18101: docuname: username or courseid of destination for the file
18102: docudom: domain of user/course of destination for the file
18103: old: current file name (including any subdirs under userfiles)
18104: new: desired file name (including any subdirs under userfiles)
18105:
18106: =item *
18107:
18108: mkdiruserfile(): creates a directory is a userfiles dir
18109:
18110: Args:
18111: docuname: username or courseid of destination for the file
18112: docudom: domain of user/course of destination for the file
18113: dir: dir to create (including any subdirs under userfiles)
18114:
18115: =item *
18116:
18117: removeuserfile(): removes a file that exists in userfiles
18118:
18119: Args:
18120: docuname: username or courseid of destination for the file
18121: docudom: domain of user/course of destination for the file
18122: fname: filname to delete (including any subdirs under userfiles)
18123:
18124: =item *
18125:
18126: removeuploadedurl(): convience function for removeuserfile()
18127:
18128: Args:
18129: url: a full /uploaded/... url to delete
18130:
1.747 albertel 18131: =item *
18132:
18133: get_portfile_permissions():
18134: Args:
18135: domain: domain of user or course contain the portfolio files
18136: user: name of user or num of course contain the portfolio files
18137: Returns:
18138: hashref of a dump of the proper file_permissions.db
18139:
18140:
18141: =item *
18142:
18143: get_access_controls():
18144:
18145: Args:
18146: current_permissions: the hash ref returned from get_portfile_permissions()
18147: group: (optional) the group you want the files associated with
18148: file: (optional) the file you want access info on
18149:
18150: Returns:
1.749 raeburn 18151: a hash (keys are file names) of hashes containing
18152: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
18153: values are XML containing access control settings (see below)
1.747 albertel 18154:
18155: Internal notes:
18156:
1.749 raeburn 18157: access controls are stored in file_permissions.db as key=value pairs.
18158: key -> path to file/file_name\0uniqueID:scope_end_start
18159: where scope -> public,guest,course,group,domains or users.
18160: end -> UNIX time for end of access (0 -> no end date)
18161: start -> UNIX time for start of access
18162:
18163: value -> XML description of access control
18164: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
18165: <start></start>
18166: <end></end>
18167:
18168: <password></password> for scope type = guest
18169:
18170: <domain></domain> for scope type = course or group
18171: <number></number>
18172: <roles id="">
18173: <role></role>
18174: <access></access>
18175: <section></section>
18176: <group></group>
18177: </roles>
18178:
18179: <dom></dom> for scope type = domains
18180:
18181: <users> for scope type = users
18182: <user>
18183: <uname></uname>
18184: <udom></udom>
18185: </user>
18186: </users>
18187: </scope>
18188:
18189: Access data is also aggregated for each file in an additional key=value pair:
18190: key -> path to file/file_name\0accesscontrol
18191: value -> reference to hash
18192: hash contains key = value pairs
18193: where key = uniqueID:scope_end_start
18194: value = UNIX time record was last updated
18195:
18196: Used to improve speed of look-ups of access controls for each file.
18197:
18198: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
18199:
1.1198 raeburn 18200: =item *
18201:
1.749 raeburn 18202: modify_access_controls():
18203:
18204: Modifies access controls for a portfolio file
18205: Args
18206: 1. file name
18207: 2. reference to hash of required changes,
18208: 3. domain
18209: 4. username
18210: where domain,username are the domain of the portfolio owner
18211: (either a user or a course)
18212:
18213: Returns:
18214: 1. result of additions or updates ('ok' or 'error', with error message).
18215: 2. result of deletions ('ok' or 'error', with error message).
18216: 3. reference to hash of any new or updated access controls.
18217: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
18218: key = integer (inbound ID)
1.1198 raeburn 18219: value = uniqueID
18220:
18221: =item *
18222:
18223: get_timebased_id():
18224:
18225: Attempts to get a unique timestamp-based suffix for use with items added to a
18226: course via the Course Editor (e.g., folders, composite pages,
18227: group bulletin boards).
18228:
18229: Args: (first three required; six others optional)
18230:
18231: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
18232: docssequence, or name of group
18233:
18234: 2. keyid (alphanumeric): name of temporary locking key in hash,
18235: e.g., num, boardids
18236:
18237: 3. namespace: name of gdbm file used to store suffixes already assigned;
18238: file will be named nohist_namespace.db
18239:
18240: 4. cdom: domain of course; default is current course domain from %env
18241:
18242: 5. cnum: course number; default is current course number from %env
18243:
18244: 6. idtype: set to concat if an additional digit is to be appended to the
18245: unix timestamp to form the suffix, if the plain timestamp is already
18246: in use. Default is to not do this, but simply increment the unix
18247: timestamp by 1 until a unique key is obtained.
18248:
18249: 7. who: holder of locking key; defaults to user:domain for user.
18250:
18251: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
18252: retrying); default is 3.
18253:
18254: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
18255:
18256: Returns:
18257:
18258: 1. suffix obtained (numeric)
18259:
18260: 2. result of deleting locking key (ok if deleted, or lock never obtained)
18261:
18262: 3. error: contains (localized) error message if an error occurred.
18263:
1.747 albertel 18264:
1.608 albertel 18265: =back
18266:
1.243 albertel 18267: =head2 HTTP Helper Routines
18268:
18269: =over 4
18270:
1.191 harris41 18271: =item *
18272:
18273: escape() : unpack non-word characters into CGI-compatible hex codes
18274:
18275: =item *
18276:
18277: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
18278:
1.243 albertel 18279: =back
18280:
18281: =head1 PRIVATE SUBROUTINES
18282:
18283: =head2 Underlying communication routines (Shouldn't call)
18284:
18285: =over 4
18286:
18287: =item *
18288:
18289: subreply() : tries to pass a message to lonc, returns con_lost if incapable
18290:
18291: =item *
18292:
18293: reply() : uses subreply to send a message to remote machine, logs all failures
18294:
18295: =item *
18296:
18297: critical() : passes a critical message to another server; if cannot
18298: get through then place message in connection buffer directory and
18299: returns con_delayed, if incapable of saving message, returns
18300: con_failed
18301:
18302: =item *
18303:
18304: reconlonc() : tries to reconnect lonc client processes.
18305:
18306: =back
18307:
18308: =head2 Resource Access Logging
18309:
18310: =over 4
18311:
18312: =item *
18313:
18314: flushcourselogs() : flush (save) buffer logs and access logs
18315:
18316: =item *
18317:
18318: courselog($what) : save message for course in hash
18319:
18320: =item *
18321:
18322: courseacclog($what) : save message for course using &courselog(). Perform
18323: special processing for specific resource types (problems, exams, quizzes, etc).
18324:
1.191 harris41 18325: =item *
18326:
18327: goodbye() : flush course logs and log shutting down; it is called in srm.conf
18328: as a PerlChildExitHandler
1.243 albertel 18329:
18330: =back
18331:
18332: =head2 Other
18333:
18334: =over 4
18335:
18336: =item *
18337:
18338: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 18339:
18340: =back
18341:
18342: =cut
1.877 foxr 18343:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>