Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1531
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1531 ! raeburn 4: # $Id: lonnet.pm,v 1.1530 2024/11/21 07:26:02 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.1530 raeburn 6752: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore,$ip,$nolog) = @_;
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.1530 raeburn 6777: if ($ip ne '') {
6778: $$storehash{'ip'} = $ip;
6779: } else {
6780: $$storehash{'ip'} = &get_requestor_ip();
6781: }
1.447 www 6782: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 6783:
1.47 www 6784: my $namevalue='';
1.800 albertel 6785: foreach my $key (keys(%$storehash)) {
6786: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 6787: }
1.47 www 6788: $namevalue=~s/\&$//;
1.1530 raeburn 6789: unless ($nolog) {
6790: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
6791: }
1.188 www 6792: return critical
1.1269 raeburn 6793: ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47 www 6794: }
6795:
1.9 www 6796: # --------------------------------------------------------------------- Restore
6797:
6798: sub restore {
1.124 www 6799: my ($symb,$namespace,$domain,$stuname) = @_;
6800: my $home='';
6801:
1.168 albertel 6802: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 6803:
1.122 albertel 6804: if (!$symb) {
1.1224 raeburn 6805: return if ($namespace eq 'courserequests');
6806: unless ($symb=escape(&symbread())) { return ''; }
1.122 albertel 6807: } else {
1.1224 raeburn 6808: unless ($namespace eq 'courserequests') {
6809: $symb=&escape(&symbclean($symb));
6810: }
1.122 albertel 6811: }
1.188 www 6812: if (!$namespace) {
1.620 albertel 6813: unless ($namespace=$env{'request.course.id'}) {
1.188 www 6814: return '';
6815: }
6816: }
1.620 albertel 6817: if (!$domain) { $domain=$env{'user.domain'}; }
6818: if (!$stuname) { $stuname=$env{'user.name'}; }
6819: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 6820: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
6821:
1.12 www 6822: my %returnhash=();
1.800 albertel 6823: foreach my $line (split(/\&/,$answer)) {
6824: my ($name,$value)=split(/\=/,$line);
1.591 albertel 6825: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 6826: }
1.75 www 6827: my $version;
6828: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 6829: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
6830: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 6831: }
1.75 www 6832: }
1.13 www 6833: return %returnhash;
1.34 www 6834: }
6835:
6836: # ---------------------------------------------------------- Course Description
1.1118 foxr 6837: #
6838: #
1.34 www 6839:
6840: sub coursedescription {
1.731 albertel 6841: my ($courseid,$args)=@_;
1.34 www 6842: $courseid=~s/^\///;
1.49 www 6843: $courseid=~s/\_/\//g;
1.34 www 6844: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 6845: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 6846: my $normalid=$cdomain.'_'.$cnum;
6847: # need to always cache even if we get errors otherwise we keep
6848: # trying and trying and trying to get the course description.
6849: my %envhash=();
6850: my %returnhash=();
1.731 albertel 6851:
6852: my $expiretime=600;
6853: if ($env{'request.course.id'} eq $normalid) {
6854: $expiretime=120;
6855: }
6856:
6857: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
6858: if (!$args->{'freshen_cache'}
6859: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
6860: foreach my $key (keys(%env)) {
6861: next if ($key !~ /^\Q$prefix\E(.*)/);
6862: my ($setting) = $1;
6863: $returnhash{$setting} = $env{$key};
6864: }
6865: return %returnhash;
6866: }
6867:
1.1118 foxr 6868: # get the data again
6869:
1.731 albertel 6870: if (!$args->{'one_time'}) {
6871: $envhash{'course.'.$normalid.'.last_cache'}=time;
6872: }
1.811 albertel 6873:
1.34 www 6874: if ($chome ne 'no_host') {
1.302 albertel 6875: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 6876: if (!exists($returnhash{'con_lost'})) {
1.1118 foxr 6877: my $username = $env{'user.name'}; # Defult username
6878: if(defined $args->{'user'}) {
6879: $username = $args->{'user'};
6880: }
1.129 albertel 6881: $returnhash{'home'}= $chome;
6882: $returnhash{'domain'} = $cdomain;
6883: $returnhash{'num'} = $cnum;
1.741 raeburn 6884: if (!defined($returnhash{'type'})) {
6885: $returnhash{'type'} = 'Course';
6886: }
1.130 albertel 6887: while (my ($name,$value) = each %returnhash) {
1.53 www 6888: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 6889: }
1.270 www 6890: $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117 foxr 6891: $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118 foxr 6892: $username.'_'.$cdomain.'_'.$cnum;
1.60 www 6893: $envhash{'course.'.$normalid.'.home'}=$chome;
6894: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
6895: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 6896: }
6897: }
1.731 albertel 6898: if (!$args->{'one_time'}) {
1.949 raeburn 6899: &appenv(\%envhash);
1.731 albertel 6900: }
1.302 albertel 6901: return %returnhash;
1.461 www 6902: }
6903:
1.1080 raeburn 6904: sub update_released_required {
6905: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
6906: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
6907: $cid = $env{'request.course.id'};
6908: $cdom = $env{'course.'.$cid.'.domain'};
6909: $cnum = $env{'course.'.$cid.'.num'};
6910: $chome = $env{'course.'.$cid.'.home'};
6911: }
6912: if ($needsrelease) {
6913: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
6914: my $needsupdate;
6915: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
6916: $needsupdate = 1;
6917: } else {
6918: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
6919: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
6920: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
6921: $needsupdate = 1;
6922: }
6923: }
6924: if ($needsupdate) {
6925: my %needshash = (
6926: 'internal.releaserequired' => $needsrelease,
6927: );
6928: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
6929: if ($putresult eq 'ok') {
6930: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
6931: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
6932: if (ref($crsinfo{$cid}) eq 'HASH') {
6933: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
6934: &courseidput($cdom,\%crsinfo,$chome,'notime');
6935: }
6936: }
6937: }
6938: }
6939: return;
6940: }
6941:
1.461 www 6942: # -------------------------------------------------See if a user is privileged
6943:
6944: sub privileged {
1.1219 raeburn 6945: my ($username,$domain,$possdomains,$possroles)=@_;
1.1170 droeschl 6946: my $now = time;
1.1219 raeburn 6947: my $roles;
6948: if (ref($possroles) eq 'ARRAY') {
6949: $roles = $possroles;
6950: } else {
6951: $roles = ['dc','su'];
6952: }
6953: if (ref($possdomains) eq 'ARRAY') {
6954: my %privileged = &privileged_by_domain($possdomains,$roles);
6955: foreach my $dom (@{$possdomains}) {
6956: if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
6957: (ref($privileged{$dom}) eq 'HASH')) {
6958: foreach my $role (@{$roles}) {
6959: if (ref($privileged{$dom}{$role}) eq 'HASH') {
6960: if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
6961: my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
6962: return 1 unless (($end && $end < $now) ||
6963: ($start && $start > $now));
6964: }
6965: }
6966: }
6967: }
6968: }
6969: } else {
6970: my %rolesdump = &dump("roles", $domain, $username) or return 0;
6971: my $now = time;
1.1170 droeschl 6972:
1.1275 musolffc 6973: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170 droeschl 6974: my ($trole, $tend, $tstart) = split(/_/, $role);
1.1219 raeburn 6975: if (grep(/^\Q$trole\E$/,@{$roles})) {
1.1170 droeschl 6976: return 1 unless ($tend && $tend < $now)
1.1219 raeburn 6977: or ($tstart && $tstart > $now);
1.1170 droeschl 6978: }
1.1219 raeburn 6979: }
6980: }
6981: return 0;
6982: }
1.1170 droeschl 6983:
1.1219 raeburn 6984: sub privileged_by_domain {
6985: my ($domains,$roles) = @_;
6986: my %privileged = ();
6987: my $cachetime = 60*60*24;
6988: my $now = time;
6989: unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
6990: return %privileged;
6991: }
6992: foreach my $dom (@{$domains}) {
6993: next if (ref($privileged{$dom}) eq 'HASH');
6994: my $needroles;
6995: foreach my $role (@{$roles}) {
6996: my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
6997: if (defined($cached)) {
6998: if (ref($result) eq 'HASH') {
6999: $privileged{$dom}{$role} = $result;
7000: }
7001: } else {
7002: $needroles = 1;
7003: }
7004: }
7005: if ($needroles) {
7006: my %dompersonnel = &get_domain_roles($dom,$roles);
7007: $privileged{$dom} = {};
7008: foreach my $server (keys(%dompersonnel)) {
7009: if (ref($dompersonnel{$server}) eq 'HASH') {
7010: foreach my $item (keys(%{$dompersonnel{$server}})) {
7011: my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
7012: my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
7013: next if ($end && $end < $now);
7014: $privileged{$dom}{$trole}{$uname.':'.$udom} =
7015: $dompersonnel{$server}{$item};
7016: }
7017: }
7018: }
7019: if (ref($privileged{$dom}) eq 'HASH') {
7020: foreach my $role (@{$roles}) {
7021: if (ref($privileged{$dom}{$role}) eq 'HASH') {
7022: &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
7023: } else {
7024: my %hash = ();
7025: &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
7026: }
7027: }
7028: }
7029: }
7030: }
7031: return %privileged;
1.9 www 7032: }
1.1 albertel 7033:
1.103 harris41 7034: # -------------------------------------------------------- Get user privileges
1.11 www 7035:
7036: sub rolesinit {
1.1169 droeschl 7037: my ($domain, $username) = @_;
7038: my %userroles = ('user.login.time' => time);
7039: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
7040:
7041: # firstaccess and timerinterval are related to timed maps/resources.
7042: # also, blocking can be triggered by an activating timer
7043: # it's saved in the user's %env.
7044: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
7045: my %timerinterval = &dump('timerinterval', $domain, $username);
7046: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
1.1517 raeburn 7047: %timerintchk, %timerintenv, %coauthorenv);
1.1169 droeschl 7048:
1.1162 raeburn 7049: foreach my $key (keys(%firstaccess)) {
1.1169 droeschl 7050: my ($cid, $rest) = split(/\0/, $key);
1.1162 raeburn 7051: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
7052: }
1.1169 droeschl 7053:
1.1162 raeburn 7054: foreach my $key (keys(%timerinterval)) {
7055: my ($cid,$rest) = split(/\0/,$key);
7056: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
7057: }
1.1169 droeschl 7058:
1.11 www 7059: my %allroles=();
1.1162 raeburn 7060: my %allgroups=();
1.1517 raeburn 7061: my %gotcoauconfig=();
1.1524 raeburn 7062: my %domdefaults=();
1.11 www 7063:
1.1274 raeburn 7064: for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169 droeschl 7065: my $role = $rolesdump{$area};
7066: $area =~ s/\_\w\w$//;
7067:
7068: my ($trole, $tend, $tstart, $group_privs);
7069:
7070: if ($role =~ /^cr/) {
7071: # Custom role, defined by a user
7072: # e.g., user.role.cr/msu/smith/mynewrole
7073: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
7074: $trole = $1;
7075: ($tend, $tstart) = split('_', $2);
7076: } else {
7077: $trole = $role;
7078: }
7079: } elsif ($role =~ m|^gr/|) {
7080: # Role of member in a group, defined within a course/community
7081: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
7082: ($trole, $tend, $tstart) = split(/_/, $role);
7083: next if $tstart eq '-1';
7084: ($trole, $group_privs) = split(/\//, $trole);
7085: $group_privs = &unescape($group_privs);
7086: } else {
7087: # Just a normal role, defined in roles.tab
7088: ($trole, $tend, $tstart) = split(/_/,$role);
7089: }
7090:
7091: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
7092: $username);
7093: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
7094:
7095: # role expired or not available yet?
7096: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
7097: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
7098:
7099: next if $area eq '' or $trole eq '';
7100:
7101: my $spec = "$trole.$area";
7102: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
7103:
7104: if ($trole =~ /^cr\//) {
7105: # Custom role, defined by a user
7106: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
7107: } elsif ($trole eq 'gr') {
7108: # Role of a member in a group, defined within a course/community
7109: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
7110: next;
7111: } else {
7112: # Normal role, defined in roles.tab
7113: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.1517 raeburn 7114: if (($trole eq 'ca') || ($trole eq 'aa')) {
7115: (undef,my ($audom,$auname)) = split(/\//,$area);
7116: unless ($gotcoauconfig{$area}) {
7117: my @ca_settings = ('authoreditors','coauthorlist','coauthoroptin');
7118: my %info = &userenvironment($audom,$auname,@ca_settings);
7119: $gotcoauconfig{$area} = 1;
7120: foreach my $item (@ca_settings) {
7121: if (exists($info{$item})) {
1.1519 raeburn 7122: my $name = $item;
7123: if ($item eq 'authoreditors') {
7124: $name = 'editors';
1.1524 raeburn 7125: unless ($info{'authoreditors'}) {
7126: my %domdefs;
7127: if (ref($domdefaults{$audom}) eq 'HASH') {
7128: %domdefs = %{$domdefaults{$audom}};
7129: } else {
7130: %domdefs = &get_domain_defaults($audom);
7131: $domdefaults{$audom} = \%domdefs;
7132: }
7133: if ($domdefs{$name} ne '') {
7134: $info{'authoreditors'} = $domdefs{$name};
7135: } else {
7136: $info{'authoreditors'} = 'edit,xml';
7137: }
7138: }
1.1519 raeburn 7139: }
7140: $coauthorenv{"environment.internal.$name.$area"} = $info{$item};
1.1517 raeburn 7141: }
7142: }
7143: }
7144: }
1.1169 droeschl 7145: }
7146:
7147: my $cid = $tdomain.'_'.$trest;
7148: unless ($firstaccchk{$cid}) {
7149: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
7150: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
7151: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
7152: $coursetimerstarts{$cid}{$item};
7153: }
7154: }
7155: $firstaccchk{$cid} = 1;
7156: }
7157: unless ($timerintchk{$cid}) {
7158: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
7159: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
7160: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
7161: $coursetimerintervals{$cid}{$item};
1.1162 raeburn 7162: }
1.12 www 7163: }
1.1169 droeschl 7164: $timerintchk{$cid} = 1;
1.191 harris41 7165: }
1.11 www 7166: }
1.1169 droeschl 7167:
1.1341 raeburn 7168: @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
7169: \%allroles, \%allgroups);
1.1169 droeschl 7170: $env{'user.adv'} = $userroles{'user.adv'};
1.1341 raeburn 7171: $env{'user.rar'} = $userroles{'user.rar'};
1.1169 droeschl 7172:
1.1517 raeburn 7173: return (\%userroles,\%firstaccenv,\%timerintenv,\%coauthorenv);
1.11 www 7174: }
7175:
1.567 raeburn 7176: sub set_arearole {
1.1215 raeburn 7177: my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
7178: unless ($nolog) {
1.567 raeburn 7179: # log the associated role with the area
1.1215 raeburn 7180: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
7181: }
1.743 albertel 7182: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 7183: }
7184:
7185: sub custom_roleprivs {
7186: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
7187: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1250 raeburn 7188: my $homsvr = &homeserver($rauthor,$rdomain);
1.838 albertel 7189: if (&hostname($homsvr) ne '') {
1.567 raeburn 7190: my ($rdummy,$roledef)=
7191: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
7192: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
7193: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
7194: if (defined($syspriv)) {
1.1043 raeburn 7195: if ($trest =~ /^$match_community$/) {
7196: $syspriv =~ s/bre\&S//;
7197: }
1.567 raeburn 7198: $$allroles{'cm./'}.=':'.$syspriv;
7199: $$allroles{$spec.'./'}.=':'.$syspriv;
7200: }
7201: if ($tdomain ne '') {
7202: if (defined($dompriv)) {
7203: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
7204: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
7205: }
7206: if (($trest ne '') && (defined($coursepriv))) {
1.1332 raeburn 7207: if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
7208: my $rolename = $1;
7209: $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
7210: }
1.567 raeburn 7211: $$allroles{'cm.'.$area}.=':'.$coursepriv;
7212: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
7213: }
7214: }
7215: }
7216: }
7217: }
7218:
1.1332 raeburn 7219: sub course_adhocrole_privs {
7220: my ($rolename,$cdom,$cnum,$coursepriv) = @_;
7221: my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
7222: if ($overrides{"internal.adhocpriv.$rolename"}) {
7223: my (%currprivs,%storeprivs);
7224: foreach my $item (split(/:/,$coursepriv)) {
7225: my ($priv,$restrict) = split(/\&/,$item);
7226: $currprivs{$priv} = $restrict;
7227: }
7228: my (%possadd,%possremove,%full);
7229: foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
7230: my ($priv,$restrict)=split(/\&/,$item);
7231: $full{$priv} = $restrict;
7232: }
7233: foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
1.1490 raeburn 7234: next if ($item eq '');
7235: my ($rule,$rest) = split(/=/,$item);
7236: next unless (($rule eq 'off') || ($rule eq 'on'));
7237: foreach my $priv (split(/:/,$rest)) {
7238: if ($priv ne '') {
7239: if ($rule eq 'off') {
7240: $possremove{$priv} = 1;
7241: } else {
7242: $possadd{$priv} = 1;
7243: }
7244: }
7245: }
7246: }
7247: foreach my $priv (sort(keys(%full))) {
7248: if (exists($currprivs{$priv})) {
7249: unless (exists($possremove{$priv})) {
7250: $storeprivs{$priv} = $currprivs{$priv};
7251: }
7252: } elsif (exists($possadd{$priv})) {
7253: $storeprivs{$priv} = $full{$priv};
7254: }
7255: }
7256: $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
7257: }
7258: return $coursepriv;
1.1332 raeburn 7259: }
7260:
1.678 raeburn 7261: sub group_roleprivs {
7262: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
7263: my $access = 1;
7264: my $now = time;
7265: if (($tend!=0) && ($tend<$now)) { $access = 0; }
7266: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
7267: if ($access) {
1.811 albertel 7268: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 7269: $$allgroups{$course}{$group} .=':'.$group_privs;
7270: }
7271: }
1.567 raeburn 7272:
7273: sub standard_roleprivs {
7274: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
7275: if (defined($pr{$trole.':s'})) {
7276: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
7277: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
7278: }
7279: if ($tdomain ne '') {
7280: if (defined($pr{$trole.':d'})) {
7281: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
7282: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
7283: }
7284: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
7285: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
7286: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
7287: }
7288: }
7289: }
7290:
7291: sub set_userprivs {
1.1064 raeburn 7292: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 7293: my $author=0;
7294: my $adv=0;
1.1341 raeburn 7295: my $rar=0;
1.678 raeburn 7296: my %grouproles = ();
7297: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 7298: my @groupkeys;
1.1000 raeburn 7299: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 7300: push(@groupkeys,$role);
7301: }
7302: if (ref($groups_roles) eq 'HASH') {
7303: foreach my $key (keys(%{$groups_roles})) {
7304: unless (grep(/^\Q$key\E$/,@groupkeys)) {
7305: push(@groupkeys,$key);
7306: }
7307: }
7308: }
7309: if (@groupkeys > 0) {
7310: foreach my $role (@groupkeys) {
7311: my ($trole,$area,$sec,$extendedarea);
7312: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
7313: $trole = $1;
7314: $area = $2;
7315: $sec = $3;
7316: $extendedarea = $area.$sec;
7317: if (exists($$allgroups{$area})) {
7318: foreach my $group (keys(%{$$allgroups{$area}})) {
7319: my $spec = $trole.'.'.$extendedarea;
7320: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 7321: $$allgroups{$area}{$group};
1.1064 raeburn 7322: }
1.678 raeburn 7323: }
7324: }
7325: }
7326: }
7327: }
1.800 albertel 7328: foreach my $group (keys(%grouproles)) {
7329: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 7330: }
1.800 albertel 7331: foreach my $role (keys(%{$allroles})) {
7332: my %thesepriv;
1.941 raeburn 7333: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 7334: foreach my $item (split(/:/,$$allroles{$role})) {
7335: if ($item ne '') {
7336: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 7337: if ($restrictions eq '') {
7338: $thesepriv{$privilege}='F';
7339: } elsif ($thesepriv{$privilege} ne 'F') {
7340: $thesepriv{$privilege}.=$restrictions;
7341: }
7342: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1341 raeburn 7343: if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567 raeburn 7344: }
7345: }
7346: my $thesestr='';
1.1104 raeburn 7347: foreach my $priv (sort(keys(%thesepriv))) {
1.800 albertel 7348: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
7349: }
7350: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 7351: }
1.1341 raeburn 7352: return ($author,$adv,$rar);
1.567 raeburn 7353: }
7354:
1.994 raeburn 7355: sub role_status {
1.1104 raeburn 7356: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 7357: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1250 raeburn 7358: my ($one,$two) = split(m{\./},$rolekey,2);
7359: (undef,undef,$$role) = split(/\./,$one,3);
1.994 raeburn 7360: unless (!defined($$role) || $$role eq '') {
1.1251 raeburn 7361: $$where = '/'.$two;
1.994 raeburn 7362: $$trolecode=$$role.'.'.$$where;
7363: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
7364: $$tstatus='is';
1.1104 raeburn 7365: if ($$tstart && $$tstart>$update) {
1.994 raeburn 7366: $$tstatus='future';
1.1034 raeburn 7367: if ($$tstart<$now) {
7368: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 7369: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 7370: my (%allroles,%allgroups,$group_privs,
7371: %groups_roles,@rolecodes);
1.1002 raeburn 7372: my %userroles = (
7373: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
7374: );
1.1064 raeburn 7375: @rolecodes = ('cm');
1.1002 raeburn 7376: my $spec=$$role.'.'.$$where;
7377: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
7378: if ($$role =~ /^cr\//) {
7379: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 7380: push(@rolecodes,'cr');
1.1002 raeburn 7381: } elsif ($$role eq 'gr') {
1.1064 raeburn 7382: push(@rolecodes,$$role);
1.1002 raeburn 7383: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
7384: $env{'user.name'});
1.1064 raeburn 7385: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 7386: (undef,my $group_privs) = split(/\//,$trole);
7387: $group_privs = &unescape($group_privs);
7388: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 7389: 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 7390: &get_groups_roles($tdomain,$trest,
7391: \%course_roles,\@rolecodes,
7392: \%groups_roles);
1.1002 raeburn 7393: } else {
1.1064 raeburn 7394: push(@rolecodes,$$role);
1.1002 raeburn 7395: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
7396: }
1.1341 raeburn 7397: my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
7398: \%groups_roles);
1.1064 raeburn 7399: &appenv(\%userroles,\@rolecodes);
1.1342 raeburn 7400: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002 raeburn 7401: }
7402: }
1.1034 raeburn 7403: $$tstatus = 'is';
1.1002 raeburn 7404: }
1.994 raeburn 7405: }
7406: if ($$tend) {
1.1104 raeburn 7407: if ($$tend<$update) {
1.994 raeburn 7408: $$tstatus='expired';
7409: } elsif ($$tend<$now) {
7410: $$tstatus='will_not';
7411: }
7412: }
7413: }
7414: }
7415: }
7416:
1.1104 raeburn 7417: sub get_groups_roles {
7418: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
7419: return unless((ref($cdom_courseroles) eq 'HASH') &&
7420: (ref($rolecodes) eq 'ARRAY') &&
7421: (ref($groups_roles) eq 'HASH'));
7422: if (keys(%{$cdom_courseroles}) > 0) {
7423: my ($cnum) = ($rest =~ /^($match_courseid)/);
7424: if ($cdom ne '' && $cnum ne '') {
7425: foreach my $key (keys(%{$cdom_courseroles})) {
7426: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
7427: my $crsrole = $1;
7428: my $crssec = $2;
7429: if ($crsrole =~ /^cr/) {
7430: unless (grep(/^cr$/,@{$rolecodes})) {
7431: push(@{$rolecodes},'cr');
7432: }
7433: } else {
7434: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
7435: push(@{$rolecodes},$crsrole);
7436: }
7437: }
7438: my $rolekey = "$crsrole./$cdom/$cnum";
7439: if ($crssec ne '') {
7440: $rolekey .= "/$crssec";
7441: }
7442: $rolekey .= './';
7443: $groups_roles->{$rolekey} = $rolecodes;
7444: }
7445: }
7446: }
7447: }
7448: return;
7449: }
7450:
7451: sub delete_env_groupprivs {
7452: my ($where,$courseroles,$possroles) = @_;
7453: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
7454: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
7455: unless (ref($courseroles->{$udom}) eq 'HASH') {
7456: %{$courseroles->{$udom}} =
7457: &get_my_roles('','','userroles',['active'],
7458: $possroles,[$udom],1);
7459: }
7460: if (ref($courseroles->{$udom}) eq 'HASH') {
7461: foreach my $item (keys(%{$courseroles->{$udom}})) {
7462: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
7463: my $area = '/'.$cdom.'/'.$cnum;
7464: my $privkey = "user.priv.$crsrole.$area";
7465: if ($crssec ne '') {
7466: $privkey .= '/'.$crssec;
7467: }
7468: $privkey .= ".$area/$group";
7469: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
7470: }
7471: }
7472: return;
7473: }
7474:
1.994 raeburn 7475: sub check_adhoc_privs {
1.1329 raeburn 7476: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994 raeburn 7477: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1329 raeburn 7478: if ($sec) {
7479: $cckey .= '/'.$sec;
7480: }
1.1185 raeburn 7481: my $setprivs;
1.994 raeburn 7482: if ($env{$cckey}) {
7483: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104 raeburn 7484: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 7485: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1329 raeburn 7486: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185 raeburn 7487: $setprivs = 1;
1.994 raeburn 7488: }
7489: } else {
1.1330 raeburn 7490: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185 raeburn 7491: $setprivs = 1;
1.994 raeburn 7492: }
1.1185 raeburn 7493: return $setprivs;
1.994 raeburn 7494: }
7495:
7496: sub set_adhoc_privileges {
1.1326 raeburn 7497: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1329 raeburn 7498: my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994 raeburn 7499: my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1329 raeburn 7500: if ($sec ne '') {
7501: $area .= '/'.$sec;
7502: }
1.994 raeburn 7503: my $spec = $role.'.'.$area;
7504: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1215 raeburn 7505: $env{'user.name'},1);
1.1326 raeburn 7506: my %rolehash = ();
1.1332 raeburn 7507: if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
7508: my $rolename = $1;
1.1326 raeburn 7509: &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1332 raeburn 7510: my %domdef = &get_domain_defaults($dcdom);
7511: if (ref($domdef{'adhocroles'}) eq 'HASH') {
7512: if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
7513: &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
7514: }
7515: }
1.1326 raeburn 7516: } else {
7517: &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
7518: }
1.1341 raeburn 7519: my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994 raeburn 7520: &appenv(\%userroles,[$role,'cm']);
1.1342 raeburn 7521: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1402 raeburn 7522: unless (($caller eq 'constructaccess' && $env{'request.course.id'}) ||
7523: ($caller eq 'tiny')) {
1.1088 raeburn 7524: &appenv( {'request.role' => $spec,
7525: 'request.role.domain' => $dcdom,
1.1332 raeburn 7526: 'request.course.sec' => $sec,
1.1088 raeburn 7527: }
7528: );
7529: my $tadv=0;
7530: if (&allowed('adv') eq 'F') { $tadv=1; }
7531: &appenv({'request.role.adv' => $tadv});
7532: }
1.994 raeburn 7533: }
7534:
1.12 www 7535: # --------------------------------------------------------------- get interface
7536:
7537: sub get {
1.131 albertel 7538: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 7539: my $items='';
1.800 albertel 7540: foreach my $item (@$storearr) {
7541: $items.=&escape($item).'&';
1.191 harris41 7542: }
1.12 www 7543: $items=~s/\&$//;
1.620 albertel 7544: if (!$udomain) { $udomain=$env{'user.domain'}; }
7545: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 7546: my $uhome=&homeserver($uname,$udomain);
7547:
1.133 albertel 7548: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 7549: my @pairs=split(/\&/,$rep);
1.273 albertel 7550: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
7551: return @pairs;
7552: }
1.15 www 7553: my %returnhash=();
1.42 www 7554: my $i=0;
1.800 albertel 7555: foreach my $item (@$storearr) {
7556: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 7557: $i++;
1.191 harris41 7558: }
1.15 www 7559: return %returnhash;
1.27 www 7560: }
7561:
7562: # --------------------------------------------------------------- del interface
7563:
7564: sub del {
1.133 albertel 7565: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 7566: my $items='';
1.800 albertel 7567: foreach my $item (@$storearr) {
7568: $items.=&escape($item).'&';
1.191 harris41 7569: }
1.984 neumanie 7570:
1.27 www 7571: $items=~s/\&$//;
1.620 albertel 7572: if (!$udomain) { $udomain=$env{'user.domain'}; }
7573: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 7574: my $uhome=&homeserver($uname,$udomain);
7575: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 7576: }
7577:
7578: # -------------------------------------------------------------- dump interface
7579:
1.1180 droeschl 7580: sub unserialize {
7581: my ($rep, $escapedkeys) = @_;
7582:
7583: return {} if $rep =~ /^error/;
7584:
7585: my %returnhash=();
1.1252 raeburn 7586: foreach my $item (split(/\&/,$rep)) {
1.1180 droeschl 7587: my ($key, $value) = split(/=/, $item, 2);
7588: $key = unescape($key) unless $escapedkeys;
7589: next if $key =~ /^error: 2 /;
1.1252 raeburn 7590: $returnhash{$key} = &thaw_unescape($value);
1.1180 droeschl 7591: }
7592: #return %returnhash;
7593: return \%returnhash;
7594: }
7595:
7596: # see Lond::dump_with_regexp
7597: # if $escapedkeys hash keys won't get unescaped.
1.15 www 7598: sub dump {
1.1462 raeburn 7599: my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys,$encrypt)=@_;
1.755 albertel 7600: if (!$udomain) { $udomain=$env{'user.domain'}; }
7601: if (!$uname) { $uname=$env{'user.name'}; }
7602: my $uhome=&homeserver($uname,$udomain);
1.1167 droeschl 7603:
1.1266 raeburn 7604: if ($regexp) {
7605: $regexp=&escape($regexp);
7606: } else {
7607: $regexp='.';
7608: }
1.1180 droeschl 7609: if (grep { $_ eq $uhome } current_machine_ids()) {
7610: # user is hosted on this machine
1.1266 raeburn 7611: my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
1.1226 raeburn 7612: $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1180 droeschl 7613: return %{unserialize($reply, $escapedkeys)};
7614: }
1.1462 raeburn 7615: my $rep;
7616: if ($encrypt) {
7617: $rep=&reply("encrypt:edump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.1463 raeburn 7618: } else {
1.1462 raeburn 7619: $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
7620: }
1.755 albertel 7621: my @pairs=split(/\&/,$rep);
7622: my %returnhash=();
1.1098 foxr 7623: if (!($rep =~ /^error/ )) {
7624: foreach my $item (@pairs) {
7625: my ($key,$value)=split(/=/,$item,2);
1.1180 droeschl 7626: $key = unescape($key) unless $escapedkeys;
7627: #$key = &unescape($key);
1.1098 foxr 7628: next if ($key =~ /^error: 2 /);
7629: $returnhash{$key}=&thaw_unescape($value);
7630: }
1.755 albertel 7631: }
7632: return %returnhash;
1.407 www 7633: }
7634:
1.1098 foxr 7635:
1.717 albertel 7636: # --------------------------------------------------------- dumpstore interface
7637:
7638: sub dumpstore {
7639: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180 droeschl 7640: # same as dump but keys must be escaped. They may contain colon separated
7641: # lists of values that may themself contain colons (e.g. symbs).
7642: return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717 albertel 7643: }
7644:
1.407 www 7645: # -------------------------------------------------------------- keys interface
7646:
7647: sub getkeys {
7648: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 7649: if (!$udomain) { $udomain=$env{'user.domain'}; }
7650: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 7651: my $uhome=&homeserver($uname,$udomain);
7652: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
7653: my @keyarray=();
1.800 albertel 7654: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 7655: next if ($key =~ /^error: 2 /);
1.800 albertel 7656: push(@keyarray,&unescape($key));
1.407 www 7657: }
7658: return @keyarray;
1.318 matthew 7659: }
7660:
1.319 matthew 7661: # --------------------------------------------------------------- currentdump
7662: sub currentdump {
1.328 matthew 7663: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 7664: $courseid = $env{'request.course.id'} if (! defined($courseid));
7665: $sdom = $env{'user.domain'} if (! defined($sdom));
7666: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 7667: my $uhome = &homeserver($sname,$sdom);
1.1180 droeschl 7668: my $rep;
7669:
7670: if (grep { $_ eq $uhome } current_machine_ids()) {
7671: $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
7672: $courseid)));
7673: } else {
7674: $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
7675: }
7676:
1.318 matthew 7677: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 7678: #
1.318 matthew 7679: my %returnhash=();
1.319 matthew 7680: #
1.1343 raeburn 7681: if ($rep eq 'unknown_cmd') {
1.319 matthew 7682: # an old lond will not know currentdump
7683: # Do a dump and make it look like a currentdump
1.822 albertel 7684: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 7685: return if ($tmp[0] =~ /^(error:|no_such_host)/);
7686: my %hash = @tmp;
7687: @tmp=();
1.424 matthew 7688: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 7689: } else {
7690: my @pairs=split(/\&/,$rep);
1.800 albertel 7691: foreach my $pair (@pairs) {
7692: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 7693: my ($symb,$param) = split(/:/,$key);
7694: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 7695: &thaw_unescape($value);
1.319 matthew 7696: }
1.191 harris41 7697: }
1.12 www 7698: return %returnhash;
1.424 matthew 7699: }
7700:
7701: sub convert_dump_to_currentdump{
7702: my %hash = %{shift()};
7703: my %returnhash;
7704: # Code ripped from lond, essentially. The only difference
7705: # here is the unescaping done by lonnet::dump(). Conceivably
7706: # we might run in to problems with parameter names =~ /^v\./
7707: while (my ($key,$value) = each(%hash)) {
7708: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 7709: $symb = &unescape($symb);
7710: $param = &unescape($param);
1.424 matthew 7711: next if ($v eq 'version' || $symb eq 'keys');
7712: next if (exists($returnhash{$symb}) &&
7713: exists($returnhash{$symb}->{$param}) &&
7714: $returnhash{$symb}->{'v.'.$param} > $v);
7715: $returnhash{$symb}->{$param}=$value;
7716: $returnhash{$symb}->{'v.'.$param}=$v;
7717: }
7718: #
7719: # Remove all of the keys in the hashes which keep track of
7720: # the version of the parameter.
7721: while (my ($symb,$param_hash) = each(%returnhash)) {
7722: # use a foreach because we are going to delete from the hash.
7723: foreach my $key (keys(%$param_hash)) {
7724: delete($param_hash->{$key}) if ($key =~ /^v\./);
7725: }
7726: }
7727: return \%returnhash;
1.12 www 7728: }
7729:
1.627 albertel 7730: # ------------------------------------------------------ critical inc interface
7731:
7732: sub cinc {
7733: return &inc(@_,'critical');
7734: }
7735:
1.449 matthew 7736: # --------------------------------------------------------------- inc interface
7737:
7738: sub inc {
1.627 albertel 7739: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 7740: if (!$udomain) { $udomain=$env{'user.domain'}; }
7741: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 7742: my $uhome=&homeserver($uname,$udomain);
7743: my $items='';
7744: if (! ref($store)) {
7745: # got a single value, so use that instead
7746: $items = &escape($store).'=&';
7747: } elsif (ref($store) eq 'SCALAR') {
7748: $items = &escape($$store).'=&';
7749: } elsif (ref($store) eq 'ARRAY') {
7750: $items = join('=&',map {&escape($_);} @{$store});
7751: } elsif (ref($store) eq 'HASH') {
7752: while (my($key,$value) = each(%{$store})) {
7753: $items.= &escape($key).'='.&escape($value).'&';
7754: }
7755: }
7756: $items=~s/\&$//;
1.627 albertel 7757: if ($critical) {
7758: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
7759: } else {
7760: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
7761: }
1.449 matthew 7762: }
7763:
1.12 www 7764: # --------------------------------------------------------------- put interface
7765:
7766: sub put {
1.1462 raeburn 7767: my ($namespace,$storehash,$udomain,$uname,$encrypt)=@_;
1.620 albertel 7768: if (!$udomain) { $udomain=$env{'user.domain'}; }
7769: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 7770: my $uhome=&homeserver($uname,$udomain);
1.12 www 7771: my $items='';
1.800 albertel 7772: foreach my $item (keys(%$storehash)) {
7773: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 7774: }
1.12 www 7775: $items=~s/\&$//;
1.1462 raeburn 7776: if ($encrypt) {
7777: return &reply("encrypt:put:$udomain:$uname:$namespace:$items",$uhome);
7778: } else {
7779: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
7780: }
1.47 www 7781: }
7782:
1.631 albertel 7783: # ------------------------------------------------------------ newput interface
7784:
7785: sub newput {
7786: my ($namespace,$storehash,$udomain,$uname)=@_;
7787: if (!$udomain) { $udomain=$env{'user.domain'}; }
7788: if (!$uname) { $uname=$env{'user.name'}; }
7789: my $uhome=&homeserver($uname,$udomain);
7790: my $items='';
7791: foreach my $key (keys(%$storehash)) {
7792: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
7793: }
7794: $items=~s/\&$//;
7795: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
7796: }
7797:
7798: # --------------------------------------------------------- putstore interface
7799:
1.524 raeburn 7800: sub putstore {
1.1269 raeburn 7801: my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620 albertel 7802: if (!$udomain) { $udomain=$env{'user.domain'}; }
7803: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 7804: my $uhome=&homeserver($uname,$udomain);
7805: my $items='';
1.715 albertel 7806: foreach my $key (keys(%$storehash)) {
7807: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 7808: }
1.715 albertel 7809: $items=~s/\&$//;
1.716 albertel 7810: my $esc_symb=&escape($symb);
7811: my $esc_v=&escape($version);
1.715 albertel 7812: my $reply =
1.716 albertel 7813: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 7814: $uhome);
1.1269 raeburn 7815: if (($tolog) && ($reply eq 'ok')) {
7816: my $namevalue='';
7817: foreach my $key (keys(%{$storehash})) {
7818: $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
7819: }
1.1434 raeburn 7820: my $ip = &get_requestor_ip();
7821: $namevalue .= 'ip='.&escape($ip).
1.1269 raeburn 7822: '&host='.&escape($perlvar{'lonHostID'}).
7823: '&version='.$esc_v.
7824: '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
1.1494 raeburn 7825: &courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
1.1269 raeburn 7826: }
1.715 albertel 7827: if ($reply eq 'unknown_cmd') {
1.716 albertel 7828: # gfall back to way things use to be done
1.715 albertel 7829: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
7830: $uname);
1.524 raeburn 7831: }
1.715 albertel 7832: return $reply;
7833: }
7834:
7835: sub old_putstore {
1.716 albertel 7836: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
7837: if (!$udomain) { $udomain=$env{'user.domain'}; }
7838: if (!$uname) { $uname=$env{'user.name'}; }
7839: my $uhome=&homeserver($uname,$udomain);
7840: my %newstorehash;
1.800 albertel 7841: foreach my $item (keys(%$storehash)) {
7842: my $key = $version.':'.&escape($symb).':'.$item;
7843: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 7844: }
7845: my $items='';
7846: my %allitems = ();
1.800 albertel 7847: foreach my $item (keys(%newstorehash)) {
7848: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 7849: my $key = $1.':keys:'.$2;
7850: $allitems{$key} .= $3.':';
7851: }
1.800 albertel 7852: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 7853: }
1.800 albertel 7854: foreach my $item (keys(%allitems)) {
7855: $allitems{$item} =~ s/\:$//;
7856: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 7857: }
7858: $items=~s/\&$//;
7859: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 7860: }
7861:
1.47 www 7862: # ------------------------------------------------------ critical put interface
7863:
7864: sub cput {
1.134 albertel 7865: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 7866: if (!$udomain) { $udomain=$env{'user.domain'}; }
7867: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 7868: my $uhome=&homeserver($uname,$udomain);
1.47 www 7869: my $items='';
1.800 albertel 7870: foreach my $item (keys(%$storehash)) {
7871: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 7872: }
1.47 www 7873: $items=~s/\&$//;
1.134 albertel 7874: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 7875: }
7876:
7877: # -------------------------------------------------------------- eget interface
7878:
7879: sub eget {
1.133 albertel 7880: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 7881: my $items='';
1.800 albertel 7882: foreach my $item (@$storearr) {
7883: $items.=&escape($item).'&';
1.191 harris41 7884: }
1.12 www 7885: $items=~s/\&$//;
1.620 albertel 7886: if (!$udomain) { $udomain=$env{'user.domain'}; }
7887: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 7888: my $uhome=&homeserver($uname,$udomain);
7889: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 7890: my @pairs=split(/\&/,$rep);
7891: my %returnhash=();
1.42 www 7892: my $i=0;
1.800 albertel 7893: foreach my $item (@$storearr) {
7894: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 7895: $i++;
1.191 harris41 7896: }
1.12 www 7897: return %returnhash;
7898: }
7899:
1.667 albertel 7900: # ------------------------------------------------------------ tmpput interface
7901: sub tmpput {
1.802 raeburn 7902: my ($storehash,$server,$context)=@_;
1.667 albertel 7903: my $items='';
1.800 albertel 7904: foreach my $item (keys(%$storehash)) {
7905: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 7906: }
7907: $items=~s/\&$//;
1.802 raeburn 7908: if (defined($context)) {
7909: $items .= ':'.&escape($context);
7910: }
1.667 albertel 7911: return &reply("tmpput:$items",$server);
7912: }
7913:
7914: # ------------------------------------------------------------ tmpget interface
7915: sub tmpget {
1.688 albertel 7916: my ($token,$server)=@_;
7917: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
7918: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 7919: my %returnhash;
1.1328 raeburn 7920: if ($rep =~ /^(con_lost|error|no_such_host)/i) {
7921: return %returnhash;
7922: }
1.667 albertel 7923: foreach my $item (split(/\&/,$rep)) {
7924: my ($key,$value)=split(/=/,$item);
7925: $returnhash{&unescape($key)}=&thaw_unescape($value);
7926: }
7927: return %returnhash;
7928: }
7929:
1.1113 raeburn 7930: # ------------------------------------------------------------ tmpdel interface
1.688 albertel 7931: sub tmpdel {
7932: my ($token,$server)=@_;
7933: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
7934: return &reply("tmpdel:$token",$server);
7935: }
7936:
1.1198 raeburn 7937: # ------------------------------------------------------------ get_timebased_id
7938:
7939: sub get_timebased_id {
7940: my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
7941: $maxtries) = @_;
7942: my ($newid,$error,$dellock);
7943: unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
7944: return ('','ok','invalid call to get suffix');
7945: }
7946:
7947: # set defaults for any optional args for which values were not supplied
7948: if ($who eq '') {
7949: $who = $env{'user.name'}.':'.$env{'user.domain'};
7950: }
7951: if (!$locktries) {
7952: $locktries = 3;
7953: }
7954: if (!$maxtries) {
7955: $maxtries = 10;
7956: }
7957:
7958: if (($cdom eq '') || ($cnum eq '')) {
7959: if ($env{'request.course.id'}) {
7960: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7961: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7962: }
7963: if (($cdom eq '') || ($cnum eq '')) {
7964: return ('','ok','call to get suffix not in course context');
7965: }
7966: }
7967:
7968: # construct locking item
7969: my $lockhash = {
7970: $prefix."\0".'locked_'.$keyid => $who,
7971: };
7972: my $tries = 0;
7973:
7974: # attempt to get lock on nohist_$namespace file
1.1494 raeburn 7975: my $gotlock = &newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
1.1198 raeburn 7976: while (($gotlock ne 'ok') && $tries <$locktries) {
7977: $tries ++;
7978: sleep 1;
1.1494 raeburn 7979: $gotlock = &newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
1.1198 raeburn 7980: }
7981:
7982: # attempt to get unique identifier, based on current timestamp
7983: if ($gotlock eq 'ok') {
1.1494 raeburn 7984: my %inuse = &dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
1.1198 raeburn 7985: my $id = time;
7986: $newid = $id;
1.1268 raeburn 7987: if ($idtype eq 'addcode') {
7988: $newid .= &sixnum_code();
7989: }
1.1198 raeburn 7990: my $idtries = 0;
7991: while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
7992: if ($idtype eq 'concat') {
7993: $newid = $id.$idtries;
1.1268 raeburn 7994: } elsif ($idtype eq 'addcode') {
7995: $newid = $newid.&sixnum_code();
1.1198 raeburn 7996: } else {
7997: $newid ++;
7998: }
7999: $idtries ++;
8000: }
8001: if (!exists($inuse{$prefix."\0".$newid})) {
8002: my %new_item = (
8003: $prefix."\0".$newid => $who,
8004: );
1.1494 raeburn 8005: my $putresult = &put('nohist_'.$namespace,\%new_item,
1.1198 raeburn 8006: $cdom,$cnum);
8007: if ($putresult ne 'ok') {
8008: undef($newid);
8009: $error = 'error saving new item: '.$putresult;
8010: }
8011: } else {
1.1268 raeburn 8012: undef($newid);
1.1198 raeburn 8013: $error = ('error: no unique suffix available for the new item ');
8014: }
8015: # remove lock
8016: my @del_lock = ($prefix."\0".'locked_'.$keyid);
8017: $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
8018: } else {
8019: $error = "error: could not obtain lockfile\n";
8020: $dellock = 'ok';
1.1276 raeburn 8021: if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
8022: $dellock = 'nolock';
8023: }
1.1198 raeburn 8024: }
8025: return ($newid,$dellock,$error);
8026: }
8027:
1.1268 raeburn 8028: sub sixnum_code {
8029: my $code;
8030: for (0..6) {
8031: $code .= int( rand(9) );
8032: }
8033: return $code;
8034: }
8035:
1.765 albertel 8036: # -------------------------------------------------- portfolio access checking
8037:
8038: sub portfolio_access {
1.1270 raeburn 8039: my ($requrl,$clientip) = @_;
1.765 albertel 8040: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1270 raeburn 8041: my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814 raeburn 8042: if ($result) {
8043: my %setters;
8044: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
1.1473 raeburn 8045: my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
8046: &Apache::loncommon::blockcheck(\%setters,'port',$clientip,$unum,$udom);
8047: if (($startblock && $endblock) || ($by_ip)) {
1.814 raeburn 8048: return 'B';
8049: }
8050: } else {
1.1473 raeburn 8051: my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
8052: &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
8053: if (($startblock && $endblock) || ($by_ip)) {
1.814 raeburn 8054: return 'B';
8055: }
8056: }
8057: }
1.765 albertel 8058: if ($result eq 'ok') {
1.766 albertel 8059: return 'F';
1.765 albertel 8060: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 8061: return 'A';
1.765 albertel 8062: }
1.766 albertel 8063: return '';
1.765 albertel 8064: }
8065:
8066: sub get_portfolio_access {
1.1521 raeburn 8067: my ($udom,$unum,$file_name,$group,$clientip,$access_hash,$portaccessref) = @_;
1.767 albertel 8068:
8069: if (!ref($access_hash)) {
8070: my $current_perms = &get_portfile_permissions($udom,$unum);
8071: my %access_controls = &get_access_controls($current_perms,$group,
8072: $file_name);
8073: $access_hash = $access_controls{$file_name};
8074: }
8075:
1.1521 raeburn 8076: my $portaccess;
8077: if (ref($portaccess) eq 'SCALAR') {
8078: $portaccess = $$portaccessref;
8079: } else {
8080: $portaccess = &usertools_access($unum,$udom,'portaccess',undef,'tools');
8081: }
8082:
1.1522 raeburn 8083: my ($public,$guest,@domains,@users,@courses,@groups,@ips,@userips);
1.765 albertel 8084: my $now = time;
8085: if (ref($access_hash) eq 'HASH') {
8086: foreach my $key (keys(%{$access_hash})) {
8087: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
1.1521 raeburn 8088: next if (($scope ne 'ip') && ($portaccess == 0));
1.765 albertel 8089: if ($start > $now) {
8090: next;
8091: }
8092: if ($end && $end<$now) {
8093: next;
8094: }
8095: if ($scope eq 'public') {
8096: $public = $key;
8097: last;
8098: } elsif ($scope eq 'guest') {
8099: $guest = $key;
8100: } elsif ($scope eq 'domains') {
8101: push(@domains,$key);
8102: } elsif ($scope eq 'users') {
8103: push(@users,$key);
8104: } elsif ($scope eq 'course') {
8105: push(@courses,$key);
8106: } elsif ($scope eq 'group') {
8107: push(@groups,$key);
1.1270 raeburn 8108: } elsif ($scope eq 'ip') {
8109: push(@ips,$key);
1.1522 raeburn 8110: } elsif ($scope eq 'userip') {
8111: push(@userips,$key);
1.765 albertel 8112: }
8113: }
8114: if ($public) {
8115: return 'ok';
1.1270 raeburn 8116: } elsif (@ips > 0) {
8117: my $allowed;
8118: foreach my $ipkey (@ips) {
8119: if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
8120: if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
8121: $allowed = 1;
8122: last;
8123: }
8124: }
8125: }
8126: if ($allowed) {
8127: return 'ok';
8128: }
1.1522 raeburn 8129: } elsif (@userips > 0) {
8130: my $allowed;
8131: foreach my $useripkey (@userips) {
8132: if (ref($access_hash->{$useripkey}{'ip'}) eq 'ARRAY') {
8133: if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$useripkey}{'ip'}}),$clientip)) {
8134: $allowed = 1;
8135: last;
8136: }
8137: }
8138: }
8139: if ($allowed) {
8140: return 'ok';
8141: }
1.765 albertel 8142: }
8143: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
8144: if ($guest) {
8145: return $guest;
8146: }
8147: } else {
8148: if (@domains > 0) {
8149: foreach my $domkey (@domains) {
8150: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
8151: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
8152: return 'ok';
8153: }
8154: }
8155: }
8156: }
8157: if (@users > 0) {
8158: foreach my $userkey (@users) {
1.865 raeburn 8159: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
8160: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
8161: if (ref($item) eq 'HASH') {
8162: if (($item->{'uname'} eq $env{'user.name'}) &&
8163: ($item->{'udom'} eq $env{'user.domain'})) {
8164: return 'ok';
8165: }
8166: }
8167: }
8168: }
1.765 albertel 8169: }
8170: }
8171: my %roleshash;
8172: my @courses_and_groups = @courses;
8173: push(@courses_and_groups,@groups);
8174: if (@courses_and_groups > 0) {
8175: my (%allgroups,%allroles);
8176: my ($start,$end,$role,$sec,$group);
8177: foreach my $envkey (%env) {
1.1060 raeburn 8178: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 8179: my $cid = $2.'_'.$3;
8180: if ($1 eq 'gr') {
8181: $group = $4;
8182: $allgroups{$cid}{$group} = $env{$envkey};
8183: } else {
8184: if ($4 eq '') {
8185: $sec = 'none';
8186: } else {
8187: $sec = $4;
8188: }
8189: $allroles{$cid}{$1}{$sec} = $env{$envkey};
8190: }
1.811 albertel 8191: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 8192: my $cid = $2.'_'.$3;
8193: if ($4 eq '') {
8194: $sec = 'none';
8195: } else {
8196: $sec = $4;
8197: }
8198: $allroles{$cid}{$1}{$sec} = $env{$envkey};
8199: }
8200: }
8201: if (keys(%allroles) == 0) {
8202: return;
8203: }
8204: foreach my $key (@courses_and_groups) {
8205: my %content = %{$$access_hash{$key}};
8206: my $cnum = $content{'number'};
8207: my $cdom = $content{'domain'};
8208: my $cid = $cdom.'_'.$cnum;
8209: if (!exists($allroles{$cid})) {
8210: next;
8211: }
8212: foreach my $role_id (keys(%{$content{'roles'}})) {
8213: my @sections = @{$content{'roles'}{$role_id}{'section'}};
8214: my @groups = @{$content{'roles'}{$role_id}{'group'}};
8215: my @status = @{$content{'roles'}{$role_id}{'access'}};
8216: my @roles = @{$content{'roles'}{$role_id}{'role'}};
8217: foreach my $role (keys(%{$allroles{$cid}})) {
8218: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
8219: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
8220: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
8221: if (grep/^all$/,@sections) {
8222: return 'ok';
8223: } else {
8224: if (grep/^$sec$/,@sections) {
8225: return 'ok';
8226: }
8227: }
8228: }
8229: }
8230: if (keys(%{$allgroups{$cid}}) == 0) {
8231: if (grep/^none$/,@groups) {
8232: return 'ok';
8233: }
8234: } else {
8235: if (grep/^all$/,@groups) {
8236: return 'ok';
8237: }
8238: foreach my $group (keys(%{$allgroups{$cid}})) {
8239: if (grep/^$group$/,@groups) {
8240: return 'ok';
8241: }
8242: }
8243: }
8244: }
8245: }
8246: }
8247: }
8248: }
8249: if ($guest) {
8250: return $guest;
8251: }
8252: }
8253: }
8254: return;
8255: }
8256:
8257: sub course_group_datechecker {
8258: my ($dates,$now,$status) = @_;
8259: my ($start,$end) = split(/\./,$dates);
8260: if (!$start && !$end) {
8261: return 'ok';
8262: }
8263: if (grep/^active$/,@{$status}) {
8264: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
8265: return 'ok';
8266: }
8267: }
8268: if (grep/^previous$/,@{$status}) {
8269: if ($end > $now ) {
8270: return 'ok';
8271: }
8272: }
8273: if (grep/^future$/,@{$status}) {
8274: if ($start > $now) {
8275: return 'ok';
8276: }
8277: }
8278: return;
8279: }
8280:
8281: sub parse_portfolio_url {
8282: my ($url) = @_;
8283:
8284: my ($type,$udom,$unum,$group,$file_name);
8285:
1.823 albertel 8286: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 8287: $type = 1;
8288: $udom = $1;
8289: $unum = $2;
8290: $file_name = $3;
1.823 albertel 8291: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 8292: $type = 2;
8293: $udom = $1;
8294: $unum = $2;
8295: $group = $3;
8296: $file_name = $3.'/'.$4;
8297: }
8298: if (wantarray) {
8299: return ($type,$udom,$unum,$file_name,$group);
8300: }
8301: return $type;
8302: }
8303:
8304: sub is_portfolio_url {
8305: my ($url) = @_;
8306: return scalar(&parse_portfolio_url($url));
8307: }
8308:
1.798 raeburn 8309: sub is_portfolio_file {
8310: my ($file) = @_;
1.820 raeburn 8311: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 8312: return 1;
8313: }
8314: return;
8315: }
8316:
1.1504 raeburn 8317: sub is_coursetool_logo {
8318: my ($uri) = @_;
8319: if ($env{'request.course.id'}) {
8320: my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
8321: if ($uri =~ m{^/*uploaded\Q$courseurl\E/toollogo/\d+/[^/]+$}) {
8322: return 1;
8323: }
8324: }
8325: return;
8326: }
8327:
1.976 raeburn 8328: sub usertools_access {
1.1084 raeburn 8329: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 8330: my ($access,%tools);
8331: if ($context eq '') {
8332: $context = 'tools';
8333: }
8334: if ($context eq 'requestcourses') {
8335: %tools = (
8336: official => 1,
8337: unofficial => 1,
1.1006 raeburn 8338: community => 1,
1.1246 raeburn 8339: textbook => 1,
1.1305 raeburn 8340: placement => 1,
1.1368 raeburn 8341: lti => 1,
1.985 raeburn 8342: );
1.1183 raeburn 8343: } elsif ($context eq 'requestauthor') {
8344: %tools = (
8345: requestauthor => 1,
8346: );
1.1517 raeburn 8347: } elsif ($context eq 'authordefaults') {
8348: %tools = (
8349: webdav => 1,
8350: );
1.985 raeburn 8351: } else {
8352: %tools = (
8353: aboutme => 1,
8354: blog => 1,
1.1526 raeburn 8355: webdav => 1,
1.985 raeburn 8356: portfolio => 1,
1.1517 raeburn 8357: portaccess => 1,
1.1489 raeburn 8358: timezone => 1,
1.985 raeburn 8359: );
8360: }
1.976 raeburn 8361: return if (!defined($tools{$tool}));
8362:
1.1242 raeburn 8363: if (($udom eq '') || ($uname eq '')) {
1.976 raeburn 8364: $udom = $env{'user.domain'};
8365: $uname = $env{'user.name'};
8366: }
8367:
1.978 raeburn 8368: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
8369: if ($action ne 'reload') {
1.985 raeburn 8370: if ($context eq 'requestcourses') {
8371: return $env{'environment.canrequest.'.$tool};
1.1183 raeburn 8372: } elsif ($context eq 'requestauthor') {
8373: return $env{'environment.canrequest.author'};
1.1517 raeburn 8374: } elsif ($context eq 'authordefaults') {
8375: if ($tool eq 'webdav') {
8376: return $env{'environment.availabletools.'.$tool};
8377: }
1.985 raeburn 8378: } else {
8379: return $env{'environment.availabletools.'.$tool};
8380: }
8381: }
1.976 raeburn 8382: }
8383:
1.1183 raeburn 8384: my ($toolstatus,$inststatus,$envkey);
8385: if ($context eq 'requestauthor') {
1.1517 raeburn 8386: $envkey = $context;
8387: } elsif ($context eq 'authordefaults') {
8388: if ($tool eq 'webdav') {
8389: $envkey = 'tools.'.$tool;
8390: }
1.1183 raeburn 8391: } else {
8392: $envkey = $context.'.'.$tool;
8393: }
1.976 raeburn 8394:
1.985 raeburn 8395: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
8396: ($action ne 'reload')) {
1.1183 raeburn 8397: $toolstatus = $env{'environment.'.$envkey};
1.976 raeburn 8398: $inststatus = $env{'environment.inststatus'};
8399: } else {
1.1084 raeburn 8400: if (ref($userenvref) eq 'HASH') {
1.1183 raeburn 8401: $toolstatus = $userenvref->{$envkey};
1.1084 raeburn 8402: $inststatus = $userenvref->{'inststatus'};
8403: } else {
1.1183 raeburn 8404: my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
8405: $toolstatus = $userenv{$envkey};
1.1084 raeburn 8406: $inststatus = $userenv{'inststatus'};
8407: }
1.976 raeburn 8408: }
8409:
8410: if ($toolstatus ne '') {
8411: if ($toolstatus) {
8412: $access = 1;
8413: } else {
8414: $access = 0;
8415: }
8416: return $access;
8417: }
8418:
1.1084 raeburn 8419: my ($is_adv,%domdef);
8420: if (ref($is_advref) eq 'HASH') {
8421: $is_adv = $is_advref->{'is_adv'};
8422: } else {
8423: $is_adv = &is_advanced_user($udom,$uname);
8424: }
8425: if (ref($domdefref) eq 'HASH') {
8426: %domdef = %{$domdefref};
8427: } else {
8428: %domdef = &get_domain_defaults($udom);
8429: }
1.976 raeburn 8430: if (ref($domdef{$tool}) eq 'HASH') {
8431: if ($is_adv) {
8432: if ($domdef{$tool}{'_LC_adv'} ne '') {
8433: if ($domdef{$tool}{'_LC_adv'}) {
8434: $access = 1;
8435: } else {
8436: $access = 0;
8437: }
8438: return $access;
8439: }
8440: }
8441: if ($inststatus ne '') {
8442: my ($hasaccess,$hasnoaccess);
8443: foreach my $affiliation (split(/:/,$inststatus)) {
8444: if ($domdef{$tool}{$affiliation} ne '') {
8445: if ($domdef{$tool}{$affiliation}) {
8446: $hasaccess = 1;
8447: } else {
8448: $hasnoaccess = 1;
8449: }
8450: }
8451: }
8452: if ($hasaccess || $hasnoaccess) {
8453: if ($hasaccess) {
8454: $access = 1;
8455: } elsif ($hasnoaccess) {
8456: $access = 0;
8457: }
8458: return $access;
8459: }
8460: } else {
8461: if ($domdef{$tool}{'default'} ne '') {
8462: if ($domdef{$tool}{'default'}) {
8463: $access = 1;
8464: } elsif ($domdef{$tool}{'default'} == 0) {
8465: $access = 0;
8466: }
8467: return $access;
8468: }
8469: }
8470: } else {
1.1177 raeburn 8471: if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985 raeburn 8472: $access = 1;
8473: } else {
8474: $access = 0;
8475: }
1.976 raeburn 8476: return $access;
8477: }
8478: }
8479:
1.1050 raeburn 8480: sub is_course_owner {
8481: my ($cdom,$cnum,$udom,$uname) = @_;
8482: if (($udom eq '') || ($uname eq '')) {
8483: $udom = $env{'user.domain'};
8484: $uname = $env{'user.name'};
8485: }
8486: unless (($udom eq '') || ($uname eq '')) {
8487: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
8488: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
8489: return 1;
8490: } else {
1.1494 raeburn 8491: my %courseinfo = &coursedescription($cdom.'/'.$cnum);
1.1050 raeburn 8492: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
8493: return 1;
8494: }
8495: }
8496: }
8497: }
8498: return;
8499: }
8500:
1.976 raeburn 8501: sub is_advanced_user {
1.1512 raeburn 8502: my ($udom,$uname,$nocache) = @_;
8503: my ($is_adv,$is_author,$use_cache,$hashid);
1.1085 raeburn 8504: if ($udom ne '' && $uname ne '') {
8505: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128 raeburn 8506: if (wantarray) {
8507: return ($env{'user.adv'},$env{'user.author'});
8508: } else {
8509: return $env{'user.adv'};
8510: }
1.1512 raeburn 8511: } elsif (!$nocache) {
8512: $use_cache = 1;
8513: $hashid = "$udom:$uname";
8514: my ($info,$cached)=&is_cached_new('isadvau',$hashid);
8515: if ($cached) {
8516: ($is_adv,$is_author) = split(/:/,$info);
8517: if (wantarray) {
8518: return ($is_adv,$is_author);
8519: }
8520: return $is_adv;
8521: }
1.1085 raeburn 8522: }
8523: }
1.976 raeburn 8524: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
8525: my %allroles;
8526: foreach my $role (keys(%roleshash)) {
8527: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
8528: my $area = '/'.$tdomain.'/'.$trest;
8529: if ($sec ne '') {
8530: $area .= '/'.$sec;
8531: }
8532: if (($area ne '') && ($trole ne '')) {
8533: my $spec=$trole.'.'.$area;
8534: if ($trole =~ /^cr\//) {
8535: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
8536: } elsif ($trole ne 'gr') {
8537: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
8538: }
1.1128 raeburn 8539: if ($trole eq 'au') {
8540: $is_author = 1;
8541: }
1.976 raeburn 8542: }
8543: }
8544: foreach my $role (keys(%allroles)) {
8545: last if ($is_adv);
8546: foreach my $item (split(/:/,$allroles{$role})) {
8547: if ($item ne '') {
8548: my ($privilege,$restrictions)=split(/&/,$item);
8549: if ($privilege eq 'adv') {
8550: $is_adv = 1;
8551: last;
8552: }
8553: }
8554: }
8555: }
1.1512 raeburn 8556: if ($use_cache) {
8557: my $cachetime = 600;
8558: &do_cache_new('isadvau',$hashid,$is_adv.':'.$is_author,$cachetime);
8559: }
1.1128 raeburn 8560: if (wantarray) {
8561: return ($is_adv,$is_author);
8562: }
1.976 raeburn 8563: return $is_adv;
8564: }
1.798 raeburn 8565:
1.1035 raeburn 8566: sub check_can_request {
1.1368 raeburn 8567: my ($dom,$can_request,$request_domains,$uname,$udom) = @_;
1.1035 raeburn 8568: my $canreq = 0;
1.1368 raeburn 8569: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
8570: $uname = $env{'user.name'};
8571: $udom = $env{'user.domain'};
8572: }
1.1035 raeburn 8573: my ($types,$typename) = &Apache::loncommon::course_types();
8574: my @options = ('approval','validate','autolimit');
8575: my $optregex = join('|',@options);
8576: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
1.1486 raeburn 8577: my %willtrust;
1.1035 raeburn 8578: foreach my $type (@{$types}) {
1.1368 raeburn 8579: if (&usertools_access($uname,$udom,$type,undef,
8580: 'requestcourses')) {
1.1035 raeburn 8581: $canreq ++;
1.1036 raeburn 8582: if (ref($request_domains) eq 'HASH') {
1.1368 raeburn 8583: push(@{$request_domains->{$type}},$udom);
1.1036 raeburn 8584: }
1.1368 raeburn 8585: if ($dom eq $udom) {
1.1035 raeburn 8586: $can_request->{$type} = 1;
8587: }
8588: }
1.1368 raeburn 8589: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
8590: ($env{'environment.reqcrsotherdom.'.$type} ne '')) {
1.1035 raeburn 8591: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
8592: if (@curr > 0) {
1.1036 raeburn 8593: foreach my $item (@curr) {
8594: if (ref($request_domains) eq 'HASH') {
8595: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
8596: if ($otherdom ne '') {
1.1486 raeburn 8597: unless (exists($willtrust{$otherdom})) {
8598: $willtrust{$otherdom} = &will_trust('reqcrs',$env{'user.domain'},$otherdom);
8599: }
8600: if ($willtrust{$otherdom}) {
8601: if (ref($request_domains->{$type}) eq 'ARRAY') {
8602: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
8603: push(@{$request_domains->{$type}},$otherdom);
8604: }
8605: } else {
1.1036 raeburn 8606: push(@{$request_domains->{$type}},$otherdom);
8607: }
8608: }
8609: }
8610: }
8611: }
1.1368 raeburn 8612: unless ($dom eq $env{'user.domain'}) {
1.1036 raeburn 8613: $canreq ++;
1.1035 raeburn 8614: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
8615: $can_request->{$type} = 1;
8616: }
8617: }
8618: }
8619: }
8620: }
8621: }
8622: return $canreq;
8623: }
8624:
1.341 www 8625: # ---------------------------------------------- Custom access rule evaluation
8626:
8627: sub customaccess {
8628: my ($priv,$uri)=@_;
1.807 albertel 8629: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 8630: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 8631: $udom = &LONCAPA::clean_domain($udom);
8632: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 8633: my $access=0;
1.800 albertel 8634: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 8635: my ($effect,$realm,$role,$type)=split(/\:/,$right);
8636: if ($type eq 'user') {
8637: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 8638: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 8639: if ($tdom) {
8640: if ($tdom ne $env{'user.domain'}) { next; }
8641: }
1.896 albertel 8642: if ($tuname) {
8643: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 8644: }
8645: $access=($effect eq 'allow');
8646: last;
8647: }
8648: } else {
8649: if ($role) {
8650: if ($role ne $urole) { next; }
8651: }
8652: foreach my $scope (split(/\s*\,\s*/,$realm)) {
8653: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
8654: if ($tdom) {
8655: if ($tdom ne $udom) { next; }
8656: }
8657: if ($tcrs) {
8658: if ($tcrs ne $ucrs) { next; }
8659: }
8660: if ($tsec) {
8661: if ($tsec ne $usec) { next; }
8662: }
8663: $access=($effect eq 'allow');
8664: last;
8665: }
8666: if ($realm eq '' && $role eq '') {
8667: $access=($effect eq 'allow');
8668: }
1.402 bowersj2 8669: }
1.341 www 8670: }
8671: return $access;
8672: }
8673:
1.103 harris41 8674: # ------------------------------------------------- Check for a user privilege
1.12 www 8675:
8676: sub allowed {
1.1461 raeburn 8677: my ($priv,$uri,$symb,$role,$clientip,$noblockcheck,$ignorecache,$nodeeplinkcheck,$nodeeplinkout)=@_;
1.705 albertel 8678: my $ver_orguri=$uri;
1.439 www 8679: $uri=&deversion($uri);
1.152 www 8680: my $orguri=$uri;
1.52 www 8681: $uri=&declutter($uri);
1.809 raeburn 8682:
1.810 raeburn 8683: if ($priv eq 'evb') {
1.1478 raeburn 8684: # Evade communication block restrictions for specified role in a course or domain
1.810 raeburn 8685: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
8686: return $1;
8687: } else {
8688: return;
8689: }
8690: }
8691:
1.620 albertel 8692: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 8693: # Free bre access to adm and meta resources
1.1436 raeburn 8694: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|viewclasslist|aboutme|ext\.tool)$}))
1.769 albertel 8695: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
8696: && ($priv eq 'bre')) {
1.14 www 8697: return 'F';
1.159 www 8698: }
8699:
1.545 banghart 8700: # Free bre access to user's own portfolio contents
1.714 raeburn 8701: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 8702: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 8703: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 8704: my %setters;
1.1473 raeburn 8705: my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
8706: &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
8707: if (($startblock && $endblock) || ($by_ip)) {
1.814 raeburn 8708: return 'B';
8709: } else {
8710: return 'F';
8711: }
1.545 banghart 8712: }
8713:
1.762 raeburn 8714: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 8715: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
8716: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
8717: if (exists($env{'request.course.id'})) {
8718: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
8719: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
8720: if (($domain eq $cdom) && ($name eq $cnum)) {
8721: my $courseprivid=$env{'request.course.id'};
8722: $courseprivid=~s/\_/\//;
8723: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
8724: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
8725: return $1;
1.762 raeburn 8726: } else {
8727: if ($env{'request.course.sec'}) {
8728: $courseprivid.='/'.$env{'request.course.sec'};
8729: }
8730: if ($env{'user.priv.'.$env{'request.role'}.'./'.
8731: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
8732: return $2;
8733: }
1.714 raeburn 8734: }
8735: }
8736: }
8737: }
8738:
1.159 www 8739: # Free bre to public access
8740:
8741: if ($priv eq 'bre') {
1.1362 raeburn 8742: my $copyright;
8743: unless ($uri =~ /ext\.tool/) {
8744: $copyright=&metadata($uri,'copyright');
8745: }
1.620 albertel 8746: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 8747: return 'F';
8748: }
1.238 www 8749: if ($copyright eq 'priv') {
8750: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 8751: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 8752: return '';
8753: }
8754: }
8755: if ($copyright eq 'domain') {
8756: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 8757: unless (($env{'user.domain'} eq $1) ||
8758: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 8759: return '';
8760: }
1.262 matthew 8761: }
1.620 albertel 8762: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 8763: # Library role, so allow browsing of resources in this domain.
8764: return 'F';
1.238 www 8765: }
1.341 www 8766: if ($copyright eq 'custom') {
8767: unless (&customaccess($priv,$uri)) { return ''; }
8768: }
1.14 www 8769: }
1.264 matthew 8770: # Domain coordinator is trying to create a course
1.620 albertel 8771: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 8772: # uri is the requested domain in this case.
8773: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 8774: # a role of dc for the domain in question.
1.620 albertel 8775: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 8776: }
1.29 www 8777:
1.52 www 8778: my $thisallowed='';
8779: my $statecond=0;
8780: my $courseprivid='';
8781:
1.1039 raeburn 8782: my $ownaccess;
1.1043 raeburn 8783: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 8784: if (($priv eq 'bro') && ($env{'user.author'})) {
8785: if ($uri eq '') {
8786: $ownaccess = 1;
8787: } else {
8788: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
8789: my $udom = $env{'user.domain'};
8790: my $uname = $env{'user.name'};
8791: if ($uri =~ m{^\Q$udom\E/?$}) {
8792: $ownaccess = 1;
1.1040 raeburn 8793: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 8794: unless ($uri =~ m{\.\./}) {
8795: $ownaccess = 1;
8796: }
8797: } elsif (($udom ne 'public') && ($uname ne 'public')) {
8798: my $now = time;
8799: if ($uri =~ m{^([^/]+)/?$}) {
8800: my $adom = $1;
8801: foreach my $key (keys(%env)) {
1.1042 raeburn 8802: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1452 raeburn 8803: my ($start,$end) = split(/\./,$env{$key});
8804: if (($now >= $start) && (!$end || $end > $now)) {
1.1039 raeburn 8805: $ownaccess = 1;
8806: last;
8807: }
8808: }
8809: }
8810: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
8811: my $adom = $1;
8812: my $aname = $2;
1.1042 raeburn 8813: foreach my $role ('ca','aa') {
8814: if ($env{"user.role.$role./$adom/$aname"}) {
8815: my ($start,$end) =
1.1452 raeburn 8816: split(/\./,$env{"user.role.$role./$adom/$aname"});
8817: if (($now >= $start) && (!$end || $end > $now)) {
1.1042 raeburn 8818: $ownaccess = 1;
8819: last;
8820: }
1.1039 raeburn 8821: }
8822: }
8823: }
8824: }
8825: }
8826: }
8827: }
8828:
1.52 www 8829: # Course
8830:
1.620 albertel 8831: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 8832: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 8833: $thisallowed.=$1;
8834: }
1.52 www 8835: }
1.29 www 8836:
1.52 www 8837: # Domain
8838:
1.620 albertel 8839: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 8840: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 8841: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 8842: $thisallowed.=$1;
8843: }
1.12 www 8844: }
1.52 www 8845:
1.1141 raeburn 8846: # User who is not author or co-author might still be able to edit
8847: # resource of an author in the domain (e.g., if Domain Coordinator).
8848: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
8849: (&allowed('mdc',$env{'request.course.id'}))) {
8850: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
8851: $thisallowed.=$1;
8852: }
8853: }
8854:
1.52 www 8855: # Course: uri itself is a course
1.66 www 8856: my $courseuri=$uri;
8857: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 8858: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 8859:
1.620 albertel 8860: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 8861: =~/\Q$priv\E\&([^\:]*)/) {
1.1409 raeburn 8862: if ($priv eq 'mip') {
8863: my $rem = $1;
8864: if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
8865: ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
8866: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
8867: if ($cdom ne '') {
1.1410 raeburn 8868: my %passwdconf = &get_passwdconf($cdom);
8869: if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
8870: if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
8871: if (@{$passwdconf{'crsownerchg'}{'by'}}) {
8872: my @inststatuses = split(':',$env{'environment.inststatus'});
8873: unless (@inststatuses) {
8874: @inststatuses = ('default');
8875: }
8876: foreach my $status (@inststatuses) {
8877: if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
8878: $thisallowed.=$rem;
8879: }
8880: }
8881: }
8882: }
1.1409 raeburn 8883: }
8884: }
8885: }
8886: } else {
8887: unless (($priv eq 'bro') && (!$ownaccess)) {
8888: $thisallowed.=$1;
8889: }
1.1039 raeburn 8890: }
1.12 www 8891: }
1.29 www 8892:
1.665 albertel 8893: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 8894: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 8895: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 8896: $thisallowed='';
1.671 raeburn 8897: my ($match)=&is_on_map($uri);
8898: if ($match) {
8899: if ($env{'user.priv.'.$env{'request.role'}.'./'}
8900: =~/\Q$priv\E\&([^\:]*)/) {
1.1281 raeburn 8901: my $value = $1;
1.1461 raeburn 8902: my $deeplinkblock;
8903: unless ($nodeeplinkcheck) {
8904: $deeplinkblock = &deeplink_check($priv,$symb,$uri);
8905: }
1.1402 raeburn 8906: if ($deeplinkblock) {
8907: $thisallowed='D';
8908: } elsif ($noblockcheck) {
1.1281 raeburn 8909: $thisallowed.=$value;
1.1162 raeburn 8910: } else {
1.1424 raeburn 8911: my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1281 raeburn 8912: if (@blockers > 0) {
8913: $thisallowed = 'B';
8914: } else {
8915: $thisallowed.=$value;
8916: }
1.1162 raeburn 8917: }
1.671 raeburn 8918: }
8919: } else {
1.705 albertel 8920: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 8921: if ($refuri) {
8922: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 8923: $thisallowed='F';
1.671 raeburn 8924: } else {
8925: $refuri=&declutter($refuri);
8926: my ($match) = &is_on_map($refuri);
8927: if ($match) {
1.1461 raeburn 8928: my $deeplinkblock;
8929: unless ($nodeeplinkcheck) {
8930: $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
8931: }
1.1402 raeburn 8932: if ($deeplinkblock) {
8933: $thisallowed='D';
8934: } elsif ($noblockcheck) {
1.1281 raeburn 8935: $thisallowed='F';
1.1162 raeburn 8936: } else {
1.1426 raeburn 8937: my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1281 raeburn 8938: if (@blockers > 0) {
8939: $thisallowed = 'B';
8940: } else {
8941: $thisallowed='F';
8942: }
1.1162 raeburn 8943: }
1.671 raeburn 8944: }
1.669 raeburn 8945: }
1.671 raeburn 8946: }
8947: }
1.314 www 8948: }
1.492 albertel 8949:
1.766 albertel 8950: if ($priv eq 'bre'
8951: && $thisallowed ne 'F'
8952: && $thisallowed ne '2'
8953: && &is_portfolio_url($uri)) {
1.1270 raeburn 8954: $thisallowed = &portfolio_access($uri,$clientip);
1.766 albertel 8955: }
1.1250 raeburn 8956:
1.52 www 8957: # Full access at system, domain or course-wide level? Exit.
1.29 www 8958: if ($thisallowed=~/F/) {
8959: return 'F';
8960: }
8961:
1.52 www 8962: # If this is generating or modifying users, exit with special codes
1.29 www 8963:
1.1517 raeburn 8964: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:vca:vaa:'=~/\:\Q$priv\E\:/) {
1.643 www 8965: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 8966: my ($audom,$auname)=split('/',$uri);
1.643 www 8967: # no author name given, so this just checks on the general right to make a co-author in this domain
8968: unless ($auname) { return $thisallowed; }
8969: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 8970: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
8971: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
8972: ($audom ne $env{'request.role.domain'}))) { return ''; }
1.1517 raeburn 8973: } elsif (($priv eq 'vca') || ($priv eq 'vaa')) {
8974: my ($audom,$auname)=split('/',$uri);
8975: unless ($auname) { return $thisallowed; }
8976: unless (($env{'request.role'} eq "dc./$audom") ||
8977: ($env{'request.role'} eq "ca./$uri")) {
8978: return '';
8979: }
1.642 albertel 8980: }
1.52 www 8981: return $thisallowed;
8982: }
8983: #
1.103 harris41 8984: # Gathered so far: system, domain and course wide privileges
1.52 www 8985: #
8986: # Course: See if uri or referer is an individual resource that is part of
8987: # the course
8988:
1.620 albertel 8989: if ($env{'request.course.id'}) {
1.232 www 8990:
1.1504 raeburn 8991: if ($priv eq 'bre') {
8992: if (&is_coursetool_logo($uri)) {
8993: return 'F';
8994: }
8995: }
8996:
1.1409 raeburn 8997: # If this is modifying password (internal auth) domains must match for user and user's role.
8998:
8999: if ($priv eq 'mip') {
9000: if ($env{'user.domain'} eq $env{'request.role.domain'}) {
9001: return $thisallowed;
9002: } else {
9003: return '';
9004: }
9005: }
9006:
1.620 albertel 9007: $courseprivid=$env{'request.course.id'};
9008: if ($env{'request.course.sec'}) {
9009: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 9010: }
9011: $courseprivid=~s/\_/\//;
9012: my $checkreferer=1;
1.232 www 9013: my ($match,$cond)=&is_on_map($uri);
9014: if ($match) {
9015: $statecond=$cond;
1.620 albertel 9016: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 9017: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 9018: my $value = $1;
9019: if ($priv eq 'bre') {
1.1461 raeburn 9020: my $deeplinkblock;
9021: unless ($nodeeplinkcheck) {
9022: $deeplinkblock = &deeplink_check($priv,$symb,$uri);
9023: }
1.1458 raeburn 9024: if ($deeplinkblock) {
9025: $thisallowed = 'D';
9026: } elsif ($noblockcheck) {
1.1281 raeburn 9027: $thisallowed.=$value;
1.1162 raeburn 9028: } else {
1.1424 raeburn 9029: my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1281 raeburn 9030: if (@blockers > 0) {
9031: $thisallowed = 'B';
9032: } else {
9033: $thisallowed.=$value;
9034: }
1.1162 raeburn 9035: }
9036: } else {
9037: $thisallowed.=$value;
9038: }
1.52 www 9039: $checkreferer=0;
9040: }
1.29 www 9041: }
1.1424 raeburn 9042:
1.148 www 9043: if ($checkreferer) {
1.620 albertel 9044: my $refuri=$env{'httpref.'.$orguri};
1.148 www 9045: unless ($refuri) {
1.800 albertel 9046: foreach my $key (keys(%env)) {
9047: if ($key=~/^httpref\..*\*/) {
9048: my $pattern=$key;
1.156 www 9049: $pattern=~s/^httpref\.\/res\///;
1.148 www 9050: $pattern=~s/\*/\[\^\/\]\+/g;
9051: $pattern=~s/\//\\\//g;
1.152 www 9052: if ($orguri=~/$pattern/) {
1.800 albertel 9053: $refuri=$env{$key};
1.148 www 9054: }
9055: }
1.191 harris41 9056: }
1.148 www 9057: }
1.232 www 9058:
1.148 www 9059: if ($refuri) {
1.152 www 9060: $refuri=&declutter($refuri);
1.232 www 9061: my ($match,$cond)=&is_on_map($refuri);
9062: if ($match) {
9063: my $refstatecond=$cond;
1.620 albertel 9064: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 9065: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 9066: my $value = $1;
9067: if ($priv eq 'bre') {
1.1461 raeburn 9068: my $deeplinkblock;
9069: unless ($nodeeplinkcheck) {
9070: $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
9071: }
1.1402 raeburn 9072: if ($deeplinkblock) {
9073: $thisallowed = 'D';
9074: } elsif ($noblockcheck) {
1.1281 raeburn 9075: $thisallowed.=$value;
1.1162 raeburn 9076: } else {
1.1426 raeburn 9077: my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1281 raeburn 9078: if (@blockers > 0) {
9079: $thisallowed = 'B';
9080: } else {
9081: $thisallowed.=$value;
9082: }
1.1162 raeburn 9083: }
9084: } else {
9085: $thisallowed.=$value;
9086: }
1.53 www 9087: $uri=$refuri;
9088: $statecond=$refstatecond;
1.52 www 9089: }
9090: }
1.148 www 9091: }
1.29 www 9092: }
1.52 www 9093: }
1.29 www 9094:
1.52 www 9095: #
1.103 harris41 9096: # Gathered now: all privileges that could apply, and condition number
1.52 www 9097: #
9098: #
9099: # Full or no access?
9100: #
1.29 www 9101:
1.52 www 9102: if ($thisallowed=~/F/) {
9103: return 'F';
9104: }
1.29 www 9105:
1.52 www 9106: unless ($thisallowed) {
9107: return '';
9108: }
1.29 www 9109:
1.52 www 9110: # Restrictions exist, deal with them
9111: #
9112: # C:according to course preferences
9113: # R:according to resource settings
9114: # L:unless locked
9115: # X:according to user session state
9116: #
9117:
9118: # Possibly locked functionality, check all courses
1.1454 raeburn 9119: # In roles.tab, L (unless locked) available for bre, pch, plc, pac and sma.
1.54 www 9120: # Locks might take effect only after 10 minutes cache expiration for other
1.1454 raeburn 9121: # courses, and 2 minutes for current course, in which user has st or ta role
9122: # which is neither expired nor a future role (unless current course).
1.52 www 9123:
1.1454 raeburn 9124: my ($needlockcheck,$now,$crsonly);
1.52 www 9125: if ($thisallowed=~/L/) {
1.1454 raeburn 9126: $now = time;
9127: if ($priv eq 'bre') {
9128: if ($uri ne '') {
9129: if ($orguri =~ m{^/+res/}) {
9130: if ($uri =~ m{^lib/templates/}) {
9131: if ($env{'request.course.id'}) {
9132: $crsonly = 1;
9133: $needlockcheck = 1;
9134: }
9135: } else {
9136: $needlockcheck = 1;
9137: }
9138: } elsif ($env{'request.course.id'}) {
9139: my ($crsdom,$crsnum) = split('_',$env{'request.course.id'});
9140: if (($uri =~ m{^(adm|uploaded|public)/$crsdom/$crsnum/}) ||
9141: ($uri =~ m{^adm/$match_domain/$match_username/\d+/(smppg|bulletinboard)$})) {
9142: $crsonly = 1;
9143: }
9144: $needlockcheck = 1;
9145: }
9146: }
9147: } elsif (($priv eq 'pch') || ($priv eq 'plc') || ($priv eq 'pac') || ($priv eq 'sma')) {
9148: $needlockcheck = 1;
9149: }
9150: }
9151: if ($needlockcheck) {
1.1453 raeburn 9152: foreach my $envkey (keys(%env)) {
1.54 www 9153: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
9154: my $courseid=$2;
9155: my $roleid=$1.'.'.$2;
1.92 www 9156: $courseid=~s/^\///;
1.1453 raeburn 9157: unless ($env{'request.role'} eq $roleid) {
9158: my ($start,$end) = split(/\./,$env{$envkey});
9159: next unless (($now >= $start) && (!$end || $end > $now));
9160: }
1.54 www 9161: my $expiretime=600;
1.620 albertel 9162: if ($env{'request.role'} eq $roleid) {
1.54 www 9163: $expiretime=120;
9164: }
9165: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
9166: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 9167: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 9168: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 9169: }
1.620 albertel 9170: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
9171: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
9172: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
9173: &log($env{'user.domain'},$env{'user.name'},
9174: $env{'user.home'},
1.57 www 9175: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 9176: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 9177: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 9178: return '';
9179: }
9180: }
1.620 albertel 9181: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
9182: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
1.1455 raeburn 9183: if ($env{$prefix.'priv.'.$priv.'.lock.expire'}>time) {
1.620 albertel 9184: &log($env{'user.domain'},$env{'user.name'},
9185: $env{'user.home'},
1.57 www 9186: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 9187: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 9188: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 9189: return '';
9190: }
9191: }
9192: }
1.29 www 9193: }
1.52 www 9194: }
1.1424 raeburn 9195:
1.52 www 9196: #
9197: # Rest of the restrictions depend on selected course
9198: #
9199:
1.620 albertel 9200: unless ($env{'request.course.id'}) {
1.766 albertel 9201: if ($thisallowed eq 'A') {
9202: return 'A';
1.814 raeburn 9203: } elsif ($thisallowed eq 'B') {
9204: return 'B';
1.766 albertel 9205: } else {
9206: return '1';
9207: }
1.52 www 9208: }
1.29 www 9209:
1.52 www 9210: #
9211: # Now user is definitely in a course
9212: #
1.53 www 9213:
9214:
9215: # Course preferences
9216:
9217: if ($thisallowed=~/C/) {
1.620 albertel 9218: my $rolecode=(split(/\./,$env{'request.role'}))[0];
9219: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
9220: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 9221: =~/\Q$rolecode\E/) {
1.1304 raeburn 9222: if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689 albertel 9223: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
9224: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
9225: $env{'request.course.id'});
9226: }
1.237 www 9227: return '';
9228: }
9229:
1.620 albertel 9230: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 9231: =~/\Q$unamedom\E/) {
1.1304 raeburn 9232: if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689 albertel 9233: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
9234: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
9235: $env{'request.course.id'});
9236: }
1.54 www 9237: return '';
9238: }
1.53 www 9239: }
9240:
9241: # Resource preferences
9242:
9243: if ($thisallowed=~/R/) {
1.620 albertel 9244: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 9245: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103 raeburn 9246: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 9247: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
9248: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
9249: }
9250: return '';
1.54 www 9251: }
1.53 www 9252: }
1.30 www 9253:
1.1461 raeburn 9254: # Restricted for deeplinked session?
9255:
9256: if ($env{'request.deeplink.login'}) {
9257: if ($env{'acc.deeplinkout'} && !$nodeeplinkout) {
9258: if (!$symb) { $symb=&symbread($uri,1); }
9259: if (($symb) && ($env{'acc.deeplinkout'}=~/\&\Q$symb\E\&/)) {
9260: return '';
9261: }
9262: }
9263: }
9264:
1.246 www 9265: # Restricted by state or randomout?
1.30 www 9266:
1.52 www 9267: if ($thisallowed=~/X/) {
1.620 albertel 9268: if ($env{'acc.randomout'}) {
1.579 albertel 9269: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 9270: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 9271: return '';
9272: }
1.247 www 9273: }
9274: if (&condval($statecond)) {
1.52 www 9275: return '2';
9276: } else {
9277: return '';
9278: }
9279: }
1.30 www 9280:
1.766 albertel 9281: if ($thisallowed eq 'A') {
9282: return 'A';
1.814 raeburn 9283: } elsif ($thisallowed eq 'B') {
9284: return 'B';
1.1402 raeburn 9285: } elsif ($thisallowed eq 'D') {
9286: return 'D';
1.766 albertel 9287: }
1.52 www 9288: return 'F';
1.232 www 9289: }
1.1162 raeburn 9290:
1.1192 raeburn 9291: # ------------------------------------------- Check construction space access
9292:
9293: sub constructaccess {
9294: my ($url,$setpriv)=@_;
9295:
9296: # We do not allow editing of previous versions of files
9297: if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
9298:
9299: # Get username and domain from URL
9300: my ($ownername,$ownerdomain,$ownerhome);
9301:
9302: ($ownerdomain,$ownername) =
1.1325 raeburn 9303: ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
1.1192 raeburn 9304:
9305: # The URL does not really point to any authorspace, forget it
9306: unless (($ownername) && ($ownerdomain)) { return ''; }
9307:
9308: # Now we need to see if the user has access to the authorspace of
9309: # $ownername at $ownerdomain
9310:
9311: if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
9312: # Real author for this?
9313: $ownerhome = $env{'user.home'};
9314: if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
9315: return ($ownername,$ownerdomain,$ownerhome);
9316: }
1.1506 raeburn 9317: } elsif (&is_course($ownerdomain,$ownername)) {
9318: # Course Authoring Space?
1.1312 raeburn 9319: if ($env{'request.course.id'}) {
9320: if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
9321: ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
9322: if (&allowed('mdc',$env{'request.course.id'})) {
1.1520 raeburn 9323: return if ($env{'course.'.$env{'request.course.id'}.'.internal.crsauthor'} eq '0');
9324: unless ($env{'course.'.$env{'request.course.id'}.'.internal.crsauthor'}) {
9325: my %domdefs = &get_domain_defaults($ownerdomain);
9326: my $type = lc($env{'course.'.$env{'request.course.id'}.'.type'});
9327: unless (($type eq 'community') || ($type eq 'placement')) {
9328: $type = 'unofficial';
9329: if ($env{'course.'.$env{'request.course.id'}.'internal.coursecode'} ne '') {
9330: $type = 'official';
9331: } elsif ($env{'course.'.$env{'request.course.id'}.'internal.textbook'} ne '') {
9332: $type = 'textbook';
9333: } else {
9334: $type = 'unofficial';
9335: }
9336: }
9337: return if ($domdefs{$type.'crsauthor'} eq '0');
9338: }
1.1312 raeburn 9339: $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
9340: return ($ownername,$ownerdomain,$ownerhome);
9341: }
9342: }
9343: }
1.1506 raeburn 9344: return '';
9345: } else {
9346: # Co-author for this?
9347: if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
9348: exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
9349: $ownerhome = &homeserver($ownername,$ownerdomain);
9350: return ($ownername,$ownerdomain,$ownerhome);
9351: }
1.1192 raeburn 9352: }
9353:
9354: # We don't have any access right now. If we are not possibly going to do anything about this,
9355: # we might as well leave
9356: unless ($setpriv) { return ''; }
9357:
9358: # Backdoor access?
9359: my $allowed=&allowed('eco',$ownerdomain);
9360: # Nope
9361: unless ($allowed) { return ''; }
9362: # Looks like we may have access, but could be locked by the owner of the construction space
9363: if ($allowed eq 'U') {
9364: my %blocked=&get('environment',['domcoord.author'],
9365: $ownerdomain,$ownername);
9366: # Is blocked by owner
9367: if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
9368: }
9369: if (($allowed eq 'F') || ($allowed eq 'U')) {
9370: # Grant temporary access
9371: my $then=$env{'user.login.time'};
1.1209 raeburn 9372: my $update=$env{'user.update.time'};
1.1192 raeburn 9373: if (!$update) { $update = $then; }
9374: my $refresh=$env{'user.refresh.time'};
9375: if (!$refresh) { $refresh = $update; }
9376: my $now = time;
9377: &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
9378: $now,'ca','constructaccess');
9379: $ownerhome = &homeserver($ownername,$ownerdomain);
9380: return($ownername,$ownerdomain,$ownerhome);
9381: }
9382: # No business here
9383: return '';
9384: }
9385:
1.1282 raeburn 9386: # ----------------------------------------------------------- Content Blocking
9387:
9388: {
9389: # Caches for faster Course Contents display where content blocking
9390: # is in operation (i.e., interval param set) for timed quiz.
9391: #
9392: # User for whom data are being temporarily cached.
9393: my $cacheduser='';
1.1424 raeburn 9394: # Course for which data are being temporarily cached.
9395: my $cachedcid='';
1.1282 raeburn 9396: # Cached blockers for this user (a hash of blocking items).
9397: my %cachedblockers=();
9398: # When the data were last cached.
9399: my $cachedlast='';
9400:
9401: sub load_all_blockers {
1.1427 raeburn 9402: my ($uname,$udom)=@_;
1.1282 raeburn 9403: if (($uname ne '') && ($udom ne '')) {
9404: if (($cacheduser eq $uname.':'.$udom) &&
1.1424 raeburn 9405: ($cachedcid eq $env{'request.course.id'}) &&
1.1427 raeburn 9406: (abs($cachedlast-time)<5)) {
1.1282 raeburn 9407: return;
9408: }
9409: }
9410: $cachedlast=time;
9411: $cacheduser=$uname.':'.$udom;
1.1424 raeburn 9412: $cachedcid=$env{'request.course.id'};
1.1427 raeburn 9413: %cachedblockers = &get_commblock_resources();
1.1424 raeburn 9414: return;
1.1282 raeburn 9415: }
9416:
1.1162 raeburn 9417: sub get_comm_blocks {
9418: my ($cdom,$cnum) = @_;
9419: if ($cdom eq '' || $cnum eq '') {
9420: return unless ($env{'request.course.id'});
9421: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
9422: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
9423: }
9424: my %commblocks;
9425: my $hashid=$cdom.'_'.$cnum;
9426: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
9427: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
9428: %commblocks = %{$blocksref};
9429: } else {
1.1494 raeburn 9430: %commblocks = &dump('comm_block',$cdom,$cnum);
1.1162 raeburn 9431: my $cachetime = 600;
9432: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
9433: }
9434: return %commblocks;
9435: }
9436:
1.1282 raeburn 9437: sub get_commblock_resources {
9438: my ($blocks) = @_;
9439: my %blockers = ();
9440: return %blockers unless ($env{'request.course.id'});
1.1470 raeburn 9441: my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
9442: if ($env{'request.course.sec'}) {
9443: $courseurl .= '/'.$env{'request.course.sec'};
9444: }
9445: return %blockers if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
1.1162 raeburn 9446: my %commblocks;
9447: if (ref($blocks) eq 'HASH') {
9448: %commblocks = %{$blocks};
9449: } else {
9450: %commblocks = &get_comm_blocks();
9451: }
1.1282 raeburn 9452: return %blockers unless (keys(%commblocks) > 0);
9453: my $navmap = Apache::lonnavmaps::navmap->new();
9454: return %blockers unless (ref($navmap));
1.1162 raeburn 9455: my $now = time;
9456: foreach my $block (keys(%commblocks)) {
9457: if ($block =~ /^(\d+)____(\d+)$/) {
9458: my ($start,$end) = ($1,$2);
9459: if ($start <= $now && $end >= $now) {
9460: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
9461: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
9462: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1282 raeburn 9463: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
9464: $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162 raeburn 9465: }
9466: }
9467: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1282 raeburn 9468: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
9469: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162 raeburn 9470: }
9471: }
9472: }
9473: }
9474: }
9475: } elsif ($block =~ /^firstaccess____(.+)$/) {
9476: my $item = $1;
9477: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
9478: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1471 raeburn 9479: my (@interval,$mapname);
1.1282 raeburn 9480: my $type = 'map';
9481: if ($item eq 'course') {
9482: $type = 'course';
9483: @interval=&EXT("resource.0.interval");
9484: } else {
9485: if ($item =~ /___\d+___/) {
9486: $type = 'resource';
9487: @interval=&EXT("resource.0.interval",$item);
1.1162 raeburn 9488: } else {
1.1471 raeburn 9489: $mapname = &deversion($item);
9490: if (ref($navmap)) {
9491: my $timelimit = $navmap->get_mapparam(undef,$mapname,'0.interval');
9492: @interval = ($timelimit,'map');
1.1162 raeburn 9493: }
9494: }
1.1282 raeburn 9495: }
1.1310 raeburn 9496: if ($interval[0] =~ /^(\d+)/) {
1.1308 raeburn 9497: my $timelimit = $1;
1.1282 raeburn 9498: my $first_access;
9499: if ($type eq 'resource') {
9500: $first_access=&get_first_access($interval[1],$item);
9501: } elsif ($type eq 'map') {
9502: $first_access=&get_first_access($interval[1],undef,$item);
9503: } else {
9504: $first_access=&get_first_access($interval[1]);
9505: }
9506: if ($first_access) {
1.1292 raeburn 9507: my $timesup = $first_access+$timelimit;
1.1282 raeburn 9508: if ($timesup > $now) {
9509: my $activeblock;
1.1471 raeburn 9510: if ($type eq 'resource') {
9511: if (ref($navmap)) {
9512: my $res = $navmap->getBySymb($item);
9513: if ($res->answerable()) {
9514: $activeblock = 1;
9515: }
9516: }
9517: } elsif ($type eq 'map') {
9518: my $mapsymb = &symbread($mapname,1);
9519: if (($mapsymb) && (ref($navmap))) {
9520: my $mapres = $navmap->getBySymb($mapsymb);
9521: if (ref($mapres)) {
9522: my $first = $mapres->map_start();
9523: my $finish = $mapres->map_finish();
9524: my $it = $navmap->getIterator($first,$finish,undef,0,0);
9525: if (ref($it)) {
9526: my $res;
9527: while ($res = $it->next(undef,1)) {
9528: next unless (ref($res));
9529: my $symb = $res->symb();
9530: next if (($symb eq $mapsymb) || ($symb eq ''));
9531: @interval=&EXT("resource.0.interval",$symb);
9532: if ($interval[1] eq 'map') {
9533: if ($res->answerable()) {
9534: $activeblock = 1;
9535: last;
9536: }
9537: }
9538: }
9539: }
9540: }
1.1282 raeburn 9541: }
9542: }
9543: if ($activeblock) {
9544: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
9545: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
9546: $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
9547: }
9548: }
9549: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
9550: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
9551: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163 raeburn 9552: }
1.1162 raeburn 9553: }
9554: }
9555: }
9556: }
9557: }
9558: }
9559: }
9560: }
9561: }
1.1282 raeburn 9562: return %blockers;
1.1162 raeburn 9563: }
9564:
1.1282 raeburn 9565: sub has_comm_blocking {
1.1427 raeburn 9566: my ($priv,$symb,$uri,$ignoresymbdb,$noenccheck,$blocked,$blocks) = @_;
1.1282 raeburn 9567: my @blockers;
9568: return unless ($env{'request.course.id'});
9569: return unless ($priv eq 'bre');
9570: return if ($env{'request.state'} eq 'construct');
1.1470 raeburn 9571: my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
9572: if ($env{'request.course.sec'}) {
9573: $courseurl .= '/'.$env{'request.course.sec'};
9574: }
9575: return if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
1.1427 raeburn 9576: my %blockinfo;
9577: if (ref($blocks) eq 'HASH') {
9578: %blockinfo = &get_commblock_resources($blocks);
9579: } else {
9580: &load_all_blockers($env{'user.name'},$env{'user.domain'});
9581: %blockinfo = %cachedblockers;
9582: }
9583: return unless (keys(%blockinfo) > 0);
1.1282 raeburn 9584: my (%possibles,@symbs);
9585: if (!$symb) {
1.1427 raeburn 9586: $symb = &symbread($uri,1,1,1,\%possibles,$ignoresymbdb,$noenccheck);
1.1162 raeburn 9587: }
1.1282 raeburn 9588: if ($symb) {
9589: @symbs = ($symb);
9590: } elsif (keys(%possibles)) {
9591: @symbs = keys(%possibles);
9592: }
9593: my $noblock;
9594: foreach my $symb (@symbs) {
9595: last if ($noblock);
9596: my ($map,$resid,$resurl)=&decode_symb($symb);
1.1427 raeburn 9597: foreach my $block (keys(%blockinfo)) {
1.1282 raeburn 9598: if ($block =~ /^firstaccess____(.+)$/) {
9599: my $item = $1;
1.1424 raeburn 9600: unless ($blocked) {
9601: if (($item eq $map) || ($item eq $symb)) {
9602: $noblock = 1;
9603: last;
9604: }
1.1282 raeburn 9605: }
9606: }
1.1427 raeburn 9607: if (ref($blockinfo{$block}) eq 'HASH') {
9608: if (ref($blockinfo{$block}{'resources'}) eq 'HASH') {
9609: if ($blockinfo{$block}{'resources'}{$symb}) {
1.1282 raeburn 9610: unless (grep(/^\Q$block\E$/,@blockers)) {
9611: push(@blockers,$block);
9612: }
9613: }
9614: }
1.1427 raeburn 9615: if (ref($blockinfo{$block}{'maps'}) eq 'HASH') {
9616: if ($blockinfo{$block}{'maps'}{$map}) {
1.1424 raeburn 9617: unless (grep(/^\Q$block\E$/,@blockers)) {
9618: push(@blockers,$block);
9619: }
1.1282 raeburn 9620: }
9621: }
1.1162 raeburn 9622: }
9623: }
9624: }
1.1424 raeburn 9625: unless ($noblock) {
9626: return @blockers;
9627: }
9628: return;
1.1282 raeburn 9629: }
1.1162 raeburn 9630: }
9631:
1.1402 raeburn 9632: sub deeplink_check {
9633: my ($priv,$symb,$uri) = @_;
9634: return unless ($env{'request.course.id'});
9635: return unless ($priv eq 'bre');
9636: return if ($env{'request.state'} eq 'construct');
9637: return if ($env{'request.role.adv'});
9638: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
9639: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
9640: my (%possibles,@symbs);
9641: if (!$symb) {
9642: $symb = &symbread($uri,1,1,1,\%possibles);
9643: }
9644: if ($symb) {
9645: @symbs = ($symb);
9646: } elsif (keys(%possibles)) {
9647: @symbs = keys(%possibles);
9648: }
9649:
1.1461 raeburn 9650: my ($deeplink_symb,$allow);
9651: if ($env{'request.deeplink.login'}) {
9652: $deeplink_symb = &Apache::loncommon::deeplink_login_symb($cnum,$cdom);
1.1402 raeburn 9653: }
9654: foreach my $symb (@symbs) {
9655: last if ($allow);
9656: my $deeplink = &EXT("resource.0.deeplink",$symb);
9657: if ($deeplink eq '') {
9658: $allow = 1;
9659: } else {
1.1463 raeburn 9660: my ($state,$others,$listed,$scope,$protect) = split(/,/,$deeplink);
9661: if ($state ne 'only') {
1.1402 raeburn 9662: $allow = 1;
1.1463 raeburn 9663: } else {
9664: my $check_deeplink_entry;
9665: if ($protect ne 'none') {
9666: my ($acctype,$item) = split(/:/,$protect);
9667: if (($acctype eq 'ltic') && ($env{'user.linkprotector'})) {
9668: if (grep(/^\Q$item\Ec$/,split(/,/,$env{'user.linkprotector'}))) {
9669: $check_deeplink_entry = 1
9670: }
9671: } elsif (($acctype eq 'ltid') && ($env{'user.linkprotector'})) {
9672: if (grep(/^\Q$item\Ed$/,split(/,/,$env{'user.linkprotector'}))) {
9673: $check_deeplink_entry = 1;
9674: }
9675: } elsif (($acctype eq 'key') && ($env{'user.deeplinkkey'})) {
9676: if (grep(/^\Q$item\E$/,split(/,/,$env{'user.deeplinkkey'}))) {
9677: $check_deeplink_entry = 1;
9678: }
9679: }
9680: }
9681: if (($protect eq 'none') || ($check_deeplink_entry)) {
1.1402 raeburn 9682: if ($scope eq 'res') {
1.1461 raeburn 9683: if ($symb eq $deeplink_symb) {
1.1402 raeburn 9684: $allow = 1;
9685: }
1.1459 raeburn 9686: } elsif (($scope eq 'map') || ($scope eq 'rec')) {
1.1463 raeburn 9687: my ($map_from_symb,$map_from_login);
1.1461 raeburn 9688: $map_from_symb = &deversion((&decode_symb($symb))[0]);
9689: if ($deeplink_symb =~ /\.(page|sequence)$/) {
9690: $map_from_login = &deversion((&decode_symb($deeplink_symb))[2]);
9691: } else {
9692: $map_from_login = &deversion((&decode_symb($deeplink_symb))[0]);
9693: }
1.1459 raeburn 9694: if (($map_from_symb) && ($map_from_login)) {
9695: if ($map_from_symb eq $map_from_login) {
9696: $allow = 1;
9697: } elsif ($scope eq 'rec') {
9698: my @recurseup = &get_map_hierarchy($map_from_symb,$env{'request.course.id'});
9699: if (grep(/^\Q$map_from_login\E$/,@recurseup)) {
9700: $allow = 1;
9701: }
9702: }
9703: }
1.1402 raeburn 9704: }
9705: }
9706: }
9707: }
9708: }
9709: return if ($allow);
9710: return 1;
9711: }
9712:
1.1282 raeburn 9713: # -------------------------------- Deversion and split uri into path an filename
9714:
1.1133 foxr 9715: #
1.1282 raeburn 9716: # Removes the version from a URI and
1.1133 foxr 9717: # splits it in to its filename and path to the filename.
9718: # Seems like File::Basename could have done this more clearly.
9719: # Parameters:
9720: # $uri - input URI
9721: # Returns:
9722: # Two element list consisting of
9723: # $pathname - the URI up to and excluding the trailing /
9724: # $filename - The part of the URI following the last /
9725: # NOTE:
9726: # Another realization of this is simply:
9727: # use File::Basename;
9728: # ...
9729: # $uri = shift;
9730: # $filename = basename($uri);
9731: # $path = dirname($uri);
9732: # return ($filename, $path);
9733: #
9734: # The implementation below is probably faster however.
9735: #
1.710 albertel 9736: sub split_uri_for_cond {
9737: my $uri=&deversion(&declutter(shift));
9738: my @uriparts=split(/\//,$uri);
9739: my $filename=pop(@uriparts);
9740: my $pathname=join('/',@uriparts);
9741: return ($pathname,$filename);
9742: }
1.232 www 9743: # --------------------------------------------------- Is a resource on the map?
9744:
9745: sub is_on_map {
1.710 albertel 9746: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 9747: #Trying to find the conditional for the file
1.620 albertel 9748: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 9749: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 9750: if ($match) {
1.289 bowersj2 9751: return (1,$1);
9752: } else {
1.434 www 9753: return (0,0);
1.289 bowersj2 9754: }
1.12 www 9755: }
9756:
1.427 www 9757: # --------------------------------------------------------- Get symb from alias
9758:
9759: sub get_symb_from_alias {
9760: my $symb=shift;
9761: my ($map,$resid,$url)=&decode_symb($symb);
9762: # Already is a symb
9763: if ($url) { return $symb; }
9764: # Must be an alias
9765: my $aliassymb='';
9766: my %bighash;
1.620 albertel 9767: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 9768: &GDBM_READER(),0640)) {
9769: my $rid=$bighash{'mapalias_'.$symb};
9770: if ($rid) {
9771: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 9772: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
9773: $resid,$bighash{'src_'.$rid});
1.427 www 9774: }
9775: untie %bighash;
9776: }
9777: return $aliassymb;
9778: }
9779:
1.12 www 9780: # ----------------------------------------------------------------- Define Role
9781:
9782: sub definerole {
9783: if (allowed('mcr','/')) {
1.1326 raeburn 9784: my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800 albertel 9785: foreach my $role (split(':',$sysrole)) {
9786: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 9787: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
9788: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
9789: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 9790: return "refused:s:$crole&$cqual";
9791: }
9792: }
1.191 harris41 9793: }
1.800 albertel 9794: foreach my $role (split(':',$domrole)) {
9795: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 9796: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
9797: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
9798: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 9799: return "refused:d:$crole&$cqual";
9800: }
9801: }
1.191 harris41 9802: }
1.800 albertel 9803: foreach my $role (split(':',$courole)) {
9804: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 9805: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
9806: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
9807: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 9808: return "refused:c:$crole&$cqual";
9809: }
9810: }
1.191 harris41 9811: }
1.1326 raeburn 9812: my $uhome;
9813: if (($uname ne '') && ($udom ne '')) {
9814: $uhome = &homeserver($uname,$udom);
9815: return $uhome if ($uhome eq 'no_host');
9816: } else {
9817: $uname = $env{'user.name'};
9818: $udom = $env{'user.domain'};
9819: $uhome = $env{'user.home'};
9820: }
1.620 albertel 9821: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1326 raeburn 9822: "$udom:$uname:rolesdef_$rolename=".
1.21 www 9823: escape($sysrole.'_'.$domrole.'_'.$courole);
1.1326 raeburn 9824: return reply($command,$uhome);
1.12 www 9825: } else {
9826: return 'refused';
9827: }
1.105 harris41 9828: }
9829:
9830: # ---------------- Make a metadata query against the network of library servers
9831:
9832: sub metadata_query {
1.1237 raeburn 9833: my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120 harris41 9834: my %rhash;
1.845 albertel 9835: my %libserv = &all_library();
1.244 matthew 9836: my @server_list = (defined($server_array) ? @$server_array
9837: : keys(%libserv) );
9838: for my $server (@server_list) {
1.1237 raeburn 9839: my $domains = '';
9840: if (ref($domains_hash) eq 'HASH') {
9841: $domains = $domains_hash->{$server};
9842: }
1.118 harris41 9843: unless ($custom or $customshow) {
1.1237 raeburn 9844: my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118 harris41 9845: $rhash{$server}=$reply;
9846: }
9847: else {
9848: my $reply=&reply("querysend:".&escape($query).':'.
1.1237 raeburn 9849: &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118 harris41 9850: $server);
9851: $rhash{$server}=$reply;
9852: }
1.112 harris41 9853: }
1.118 harris41 9854: return \%rhash;
1.240 www 9855: }
9856:
9857: # ----------------------------------------- Send log queries and wait for reply
9858:
9859: sub log_query {
9860: my ($uname,$udom,$query,%filters)=@_;
9861: my $uhome=&homeserver($uname,$udom);
9862: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 9863: my $uhost=&hostname($uhome);
1.800 albertel 9864: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 9865: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
9866: $uhome);
1.479 albertel 9867: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 9868: return get_query_reply($queryid);
9869: }
9870:
1.818 raeburn 9871: # -------------------------- Update MySQL table for portfolio file
9872:
9873: sub update_portfolio_table {
1.821 raeburn 9874: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 9875: if ($group ne '') {
9876: $file_name =~s /^\Q$group\E//;
9877: }
1.818 raeburn 9878: my $homeserver = &homeserver($uname,$udom);
9879: my $queryid=
1.821 raeburn 9880: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
9881: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 9882: my $reply = &get_query_reply($queryid);
9883: return $reply;
9884: }
9885:
1.899 raeburn 9886: # -------------------------- Update MySQL allusers table
9887:
9888: sub update_allusers_table {
9889: my ($uname,$udom,$names) = @_;
9890: my $homeserver = &homeserver($uname,$udom);
9891: my $queryid=
9892: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
9893: 'lastname='.&escape($names->{'lastname'}).'%%'.
9894: 'firstname='.&escape($names->{'firstname'}).'%%'.
9895: 'middlename='.&escape($names->{'middlename'}).'%%'.
9896: 'generation='.&escape($names->{'generation'}).'%%'.
9897: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
9898: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 9899: return;
1.899 raeburn 9900: }
9901:
1.508 raeburn 9902: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 9903:
9904: sub fetch_enrollment_query {
1.511 raeburn 9905: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1317 raeburn 9906: my ($homeserver,$sleep,$loopmax);
1.547 raeburn 9907: my $maxtries = 1;
1.508 raeburn 9908: if ($context eq 'automated') {
9909: $homeserver = $perlvar{'lonHostID'};
1.1317 raeburn 9910: $sleep = 2;
9911: $loopmax = 100;
1.547 raeburn 9912: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 9913: } else {
9914: $homeserver = &homeserver($cnum,$dom);
9915: }
1.838 albertel 9916: my $host=&hostname($homeserver);
1.506 raeburn 9917: my $cmd = '';
1.1000 raeburn 9918: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 9919: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 9920: }
9921: $cmd =~ s/%%$//;
9922: $cmd = &escape($cmd);
9923: my $query = 'fetchenrollment';
1.620 albertel 9924: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 9925: unless ($queryid=~/^\Q$host\E\_/) {
9926: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
9927: return 'error: '.$queryid;
9928: }
1.1317 raeburn 9929: my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547 raeburn 9930: my $tries = 1;
9931: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1317 raeburn 9932: $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547 raeburn 9933: $tries ++;
9934: }
1.526 raeburn 9935: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 9936: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 9937: } else {
1.901 albertel 9938: my @responses = split(/:/,$reply);
1.1322 raeburn 9939: if (grep { $_ eq $homeserver } ¤t_machine_ids()) {
1.800 albertel 9940: foreach my $line (@responses) {
9941: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 9942: $$replyref{$key} = $value;
9943: }
9944: } else {
1.1117 foxr 9945: my $pathname = LONCAPA::tempdir();
1.800 albertel 9946: foreach my $line (@responses) {
9947: my ($key,$value) = split(/=/,$line);
1.506 raeburn 9948: $$replyref{$key} = $value;
9949: if ($value > 0) {
1.800 albertel 9950: foreach my $item (@{$$affiliatesref{$key}}) {
9951: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 9952: my $destname = $pathname.'/'.$filename;
9953: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 9954: if ($xml_classlist =~ /^error/) {
9955: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
9956: } else {
1.1359 raeburn 9957: if ( open(FILE,">",$destname) ) {
1.506 raeburn 9958: print FILE &unescape($xml_classlist);
9959: close(FILE);
1.526 raeburn 9960: } else {
9961: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 9962: }
9963: }
9964: }
9965: }
9966: }
9967: }
9968: return 'ok';
9969: }
9970: return 'error';
9971: }
9972:
1.242 www 9973: sub get_query_reply {
1.1471 raeburn 9974: my ($queryid,$sleep,$loopmax) = @_;
1.1317 raeburn 9975: if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
9976: $sleep = 0.2;
9977: }
9978: if (($loopmax eq '') || ($loopmax =~ /\D/)) {
9979: $loopmax = 100;
9980: }
1.1117 foxr 9981: my $replyfile=LONCAPA::tempdir().$queryid;
1.240 www 9982: my $reply='';
1.1317 raeburn 9983: for (1..$loopmax) {
9984: sleep($sleep);
1.240 www 9985: if (-e $replyfile.'.end') {
1.1359 raeburn 9986: if (open(my $fh,"<",$replyfile)) {
1.904 albertel 9987: $reply = join('',<$fh>);
9988: close($fh);
1.240 www 9989: } else { return 'error: reply_file_error'; }
1.242 www 9990: return &unescape($reply);
9991: }
1.240 www 9992: }
1.242 www 9993: return 'timeout:'.$queryid;
1.240 www 9994: }
9995:
9996: sub courselog_query {
1.241 www 9997: #
9998: # possible filters:
9999: # url: url or symb
10000: # username
10001: # domain
10002: # action: view, submit, grade
10003: # start: timestamp
10004: # end: timestamp
10005: #
1.240 www 10006: my (%filters)=@_;
1.620 albertel 10007: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 10008: if ($filters{'url'}) {
10009: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
10010: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
10011: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
10012: }
1.620 albertel 10013: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
10014: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 10015: return &log_query($cname,$cdom,'courselog',%filters);
10016: }
10017:
10018: sub userlog_query {
1.858 raeburn 10019: #
10020: # possible filters:
10021: # action: log check role
10022: # start: timestamp
10023: # end: timestamp
10024: #
1.240 www 10025: my ($uname,$udom,%filters)=@_;
10026: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 10027: }
10028:
1.506 raeburn 10029: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
10030:
10031: sub auto_run {
1.508 raeburn 10032: my ($cnum,$cdom) = @_;
1.876 raeburn 10033: my $response = 0;
10034: my $settings;
10035: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
10036: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
10037: $settings = $domconfig{'autoenroll'};
10038: if ($settings->{'run'} eq '1') {
10039: $response = 1;
10040: }
10041: } else {
1.934 raeburn 10042: my $homeserver;
10043: if (&is_course($cdom,$cnum)) {
10044: $homeserver = &homeserver($cnum,$cdom);
10045: } else {
10046: $homeserver = &domain($cdom,'primary');
10047: }
10048: if ($homeserver ne 'no_host') {
10049: $response = &reply('autorun:'.$cdom,$homeserver);
10050: }
1.876 raeburn 10051: }
1.506 raeburn 10052: return $response;
10053: }
1.776 albertel 10054:
1.506 raeburn 10055: sub auto_get_sections {
1.508 raeburn 10056: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 10057: my $homeserver;
10058: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
10059: $homeserver = &homeserver($cnum,$cdom);
10060: }
10061: if (!defined($homeserver)) {
10062: if ($cdom =~ /^$match_domain$/) {
10063: $homeserver = &domain($cdom,'primary');
10064: }
10065: }
10066: my @secs;
10067: if (defined($homeserver)) {
10068: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
10069: unless ($response eq 'refused') {
10070: @secs = split(/:/,$response);
10071: }
1.506 raeburn 10072: }
10073: return @secs;
10074: }
1.776 albertel 10075:
1.506 raeburn 10076: sub auto_new_course {
1.1099 raeburn 10077: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 10078: my $homeserver = &homeserver($cnum,$cdom);
1.1099 raeburn 10079: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 10080: return $response;
10081: }
1.776 albertel 10082:
1.506 raeburn 10083: sub auto_validate_courseID {
1.508 raeburn 10084: my ($cnum,$cdom,$inst_course_id) = @_;
10085: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 10086: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 10087: return $response;
10088: }
1.776 albertel 10089:
1.1007 raeburn 10090: sub auto_validate_instcode {
1.1020 raeburn 10091: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 10092: my ($homeserver,$response);
10093: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
10094: $homeserver = &homeserver($cnum,$cdom);
10095: }
10096: if (!defined($homeserver)) {
10097: if ($cdom =~ /^$match_domain$/) {
10098: $homeserver = &domain($cdom,'primary');
10099: }
10100: }
1.1065 raeburn 10101: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
10102: &escape($instcode).':'.&escape($owner),$homeserver));
1.1216 raeburn 10103: my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
10104: return ($outcome,$description,$defaultcredits);
1.1007 raeburn 10105: }
10106:
1.1444 raeburn 10107: sub auto_validate_inst_crosslist {
10108: my ($cnum,$cdom,$instcode,$inst_xlist,$coowner) = @_;
10109: my ($homeserver,$response);
10110: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
10111: $homeserver = &homeserver($cnum,$cdom);
10112: }
10113: if (!defined($homeserver)) {
10114: if ($cdom =~ /^$match_domain$/) {
10115: $homeserver = &domain($cdom,'primary');
10116: }
10117: }
10118: unless (($homeserver eq '') || ($homeserver eq 'no_host')) {
10119: $response=&reply('autovalidateinstcrosslist:'.$cdom.':'.
10120: &escape($instcode).':'.&escape($inst_xlist).':'.
1.1445 raeburn 10121: &escape($coowner),$homeserver);
1.1444 raeburn 10122: }
10123: return $response;
10124: }
10125:
1.506 raeburn 10126: sub auto_create_password {
1.873 raeburn 10127: my ($cnum,$cdom,$authparam,$udom) = @_;
10128: my ($homeserver,$response);
1.506 raeburn 10129: my $create_passwd = 0;
10130: my $authchk = '';
1.873 raeburn 10131: if ($udom =~ /^$match_domain$/) {
10132: $homeserver = &domain($udom,'primary');
10133: }
10134: if ($homeserver eq '') {
10135: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
10136: $homeserver = &homeserver($cnum,$cdom);
10137: }
10138: }
10139: if ($homeserver eq '') {
10140: $authchk = 'nodomain';
1.506 raeburn 10141: } else {
1.873 raeburn 10142: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
10143: if ($response eq 'refused') {
10144: $authchk = 'refused';
10145: } else {
1.901 albertel 10146: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 10147: }
1.506 raeburn 10148: }
10149: return ($authparam,$create_passwd,$authchk);
10150: }
10151:
1.706 raeburn 10152: sub auto_photo_permission {
10153: my ($cnum,$cdom,$students) = @_;
10154: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 10155: my ($outcome,$perm_reqd,$conditions) =
10156: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 10157: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
10158: return (undef,undef);
10159: }
1.706 raeburn 10160: return ($outcome,$perm_reqd,$conditions);
10161: }
10162:
10163: sub auto_checkphotos {
10164: my ($uname,$udom,$pid) = @_;
10165: my $homeserver = &homeserver($uname,$udom);
10166: my ($result,$resulttype);
10167: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 10168: &escape($uname).':'.&escape($pid),
10169: $homeserver));
1.709 albertel 10170: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
10171: return (undef,undef);
10172: }
1.706 raeburn 10173: if ($outcome) {
10174: ($result,$resulttype) = split(/:/,$outcome);
10175: }
10176: return ($result,$resulttype);
10177: }
10178:
10179: sub auto_photochoice {
10180: my ($cnum,$cdom) = @_;
10181: my $homeserver = &homeserver($cnum,$cdom);
10182: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 10183: &escape($cdom),
10184: $homeserver)));
1.709 albertel 10185: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
10186: return (undef,undef);
10187: }
1.706 raeburn 10188: return ($update,$comment);
10189: }
10190:
10191: sub auto_photoupdate {
10192: my ($affiliatesref,$dom,$cnum,$photo) = @_;
10193: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 10194: my $host=&hostname($homeserver);
1.706 raeburn 10195: my $cmd = '';
10196: my $maxtries = 1;
1.800 albertel 10197: foreach my $affiliate (keys(%{$affiliatesref})) {
10198: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 10199: }
10200: $cmd =~ s/%%$//;
10201: $cmd = &escape($cmd);
10202: my $query = 'institutionalphotos';
10203: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
10204: unless ($queryid=~/^\Q$host\E\_/) {
10205: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
10206: return 'error: '.$queryid;
10207: }
10208: my $reply = &get_query_reply($queryid);
10209: my $tries = 1;
10210: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
10211: $reply = &get_query_reply($queryid);
10212: $tries ++;
10213: }
10214: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
10215: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
10216: } else {
10217: my @responses = split(/:/,$reply);
10218: my $outcome = shift(@responses);
10219: foreach my $item (@responses) {
10220: my ($key,$value) = split(/=/,$item);
10221: $$photo{$key} = $value;
10222: }
10223: return $outcome;
10224: }
10225: return 'error';
10226: }
10227:
1.521 raeburn 10228: sub auto_instcode_format {
1.793 albertel 10229: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
10230: $cat_order) = @_;
1.521 raeburn 10231: my $courses = '';
1.772 raeburn 10232: my @homeservers;
1.521 raeburn 10233: if ($caller eq 'global') {
1.841 albertel 10234: my %servers = &get_servers($codedom,'library');
10235: foreach my $tryserver (keys(%servers)) {
10236: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
10237: push(@homeservers,$tryserver);
10238: }
1.584 raeburn 10239: }
1.1022 raeburn 10240: } elsif ($caller eq 'requests') {
10241: if ($codedom =~ /^$match_domain$/) {
10242: my $chome = &domain($codedom,'primary');
10243: unless ($chome eq 'no_host') {
10244: push(@homeservers,$chome);
10245: }
10246: }
1.521 raeburn 10247: } else {
1.772 raeburn 10248: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 10249: }
1.793 albertel 10250: foreach my $code (keys(%{$instcodes})) {
10251: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 10252: }
10253: chop($courses);
1.772 raeburn 10254: my $ok_response = 0;
10255: my $response;
10256: while (@homeservers > 0 && $ok_response == 0) {
10257: my $server = shift(@homeservers);
10258: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
10259: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
10260: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 10261: split(/:/,$response);
1.772 raeburn 10262: %{$codes} = (%{$codes},&str2hash($codes_str));
10263: push(@{$codetitles},&str2array($codetitles_str));
10264: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
10265: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
10266: $ok_response = 1;
10267: }
10268: }
10269: if ($ok_response) {
1.521 raeburn 10270: return 'ok';
1.772 raeburn 10271: } else {
10272: return $response;
1.521 raeburn 10273: }
10274: }
10275:
1.792 raeburn 10276: sub auto_instcode_defaults {
10277: my ($domain,$returnhash,$code_order) = @_;
10278: my @homeservers;
1.841 albertel 10279:
10280: my %servers = &get_servers($domain,'library');
10281: foreach my $tryserver (keys(%servers)) {
10282: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
10283: push(@homeservers,$tryserver);
10284: }
1.792 raeburn 10285: }
1.841 albertel 10286:
1.792 raeburn 10287: my $response;
1.841 albertel 10288: foreach my $server (@homeservers) {
1.792 raeburn 10289: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 10290: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
10291:
10292: foreach my $pair (split(/\&/,$response)) {
10293: my ($name,$value)=split(/\=/,$pair);
10294: if ($name eq 'code_order') {
10295: @{$code_order} = split(/\&/,&unescape($value));
10296: } else {
10297: $returnhash->{&unescape($name)}=&unescape($value);
10298: }
10299: }
10300: return 'ok';
1.792 raeburn 10301: }
1.841 albertel 10302:
10303: return $response;
1.1003 raeburn 10304: }
10305:
10306: sub auto_possible_instcodes {
1.1007 raeburn 10307: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
10308: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
10309: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
10310: return;
10311: }
1.1003 raeburn 10312: my (@homeservers,$uhome);
10313: if (defined(&domain($domain,'primary'))) {
10314: $uhome=&domain($domain,'primary');
10315: push(@homeservers,&domain($domain,'primary'));
10316: } else {
10317: my %servers = &get_servers($domain,'library');
10318: foreach my $tryserver (keys(%servers)) {
10319: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
10320: push(@homeservers,$tryserver);
10321: }
10322: }
10323: }
10324: my $response;
10325: foreach my $server (@homeservers) {
10326: $response=&reply('autopossibleinstcodes:'.$domain,$server);
10327: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 10328: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
10329: split(':',$response);
10330: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
10331: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 10332: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 10333: my ($name,$value)=split('=',$item);
10334: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 10335: }
10336: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 10337: my ($name,$value)=split('=',$item);
10338: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 10339: }
10340: return 'ok';
10341: }
10342: return $response;
10343: }
1.792 raeburn 10344:
1.1010 raeburn 10345: sub auto_courserequest_checks {
10346: my ($dom) = @_;
1.1020 raeburn 10347: my ($homeserver,%validations);
10348: if ($dom =~ /^$match_domain$/) {
10349: $homeserver = &domain($dom,'primary');
10350: }
10351: unless ($homeserver eq 'no_host') {
10352: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
10353: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
10354: my @items = split(/&/,$response);
10355: foreach my $item (@items) {
10356: my ($key,$value) = split('=',$item);
10357: $validations{&unescape($key)} = &thaw_unescape($value);
10358: }
10359: }
10360: }
1.1010 raeburn 10361: return %validations;
10362: }
10363:
1.1020 raeburn 10364: sub auto_courserequest_validation {
1.1255 raeburn 10365: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020 raeburn 10366: my ($homeserver,$response);
10367: if ($dom =~ /^$match_domain$/) {
10368: $homeserver = &domain($dom,'primary');
10369: }
1.1255 raeburn 10370: unless ($homeserver eq 'no_host') {
10371: my $customdata;
10372: if (ref($custominfo) eq 'HASH') {
10373: $customdata = &freeze_escape($custominfo);
10374: }
1.1020 raeburn 10375: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 10376: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1255 raeburn 10377: ':'.&escape($instcode).':'.&escape($instseclist).':'.
10378: $customdata,$homeserver));
1.1020 raeburn 10379: }
10380: return $response;
10381: }
10382:
1.777 albertel 10383: sub auto_validate_class_sec {
1.918 raeburn 10384: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 10385: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 10386: my $ownerlist;
10387: if (ref($owners) eq 'ARRAY') {
10388: $ownerlist = join(',',@{$owners});
10389: } else {
10390: $ownerlist = $owners;
10391: }
1.773 raeburn 10392: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 10393: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 10394: return $response;
10395: }
10396:
1.1460 raeburn 10397: sub auto_instsec_reformat {
10398: my ($cdom,$action,$instsecref) = @_;
10399: return unless(($action eq 'clutter') || ($action eq 'declutter'));
10400: my @homeservers;
10401: if (defined(&domain($cdom,'primary'))) {
10402: push(@homeservers,&domain($cdom,'primary'));
10403: } else {
10404: my %servers = &get_servers($cdom,'library');
10405: foreach my $tryserver (keys(%servers)) {
10406: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
10407: push(@homeservers,$tryserver);
10408: }
10409: }
10410: }
10411: my $response;
10412: my %reformatted = %{$instsecref};
10413: foreach my $server (@homeservers) {
10414: if (ref($instsecref) eq 'HASH') {
10415: my $info = &freeze_escape($instsecref);
10416: my $response=&reply('autoinstsecreformat:'.$cdom.':'.
10417: $action.':'.$info,$server);
1.1531 ! raeburn 10418: next if ($response =~ /(con_lost|error|no_such_host|refused|unknown_cmd)/);
1.1460 raeburn 10419: my @items = split(/&/,$response);
10420: foreach my $item (@items) {
10421: my ($key,$value) = split(/=/,$item);
10422: $reformatted{&unescape($key)} = &thaw_unescape($value);
10423: }
10424: }
10425: }
10426: return %reformatted;
10427: }
10428:
1.1367 raeburn 10429: sub auto_validate_instclasses {
10430: my ($cdom,$cnum,$owners,$classesref) = @_;
10431: my ($homeserver,%validations);
10432: $homeserver = &homeserver($cnum,$cdom);
10433: unless ($homeserver eq 'no_host') {
10434: my $ownerlist;
10435: if (ref($owners) eq 'ARRAY') {
10436: $ownerlist = join(',',@{$owners});
10437: } else {
10438: $ownerlist = $owners;
10439: }
10440: if (ref($classesref) eq 'HASH') {
10441: my $classes = &freeze_escape($classesref);
10442: my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
10443: ':'.$cdom.':'.$classes,$homeserver);
10444: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
10445: my @items = split(/&/,$response);
10446: foreach my $item (@items) {
10447: my ($key,$value) = split('=',$item);
10448: $validations{&unescape($key)} = &thaw_unescape($value);
10449: }
10450: }
10451: }
10452: }
10453: return %validations;
10454: }
10455:
1.1248 raeburn 10456: sub auto_crsreq_update {
10457: my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1257 raeburn 10458: $code,$accessstart,$accessend,$inbound) = @_;
1.1248 raeburn 10459: my ($homeserver,%crsreqresponse);
10460: if ($cdom =~ /^$match_domain$/) {
10461: $homeserver = &domain($cdom,'primary');
10462: }
10463: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
10464: my $info;
10465: if (ref($inbound) eq 'HASH') {
10466: $info = &freeze_escape($inbound);
10467: }
10468: my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
10469: ':'.&escape($action).':'.&escape($ownername).':'.
10470: &escape($ownerdomain).':'.&escape($fullname).':'.
1.1257 raeburn 10471: &escape($title).':'.&escape($code).':'.
10472: &escape($accessstart).':'.&escape($accessend).':'.$info,
10473: $homeserver);
1.1248 raeburn 10474: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
10475: my @items = split(/&/,$response);
10476: foreach my $item (@items) {
10477: my ($key,$value) = split('=',$item);
10478: $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
10479: }
10480: }
10481: }
10482: return \%crsreqresponse;
10483: }
10484:
1.1305 raeburn 10485: sub auto_export_grades {
1.1309 raeburn 10486: my ($cdom,$cnum,$inforef,$gradesref) = @_;
10487: my ($homeserver,%exportresponse);
10488: if ($cdom =~ /^$match_domain$/) {
10489: $homeserver = &domain($cdom,'primary');
10490: }
10491: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
10492: my $info;
10493: if (ref($inforef) eq 'HASH') {
10494: $info = &freeze_escape($inforef);
10495: }
10496: if (ref($gradesref) eq 'HASH') {
10497: my $grades = &freeze_escape($gradesref);
10498: my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
10499: $info.':'.$grades,$homeserver);
1.1531 ! raeburn 10500: unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_cmd)/) {
1.1309 raeburn 10501: my @items = split(/&/,$response);
10502: foreach my $item (@items) {
10503: my ($key,$value) = split('=',$item);
10504: $exportresponse{&unescape($key)} = &thaw_unescape($value);
10505: }
10506: }
10507: }
10508: }
10509: return \%exportresponse;
1.1305 raeburn 10510: }
10511:
1.1287 raeburn 10512: sub check_instcode_cloning {
10513: my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
10514: unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
10515: return;
10516: }
10517: my $canclone;
10518: if (@{$code_order} > 0) {
10519: my $instcoderegexp ='^';
10520: my @clonecodes = split(/\&/,$cloner);
10521: foreach my $item (@{$code_order}) {
10522: if (grep(/^\Q$item\E=/,@clonecodes)) {
10523: foreach my $pair (@clonecodes) {
10524: my ($key,$val) = split(/\=/,$pair,2);
10525: $val = &unescape($val);
10526: if ($key eq $item) {
10527: $instcoderegexp .= '('.$val.')';
10528: last;
10529: }
10530: }
10531: } else {
10532: $instcoderegexp .= $codedefaults->{$item};
10533: }
10534: }
10535: $instcoderegexp .= '$';
10536: my (@from,@to);
10537: eval {
10538: (@from) = ($clonefromcode =~ /$instcoderegexp/);
10539: (@to) = ($clonetocode =~ /$instcoderegexp/);
10540: };
10541: if ((@from > 0) && (@to > 0)) {
10542: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
10543: if (!@diffs) {
10544: $canclone = 1;
10545: }
10546: }
10547: }
10548: return $canclone;
10549: }
10550:
10551: sub default_instcode_cloning {
10552: my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
10553: my (%codedefaults,@code_order,$canclone);
10554: if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
10555: %codedefaults = %{$codedefaultsref};
10556: @code_order = @{$codeorderref};
10557: } elsif ($clonedom) {
10558: &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
10559: }
10560: if (($domdefclone) && (@code_order)) {
10561: my @clonecodes = split(/\+/,$domdefclone);
10562: my $instcoderegexp ='^';
10563: foreach my $item (@code_order) {
10564: if (grep(/^\Q$item\E$/,@clonecodes)) {
10565: $instcoderegexp .= '('.$codedefaults{$item}.')';
10566: } else {
10567: $instcoderegexp .= $codedefaults{$item};
10568: }
10569: }
10570: $instcoderegexp .= '$';
10571: my (@from,@to);
10572: eval {
10573: (@from) = ($clonefromcode =~ /$instcoderegexp/);
10574: (@to) = ($clonetocode =~ /$instcoderegexp/);
10575: };
10576: if ((@from > 0) && (@to > 0)) {
10577: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
10578: if (!@diffs) {
10579: $canclone = 1;
10580: }
10581: }
10582: }
10583: return $canclone;
10584: }
10585:
1.679 raeburn 10586: # ------------------------------------------------------- Course Group routines
10587:
10588: sub get_coursegroups {
1.809 raeburn 10589: my ($cdom,$cnum,$group,$namespace) = @_;
10590: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 10591: }
10592:
1.679 raeburn 10593: sub modify_coursegroup {
10594: my ($cdom,$cnum,$groupsettings) = @_;
10595: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
10596: }
10597:
1.809 raeburn 10598: sub toggle_coursegroup_status {
10599: my ($cdom,$cnum,$group,$action) = @_;
10600: my ($from_namespace,$to_namespace);
10601: if ($action eq 'delete') {
10602: $from_namespace = 'coursegroups';
10603: $to_namespace = 'deleted_groups';
10604: } else {
10605: $from_namespace = 'deleted_groups';
10606: $to_namespace = 'coursegroups';
10607: }
10608: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 10609: if (my $tmp = &error(%curr_group)) {
10610: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
10611: return ('read error',$tmp);
10612: } else {
10613: my %savedsettings = %curr_group;
1.809 raeburn 10614: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 10615: my $deloutcome;
10616: if ($result eq 'ok') {
1.809 raeburn 10617: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 10618: } else {
10619: return ('write error',$result);
10620: }
10621: if ($deloutcome eq 'ok') {
10622: return 'ok';
10623: } else {
10624: return ('delete error',$deloutcome);
10625: }
10626: }
10627: }
10628:
1.679 raeburn 10629: sub modify_group_roles {
1.1512 raeburn 10630: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context,
10631: $othdomby,$requester) = @_;
1.679 raeburn 10632: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
10633: my $role = 'gr/'.&escape($userprivs);
10634: my ($uname,$udom) = split(/:/,$user);
1.1512 raeburn 10635: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context,
10636: $othdomby,$requester);
1.684 raeburn 10637: if ($result eq 'ok') {
10638: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
10639: }
1.679 raeburn 10640: return $result;
10641: }
10642:
10643: sub modify_coursegroup_membership {
10644: my ($cdom,$cnum,$membership) = @_;
10645: my $result = &put('groupmembership',$membership,$cdom,$cnum);
10646: return $result;
10647: }
10648:
1.682 raeburn 10649: sub get_active_groups {
10650: my ($udom,$uname,$cdom,$cnum) = @_;
10651: my $now = time;
10652: my %groups = ();
10653: foreach my $key (keys(%env)) {
1.811 albertel 10654: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 10655: my ($start,$end) = split(/\./,$env{$key});
10656: if (($end!=0) && ($end<$now)) { next; }
10657: if (($start!=0) && ($start>$now)) { next; }
10658: if ($1 eq $cdom && $2 eq $cnum) {
10659: $groups{$3} = $env{$key} ;
10660: }
10661: }
10662: }
10663: return %groups;
10664: }
10665:
1.683 raeburn 10666: sub get_group_membership {
10667: my ($cdom,$cnum,$group) = @_;
10668: return(&dump('groupmembership',$cdom,$cnum,$group));
10669: }
10670:
10671: sub get_users_groups {
10672: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 10673: my @usersgroups;
1.683 raeburn 10674: my $cachetime=1800;
10675:
10676: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 10677: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
10678: if (defined($cached)) {
1.734 albertel 10679: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 10680: } else {
10681: $grouplist = '';
1.816 raeburn 10682: my $courseurl = &courseid_to_courseurl($courseid);
1.1166 raeburn 10683: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 10684: my $access_end = $env{'course.'.$courseid.
10685: '.default_enrollment_end_date'};
10686: my $now = time;
10687: foreach my $key (keys(%roleshash)) {
10688: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
10689: my $group = $1;
10690: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
10691: my $start = $2;
10692: my $end = $1;
10693: if ($start == -1) { next; } # deleted from group
10694: if (($start!=0) && ($start>$now)) { next; }
10695: if (($end!=0) && ($end<$now)) {
10696: if ($access_end && $access_end < $now) {
10697: if ($access_end - $end < 86400) {
10698: push(@usersgroups,$group);
1.733 raeburn 10699: }
10700: }
1.817 raeburn 10701: next;
1.733 raeburn 10702: }
1.817 raeburn 10703: push(@usersgroups,$group);
1.683 raeburn 10704: }
10705: }
10706: }
1.817 raeburn 10707: @usersgroups = &sort_course_groups($courseid,@usersgroups);
10708: $grouplist = join(':',@usersgroups);
10709: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 10710: }
1.733 raeburn 10711: return @usersgroups;
1.683 raeburn 10712: }
10713:
10714: sub devalidate_getgroups_cache {
10715: my ($udom,$uname,$cdom,$cnum)=@_;
10716: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 10717:
1.683 raeburn 10718: my $hashid="$udom:$uname:$courseid";
10719: &devalidate_cache_new('getgroups',$hashid);
10720: }
10721:
1.12 www 10722: # ------------------------------------------------------------------ Plain Text
10723:
10724: sub plaintext {
1.988 raeburn 10725: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 10726: if ($short =~ m{^cr/}) {
1.758 albertel 10727: return (split('/',$short))[-1];
10728: }
1.742 raeburn 10729: if (!defined($cid)) {
10730: $cid = $env{'request.course.id'};
10731: }
10732: my %rolenames = (
1.1008 raeburn 10733: Course => 'std',
10734: Community => 'alt1',
1.1305 raeburn 10735: Placement => 'std',
1.742 raeburn 10736: );
1.1037 raeburn 10737: if ($cid ne '') {
10738: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
10739: unless ($forcedefault) {
10740: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
10741: &Apache::lonlocal::mt_escape(\$roletext);
10742: return &Apache::lonlocal::mt($roletext);
10743: }
10744: }
10745: }
10746: if ((defined($type)) && (defined($rolenames{$type})) &&
10747: (defined($rolenames{$type})) &&
10748: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 10749: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 10750: } elsif ($cid ne '') {
10751: my $crstype = $env{'course.'.$cid.'.type'};
10752: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
10753: (defined($prp{$short}{$rolenames{$crstype}}))) {
10754: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
10755: }
1.742 raeburn 10756: }
1.1037 raeburn 10757: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 10758: }
10759:
10760: # ----------------------------------------------------------------- Assign Role
10761:
10762: sub assignrole {
1.957 raeburn 10763: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
1.1512 raeburn 10764: $context,$othdomby,$requester,$reqsec,$reqrole)=@_;
1.1517 raeburn 10765: my ($mrole,$rolelogcontext);
1.21 www 10766: if ($role =~ /^cr\//) {
1.393 www 10767: my $cwosec=$url;
1.811 albertel 10768: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.1502 raeburn 10769: if ((!&allowed('ccr',$cwosec)) && (!&allowed('ccr',$udom))) {
1.1512 raeburn 10770: my $refused = 1;
10771: if ($context eq 'requestcourses') {
10772: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
10773: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
10774: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
10775: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
10776: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10777: if ($crsenv{'internal.courseowner'} eq
10778: $env{'user.name'}.':'.$env{'user.domain'}) {
10779: $refused = '';
10780: }
10781: }
10782: }
10783: }
10784: } elsif (($context eq 'course') && ($othdomby eq 'othdombyuser')) {
10785: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
10786: my ($sec) = ($url =~ m{^/\Q$cwosec\E/(.*)$});
10787: my $key = "$uname:$udom:$role:$sec";
10788: my %queuedrolereq = &Apache::lonnet::get('nohist_othdomqueued',[$key],$cdom,$cnum);
10789: if ((exists($queuedrolereq{$key})) && (ref($queuedrolereq{$key}) eq 'HASH')) {
10790: if (($queuedrolereq{$key}{'adj'} eq 'user') && ($queuedrolereq{$key}{'requester'} eq $requester)) {
10791: $refused = '';
10792: }
10793: }
10794: }
10795: if ($refused) {
10796: &logthis('Refused custom assignrole: '.
10797: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
10798: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
10799: return 'refused';
10800: }
1.104 www 10801: }
1.21 www 10802: $mrole='cr';
1.678 raeburn 10803: } elsif ($role =~ /^gr\//) {
10804: my $cwogrp=$url;
1.811 albertel 10805: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.1512 raeburn 10806: if (!&allowed('mdg',$cwogrp)) {
10807: my $refused = 1;
10808: if (($refused) && ($othdomby eq 'othdombyuser') && ($requester ne '') && ($reqrole ne '')) {
10809: my ($cdom,$cnum) = ($cwogrp =~ m{^/?($match_domain)/($match_courseid)$});
10810: my $key = "$uname:$udom:$reqrole:$reqsec";
10811: my %queuedrolereq = &Apache::lonnet::get('nohist_othdomqueued',[$key],$cdom,$cnum);
10812: if ((exists($queuedrolereq{$key})) && (ref($queuedrolereq{$key}) eq 'HASH')) {
10813: if (($queuedrolereq{$key}{'adj'} eq 'user') && ($queuedrolereq{$key}{'requester'} eq $requester)) {
10814: $refused = '';
10815: }
10816: }
10817: }
10818: if ($refused) {
10819: &logthis('Refused group assignrole: '.
10820: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
10821: $env{'user.name'}.' at '.$env{'user.domain'});
10822: return 'refused';
10823: }
1.678 raeburn 10824: }
10825: $mrole='gr';
1.21 www 10826: } else {
1.82 www 10827: my $cwosec=$url;
1.811 albertel 10828: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 10829: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
10830: my $refused;
10831: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
10832: if (!(&allowed('c'.$role,$url))) {
10833: $refused = 1;
10834: }
10835: } else {
10836: $refused = 1;
10837: }
1.947 raeburn 10838: if ($refused) {
1.1045 raeburn 10839: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
1.1512 raeburn 10840: if (!$selfenroll && ($othdomby ne 'othdombyuser') &&
10841: (($context eq 'course') || ($context eq 'ltienroll' && $env{'request.lti.login'}))) {
1.1045 raeburn 10842: my %crsenv;
10843: if ($role eq 'cc' || $role eq 'co') {
10844: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10845: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
10846: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
10847: if ($crsenv{'internal.courseowner'} eq
10848: $env{'user.name'}.':'.$env{'user.domain'}) {
10849: $refused = '';
10850: }
10851: }
10852: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
10853: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
10854: if ($crsenv{'internal.courseowner'} eq
10855: $env{'user.name'}.':'.$env{'user.domain'}) {
10856: $refused = '';
10857: }
10858: }
10859: }
10860: }
1.1368 raeburn 10861: } elsif (($selfenroll == 1) && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
10862: if ($role eq 'st') {
10863: $refused = '';
1.1377 raeburn 10864: } elsif (($context eq 'ltienroll') && ($env{'request.lti.login'})) {
1.1368 raeburn 10865: $refused = '';
10866: }
1.1512 raeburn 10867: } elsif ($othdomby eq 'othdombyuser') {
10868: my ($key,%queuedrolereq);
10869: if ($context eq 'course') {
10870: my ($sec) = ($url =~ m{^/\Q$cwosec\E/(.*)$});
10871: $key = "$uname:$udom:$role:$sec";
10872: %queuedrolereq = &Apache::lonnet::get('nohist_othdomqueued',[$key],$cdom,$cnum);
10873: if ((exists($queuedrolereq{$key})) && (ref($queuedrolereq{$key}) eq 'HASH')) {
10874: if (($queuedrolereq{$key}{'adj'} eq 'user') && ($queuedrolereq{$key}{'requester'} eq $requester)) {
10875: if ((($role eq 'cc') && ($cnum !~ /^$match_community$/)) ||
10876: (($role eq 'co') && ($cnum =~ /^$match_community$/))) {
10877: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10878: if ($crsenv{'internal.courseowner'} eq $requester) {
10879: $refused = '';
10880: }
10881: } elsif ($role =~ /^(?:in|ta|ep|st)$/) {
10882: $refused = '';
10883: }
10884: }
10885: }
10886: } elsif (($context eq 'author') && ($role =~ /^ca|aa$/)) {
10887: my $key = "$uname:$udom:$role";
10888: my ($audom,$auname) = ($url =~ m{^/($match_domain)/($match_username)$});
10889: if (($audom ne '') && ($auname ne '')) {
10890: my %queuedrolereq = &Apache::lonnet::get('nohist_othdomqueued',[$key],$audom,$auname);
10891: if ((exists($queuedrolereq{$key})) && (ref($queuedrolereq{$key}) eq 'HASH')) {
10892: if (($queuedrolereq{$key}{'adj'} eq 'user') && ($queuedrolereq{$key}{'requester'} eq $requester)) {
10893: $refused = '';
10894: }
10895: }
10896: }
10897: } elsif (($context eq 'domain') && ($role ne 'dc') && ($role ne 'su')) {
10898: my $key = "$uname:$udom:$role";
10899: my ($roledom) = ($url =~ m{^/($match_domain)/\Q$role\E$});
10900: if ($roledom ne '') {
10901: my $confname = $roledom.'-domainconfig';
10902: my %queuedrolereq = &Apache::lonnet::get('nohist_othdomqueued',[$key],$roledom,$confname);
10903: if ((exists($queuedrolereq{$key})) && (ref($queuedrolereq{$key}) eq 'HASH')) {
10904: if (($queuedrolereq{$key}{'adj'} eq 'user') && ($queuedrolereq{$key}{'requester'} eq $requester)) {
10905: $refused = '';
10906: }
10907: }
10908: }
10909: }
1.1017 raeburn 10910: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 10911: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 10912: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 10913: my $wrongcc;
10914: if ($cnum =~ /^$match_community$/) {
10915: $wrongcc = 1 if ($role eq 'cc');
10916: } else {
10917: $wrongcc = 1 if ($role eq 'co');
10918: }
10919: unless ($wrongcc) {
10920: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10921: if ($crsenv{'internal.courseowner'} eq
10922: $env{'user.name'}.':'.$env{'user.domain'}) {
10923: $refused = '';
10924: }
1.1017 raeburn 10925: }
10926: }
1.1183 raeburn 10927: } elsif ($context eq 'requestauthor') {
10928: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
10929: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
10930: if ($env{'environment.requestauthor'} eq 'automatic') {
10931: $refused = '';
10932: } else {
10933: my %domdefaults = &get_domain_defaults($udom);
10934: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
10935: my $checkbystatus;
10936: if ($env{'user.adv'}) {
10937: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
10938: if ($disposition eq 'automatic') {
10939: $refused = '';
10940: } elsif ($disposition eq '') {
10941: $checkbystatus = 1;
10942: }
10943: } else {
10944: $checkbystatus = 1;
10945: }
10946: if ($checkbystatus) {
10947: if ($env{'environment.inststatus'}) {
10948: my @inststatuses = split(/,/,$env{'environment.inststatus'});
10949: foreach my $type (@inststatuses) {
10950: if (($type ne '') &&
10951: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
10952: $refused = '';
10953: }
10954: }
10955: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
10956: $refused = '';
10957: }
10958: }
10959: }
10960: }
10961: }
1.1517 raeburn 10962: } elsif (($context eq 'author') && (($role eq 'ca' || $role eq 'aa'))) {
10963: if ($url =~ m{^/($match_domain)/($match_username)$}) {
10964: my ($audom,$auname) = ($1,$2);
10965: if ((&Apache::lonnet::allowed('v'.$role,"$audom/$auname")) &&
10966: ($env{"environment.internal.manager.$url"})) {
10967: $refused = '';
10968: $rolelogcontext = 'coauthor';
10969: }
10970: }
1.1017 raeburn 10971: }
10972: if ($refused) {
1.947 raeburn 10973: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
10974: ' '.$role.' '.$end.' '.$start.' by '.
10975: $env{'user.name'}.' at '.$env{'user.domain'});
10976: return 'refused';
10977: }
1.932 raeburn 10978: }
1.1131 raeburn 10979: } elsif ($role eq 'au') {
10980: if ($url ne '/'.$udom.'/') {
10981: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
10982: ' to assign author role for '.$uname.':'.$udom.
10983: ' in domain: '.$url.' refused (wrong domain).');
10984: return 'refused';
10985: }
1.104 www 10986: }
1.21 www 10987: $mrole=$role;
10988: }
1.620 albertel 10989: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 10990: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 10991: if ($end) { $command.='_'.$end; }
1.21 www 10992: if ($start) {
10993: if ($end) {
1.81 www 10994: $command.='_'.$start;
1.21 www 10995: } else {
1.81 www 10996: $command.='_0_'.$start;
1.21 www 10997: }
10998: }
1.739 raeburn 10999: my $origstart = $start;
11000: my $origend = $end;
1.957 raeburn 11001: my $delflag;
1.357 www 11002: # actually delete
11003: if ($deleteflag) {
1.373 www 11004: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 11005: # modify command to delete the role
1.620 albertel 11006: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 11007: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 11008: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 11009: # set start and finish to negative values for userrolelog
11010: $start=-1;
11011: $end=-1;
1.957 raeburn 11012: $delflag = 1;
1.357 www 11013: }
11014: }
11015: # send command
1.349 www 11016: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 11017: # log new user role if status is ok
1.349 www 11018: if ($answer eq 'ok') {
1.663 raeburn 11019: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.1184 raeburn 11020: if (($role eq 'cc') || ($role eq 'in') ||
11021: ($role eq 'ep') || ($role eq 'ad') ||
11022: ($role eq 'ta') || ($role eq 'st') ||
11023: ($role=~/^cr/) || ($role eq 'gr') ||
11024: ($role eq 'co')) {
1.1200 raeburn 11025: # for course roles, perform group memberships changes triggered by role change.
11026: unless ($role =~ /^gr/) {
11027: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
11028: $origstart,$selfenroll,$context);
11029: }
1.1184 raeburn 11030: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
1.1512 raeburn 11031: $selfenroll,$context,$othdomby,$requester);
1.1184 raeburn 11032: } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1334 raeburn 11033: ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
11034: ($role eq 'da')) {
1.1184 raeburn 11035: &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
1.1512 raeburn 11036: $context,$othdomby,$requester);
1.1184 raeburn 11037: } elsif (($role eq 'ca') || ($role eq 'aa')) {
1.1517 raeburn 11038: if ($rolelogcontext eq '') {
11039: $rolelogcontext = $context;
11040: }
1.1184 raeburn 11041: &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
1.1517 raeburn 11042: $rolelogcontext,$othdomby,$requester);
1.1184 raeburn 11043: }
1.1053 raeburn 11044: if ($role eq 'cc') {
11045: &autoupdate_coowners($url,$end,$start,$uname,$udom);
11046: }
1.349 www 11047: }
11048: return $answer;
1.169 harris41 11049: }
11050:
1.1053 raeburn 11051: sub autoupdate_coowners {
11052: my ($url,$end,$start,$uname,$udom) = @_;
11053: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
11054: if (($cdom ne '') && ($cnum ne '')) {
11055: my $now = time;
11056: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
11057: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
11058: my %coursehash = &coursedescription($cdom.'_'.$cnum);
11059: my $instcode = $coursehash{'internal.coursecode'};
1.1444 raeburn 11060: my $xlists = $coursehash{'internal.crosslistings'};
1.1053 raeburn 11061: if ($instcode ne '') {
1.1056 raeburn 11062: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
11063: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 11064: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 11065: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
1.1444 raeburn 11066: unless ($result eq 'valid') {
11067: if ($xlists ne '') {
11068: foreach my $xlist (split(',',$xlists)) {
11069: my ($inst_crosslist,$lcsec) = split(':',$xlist);
11070: $result =
1.1446 raeburn 11071: &auto_validate_inst_crosslist($cnum,$cdom,$instcode,
11072: $inst_crosslist,$uname.':'.$udom);
11073: last if ($result eq 'valid');
1.1444 raeburn 11074: }
11075: }
11076: }
1.1056 raeburn 11077: if ($result eq 'valid') {
11078: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 11079: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
11080: push(@newcoowners,$coowner);
11081: }
11082: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
11083: push(@newcoowners,$uname.':'.$udom);
11084: }
11085: @newcoowners = sort(@newcoowners);
11086: } else {
11087: push(@newcoowners,$uname.':'.$udom);
11088: }
1.1444 raeburn 11089: } elsif ($coursehash{'internal.co-owners'}) {
11090: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
11091: unless ($coowner eq $uname.':'.$udom) {
11092: push(@newcoowners,$coowner);
1.1053 raeburn 11093: }
1.1444 raeburn 11094: }
11095: unless (@newcoowners > 0) {
11096: $delcoowners = 1;
11097: $coowners = '';
1.1053 raeburn 11098: }
11099: }
11100: if (@newcoowners || $delcoowners) {
11101: &store_coowners($cdom,$cnum,$coursehash{'home'},
11102: $delcoowners,@newcoowners);
11103: }
11104: }
11105: }
11106: }
11107: }
11108: }
11109: }
11110:
11111: sub store_coowners {
11112: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
11113: my $cid = $cdom.'_'.$cnum;
11114: my ($coowners,$delresult,$putresult);
11115: if (@newcoowners) {
11116: $coowners = join(',',@newcoowners);
11117: my %coownershash = (
11118: 'internal.co-owners' => $coowners,
11119: );
11120: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
11121: if ($putresult eq 'ok') {
11122: if ($env{'course.'.$cid.'.num'} eq $cnum) {
11123: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
11124: }
11125: }
11126: }
11127: if ($delcoowners) {
11128: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
11129: if ($delresult eq 'ok') {
11130: if ($env{'course.'.$cid.'.internal.co-owners'}) {
11131: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
11132: }
11133: }
11134: }
11135: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
11136: my %crsinfo =
1.1494 raeburn 11137: &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
1.1053 raeburn 11138: if (ref($crsinfo{$cid}) eq 'HASH') {
11139: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
1.1494 raeburn 11140: my $cidput = &courseidput($cdom,\%crsinfo,$chome,'notime');
1.1053 raeburn 11141: }
11142: }
11143: }
11144:
1.169 harris41 11145: # -------------------------------------------------- Modify user authentication
1.197 www 11146: # Overrides without validation
11147:
1.169 harris41 11148: sub modifyuserauth {
11149: my ($udom,$uname,$umode,$upass)=@_;
11150: my $uhome=&homeserver($uname,$udom);
1.1409 raeburn 11151: my $allowed;
11152: if (&allowed('mau',$udom)) {
11153: $allowed = 1;
11154: } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
11155: ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
11156: (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
11157: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
11158: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
11159: if (($cdom ne '') && ($cnum ne '')) {
11160: my $is_owner = &is_course_owner($cdom,$cnum);
11161: if ($is_owner) {
11162: $allowed = 1;
11163: }
11164: }
11165: }
11166: unless ($allowed) { return 'refused'; }
1.197 www 11167: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 11168: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
11169: ' in domain '.$env{'request.role.domain'});
1.169 harris41 11170: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
11171: &escape($upass),$uhome);
1.1434 raeburn 11172: my $ip = &get_requestor_ip();
1.620 albertel 11173: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 11174: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
1.1434 raeburn 11175: '(Remote '.$ip.'): '.$reply);
1.197 www 11176: &log($udom,,$uname,$uhome,
1.620 albertel 11177: 'Authentication changed by '.$env{'user.domain'}.', '.
11178: $env{'user.name'}.', '.$umode.
1.1435 raeburn 11179: '(Remote '.$ip.'): '.$reply);
1.169 harris41 11180: unless ($reply eq 'ok') {
1.197 www 11181: &logthis('Authentication mode error: '.$reply);
1.169 harris41 11182: return 'error: '.$reply;
11183: }
1.170 harris41 11184: return 'ok';
1.80 www 11185: }
11186:
1.81 www 11187: # --------------------------------------------------------------- Modify a user
1.80 www 11188:
1.81 www 11189: sub modifyuser {
1.206 matthew 11190: my ($udom, $uname, $uid,
11191: $umode, $upass, $first,
11192: $middle, $last, $gene,
1.1058 raeburn 11193: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 11194: $udom= &LONCAPA::clean_domain($udom);
11195: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 11196: my $showcandelete = 'none';
11197: if (ref($candelete) eq 'ARRAY') {
11198: if (@{$candelete} > 0) {
11199: $showcandelete = join(', ',@{$candelete});
11200: }
11201: }
1.81 www 11202: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 11203: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 11204: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 11205: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
11206: ' desiredhome not specified').
1.620 albertel 11207: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
11208: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 11209: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 11210: my $newuser;
11211: if ($uhome eq 'no_host') {
11212: $newuser = 1;
1.1368 raeburn 11213: unless (($umode && ($upass ne '')) || ($umode eq 'localauth') ||
11214: ($umode eq 'lti')) {
11215: return 'error: more information needed to create new user';
11216: }
1.1075 raeburn 11217: }
1.80 www 11218: # ----------------------------------------------------------------- Create User
1.406 albertel 11219: if (($uhome eq 'no_host') &&
1.1368 raeburn 11220: (($umode && $upass) || ($umode eq 'localauth') || ($umode eq 'lti'))) {
1.80 www 11221: my $unhome='';
1.844 albertel 11222: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 11223: $unhome = $desiredhome;
1.620 albertel 11224: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
11225: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 11226: } else { # load balancing routine for determining $unhome
1.81 www 11227: my $loadm=10000000;
1.841 albertel 11228: my %servers = &get_servers($udom,'library');
11229: foreach my $tryserver (keys(%servers)) {
11230: my $answer=reply('load',$tryserver);
11231: if (($answer=~/\d+/) && ($answer<$loadm)) {
11232: $loadm=$answer;
11233: $unhome=$tryserver;
11234: }
1.80 www 11235: }
11236: }
11237: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 11238: return 'error: unable to find a home server for '.$uname.
11239: ' in domain '.$udom;
1.80 www 11240: }
11241: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
11242: &escape($upass),$unhome);
11243: unless ($reply eq 'ok') {
11244: return 'error: '.$reply;
11245: }
1.230 stredwic 11246: $uhome=&homeserver($uname,$udom,'true');
1.80 www 11247: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 11248: return 'error: unable verify users home machine.';
1.80 www 11249: }
1.209 matthew 11250: } # End of creation of new user
1.80 www 11251: # ---------------------------------------------------------------------- Add ID
11252: if ($uid) {
11253: $uid=~tr/A-Z/a-z/;
11254: my %uidhash=&idrget($udom,$uname);
1.196 www 11255: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
11256: && (!$forceid)) {
1.80 www 11257: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 11258: return 'error: user id "'.$uid.'" does not match '.
11259: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 11260: }
11261: } else {
1.1300 raeburn 11262: &idput($udom,{$uname => $uid},$uhome,'ids');
1.80 www 11263: }
11264: }
11265: # -------------------------------------------------------------- Add names, etc
1.313 matthew 11266: my @tmp=&get('environment',
1.899 raeburn 11267: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 11268: 'permanentemail','inststatus'],
1.134 albertel 11269: $udom,$uname);
1.1075 raeburn 11270: my (%names,%oldnames);
1.313 matthew 11271: if ($tmp[0] =~ m/^error:.*/) {
11272: %names=();
11273: } else {
11274: %names = @tmp;
1.1075 raeburn 11275: %oldnames = %names;
1.313 matthew 11276: }
1.388 www 11277: #
1.1058 raeburn 11278: # If name, email and/or uid are blank (e.g., because an uploaded file
11279: # of users did not contain them), do not overwrite existing values
11280: # unless field is in $candelete array ref.
11281: #
11282:
11283: my @fields = ('firstname','middlename','lastname','generation',
11284: 'permanentemail','id');
11285: my %newvalues;
11286: if (ref($candelete) eq 'ARRAY') {
11287: foreach my $field (@fields) {
11288: if (grep(/^\Q$field\E$/,@{$candelete})) {
11289: if ($field eq 'firstname') {
11290: $names{$field} = $first;
11291: } elsif ($field eq 'middlename') {
11292: $names{$field} = $middle;
11293: } elsif ($field eq 'lastname') {
11294: $names{$field} = $last;
11295: } elsif ($field eq 'generation') {
11296: $names{$field} = $gene;
11297: } elsif ($field eq 'permanentemail') {
11298: $names{$field} = $email;
11299: } elsif ($field eq 'id') {
11300: $names{$field} = $uid;
11301: }
11302: }
11303: }
11304: }
1.388 www 11305: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 11306: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 11307: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 11308: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 11309: if ($email) {
11310: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 11311: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 11312: }
1.899 raeburn 11313: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 11314: if (defined($inststatus)) {
11315: $names{'inststatus'} = '';
11316: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
11317: if (ref($usertypes) eq 'HASH') {
11318: my @okstatuses;
11319: foreach my $item (split(/:/,$inststatus)) {
11320: if (defined($usertypes->{$item})) {
11321: push(@okstatuses,$item);
11322: }
11323: }
11324: if (@okstatuses) {
11325: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
11326: }
11327: }
11328: }
1.1075 raeburn 11329: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 11330: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 11331: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 11332: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
11333: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
11334: } else {
11335: $logmsg .= ' during self creation';
11336: }
1.1075 raeburn 11337: my $changed;
11338: if ($newuser) {
11339: $changed = 1;
11340: } else {
11341: foreach my $field (@fields) {
11342: if ($names{$field} ne $oldnames{$field}) {
11343: $changed = 1;
11344: last;
11345: }
11346: }
11347: }
11348: unless ($changed) {
11349: $logmsg = 'No changes in user information needed for: '.$logmsg;
11350: &logthis($logmsg);
11351: return 'ok';
11352: }
11353: my $reply = &put('environment', \%names, $udom,$uname);
11354: if ($reply ne 'ok') {
11355: return 'error: '.$reply;
11356: }
1.1087 raeburn 11357: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
1.1494 raeburn 11358: &devalidate_cache_new('emailscache',$uname.':'.$udom);
1.1087 raeburn 11359: }
1.1075 raeburn 11360: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
11361: &devalidate_cache_new('namescache',$uname.':'.$udom);
11362: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 11363: &logthis($logmsg);
1.134 albertel 11364: return 'ok';
1.80 www 11365: }
11366:
1.81 www 11367: # -------------------------------------------------------------- Modify student
1.80 www 11368:
1.81 www 11369: sub modifystudent {
11370: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 11371: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1314 raeburn 11372: $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455 albertel 11373: if (!$cid) {
1.620 albertel 11374: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 11375: return 'not_in_class';
11376: }
1.80 www 11377: }
11378: # --------------------------------------------------------------- Make the user
1.81 www 11379: my $reply=&modifyuser
1.209 matthew 11380: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 11381: $desiredhome,$email,$inststatus);
1.80 www 11382: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 11383: # This will cause &modify_student_enrollment to get the uid from the
1.1235 raeburn 11384: # student's environment
1.297 matthew 11385: $uid = undef if (!$forceid);
1.455 albertel 11386: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1216 raeburn 11387: $gene,$usec,$end,$start,$type,$locktype,
1.1314 raeburn 11388: $cid,$selfenroll,$context,$credits,$instsec);
1.297 matthew 11389: return $reply;
11390: }
11391:
11392: sub modify_student_enrollment {
1.1216 raeburn 11393: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1512 raeburn 11394: $locktype,$cid,$selfenroll,$context,$credits,$instsec,$othdomby,$requester) = @_;
1.455 albertel 11395: my ($cdom,$cnum,$chome);
11396: if (!$cid) {
1.620 albertel 11397: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 11398: return 'not_in_class';
11399: }
1.620 albertel 11400: $cdom=$env{'course.'.$cid.'.domain'};
11401: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 11402: } else {
11403: ($cdom,$cnum)=split(/_/,$cid);
11404: }
1.620 albertel 11405: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 11406: if (!$chome) {
1.457 raeburn 11407: $chome=&homeserver($cnum,$cdom);
1.297 matthew 11408: }
1.455 albertel 11409: if (!$chome) { return 'unknown_course'; }
1.297 matthew 11410: # Make sure the user exists
1.81 www 11411: my $uhome=&homeserver($uname,$udom);
11412: if (($uhome eq '') || ($uhome eq 'no_host')) {
11413: return 'error: no such user';
11414: }
1.297 matthew 11415: # Get student data if we were not given enough information
11416: if (!defined($first) || $first eq '' ||
11417: !defined($last) || $last eq '' ||
11418: !defined($uid) || $uid eq '' ||
11419: !defined($middle) || $middle eq '' ||
11420: !defined($gene) || $gene eq '') {
1.294 matthew 11421: # They did not supply us with enough data to enroll the student, so
11422: # we need to pick up more information.
1.297 matthew 11423: my %tmp = &get('environment',
1.294 matthew 11424: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 11425: ,$udom,$uname);
11426:
1.800 albertel 11427: #foreach my $key (keys(%tmp)) {
11428: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 11429: #}
1.294 matthew 11430: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
11431: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
11432: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 11433: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 11434: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
11435: }
1.556 albertel 11436: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148 raeburn 11437: my $user = "$uname:$udom";
1.1494 raeburn 11438: my %old_entry = &get('classlist',[$user],$cdom,$cnum);
1.487 albertel 11439: my $reply=cput('classlist',
1.1148 raeburn 11440: {$user =>
1.1314 raeburn 11441: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487 albertel 11442: $cdom,$cnum);
1.1148 raeburn 11443: if (($reply eq 'ok') || ($reply eq 'delayed')) {
11444: &devalidate_getsection_cache($udom,$uname,$cid);
11445: } else {
1.81 www 11446: return 'error: '.$reply;
11447: }
1.297 matthew 11448: # Add student role to user
1.83 www 11449: my $uurl='/'.$cid;
1.81 www 11450: $uurl=~s/\_/\//g;
11451: if ($usec) {
11452: $uurl.='/'.$usec;
11453: }
1.1148 raeburn 11454: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
1.1512 raeburn 11455: $selfenroll,$context,$othdomby,$requester);
1.1148 raeburn 11456: if ($result ne 'ok') {
11457: if ($old_entry{$user} ne '') {
11458: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
11459: } else {
11460: $reply = &del('classlist',[$user],$cdom,$cnum);
11461: }
11462: }
11463: return $result;
1.21 www 11464: }
11465:
1.556 albertel 11466: sub format_name {
11467: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
11468: my $name;
11469: if ($first ne 'lastname') {
11470: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
11471: } else {
11472: if ($lastname=~/\S/) {
11473: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
11474: $name=~s/\s+,/,/;
11475: } else {
11476: $name.= $firstname.' '.$middlename.' '.$generation;
11477: }
11478: }
11479: $name=~s/^\s+//;
11480: $name=~s/\s+$//;
11481: $name=~s/\s+/ /g;
11482: return $name;
11483: }
11484:
1.84 www 11485: # ------------------------------------------------- Write to course preferences
11486:
11487: sub writecoursepref {
11488: my ($courseid,%prefs)=@_;
11489: $courseid=~s/^\///;
11490: $courseid=~s/\_/\//g;
11491: my ($cdomain,$cnum)=split(/\//,$courseid);
11492: my $chome=homeserver($cnum,$cdomain);
11493: if (($chome eq '') || ($chome eq 'no_host')) {
11494: return 'error: no such course';
11495: }
11496: my $cstring='';
1.800 albertel 11497: foreach my $pref (keys(%prefs)) {
11498: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 11499: }
1.84 www 11500: $cstring=~s/\&$//;
11501: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
11502: }
11503:
11504: # ---------------------------------------------------------- Make/modify course
11505:
11506: sub createcourse {
1.741 raeburn 11507: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1423 raeburn 11508: $course_owner,$crstype,$cnum,$context,$category,$callercontext)=@_;
1.84 www 11509: $url=&declutter($url);
11510: my $cid='';
1.1028 raeburn 11511: if ($context eq 'requestcourses') {
11512: my $can_create = 0;
11513: my ($ownername,$ownerdom) = split(':',$course_owner);
11514: if ($udom eq $ownerdom) {
1.1423 raeburn 11515: my $reload;
11516: if (($callercontext eq 'auto') &&
11517: ($ownerdom eq $env{'user.domain'}) && ($ownername eq $env{'user.name'})) {
11518: $reload = 'reload';
11519: }
11520: if (&usertools_access($ownername,$ownerdom,$category,$reload,
1.1028 raeburn 11521: $context)) {
11522: $can_create = 1;
11523: }
11524: } else {
11525: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
11526: $category);
11527: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
11528: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
11529: if (@curr > 0) {
11530: my @options = qw(approval validate autolimit);
11531: my $optregex = join('|',@options);
11532: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
11533: $can_create = 1;
11534: }
11535: }
11536: }
11537: }
11538: if ($can_create) {
11539: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
11540: unless (&allowed('ccc',$udom)) {
11541: return 'refused';
11542: }
1.1017 raeburn 11543: }
11544: } else {
11545: return 'refused';
11546: }
1.1028 raeburn 11547: } elsif (!&allowed('ccc',$udom)) {
11548: return 'refused';
1.84 www 11549: }
1.1011 raeburn 11550: # --------------------------------------------------------------- Get Unique ID
11551: my $uname;
11552: if ($cnum =~ /^$match_courseid$/) {
11553: my $chome=&homeserver($cnum,$udom,'true');
11554: if (($chome eq '') || ($chome eq 'no_host')) {
11555: $uname = $cnum;
11556: } else {
1.1038 raeburn 11557: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 11558: }
11559: } else {
1.1038 raeburn 11560: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 11561: }
11562: return $uname if ($uname =~ /^error/);
11563: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 11564: if (!defined($course_server)) {
11565: if (defined(&domain($udom,'primary'))) {
11566: $course_server = &domain($udom,'primary');
11567: } else {
11568: $course_server = $env{'user.home'};
11569: }
11570: }
11571: my %host_servers =
1.1494 raeburn 11572: &get_servers($udom,'library');
1.1052 raeburn 11573: unless ($host_servers{$course_server}) {
11574: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 11575: }
1.84 www 11576: # ------------------------------------------------------------- Make the course
11577: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 11578: $course_server);
1.84 www 11579: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 11580: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 11581: if (($uhome eq '') || ($uhome eq 'no_host')) {
11582: return 'error: no such course';
11583: }
1.271 www 11584: # ----------------------------------------------------------------- Course made
1.516 raeburn 11585: # log existence
1.1029 raeburn 11586: my $now = time;
1.918 raeburn 11587: my $newcourse = {
11588: $udom.'_'.$uname => {
1.921 raeburn 11589: description => $description,
11590: inst_code => $inst_code,
11591: owner => $course_owner,
11592: type => $crstype,
1.1029 raeburn 11593: creator => $env{'user.name'}.':'.
11594: $env{'user.domain'},
11595: created => $now,
11596: context => $context,
1.918 raeburn 11597: },
11598: };
1.921 raeburn 11599: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 11600: # set toplevel url
1.271 www 11601: my $topurl=$url;
11602: unless ($nonstandard) {
11603: # ------------------------------------------ For standard courses, make top url
11604: my $mapurl=&clutter($url);
1.278 www 11605: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 11606: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 11607: <map>
11608: <resource id="1" type="start"></resource>
11609: <resource id="2" src="$mapurl"></resource>
11610: <resource id="3" type="finish"></resource>
11611: <link index="1" from="1" to="2"></link>
11612: <link index="2" from="2" to="3"></link>
11613: </map>
11614: ENDINITMAP
11615: $topurl=&declutter(
1.638 albertel 11616: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 11617: );
11618: }
11619: # ----------------------------------------------------------- Write preferences
1.84 www 11620: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 11621: ('description' => $description,
11622: 'url' => $topurl,
11623: 'internal.creator' => $env{'user.name'}.':'.
11624: $env{'user.domain'},
11625: 'internal.created' => $now,
11626: 'internal.creationcontext' => $context)
11627: );
1.84 www 11628: return '/'.$udom.'/'.$uname;
11629: }
11630:
1.1011 raeburn 11631: # ------------------------------------------------------------------- Create ID
11632: sub generate_coursenum {
1.1038 raeburn 11633: my ($udom,$crstype) = @_;
1.1011 raeburn 11634: my $domdesc = &domain($udom);
11635: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 11636: my $first;
11637: if ($crstype eq 'Community') {
11638: $first = '0';
11639: } else {
11640: $first = int(1+rand(9));
11641: }
11642: my $uname=$first.
1.1011 raeburn 11643: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
11644: substr($$.time,0,5).unpack("H8",pack("I32",time)).
11645: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
11646: # ----------------------------------------------- Make sure that does not exist
11647: my $uhome=&homeserver($uname,$udom,'true');
11648: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 11649: if ($crstype eq 'Community') {
11650: $first = '0';
11651: } else {
11652: $first = int(1+rand(9));
11653: }
11654: $uname=$first.
1.1011 raeburn 11655: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
11656: substr($$.time,0,5).unpack("H8",pack("I32",time)).
11657: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
11658: $uhome=&homeserver($uname,$udom,'true');
11659: unless (($uhome eq '') || ($uhome eq 'no_host')) {
11660: return 'error: unable to generate unique course-ID';
11661: }
11662: }
11663: return $uname;
11664: }
11665:
1.813 albertel 11666: sub is_course {
1.1167 droeschl 11667: my ($cdom, $cnum) = scalar(@_) == 1 ?
11668: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
11669:
1.1381 raeburn 11670: return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
11671: my $uhome=&homeserver($cnum,$cdom);
11672: my $iscourse;
11673: if (grep { $_ eq $uhome } current_machine_ids()) {
1.1382 raeburn 11674: $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
1.1381 raeburn 11675: } else {
11676: my $hashid = $cdom.':'.$cnum;
11677: ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
11678: unless (defined($cached)) {
11679: my %courses = &courseiddump($cdom, '.', 1, '.', '.',
11680: $cnum,undef,undef,'.');
11681: $iscourse = 0;
11682: if (exists($courses{$cdom.'_'.$cnum})) {
11683: $iscourse = 1;
11684: }
11685: &do_cache_new('iscourse',$hashid,$iscourse,3600);
11686: }
11687: }
11688: return unless ($iscourse);
1.1167 droeschl 11689: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813 albertel 11690: }
11691:
1.1015 raeburn 11692: sub store_userdata {
11693: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 11694: my $result;
1.1016 raeburn 11695: if ($datakey ne '') {
1.1013 raeburn 11696: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 11697: if ($udom eq '' || $uname eq '') {
11698: $udom = $env{'user.domain'};
11699: $uname = $env{'user.name'};
11700: }
11701: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 11702: if (($uhome eq '') || ($uhome eq 'no_host')) {
11703: $result = 'error: no_host';
11704: } else {
1.1434 raeburn 11705: $storehash->{'ip'} = &get_requestor_ip();
1.1013 raeburn 11706: $storehash->{'host'} = $perlvar{'lonHostID'};
11707:
11708: my $namevalue='';
11709: foreach my $key (keys(%{$storehash})) {
11710: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
11711: }
11712: $namevalue=~s/\&$//;
1.1224 raeburn 11713: unless ($namespace eq 'courserequests') {
11714: $datakey = &escape($datakey);
11715: }
1.1105 raeburn 11716: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
11717: $namevalue,$uhome);
1.1013 raeburn 11718: }
11719: } else {
11720: $result = 'error: data to store was not a hash reference';
11721: }
11722: } else {
11723: $result= 'error: invalid requestkey';
11724: }
11725: return $result;
11726: }
11727:
1.21 www 11728: # ---------------------------------------------------------- Assign Custom Role
11729:
11730: sub assigncustomrole {
1.1512 raeburn 11731: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,
11732: $selfenroll,$context,$othdomby,$requester)=@_;
1.21 www 11733: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.1512 raeburn 11734: $end,$start,$deleteflag,$selfenroll,$context,$othdomby,
11735: $requester);
1.21 www 11736: }
11737:
11738: # ----------------------------------------------------------------- Revoke Role
11739:
11740: sub revokerole {
1.957 raeburn 11741: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 11742: my $now=time;
1.965 raeburn 11743: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 11744: }
11745:
11746: # ---------------------------------------------------------- Revoke Custom Role
11747:
11748: sub revokecustomrole {
1.957 raeburn 11749: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 11750: my $now=time;
1.357 www 11751: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 11752: $deleteflag,$selfenroll,$context);
1.17 www 11753: }
11754:
1.533 banghart 11755: # ------------------------------------------------------------ Disk usage
1.535 albertel 11756: sub diskusage {
1.955 raeburn 11757: my ($udom,$uname,$directorypath,$getpropath)=@_;
11758: $directorypath =~ s/\/$//;
11759: my $listing=&reply('du2:'.&escape($directorypath).':'
11760: .&escape($getpropath).':'.&escape($uname).':'
11761: .&escape($udom),homeserver($uname,$udom));
11762: if ($listing eq 'unknown_cmd') {
11763: if ($getpropath) {
11764: $directorypath = &propath($udom,$uname).'/'.$directorypath;
11765: }
11766: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
11767: }
1.514 albertel 11768: return $listing;
1.512 banghart 11769: }
11770:
1.566 banghart 11771: sub is_locked {
1.1096 raeburn 11772: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 11773: my @check;
11774: my $is_locked;
1.1093 raeburn 11775: push (@check,$file_name);
1.613 albertel 11776: my %locked = &get('file_permissions',\@check,
1.620 albertel 11777: $env{'user.domain'},$env{'user.name'});
1.615 albertel 11778: my ($tmp)=keys(%locked);
11779: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 11780:
1.566 banghart 11781: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 11782: $is_locked = 'false';
11783: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 11784: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 11785: $is_locked = 'true';
1.1096 raeburn 11786: if (ref($which) eq 'ARRAY') {
11787: push(@{$which},$entry);
11788: } else {
11789: last;
11790: }
1.745 raeburn 11791: }
11792: }
1.566 banghart 11793: } else {
11794: $is_locked = 'false';
11795: }
1.1093 raeburn 11796: return $is_locked;
1.566 banghart 11797: }
11798:
1.759 albertel 11799: sub declutter_portfile {
11800: my ($file) = @_;
1.833 albertel 11801: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 11802: return $file;
11803: }
11804:
1.559 banghart 11805: # ------------------------------------------------------------- Mark as Read Only
11806:
11807: sub mark_as_readonly {
11808: my ($domain,$user,$files,$what) = @_;
1.613 albertel 11809: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 11810: my ($tmp)=keys(%current_permissions);
11811: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 11812: foreach my $file (@{$files}) {
1.759 albertel 11813: $file = &declutter_portfile($file);
1.561 banghart 11814: push(@{$current_permissions{$file}},$what);
1.559 banghart 11815: }
1.613 albertel 11816: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 11817: return;
11818: }
11819:
1.572 banghart 11820: # ------------------------------------------------------------Save Selected Files
11821:
11822: sub save_selected_files {
11823: my ($user, $path, @files) = @_;
11824: my $filename = $user."savedfiles";
1.573 banghart 11825: my @other_files = &files_not_in_path($user, $path);
1.1359 raeburn 11826: open (OUT,'>',LONCAPA::tempdir().$filename);
1.573 banghart 11827: foreach my $file (@files) {
1.620 albertel 11828: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 11829: }
11830: foreach my $file (@other_files) {
1.574 banghart 11831: print (OUT $file."\n");
1.572 banghart 11832: }
1.574 banghart 11833: close (OUT);
1.572 banghart 11834: return 'ok';
11835: }
11836:
1.574 banghart 11837: sub clear_selected_files {
11838: my ($user) = @_;
11839: my $filename = $user."savedfiles";
1.1359 raeburn 11840: open (OUT,'>',LONCAPA::tempdir().$filename);
1.574 banghart 11841: print (OUT undef);
11842: close (OUT);
11843: return ("ok");
11844: }
11845:
1.572 banghart 11846: sub files_in_path {
11847: my ($user, $path) = @_;
11848: my $filename = $user."savedfiles";
11849: my %return_files;
1.1359 raeburn 11850: open (IN,'<',LONCAPA::tempdir().$filename);
1.573 banghart 11851: while (my $line_in = <IN>) {
1.574 banghart 11852: chomp ($line_in);
11853: my @paths_and_file = split (m!/!, $line_in);
11854: my $file_part = pop (@paths_and_file);
11855: my $path_part = join ('/', @paths_and_file);
1.573 banghart 11856: $path_part.='/';
11857: my $path_and_file = $path_part.$file_part;
11858: if ($path_part eq $path) {
11859: $return_files{$file_part}= 'selected';
11860: }
11861: }
1.574 banghart 11862: close (IN);
11863: return (\%return_files);
1.572 banghart 11864: }
11865:
11866: # called in portfolio select mode, to show files selected NOT in current directory
11867: sub files_not_in_path {
11868: my ($user, $path) = @_;
11869: my $filename = $user."savedfiles";
11870: my @return_files;
11871: my $path_part;
1.1359 raeburn 11872: open(IN, '<',LONCAPA::tempdir().$filename);
1.800 albertel 11873: while (my $line = <IN>) {
1.572 banghart 11874: #ok, I know it's clunky, but I want it to work
1.800 albertel 11875: my @paths_and_file = split(m|/|, $line);
11876: my $file_part = pop(@paths_and_file);
11877: chomp($file_part);
11878: my $path_part = join('/', @paths_and_file);
1.572 banghart 11879: $path_part .= '/';
11880: my $path_and_file = $path_part.$file_part;
11881: if ($path_part ne $path) {
1.800 albertel 11882: push(@return_files, ($path_and_file));
1.572 banghart 11883: }
11884: }
1.800 albertel 11885: close(OUT);
1.574 banghart 11886: return (@return_files);
1.572 banghart 11887: }
11888:
1.1273 raeburn 11889: #------------------------------Submitted/Handedback Portfolio Files Versioning
11890:
11891: sub portfiles_versioning {
11892: my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
11893: my $portfolio_root = '/userfiles/portfolio';
11894: return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
11895: foreach my $file (@{$portfiles}) {
11896: &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
11897: my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
11898: my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
11899: my $getpropath = 1;
11900: my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
11901: $stu_name,$getpropath);
11902: my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
11903: my $new_answer =
11904: &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
11905: if ($new_answer ne 'problem getting file') {
11906: push(@{$versioned_portfiles}, $directory.$new_answer);
11907: &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
11908: [$symb,$env{'request.course.id'},'graded']);
11909: }
11910: }
11911: }
11912:
11913: sub get_next_version {
11914: my ($answer_name, $answer_ext, $dir_list) = @_;
11915: my $version;
11916: if (ref($dir_list) eq 'ARRAY') {
11917: foreach my $row (@{$dir_list}) {
11918: my ($file) = split(/\&/,$row,2);
11919: my ($file_name,$file_version,$file_ext) =
11920: &file_name_version_ext($file);
11921: if (($file_name eq $answer_name) &&
11922: ($file_ext eq $answer_ext)) {
11923: # gets here if filename and extension match,
11924: # regardless of version
11925: if ($file_version ne '') {
11926: # a versioned file is found so save it for later
11927: if ($file_version > $version) {
11928: $version = $file_version;
11929: }
11930: }
11931: }
11932: }
11933: }
11934: $version ++;
11935: return($version);
11936: }
11937:
11938: sub version_selected_portfile {
11939: my ($domain,$stu_name,$directory,$file_name,$version) = @_;
11940: my ($answer_name,$answer_ver,$answer_ext) =
11941: &file_name_version_ext($file_name);
11942: my $new_answer;
11943: $env{'form.copy'} =
11944: &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
11945: if($env{'form.copy'} eq '-1') {
11946: $new_answer = 'problem getting file';
11947: } else {
11948: $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
11949: my $copy_result =
11950: &finishuserfileupload($stu_name,$domain,'copy',
11951: '/portfolio'.$directory.$new_answer);
11952: }
11953: undef($env{'form.copy'});
11954: return ($new_answer);
11955: }
11956:
11957: sub file_name_version_ext {
11958: my ($file)=@_;
11959: my @file_parts = split(/\./, $file);
11960: my ($name,$version,$ext);
11961: if (@file_parts > 1) {
11962: $ext=pop(@file_parts);
11963: if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
11964: $version=pop(@file_parts);
11965: }
11966: $name=join('.',@file_parts);
11967: } else {
11968: $name=join('.',@file_parts);
11969: }
11970: return($name,$version,$ext);
11971: }
11972:
1.745 raeburn 11973: #----------------------------------------------Get portfolio file permissions
1.629 banghart 11974:
1.745 raeburn 11975: sub get_portfile_permissions {
11976: my ($domain,$user) = @_;
1.613 albertel 11977: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 11978: my ($tmp)=keys(%current_permissions);
11979: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 11980: return \%current_permissions;
11981: }
11982:
11983: #---------------------------------------------Get portfolio file access controls
11984:
1.749 raeburn 11985: sub get_access_controls {
1.745 raeburn 11986: my ($current_permissions,$group,$file) = @_;
1.769 albertel 11987: my %access;
11988: my $real_file = $file;
11989: $file =~ s/\.meta$//;
1.745 raeburn 11990: if (defined($file)) {
1.749 raeburn 11991: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
11992: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 11993: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 11994: }
11995: }
1.745 raeburn 11996: } else {
1.749 raeburn 11997: foreach my $key (keys(%{$current_permissions})) {
11998: if ($key =~ /\0accesscontrol$/) {
11999: if (defined($group)) {
12000: if ($key !~ m-^\Q$group\E/-) {
12001: next;
12002: }
12003: }
12004: my ($fullpath) = split(/\0/,$key);
12005: if (ref($$current_permissions{$key}) eq 'HASH') {
12006: foreach my $control (keys(%{$$current_permissions{$key}})) {
12007: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
12008: }
12009: }
12010: }
12011: }
12012: }
12013: return %access;
12014: }
12015:
12016: sub modify_access_controls {
12017: my ($file_name,$changes,$domain,$user)=@_;
12018: my ($outcome,$deloutcome);
12019: my %store_permissions;
12020: my %new_values;
12021: my %new_control;
12022: my %translation;
12023: my @deletions = ();
12024: my $now = time;
12025: if (exists($$changes{'activate'})) {
12026: if (ref($$changes{'activate'}) eq 'HASH') {
12027: my @newitems = sort(keys(%{$$changes{'activate'}}));
12028: my $numnew = scalar(@newitems);
12029: for (my $i=0; $i<$numnew; $i++) {
12030: my $newkey = $newitems[$i];
12031: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 12032: if ($newkey =~ /^\d+:/) {
12033: $newkey =~ s/^(\d+)/$newid/;
12034: $translation{$1} = $newid;
12035: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
12036: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
12037: $translation{$1} = $newid;
12038: }
1.749 raeburn 12039: $new_values{$file_name."\0".$newkey} =
12040: $$changes{'activate'}{$newitems[$i]};
12041: $new_control{$newkey} = $now;
12042: }
12043: }
12044: }
12045: my %todelete;
12046: my %changed_items;
12047: foreach my $action ('delete','update') {
12048: if (exists($$changes{$action})) {
12049: if (ref($$changes{$action}) eq 'HASH') {
12050: foreach my $key (keys(%{$$changes{$action}})) {
12051: my ($itemnum) = ($key =~ /^([^:]+):/);
12052: if ($action eq 'delete') {
12053: $todelete{$itemnum} = 1;
12054: } else {
12055: $changed_items{$itemnum} = $key;
12056: }
12057: }
1.745 raeburn 12058: }
12059: }
1.749 raeburn 12060: }
12061: # get lock on access controls for file.
12062: my $lockhash = {
12063: $file_name."\0".'locked_access_records' => $env{'user.name'}.
12064: ':'.$env{'user.domain'},
12065: };
12066: my $tries = 0;
12067: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
12068:
1.1288 damieng 12069: while (($gotlock ne 'ok') && $tries < 10) {
1.749 raeburn 12070: $tries ++;
1.1289 damieng 12071: sleep(0.1);
1.749 raeburn 12072: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
12073: }
12074: if ($gotlock eq 'ok') {
12075: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
12076: my ($tmp)=keys(%curr_permissions);
12077: if ($tmp=~/^error:/) { undef(%curr_permissions); }
12078: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
12079: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
12080: if (ref($curr_controls) eq 'HASH') {
12081: foreach my $control_item (keys(%{$curr_controls})) {
12082: my ($itemnum) = ($control_item =~ /^([^:]+):/);
12083: if (defined($todelete{$itemnum})) {
12084: push(@deletions,$file_name."\0".$control_item);
12085: } else {
12086: if (defined($changed_items{$itemnum})) {
12087: $new_control{$changed_items{$itemnum}} = $now;
12088: push(@deletions,$file_name."\0".$control_item);
12089: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
12090: } else {
12091: $new_control{$control_item} = $$curr_controls{$control_item};
12092: }
12093: }
1.745 raeburn 12094: }
12095: }
12096: }
1.970 raeburn 12097: my ($group);
12098: if (&is_course($domain,$user)) {
12099: ($group,my $file) = split(/\//,$file_name,2);
12100: }
1.749 raeburn 12101: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
12102: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
12103: $outcome = &put('file_permissions',\%new_values,$domain,$user);
12104: # remove lock
12105: my @del_lock = ($file_name."\0".'locked_access_records');
12106: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 12107: my $sqlresult =
1.970 raeburn 12108: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 12109: $group);
1.749 raeburn 12110: } else {
12111: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 12112: }
1.749 raeburn 12113: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 12114: }
12115:
1.827 raeburn 12116: sub make_public_indefinitely {
1.1271 raeburn 12117: my (@requrl) = @_;
12118: return &automated_portfile_access('public',\@requrl);
12119: }
12120:
12121: sub automated_portfile_access {
12122: my ($accesstype,$addsref,$delsref,$info) = @_;
1.1273 raeburn 12123: unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
12124: return 'invalid';
12125: }
1.1271 raeburn 12126: my %urls;
12127: if (ref($addsref) eq 'ARRAY') {
12128: foreach my $requrl (@{$addsref}) {
12129: if (&is_portfolio_url($requrl)) {
12130: unless (exists($urls{$requrl})) {
12131: $urls{$requrl} = 'add';
12132: }
12133: }
12134: }
12135: }
12136: if (ref($delsref) eq 'ARRAY') {
12137: foreach my $requrl (@{$delsref}) {
12138: if (&is_portfolio_url($requrl)) {
12139: unless (exists($urls{$requrl})) {
12140: $urls{$requrl} = 'delete';
12141: }
12142: }
12143: }
12144: }
12145: unless (keys(%urls)) {
12146: return 'invalid';
12147: }
12148: my $ip;
12149: if ($accesstype eq 'ip') {
12150: if (ref($info) eq 'HASH') {
12151: if ($info->{'ip'} ne '') {
12152: $ip = $info->{'ip'};
12153: }
12154: }
12155: if ($ip eq '') {
12156: return 'invalid';
12157: }
12158: }
12159: my $errors;
1.827 raeburn 12160: my $now = time;
1.1271 raeburn 12161: my %current_perms;
12162: foreach my $requrl (sort(keys(%urls))) {
12163: my $action;
12164: if ($urls{$requrl} eq 'add') {
12165: $action = 'activate';
12166: } else {
12167: $action = 'none';
12168: }
12169: my $aclnum = 0;
1.827 raeburn 12170: my (undef,$udom,$unum,$file_name,$group) =
12171: &parse_portfolio_url($requrl);
1.1271 raeburn 12172: unless (exists($current_perms{$unum.':'.$udom})) {
12173: $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
12174: }
12175: my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
1.827 raeburn 12176: $group,$file_name);
12177: foreach my $key (keys(%{$access_controls{$file_name}})) {
12178: my ($num,$scope,$end,$start) =
12179: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
1.1271 raeburn 12180: if ($scope eq $accesstype) {
12181: if (($start <= $now) && ($end == 0)) {
12182: if ($accesstype eq 'ip') {
12183: if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
12184: if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
12185: if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
12186: if ($urls{$requrl} eq 'add') {
12187: $action = 'none';
12188: last;
12189: } else {
12190: $action = 'delete';
12191: $aclnum = $num;
12192: last;
12193: }
12194: }
12195: }
12196: }
12197: } elsif ($accesstype eq 'public') {
12198: if ($urls{$requrl} eq 'add') {
12199: $action = 'none';
12200: last;
12201: } else {
12202: $action = 'delete';
12203: $aclnum = $num;
12204: last;
12205: }
12206: }
12207: } elsif ($accesstype eq 'public') {
1.827 raeburn 12208: $action = 'update';
12209: $aclnum = $num;
1.1271 raeburn 12210: last;
1.827 raeburn 12211: }
12212: }
12213: }
12214: if ($action eq 'none') {
1.1271 raeburn 12215: next;
1.827 raeburn 12216: } else {
12217: my %changes;
12218: my $newend = 0;
12219: my $newstart = $now;
1.1271 raeburn 12220: my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
1.827 raeburn 12221: $changes{$action}{$newkey} = {
1.1271 raeburn 12222: type => $accesstype,
1.827 raeburn 12223: time => {
12224: start => $newstart,
12225: end => $newend,
12226: },
12227: };
1.1271 raeburn 12228: if ($accesstype eq 'ip') {
12229: $changes{$action}{$newkey}{'ip'} = [$ip];
12230: }
1.827 raeburn 12231: my ($outcome,$deloutcome,$new_values,$translation) =
12232: &modify_access_controls($file_name,\%changes,$udom,$unum);
1.1271 raeburn 12233: unless ($outcome eq 'ok') {
12234: $errors .= $outcome.' ';
12235: }
1.827 raeburn 12236: }
1.1271 raeburn 12237: }
12238: if ($errors) {
12239: $errors =~ s/\s$//;
12240: return $errors;
1.827 raeburn 12241: } else {
1.1271 raeburn 12242: return 'ok';
1.827 raeburn 12243: }
12244: }
12245:
1.745 raeburn 12246: #------------------------------------------------------Get Marked as Read Only
12247:
12248: sub get_marked_as_readonly {
12249: my ($domain,$user,$what,$group) = @_;
12250: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 12251: my @readonly_files;
1.629 banghart 12252: my $cmp1=$what;
12253: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 12254: while (my ($file_name,$value) = each(%{$current_permissions})) {
12255: if (defined($group)) {
12256: if ($file_name !~ m-^\Q$group\E/-) {
12257: next;
12258: }
12259: }
1.561 banghart 12260: if (ref($value) eq "ARRAY"){
12261: foreach my $stored_what (@{$value}) {
1.629 banghart 12262: my $cmp2=$stored_what;
1.759 albertel 12263: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 12264: $cmp2=join('',@{$stored_what});
1.745 raeburn 12265: }
1.629 banghart 12266: if ($cmp1 eq $cmp2) {
1.561 banghart 12267: push(@readonly_files, $file_name);
1.745 raeburn 12268: last;
1.563 banghart 12269: } elsif (!defined($what)) {
12270: push(@readonly_files, $file_name);
1.745 raeburn 12271: last;
1.561 banghart 12272: }
12273: }
1.745 raeburn 12274: }
1.561 banghart 12275: }
12276: return @readonly_files;
12277: }
1.577 banghart 12278: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 12279:
1.577 banghart 12280: sub get_marked_as_readonly_hash {
1.745 raeburn 12281: my ($current_permissions,$group,$what) = @_;
1.577 banghart 12282: my %readonly_files;
1.745 raeburn 12283: while (my ($file_name,$value) = each(%{$current_permissions})) {
12284: if (defined($group)) {
12285: if ($file_name !~ m-^\Q$group\E/-) {
12286: next;
12287: }
12288: }
1.577 banghart 12289: if (ref($value) eq "ARRAY"){
12290: foreach my $stored_what (@{$value}) {
1.745 raeburn 12291: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 12292: foreach my $lock_descriptor(@{$stored_what}) {
12293: if ($lock_descriptor eq 'graded') {
12294: $readonly_files{$file_name} = 'graded';
12295: } elsif ($lock_descriptor eq 'handback') {
12296: $readonly_files{$file_name} = 'handback';
12297: } else {
12298: if (!exists($readonly_files{$file_name})) {
12299: $readonly_files{$file_name} = 'locked';
12300: }
12301: }
1.745 raeburn 12302: }
1.750 banghart 12303: }
1.577 banghart 12304: }
12305: }
12306: }
12307: return %readonly_files;
12308: }
1.559 banghart 12309: # ------------------------------------------------------------ Unmark as Read Only
12310:
12311: sub unmark_as_readonly {
1.629 banghart 12312: # unmarks $file_name (if $file_name is defined), or all files locked by $what
12313: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 12314: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 12315: $file_name = &declutter_portfile($file_name);
1.634 albertel 12316: my $symb_crs = $what;
12317: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 12318: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 12319: my ($tmp)=keys(%current_permissions);
12320: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 12321: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 12322: foreach my $file (@readonly_files) {
1.759 albertel 12323: my $clean_file = &declutter_portfile($file);
12324: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 12325: my $current_locks = $current_permissions{$file};
1.563 banghart 12326: my @new_locks;
12327: my @del_keys;
12328: if (ref($current_locks) eq "ARRAY"){
12329: foreach my $locker (@{$current_locks}) {
1.632 albertel 12330: my $compare=$locker;
1.749 raeburn 12331: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 12332: $compare=join('',@{$locker});
1.746 raeburn 12333: if ($compare ne $symb_crs) {
12334: push(@new_locks, $locker);
12335: }
1.563 banghart 12336: }
12337: }
1.650 albertel 12338: if (scalar(@new_locks) > 0) {
1.563 banghart 12339: $current_permissions{$file} = \@new_locks;
12340: } else {
12341: push(@del_keys, $file);
1.613 albertel 12342: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 12343: delete($current_permissions{$file});
1.563 banghart 12344: }
12345: }
1.561 banghart 12346: }
1.613 albertel 12347: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 12348: return;
12349: }
1.512 banghart 12350:
1.17 www 12351: # ------------------------------------------------------------ Directory lister
12352:
12353: sub dirlist {
1.955 raeburn 12354: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 12355: $uri=~s/^\///;
12356: $uri=~s/\/$//;
1.253 stredwic 12357: my ($udom, $uname);
1.955 raeburn 12358: if ($getuserdir) {
1.253 stredwic 12359: $udom = $userdomain;
12360: $uname = $username;
1.955 raeburn 12361: } else {
12362: (undef,$udom,$uname)=split(/\//,$uri);
12363: if(defined($userdomain)) {
12364: $udom = $userdomain;
12365: }
12366: if(defined($username)) {
12367: $uname = $username;
12368: }
1.253 stredwic 12369: }
1.955 raeburn 12370: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 12371:
1.955 raeburn 12372: $dirRoot = $perlvar{'lonDocRoot'};
12373: if (defined($getpropath)) {
12374: $dirRoot = &propath($udom,$uname);
1.253 stredwic 12375: $dirRoot =~ s/\/$//;
1.955 raeburn 12376: } elsif (defined($getuserdir)) {
12377: my $subdir=$uname.'__';
12378: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
12379: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
12380: ."/$udom/$subdir/$uname";
12381: } elsif (defined($alternateRoot)) {
12382: $dirRoot = $alternateRoot;
1.751 banghart 12383: }
1.253 stredwic 12384:
12385: if($udom) {
12386: if($uname) {
1.1135 raeburn 12387: my $uhome = &homeserver($uname,$udom);
1.1136 raeburn 12388: if ($uhome eq 'no_host') {
12389: return ([],'no_host');
12390: }
1.955 raeburn 12391: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 12392: .$getuserdir.':'.&escape($dirRoot)
1.1135 raeburn 12393: .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955 raeburn 12394: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 12395: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955 raeburn 12396: } else {
12397: @listing_results = map { &unescape($_); } split(/:/,$listing);
12398: }
1.605 matthew 12399: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 12400: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605 matthew 12401: @listing_results = split(/:/,$listing);
12402: } else {
12403: @listing_results = map { &unescape($_); } split(/:/,$listing);
12404: }
1.1135 raeburn 12405: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
1.1136 raeburn 12406: ($listing eq 'rejected') || ($listing eq 'refused') ||
12407: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
12408: return ([],$listing);
12409: } else {
12410: return (\@listing_results);
1.1135 raeburn 12411: }
1.955 raeburn 12412: } elsif(!$alternateRoot) {
1.1136 raeburn 12413: my (%allusers,%listerror);
1.841 albertel 12414: my %servers = &get_servers($udom,'library');
1.955 raeburn 12415: foreach my $tryserver (keys(%servers)) {
12416: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
12417: &escape($udom),$tryserver);
12418: if ($listing eq 'unknown_cmd') {
12419: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
12420: $udom, $tryserver);
12421: } else {
12422: @listing_results = map { &unescape($_); } split(/:/,$listing);
12423: }
1.841 albertel 12424: if ($listing eq 'unknown_cmd') {
12425: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
12426: $udom, $tryserver);
12427: @listing_results = split(/:/,$listing);
12428: } else {
12429: @listing_results =
12430: map { &unescape($_); } split(/:/,$listing);
12431: }
1.1136 raeburn 12432: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
12433: ($listing eq 'rejected') || ($listing eq 'refused') ||
12434: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
12435: $listerror{$tryserver} = $listing;
12436: } else {
1.841 albertel 12437: foreach my $line (@listing_results) {
12438: my ($entry) = split(/&/,$line,2);
12439: $allusers{$entry} = 1;
12440: }
12441: }
1.253 stredwic 12442: }
1.1136 raeburn 12443: my @alluserslist=();
1.800 albertel 12444: foreach my $user (sort(keys(%allusers))) {
1.1136 raeburn 12445: push(@alluserslist,$user.'&user');
1.253 stredwic 12446: }
1.1318 droeschl 12447:
12448: if (!%listerror) {
12449: # no errors
12450: return (\@alluserslist);
12451: } elsif (scalar(keys(%servers)) == 1) {
12452: # one library server, one error
12453: my ($key) = keys(%listerror);
12454: return (\@alluserslist, $listerror{$key});
12455: } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
12456: # con_lost indicates that we might miss data from at least one
12457: # library server
12458: return (\@alluserslist, 'con_lost');
12459: } else {
12460: # multiple library servers and no con_lost -> data should be
12461: # complete.
12462: return (\@alluserslist);
12463: }
12464:
1.253 stredwic 12465: } else {
1.1136 raeburn 12466: return ([],'missing username');
1.253 stredwic 12467: }
1.955 raeburn 12468: } elsif(!defined($getpropath)) {
1.1136 raeburn 12469: my $path = $perlvar{'lonDocRoot'}.'/res/';
12470: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
12471: return (\@all_domains);
1.955 raeburn 12472: } else {
1.1136 raeburn 12473: return ([],'missing domain');
1.275 stredwic 12474: }
12475: }
12476:
12477: # --------------------------------------------- GetFileTimestamp
12478: # This function utilizes dirlist and returns the date stamp for
12479: # when it was last modified. It will also return an error of -1
12480: # if an error occurs
12481:
12482: sub GetFileTimestamp {
1.955 raeburn 12483: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 12484: $studentDomain = &LONCAPA::clean_domain($studentDomain);
12485: $studentName = &LONCAPA::clean_username($studentName);
1.1136 raeburn 12486: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
12487: undef,$getuserdir);
12488: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
12489: return -1;
12490: }
12491: if (ref($fileref) eq 'ARRAY') {
12492: my @stats = split('&',$fileref->[0]);
1.375 matthew 12493: # @stats contains first the filename, then the stat output
12494: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 12495: } else {
12496: return -1;
1.253 stredwic 12497: }
1.26 www 12498: }
12499:
1.712 albertel 12500: sub stat_file {
12501: my ($uri) = @_;
1.787 albertel 12502: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 12503:
1.955 raeburn 12504: my ($udom,$uname,$file);
1.712 albertel 12505: if ($uri =~ m-^/(uploaded|editupload)/-) {
12506: ($udom,$uname,$file) =
1.811 albertel 12507: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 12508: $file = 'userfiles/'.$file;
12509: }
12510: if ($uri =~ m-^/res/-) {
12511: ($udom,$uname) =
1.807 albertel 12512: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 12513: $file = $uri;
12514: }
12515:
12516: if (!$udom || !$uname || !$file) {
12517: # unable to handle the uri
12518: return ();
12519: }
1.956 raeburn 12520: my $getpropath;
12521: if ($file =~ /^userfiles\//) {
12522: $getpropath = 1;
12523: }
1.1136 raeburn 12524: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
12525: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
12526: return ();
12527: } else {
12528: if (ref($listref) eq 'ARRAY') {
12529: my @stats = split('&',$listref->[0]);
12530: shift(@stats); #filename is first
12531: return @stats;
12532: }
1.712 albertel 12533: }
12534: return ();
12535: }
12536:
1.1313 raeburn 12537: # --------------------------------------------------------- recursedirs
12538: # Recursive function to traverse either a specific user's Authoring Space
12539: # or corresponding Published Resource Space, and populate the hash ref:
12540: # $dirhashref with URLs of all directories, and if $filehashref hash
12541: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
1.1503 raeburn 12542: # or .rights files in resource space, and .meta, .save, .log, .bak and
12543: # .rights files in Authoring Space.
1.1313 raeburn 12544: #
12545: # Inputs:
12546: #
12547: # $is_home - true if current server is home server for user's space
1.1503 raeburn 12548: # $recurse - if true will also traverse subdirectories recursively
12549: # $include - reference to hash containing allowed file extensions. If provided,
12550: # files which do not have a matching extension will be ignored.
12551: # $exclude - reference to hash containing excluded file extensions. If provided,
12552: # files which have a matching extension will be ignored.
12553: # $nonemptydir - if true, will only populate $fileshashref hash entry for a particular
12554: # directory with first file found (with acceptable extension).
1.1505 raeburn 12555: # $addtopdir - if true, set $dirhashref->{'/'} = 1
1.1313 raeburn 12556: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
12557: # $relpath - Current path (relative to top level).
12558: # $dirhashref - reference to hash to populate with URLs of directories (Required)
12559: # $filehashref - reference to hash to populate with URLs of files (Optional)
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.1505 raeburn 12572: my ($is_home,$recurse,$include,$exclude,$nonemptydir,$addtopdir,$toppath,$relpath,$dirhashref,$filehashref) = @_;
1.1313 raeburn 12573: return unless (ref($dirhashref) eq 'HASH');
1.1503 raeburn 12574: my $docroot = $perlvar{'lonDocRoot'};
1.1313 raeburn 12575: my $currpath = $docroot.$toppath;
1.1503 raeburn 12576: if ($relpath ne '') {
1.1313 raeburn 12577: $currpath .= "/$relpath";
12578: }
1.1503 raeburn 12579: my ($savefile,$checkinc,$checkexc);
1.1313 raeburn 12580: if (ref($filehashref)) {
12581: $savefile = 1;
12582: }
1.1503 raeburn 12583: if (ref($include) eq 'HASH') {
12584: $checkinc = 1;
12585: }
12586: if (ref($exclude) eq 'HASH') {
12587: $checkexc = 1;
12588: }
1.1313 raeburn 12589: if ($is_home) {
1.1505 raeburn 12590: if ((-e $currpath) && (opendir(my $dirh,$currpath))) {
1.1503 raeburn 12591: my $filecount = 0;
1.1313 raeburn 12592: foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
12593: next if ($item eq '');
12594: if (-d "$currpath/$item") {
12595: my $newpath;
1.1503 raeburn 12596: if ($relpath ne '') {
1.1313 raeburn 12597: $newpath = "$relpath/$item";
12598: } else {
12599: $newpath = $item;
12600: }
12601: $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
1.1503 raeburn 12602: if ($recurse) {
1.1505 raeburn 12603: &recursedirs($is_home,$recurse,$include,$exclude,$nonemptydir,$addtopdir,$toppath,$newpath,$dirhashref,$filehashref);
1.1503 raeburn 12604: }
12605: } elsif (($savefile) || ($relpath eq '')) {
12606: next if ($nonemptydir && $filecount);
12607: if ($checkinc || $checkexc) {
12608: my ($extension) = ($item =~ /\.(\w+)$/);
12609: if ($checkinc) {
12610: next unless ($extension && $include->{$extension});
12611: }
12612: if ($checkexc) {
12613: next if ($extension && $exclude->{$extension});
12614: }
12615: }
1.1505 raeburn 12616: if (($relpath eq '') && (!exists($dirhashref->{'/'}))) {
1.1503 raeburn 12617: $dirhashref->{'/'} = 1;
12618: }
12619: if ($savefile) {
12620: if ($relpath eq '') {
12621: $filehashref->{'/'}{$item} = 1;
12622: } else {
1.1313 raeburn 12623: $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
12624: }
12625: }
1.1503 raeburn 12626: $filecount ++;
1.1313 raeburn 12627: }
12628: }
12629: closedir($dirh);
12630: }
12631: } else {
12632: my ($dirlistref,$listerror) =
12633: &dirlist($toppath.$relpath);
12634: my @dir_lines;
12635: my $dirptr=16384;
12636: if (ref($dirlistref) eq 'ARRAY') {
1.1503 raeburn 12637: my $filecount = 0;
1.1313 raeburn 12638: foreach my $dir_line (sort
12639: {
12640: my ($afile)=split('&',$a,2);
12641: my ($bfile)=split('&',$b,2);
12642: return (lc($afile) cmp lc($bfile));
12643: } (@{$dirlistref})) {
12644: my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
12645: split(/\&/,$dir_line,16);
12646: $item =~ s/\s+$//;
12647: next if (($item =~ /^\.\.?$/) || ($obs));
12648: if ($dirptr&$testdir) {
12649: my $newpath;
12650: if ($relpath) {
12651: $newpath = "$relpath/$item";
12652: } else {
12653: $newpath = $item;
12654: }
12655: $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
1.1503 raeburn 12656: if ($recurse) {
1.1505 raeburn 12657: &recursedirs($is_home,$recurse,$include,$exclude,$nonemptydir,$addtopdir,$toppath,$newpath,$dirhashref,$filehashref);
1.1503 raeburn 12658: }
12659: } elsif (($savefile) || ($relpath eq '')) {
12660: next if ($nonemptydir && $filecount);
12661: if ($checkinc || $checkexc) {
12662: my $extension;
12663: if ($checkinc) {
12664: next unless ($extension && $include->{$extension});
12665: }
12666: if ($checkexc) {
12667: next if ($extension && $exclude->{$extension});
12668: }
12669: }
12670: if (($relpath eq '') && (!exists($dirhashref->{'/'}))) {
12671: $dirhashref->{'/'} = 1;
12672: }
12673: if ($savefile) {
12674: if ($relpath eq '') {
12675: $filehashref->{'/'}{$item} = 1;
12676: } else {
12677: $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
1.1313 raeburn 12678: }
12679: }
1.1503 raeburn 12680: $filecount ++;
1.1313 raeburn 12681: }
12682: }
12683: }
12684: }
1.1505 raeburn 12685: if ($addtopdir) {
12686: if (($relpath eq '') && (!exists($dirhashref->{'/'}))) {
12687: $dirhashref->{'/'} = 1;
12688: }
12689: }
1.1313 raeburn 12690: return;
12691: }
12692:
1.1503 raeburn 12693: sub priv_exclude {
12694: return {
12695: meta => 1,
12696: save => 1,
12697: log => 1,
12698: bak => 1,
12699: rights => 1,
12700: DS_Store => 1,
12701: };
12702: }
12703:
1.26 www 12704: # -------------------------------------------------------- Value of a Condition
12705:
1.713 albertel 12706: # gets the value of a specific preevaluated condition
12707: # stored in the string $env{user.state.<cid>}
12708: # or looks up a condition reference in the bighash and if if hasn't
12709: # already been evaluated recurses into docondval to get the value of
12710: # the condition, then memoizing it to
12711: # $env{user.state.<cid>.<condition>}
1.40 www 12712: sub directcondval {
12713: my $number=shift;
1.620 albertel 12714: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 12715: &Apache::lonuserstate::evalstate();
12716: }
1.713 albertel 12717: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
12718: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
12719: } elsif ($number =~ /^_/) {
12720: my $sub_condition;
12721: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12722: &GDBM_READER(),0640)) {
12723: $sub_condition=$bighash{'conditions'.$number};
12724: untie(%bighash);
12725: }
12726: my $value = &docondval($sub_condition);
1.949 raeburn 12727: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 12728: return $value;
12729: }
1.620 albertel 12730: if ($env{'user.state.'.$env{'request.course.id'}}) {
12731: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 12732: } else {
12733: return 2;
12734: }
12735: }
12736:
1.713 albertel 12737: # get the collection of conditions for this resource
1.26 www 12738: sub condval {
12739: my $condidx=shift;
1.54 www 12740: my $allpathcond='';
1.713 albertel 12741: foreach my $cond (split(/\|/,$condidx)) {
12742: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
12743: $allpathcond.=
12744: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
12745: }
1.191 harris41 12746: }
1.54 www 12747: $allpathcond=~s/\|$//;
1.713 albertel 12748: return &docondval($allpathcond);
12749: }
12750:
12751: #evaluates an expression of conditions
12752: sub docondval {
12753: my ($allpathcond) = @_;
12754: my $result=0;
12755: if ($env{'request.course.id'}
12756: && defined($allpathcond)) {
12757: my $operand='|';
12758: my @stack;
12759: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
12760: if ($chunk eq '(') {
12761: push @stack,($operand,$result);
12762: } elsif ($chunk eq ')') {
12763: my $before=pop @stack;
12764: if (pop @stack eq '&') {
12765: $result=$result>$before?$before:$result;
12766: } else {
12767: $result=$result>$before?$result:$before;
12768: }
12769: } elsif (($chunk eq '&') || ($chunk eq '|')) {
12770: $operand=$chunk;
12771: } else {
12772: my $new=directcondval($chunk);
12773: if ($operand eq '&') {
12774: $result=$result>$new?$new:$result;
12775: } else {
12776: $result=$result>$new?$result:$new;
12777: }
12778: }
12779: }
1.26 www 12780: }
12781: return $result;
1.421 albertel 12782: }
12783:
12784: # ---------------------------------------------------- Devalidate courseresdata
12785:
12786: sub devalidatecourseresdata {
12787: my ($coursenum,$coursedomain)=@_;
12788: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 12789: &devalidate_cache_new('courseres',$hashid);
1.28 www 12790: }
12791:
1.763 www 12792:
1.200 www 12793: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 12794: #
12795: # Parameters:
12796: # $coursenum - Number of the course.
12797: # $coursedomain - Domain at which the course was created.
12798: # Returns:
12799: # A hash of the course parameters along (I think) with timestamps
12800: # and version info.
1.877 foxr 12801:
1.624 albertel 12802: sub get_courseresdata {
12803: my ($coursenum,$coursedomain)=@_;
1.200 www 12804: my $coursehom=&homeserver($coursenum,$coursedomain);
12805: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 12806: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 12807: my %dumpreply;
1.417 albertel 12808: unless (defined($cached)) {
1.624 albertel 12809: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 12810: $result=\%dumpreply;
1.251 albertel 12811: my ($tmp) = keys(%dumpreply);
12812: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 12813: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 12814: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
12815: return $tmp;
1.416 albertel 12816: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 12817: $result=undef;
1.599 albertel 12818: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 12819: }
12820: }
1.624 albertel 12821: return $result;
12822: }
12823:
1.633 albertel 12824: sub devalidateuserresdata {
12825: my ($uname,$udom)=@_;
12826: my $hashid="$udom:$uname";
12827: &devalidate_cache_new('userres',$hashid);
12828: }
12829:
1.624 albertel 12830: sub get_userresdata {
12831: my ($uname,$udom)=@_;
12832: #most student don\'t have any data set, check if there is some data
12833: if (&EXT_cache_status($udom,$uname)) { return undef; }
12834:
12835: my $hashid="$udom:$uname";
12836: my ($result,$cached)=&is_cached_new('userres',$hashid);
12837: if (!defined($cached)) {
12838: my %resourcedata=&dump('resourcedata',$udom,$uname);
12839: $result=\%resourcedata;
12840: &do_cache_new('userres',$hashid,$result,600);
12841: }
12842: my ($tmp)=keys(%$result);
12843: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
12844: return $result;
12845: }
12846: #error 2 occurs when the .db doesn't exist
12847: if ($tmp!~/error: 2 /) {
1.1294 raeburn 12848: if ((!defined($cached)) || ($tmp ne 'con_lost')) {
12849: &logthis("<font color=\"blue\">WARNING:".
12850: " Trying to get resource data for ".
12851: $uname." at ".$udom.": ".
12852: $tmp."</font>");
12853: }
1.624 albertel 12854: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 12855: #&EXT_cache_set($udom,$uname);
12856: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 12857: undef($tmp); # not really an error so don't send it back
1.624 albertel 12858: }
12859: return $tmp;
12860: }
1.879 foxr 12861: #----------------------------------------------- resdata - return resource data
12862: # Purpose:
12863: # Return resource data for either users or for a course.
12864: # Parameters:
12865: # $name - Course/user name.
12866: # $domain - Name of the domain the user/course is registered on.
1.1311 raeburn 12867: # $type - Type of thing $name is (must be 'course' or 'user')
1.1301 raeburn 12868: # $mapp - decluttered URL of enclosing map
12869: # $recursed - Ref to scalar -- set to 1, if nested maps have been recursed.
12870: # $recurseup - Ref to array of map URLs, starting with map containing
12871: # $mapp up through hierarchy of nested maps to top level map.
12872: # $courseid - CourseID (first part of param identifier).
12873: # $modifier - Middle part of param identifier.
12874: # $what - Last part of param identifier.
1.879 foxr 12875: # @which - Array of names of resources desired.
12876: # Returns:
12877: # The value of the first reasource in @which that is found in the
12878: # resource hash.
12879: # Exceptional Conditions:
12880: # If the $type passed in is not valid (not the string 'course' or
12881: # 'user', an undefined reference is returned.
12882: # If none of the resources are found, an undef is returned
1.624 albertel 12883: sub resdata {
1.1301 raeburn 12884: my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
12885: $modifier,$what,@which)=@_;
1.624 albertel 12886: my $result;
12887: if ($type eq 'course') {
12888: $result=&get_courseresdata($name,$domain);
12889: } elsif ($type eq 'user') {
12890: $result=&get_userresdata($name,$domain);
12891: }
12892: if (!ref($result)) { return $result; }
1.251 albertel 12893: foreach my $item (@which) {
1.1301 raeburn 12894: if ($item->[1] eq 'course') {
12895: if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
12896: unless ($$recursed) {
1.1302 raeburn 12897: @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
1.1301 raeburn 12898: $$recursed = 1;
12899: }
12900: foreach my $item (@${recurseup}) {
12901: my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
12902: last if (defined($result->{$norecursechk}));
12903: my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
12904: if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
12905: }
12906: }
12907: }
12908: if (defined($result->{$item->[0]})) {
1.927 albertel 12909: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 12910: }
1.250 albertel 12911: }
1.291 albertel 12912: return undef;
1.200 www 12913: }
12914:
1.1360 raeburn 12915: sub get_domain_lti {
12916: my ($cdom,$context) = @_;
1.1483 raeburn 12917: my ($name,$cachename,%lti);
1.1360 raeburn 12918: if ($context eq 'consumer') {
12919: $name = 'ltitools';
12920: } elsif ($context eq 'provider') {
12921: $name = 'lti';
1.1483 raeburn 12922: } elsif ($context eq 'linkprot') {
12923: $name = 'ltisec';
1.1360 raeburn 12924: } else {
12925: return %lti;
12926: }
1.1483 raeburn 12927: if ($context eq 'linkprot') {
12928: $cachename = $context;
12929: } else {
12930: $cachename = $name;
12931: }
12932: my ($result,$cached)=&is_cached_new($cachename,$cdom);
1.1298 raeburn 12933: if (defined($cached)) {
12934: if (ref($result) eq 'HASH') {
1.1360 raeburn 12935: %lti = %{$result};
1.1298 raeburn 12936: }
12937: } else {
1.1360 raeburn 12938: my %domconfig = &get_dom('configuration',[$name],$cdom);
12939: if (ref($domconfig{$name}) eq 'HASH') {
1.1483 raeburn 12940: if ($context eq 'linkprot') {
12941: if (ref($domconfig{$name}{'linkprot'}) eq 'HASH') {
12942: %lti = %{$domconfig{$name}{'linkprot'}};
12943: }
12944: } else {
12945: %lti = %{$domconfig{$name}};
12946: }
1.1298 raeburn 12947: }
12948: my $cachetime = 24*60*60;
1.1483 raeburn 12949: &do_cache_new($cachename,$cdom,\%lti,$cachetime);
1.1298 raeburn 12950: }
1.1360 raeburn 12951: return %lti;
1.1298 raeburn 12952: }
12953:
1.1463 raeburn 12954: sub get_course_lti {
1.1510 raeburn 12955: my ($cnum,$cdom,$context) = @_;
12956: my ($name,$cachename,%lti);
12957: if ($context eq 'consumer') {
12958: $name = 'ltitools';
12959: $cachename = 'courseltitools';
12960: } elsif ($context eq 'provider') {
12961: $name = 'lti';
12962: $cachename = 'courselti';
12963: } else {
12964: return %lti;
12965: }
1.1463 raeburn 12966: my $hashid=$cdom.'_'.$cnum;
1.1510 raeburn 12967: my ($result,$cached)=&is_cached_new($cachename,$hashid);
1.1463 raeburn 12968: if (defined($cached)) {
12969: if (ref($result) eq 'HASH') {
1.1510 raeburn 12970: %lti = %{$result};
1.1463 raeburn 12971: }
12972: } else {
1.1510 raeburn 12973: %lti = &dump($name,$cdom,$cnum,undef,undef,undef,1);
1.1463 raeburn 12974: my $cachetime = 24*60*60;
1.1510 raeburn 12975: &do_cache_new($cachename,$hashid,\%lti,$cachetime);
1.1463 raeburn 12976: }
1.1510 raeburn 12977: return %lti;
1.1463 raeburn 12978: }
12979:
1.1479 raeburn 12980: sub courselti_itemid {
12981: my ($cnum,$cdom,$url,$method,$params,$context) = @_;
12982: my ($chome,$itemid);
12983: $chome = &homeserver($cnum,$cdom);
12984: return if ($chome eq 'no_host');
12985: if (ref($params) eq 'HASH') {
12986: my $rep;
12987: if (grep { $_ eq $chome } current_machine_ids()) {
12988: $rep = LONCAPA::Lond::crslti_itemid($cdom,$cnum,$url,$method,$params,$perlvar{'lonVersion'});
12989: } else {
12990: my $escurl = &escape($url);
12991: my $escmethod = &escape($method);
12992: my $items = &freeze_escape($params);
12993: $rep = &reply("encrypt:lti:$cdom:$cnum:$context:$escurl:$escmethod:$items",$chome);
12994: }
12995: unless (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
12996: ($rep eq 'unknown_cmd')) {
12997: $itemid = $rep;
12998: }
12999: }
13000: return $itemid;
13001: }
13002:
13003: sub domainlti_itemid {
13004: my ($cdom,$url,$method,$params,$context) = @_;
13005: my ($primary_id,$itemid);
13006: $primary_id = &domain($cdom,'primary');
13007: return if ($primary_id eq '');
13008: if (ref($params) eq 'HASH') {
13009: my $rep;
13010: if (grep { $_ eq $primary_id } current_machine_ids()) {
13011: $rep = LONCAPA::Lond::domlti_itemid($cdom,$context,$url,$method,$params,$perlvar{'lonVersion'});
13012: } else {
13013: my $cnum = '';
13014: my $escurl = &escape($url);
13015: my $escmethod = &escape($method);
13016: my $items = &freeze_escape($params);
13017: $rep = &reply("encrypt:lti:$cdom:$cnum:$context:$escurl:$escmethod:$items",$primary_id);
13018: }
13019: unless (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
13020: ($rep eq 'unknown_cmd')) {
13021: $itemid = $rep;
13022: }
13023: }
13024: return $itemid;
13025: }
13026:
1.1513 raeburn 13027: sub get_ltitools_id {
13028: my ($context,$cdom,$cnum,$title) = @_;
13029: my ($lockhash,$tries,$gotlock,$id,$error);
13030:
13031: # get lock on ltitools db
13032: $lockhash = {
13033: lock => $env{'user.name'}.
13034: ':'.$env{'user.domain'},
13035: };
13036: $tries = 0;
13037: if ($context eq 'domain') {
13038: $gotlock = &newput_dom('ltitools',$lockhash,$cdom);
13039: } else {
13040: $gotlock = &newput('ltitools',$lockhash,$cdom,$cnum);
13041: }
13042: while (($gotlock ne 'ok') && ($tries<10)) {
13043: $tries ++;
13044: sleep (0.1);
13045: if ($context eq 'domain') {
13046: $gotlock = &newput_dom('ltitools',$lockhash,$cdom);
13047: } else {
13048: $gotlock = &newput('ltitools',$lockhash,$cdom,$cnum);
13049: }
13050: }
13051: if ($gotlock eq 'ok') {
13052: my %currids;
13053: if ($context eq 'domain') {
13054: %currids = &dump_dom('ltitools',$cdom);
13055: } else {
13056: %currids = &dump('ltitools',$cdom,$cnum);
13057: }
13058: if ($currids{'lock'}) {
13059: delete($currids{'lock'});
13060: if (keys(%currids)) {
13061: my @curr = sort { $a <=> $b } keys(%currids);
13062: if ($curr[-1] =~ /^\d+$/) {
13063: $id = 1 + $curr[-1];
13064: }
13065: } else {
13066: $id = 1;
13067: }
13068: if ($id) {
13069: if ($context eq 'domain') {
13070: unless (&newput_dom('ltitools',{ $id => $title },$cdom) eq 'ok') {
13071: $error = 'nostore';
13072: }
13073: } else {
13074: unless (&newput('ltitools',{ $id => $title },$cdom,$cnum) eq 'ok') {
13075: $error = 'nostore';
13076: }
13077: }
13078: } else {
13079: $error = 'nonumber';
13080: }
13081: }
13082: my $dellockoutcome;
13083: if ($context eq 'domain') {
13084: $dellockoutcome = &del_dom('ltitools',['lock'],$cdom);
13085: } else {
13086: $dellockoutcome = &del('ltitools',['lock'],$cdom,$cnum);
13087: }
13088: } else {
13089: $error = 'nolock';
13090: }
13091: return ($id,$error);
13092: }
13093:
1.1496 raeburn 13094: sub count_supptools {
13095: my ($cnum,$cdom,$ignorecache,$reload)=@_;
13096: my $hashid=$cnum.':'.$cdom;
13097: my ($numexttools,$cached);
13098: unless ($ignorecache) {
13099: ($numexttools,$cached) = &is_cached_new('supptools',$hashid);
13100: }
13101: unless (defined($cached)) {
13102: my $chome=&homeserver($cnum,$cdom);
13103: $numexttools = 0;
13104: unless ($chome eq 'no_host') {
1.1500 raeburn 13105: my ($supplemental) = &Apache::loncommon::get_supplemental($cnum,$cdom,$reload);
1.1496 raeburn 13106: if (ref($supplemental) eq 'HASH') {
13107: if ((ref($supplemental->{'ids'}) eq 'HASH') && (ref($supplemental->{'hidden'}) eq 'HASH')) {
13108: foreach my $key (keys(%{$supplemental->{'ids'}})) {
13109: if ($key =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
13110: $numexttools ++;
13111: }
13112: }
13113: }
13114: }
13115: }
13116: &do_cache_new('supptools',$hashid,$numexttools,600);
13117: }
13118: return $numexttools;
13119: }
13120:
13121: sub has_unhidden_suppfiles {
1.1498 raeburn 13122: my ($cnum,$cdom,$ignorecache,$possdel)=@_;
1.1236 raeburn 13123: my $hashid=$cnum.':'.$cdom;
1.1496 raeburn 13124: my ($showsupp,$cached);
1.1236 raeburn 13125: unless ($ignorecache) {
1.1496 raeburn 13126: ($showsupp,$cached) = &is_cached_new('showsupp',$hashid);
1.1236 raeburn 13127: }
13128: unless (defined($cached)) {
13129: my $chome=&homeserver($cnum,$cdom);
13130: unless ($chome eq 'no_host') {
1.1500 raeburn 13131: my ($supplemental) = &Apache::loncommon::get_supplemental($cnum,$cdom,$ignorecache,$possdel);
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: next if ($key =~ /\.sequence$/);
13136: if (ref($supplemental->{'ids'}->{$key}) eq 'ARRAY') {
13137: foreach my $id (@{$supplemental->{'ids'}->{$key}}) {
13138: unless ($supplemental->{'hidden'}->{$id}) {
13139: $showsupp = 1;
13140: last;
13141: }
13142: }
13143: }
13144: last if ($showsupp);
13145: }
13146: }
13147: }
1.1236 raeburn 13148: }
1.1496 raeburn 13149: &do_cache_new('showsupp',$hashid,$showsupp,600);
1.1236 raeburn 13150: }
1.1496 raeburn 13151: return $showsupp;
13152: }
13153:
1.379 matthew 13154: #
13155: # EXT resource caching routines
13156: #
13157:
1.1302 raeburn 13158: {
13159: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
13160: #
13161: # The course for which we cache
13162: my $cachedmapkey='';
13163: # The cached recursive maps for this course
13164: my %cachedmaps=();
13165: # When this was last done
13166: my $cachedmaptime='';
13167:
1.379 matthew 13168: sub clear_EXT_cache_status {
1.383 albertel 13169: &delenv('cache.EXT.');
1.379 matthew 13170: }
13171:
13172: sub EXT_cache_status {
13173: my ($target_domain,$target_user) = @_;
1.383 albertel 13174: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 13175: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 13176: # We know already the user has no data
13177: return 1;
13178: } else {
13179: return 0;
13180: }
13181: }
13182:
13183: sub EXT_cache_set {
13184: my ($target_domain,$target_user) = @_;
1.383 albertel 13185: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 13186: #&appenv({$cachename => time});
1.379 matthew 13187: }
13188:
1.28 www 13189: # --------------------------------------------------------- Value of a Variable
1.58 www 13190: sub EXT {
1.715 albertel 13191:
1.1461 raeburn 13192: my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid,$recurseupref)=@_;
1.68 www 13193: unless ($varname) { return ''; }
1.218 albertel 13194: #get real user name/domain, courseid and symb
13195: my $courseid;
1.359 albertel 13196: my $publicuser;
1.427 www 13197: if ($symbparm) {
13198: $symbparm=&get_symb_from_alias($symbparm);
13199: }
1.218 albertel 13200: if (!($uname && $udom)) {
1.790 albertel 13201: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 13202: if (!$symbparm) { $symbparm=$cursymb; }
13203: } else {
1.620 albertel 13204: $courseid=$env{'request.course.id'};
1.218 albertel 13205: }
1.48 www 13206: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
13207: my $rest;
1.320 albertel 13208: if (defined($therest[0])) {
1.48 www 13209: $rest=join('.',@therest);
13210: } else {
13211: $rest='';
13212: }
1.320 albertel 13213:
1.57 www 13214: my $qualifierrest=$qualifier;
13215: if ($rest) { $qualifierrest.='.'.$rest; }
13216: my $spacequalifierrest=$space;
13217: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 13218: if ($realm eq 'user') {
1.48 www 13219: # --------------------------------------------------------------- user.resource
13220: if ($space eq 'resource') {
1.651 albertel 13221: if ( (defined($Apache::lonhomework::parsing_a_problem)
13222: || defined($Apache::lonhomework::parsing_a_task))
13223: &&
1.1469 raeburn 13224: ($symbparm eq &symbread()) ) {
1.744 albertel 13225: # if we are in the middle of processing the resource the
13226: # get the value we are planning on committing
13227: if (defined($Apache::lonhomework::results{$qualifierrest})) {
13228: return $Apache::lonhomework::results{$qualifierrest};
13229: } else {
13230: return $Apache::lonhomework::history{$qualifierrest};
13231: }
1.335 albertel 13232: } else {
1.359 albertel 13233: my %restored;
1.620 albertel 13234: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 13235: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
13236: } else {
13237: %restored=&restore($symbparm,$courseid,$udom,$uname);
13238: }
1.335 albertel 13239: return $restored{$qualifierrest};
13240: }
1.48 www 13241: # ----------------------------------------------------------------- user.access
13242: } elsif ($space eq 'access') {
1.218 albertel 13243: # FIXME - not supporting calls for a specific user
1.48 www 13244: return &allowed($qualifier,$rest);
13245: # ------------------------------------------ user.preferences, user.environment
13246: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 13247: if (($uname eq $env{'user.name'}) &&
13248: ($udom eq $env{'user.domain'})) {
13249: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 13250: } else {
1.359 albertel 13251: my %returnhash;
13252: if (!$publicuser) {
13253: %returnhash=&userenvironment($udom,$uname,
13254: $qualifierrest);
13255: }
1.218 albertel 13256: return $returnhash{$qualifierrest};
13257: }
1.48 www 13258: # ----------------------------------------------------------------- user.course
13259: } elsif ($space eq 'course') {
1.218 albertel 13260: # FIXME - not supporting calls for a specific user
1.620 albertel 13261: return $env{join('.',('request.course',$qualifier))};
1.48 www 13262: # ------------------------------------------------------------------- user.role
13263: } elsif ($space eq 'role') {
1.218 albertel 13264: # FIXME - not supporting calls for a specific user
1.620 albertel 13265: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 13266: if ($qualifier eq 'value') {
13267: return $role;
13268: } elsif ($qualifier eq 'extent') {
13269: return $where;
13270: }
13271: # ----------------------------------------------------------------- user.domain
13272: } elsif ($space eq 'domain') {
1.218 albertel 13273: return $udom;
1.48 www 13274: # ------------------------------------------------------------------- user.name
13275: } elsif ($space eq 'name') {
1.218 albertel 13276: return $uname;
1.48 www 13277: # ---------------------------------------------------- Any other user namespace
1.29 www 13278: } else {
1.359 albertel 13279: my %reply;
13280: if (!$publicuser) {
13281: %reply=&get($space,[$qualifierrest],$udom,$uname);
13282: }
13283: return $reply{$qualifierrest};
1.48 www 13284: }
1.236 www 13285: } elsif ($realm eq 'query') {
13286: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 13287: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
13288: [$spacequalifierrest]);
1.620 albertel 13289: return $env{'form.'.$spacequalifierrest};
1.236 www 13290: } elsif ($realm eq 'request') {
1.48 www 13291: # ------------------------------------------------------------- request.browser
13292: if ($space eq 'browser') {
1.1145 bisitz 13293: return $env{'browser.'.$qualifier};
1.57 www 13294: # ------------------------------------------------------------ request.filename
13295: } else {
1.620 albertel 13296: return $env{'request.'.$spacequalifierrest};
1.29 www 13297: }
1.28 www 13298: } elsif ($realm eq 'course') {
1.48 www 13299: # ---------------------------------------------------------- course.description
1.620 albertel 13300: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 13301: } elsif ($realm eq 'resource') {
1.165 www 13302:
1.620 albertel 13303: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 13304: if (!$symbparm) { $symbparm=&symbread(); }
13305: }
1.693 albertel 13306:
1.1232 raeburn 13307: if ($qualifier eq '') {
13308: if ($space eq 'title') {
13309: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
13310: return &gettitle($symbparm);
13311: }
1.693 albertel 13312:
1.1232 raeburn 13313: if ($space eq 'map') {
13314: my ($map) = &decode_symb($symbparm);
13315: return &symbread($map);
13316: }
13317: if ($space eq 'maptitle') {
13318: my ($map) = &decode_symb($symbparm);
13319: return &gettitle($map);
13320: }
13321: if ($space eq 'filename') {
13322: if ($symbparm) {
13323: return &clutter((&decode_symb($symbparm))[2]);
13324: }
13325: return &hreflocation('',$env{'request.filename'});
1.905 albertel 13326: }
1.1232 raeburn 13327:
1.1233 raeburn 13328: if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
13329: if ($space eq 'visibleparts') {
13330: my $navmap = Apache::lonnavmaps::navmap->new();
13331: my $item;
13332: if (ref($navmap)) {
13333: my $res = $navmap->getBySymb($symbparm);
13334: my $parts = $res->parts();
13335: if (ref($parts) eq 'ARRAY') {
13336: $item = join(',',@{$parts});
13337: }
13338: undef($navmap);
1.1232 raeburn 13339: }
1.1233 raeburn 13340: return $item;
1.1232 raeburn 13341: }
13342: }
13343: }
1.693 albertel 13344:
1.1301 raeburn 13345: my ($section, $group, @groups, @recurseup, $recursed);
1.1461 raeburn 13346: if (ref($recurseupref) eq 'ARRAY') {
13347: @recurseup = @{$recurseupref};
13348: $recursed = 1;
13349: }
1.1301 raeburn 13350: my ($courselevelm,$courseleveli,$courselevel,$mapp);
1.1228 raeburn 13351: if (($courseid eq '') && ($cid)) {
13352: $courseid = $cid;
13353: }
13354: if (($symbparm && $courseid) &&
13355: (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165 www 13356:
1.218 albertel 13357: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 13358:
1.60 www 13359: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 13360: my $symbp=$symbparm;
1.1301 raeburn 13361: $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 13362: my $symbparm=$symbp.'.'.$spacequalifierrest;
1.1301 raeburn 13363: my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
1.218 albertel 13364: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
1.620 albertel 13365: if (($env{'user.name'} eq $uname) &&
13366: ($env{'user.domain'} eq $udom)) {
13367: $section=$env{'request.course.sec'};
1.733 raeburn 13368: @groups = split(/:/,$env{'request.course.groups'});
13369: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 13370: } else {
1.539 albertel 13371: if (! defined($usection)) {
1.551 albertel 13372: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 13373: } else {
13374: $section = $usection;
13375: }
1.733 raeburn 13376: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 13377: }
13378:
13379: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
13380: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
1.1301 raeburn 13381: my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
1.218 albertel 13382: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
13383:
1.593 albertel 13384: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 13385: my $courselevelr=$courseid.'.'.$symbparm;
1.1301 raeburn 13386: $courseleveli=$courseid.'.'.$recurseparm;
1.593 albertel 13387: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 13388:
1.60 www 13389: # ----------------------------------------------------------- first, check user
1.624 albertel 13390:
1.1301 raeburn 13391: my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
13392: \@recurseup,$courseid,'.',$spacequalifierrest,
1.927 albertel 13393: ([$courselevelr,'resource'],
13394: [$courselevelm,'map' ],
1.1301 raeburn 13395: [$courseleveli,'map' ],
1.927 albertel 13396: [$courselevel, 'course' ]));
1.931 albertel 13397: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 13398:
1.594 albertel 13399: # ------------------------------------------------ second, check some of course
1.684 raeburn 13400: my $coursereply;
1.691 raeburn 13401: if (@groups > 0) {
13402: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
1.1301 raeburn 13403: $recurseparm,$mapparm,$spacequalifierrest,
13404: $mapp,\$recursed,\@recurseup);
13405: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 13406: }
1.96 www 13407:
1.684 raeburn 13408: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 13409: $env{'course.'.$courseid.'.domain'},
1.1301 raeburn 13410: 'course',$mapp,\$recursed,\@recurseup,
13411: $courseid,'.['.$section.'].',$spacequalifierrest,
1.927 albertel 13412: ([$seclevelr, 'resource'],
13413: [$seclevelm, 'map' ],
1.1301 raeburn 13414: [$secleveli, 'map' ],
1.927 albertel 13415: [$seclevel, 'course' ],
13416: [$courselevelr,'resource']));
13417: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 13418:
1.60 www 13419: # ------------------------------------------------------ third, check map parms
1.218 albertel 13420: my %parmhash=();
13421: my $thisparm='';
13422: if (tie(%parmhash,'GDBM_File',
1.620 albertel 13423: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 13424: &GDBM_READER(),0640)) {
1.218 albertel 13425: $thisparm=$parmhash{$symbparm};
13426: untie(%parmhash);
13427: }
1.927 albertel 13428: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 13429: }
1.594 albertel 13430: # ------------------------------------------ fourth, look in resource metadata
1.1301 raeburn 13431:
13432: my $what = $spacequalifierrest;
13433: $what=~s/\./\_/;
1.282 albertel 13434: my $filename;
13435: if (!$symbparm) { $symbparm=&symbread(); }
13436: if ($symbparm) {
1.409 www 13437: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 13438: } else {
1.620 albertel 13439: $filename=$env{'request.filename'};
1.282 albertel 13440: }
1.1362 raeburn 13441: my $toolsymb;
13442: if (($filename =~ /ext\.tool$/) && ($what ne '0_gradable')) {
13443: $toolsymb = $symbparm;
13444: }
13445: my $metadata=&metadata($filename,$what,$toolsymb);
1.927 albertel 13446: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.1362 raeburn 13447: $metadata=&metadata($filename,'parameter_'.$what,$toolsymb);
1.927 albertel 13448: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 13449:
1.1301 raeburn 13450: # ----------------------------------------------- fifth, look in rest of course
1.593 albertel 13451: if ($symbparm && defined($courseid) &&
1.620 albertel 13452: $courseid eq $env{'request.course.id'}) {
1.624 albertel 13453: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
13454: $env{'course.'.$courseid.'.domain'},
1.1301 raeburn 13455: 'course',$mapp,\$recursed,\@recurseup,
13456: $courseid,'.',$spacequalifierrest,
1.927 albertel 13457: ([$courselevelm,'map' ],
1.1301 raeburn 13458: [$courseleveli,'map' ],
1.927 albertel 13459: [$courselevel, 'course']));
13460: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 13461: }
1.145 www 13462: # ------------------------------------------------------------------ Cascade up
1.218 albertel 13463: unless ($space eq '0') {
1.336 albertel 13464: my @parts=split(/_/,$space);
13465: my $id=pop(@parts);
13466: my $part=join('_',@parts);
13467: if ($part eq '') { $part='0'; }
1.927 albertel 13468: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 13469: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 13470: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 13471: }
1.395 albertel 13472: if ($recurse) { return undef; }
1.1362 raeburn 13473: my $pack_def=&packages_tab_default($filename,$varname,$toolsymb);
1.927 albertel 13474: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 13475: # ---------------------------------------------------- Any other user namespace
13476: } elsif ($realm eq 'environment') {
13477: # ----------------------------------------------------------------- environment
1.620 albertel 13478: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
13479: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 13480: } else {
1.770 albertel 13481: if ($uname eq 'anonymous' && $udom eq '') {
13482: return '';
13483: }
1.219 albertel 13484: my %returnhash=&userenvironment($udom,$uname,
13485: $spacequalifierrest);
13486: return $returnhash{$spacequalifierrest};
13487: }
1.28 www 13488: } elsif ($realm eq 'system') {
1.48 www 13489: # ----------------------------------------------------------------- system.time
13490: if ($space eq 'time') {
13491: return time;
13492: }
1.696 albertel 13493: } elsif ($realm eq 'server') {
13494: # ----------------------------------------------------------------- system.time
13495: if ($space eq 'name') {
13496: return $ENV{'SERVER_NAME'};
13497: }
1.1415 raeburn 13498: } elsif ($realm eq 'client') {
13499: if ($space eq 'remote_addr') {
1.1441 raeburn 13500: return &get_requestor_ip();
1.1415 raeburn 13501: }
1.28 www 13502: }
1.48 www 13503: return '';
1.61 www 13504: }
13505:
1.927 albertel 13506: sub get_reply {
13507: my ($reply_value) = @_;
1.940 raeburn 13508: if (ref($reply_value) eq 'ARRAY') {
13509: if (wantarray) {
13510: return @$reply_value;
13511: }
13512: return $reply_value->[0];
13513: } else {
13514: return $reply_value;
1.927 albertel 13515: }
13516: }
13517:
1.691 raeburn 13518: sub check_group_parms {
1.1301 raeburn 13519: my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
13520: $recursed,$recurseupref) = @_;
13521: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
13522: [$what,'course']);
13523: my $coursereply;
1.691 raeburn 13524: foreach my $group (@{$groups}) {
1.1301 raeburn 13525: my @groupitems = ();
1.691 raeburn 13526: foreach my $level (@levels) {
1.927 albertel 13527: my $item = $courseid.'.['.$group.'].'.$level->[0];
13528: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 13529: }
1.1301 raeburn 13530: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
13531: $env{'course.'.$courseid.'.domain'},
13532: 'course',$mapp,$recursed,$recurseupref,
13533: $courseid,'.['.$group.'].',$what,
13534: @groupitems);
13535: last if (defined($coursereply));
1.691 raeburn 13536: }
13537: return $coursereply;
13538: }
13539:
1.1301 raeburn 13540: sub get_map_hierarchy {
1.1302 raeburn 13541: my ($mapname,$courseid) = @_;
13542: my @recurseup = ();
1.1301 raeburn 13543: if ($mapname) {
1.1302 raeburn 13544: if (($cachedmapkey eq $courseid) &&
13545: (abs($cachedmaptime-time)<5)) {
13546: if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
13547: return @{$cachedmaps{$mapname}};
13548: }
13549: }
1.1301 raeburn 13550: my $navmap = Apache::lonnavmaps::navmap->new();
13551: if (ref($navmap)) {
13552: @recurseup = $navmap->recurseup_maps($mapname);
13553: undef($navmap);
1.1302 raeburn 13554: $cachedmaps{$mapname} = \@recurseup;
13555: $cachedmaptime=time;
13556: $cachedmapkey=$courseid;
1.1301 raeburn 13557: }
13558: }
13559: return @recurseup;
13560: }
13561:
1.1302 raeburn 13562: }
13563:
1.691 raeburn 13564: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 13565: my ($courseid,@groups) = @_;
13566: @groups = sort(@groups);
1.691 raeburn 13567: return @groups;
13568: }
13569:
1.395 albertel 13570: sub packages_tab_default {
1.1362 raeburn 13571: my ($uri,$varname,$toolsymb)=@_;
1.395 albertel 13572: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 13573:
13574: my (@extension,@specifics,$do_default);
1.1362 raeburn 13575: foreach my $package (split(/,/,&metadata($uri,'packages',$toolsymb))) {
1.395 albertel 13576: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 13577: if ($pack_type eq 'default') {
13578: $do_default=1;
13579: } elsif ($pack_type eq 'extension') {
13580: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 13581: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 13582: # only look at packages defaults for packages that this id is
1.738 albertel 13583: push(@specifics,[$package,$pack_type,$pack_part]);
13584: }
13585: }
13586: # first look for a package that matches the requested part id
13587: foreach my $package (@specifics) {
13588: my (undef,$pack_type,$pack_part)=@{$package};
13589: next if ($pack_part ne $part);
13590: if (defined($packagetab{"$pack_type&$name&default"})) {
13591: return $packagetab{"$pack_type&$name&default"};
13592: }
13593: }
13594: # look for any possible matching non extension_ package
13595: foreach my $package (@specifics) {
13596: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 13597: if (defined($packagetab{"$pack_type&$name&default"})) {
13598: return $packagetab{"$pack_type&$name&default"};
13599: }
1.585 albertel 13600: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 13601: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
13602: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 13603: }
13604: }
1.738 albertel 13605: # look for any posible extension_ match
13606: foreach my $package (@extension) {
13607: my ($package,$pack_type)=@{$package};
13608: if (defined($packagetab{"$pack_type&$name&default"})) {
13609: return $packagetab{"$pack_type&$name&default"};
13610: }
13611: if (defined($packagetab{$package."&$name&default"})) {
13612: return $packagetab{$package."&$name&default"};
13613: }
13614: }
13615: # look for a global default setting
13616: if ($do_default && defined($packagetab{"default&$name&default"})) {
13617: return $packagetab{"default&$name&default"};
13618: }
1.395 albertel 13619: return undef;
13620: }
13621:
1.334 albertel 13622: sub add_prefix_and_part {
13623: my ($prefix,$part)=@_;
13624: my $keyroot;
13625: if (defined($prefix) && $prefix !~ /^__/) {
13626: # prefix that has a part already
13627: $keyroot=$prefix;
13628: } elsif (defined($prefix)) {
13629: # prefix that is missing a part
13630: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
13631: } else {
13632: # no prefix at all
13633: if (defined($part)) { $keyroot='_'.$part; }
13634: }
13635: return $keyroot;
13636: }
13637:
1.71 www 13638: # ---------------------------------------------------------------- Get metadata
13639:
1.599 albertel 13640: my %metaentry;
1.1070 www 13641: my %importedpartids;
1.1369 raeburn 13642: my %importedrespids;
1.71 www 13643: sub metadata {
1.1362 raeburn 13644: my ($uri,$what,$toolsymb,$liburi,$prefix,$depthcount)=@_;
1.71 www 13645: $uri=&declutter($uri);
1.288 albertel 13646: # if it is a non metadata possible uri return quickly
1.529 albertel 13647: if (($uri eq '') ||
13648: (($uri =~ m|^/*adm/|) &&
1.1343 raeburn 13649: ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
1.1108 raeburn 13650: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 13651: return undef;
13652: }
1.1261 raeburn 13653: if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv})
1.924 albertel 13654: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 13655: return undef;
1.288 albertel 13656: }
1.73 www 13657: my $filename=$uri;
13658: $uri=~s/\.meta$//;
1.172 www 13659: #
13660: # Is the metadata already cached?
1.177 www 13661: # Look at timestamp of caching
1.172 www 13662: # Everything is cached by the main uri, libraries are never directly cached
13663: #
1.428 albertel 13664: if (!defined($liburi)) {
1.599 albertel 13665: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 13666: if (defined($cached)) { return $result->{':'.$what}; }
13667: }
1.1362 raeburn 13668:
13669: #
13670: # If the uri is for an external tool the file from
13671: # which metadata should be retrieved depends on whether
13672: # the tool had been configured to be gradable (set in the Course
13673: # Editor or Resource Editor).
13674: #
13675: # If a valid symb has been included as the third arg in the call
13676: # to &metadata() that can be used to retrieve the value of
13677: # parameter_0_gradable set for the resource, and included in the
13678: # uploaded map containing the tool. The value is retrieved via
13679: # &EXT(), if a valid symb is available. Otherwise the value of
13680: # gradable in the exttool_$marker.db file for the tool instance
1.1364 raeburn 13681: # is retrieved via &get().
13682: #
13683: # When lonuserstate::traceroute() calls lonnet::EXT() for
13684: # hiddenresource and encrypturl (during course initialization)
13685: # the map-level parameter for resource.0.gradable included in the
13686: # uploaded map containing the tool will not yet have been stored
13687: # in the user_course_parms.db file for the user's session, so in
13688: # this case fall back to retrieving gradable status from the
13689: # exttool_$marker.db file.
1.1362 raeburn 13690: #
13691: # In order to avoid an infinite loop, &metadata() will return
13692: # before a call to &EXT(), if the uri is for an external tool
13693: # and the $what for which metadata is being requested is
13694: # parameter_0_gradable or 0_gradable.
13695: #
13696:
13697: if ($uri =~ /ext\.tool$/) {
13698: if (($what eq 'parameter_0_gradable') || ($what eq '0_gradable')) {
13699: return;
13700: } else {
13701: my ($checked,$use_passback);
13702: if ($toolsymb ne '') {
13703: (undef,undef,my $tooluri) = &decode_symb($toolsymb);
1.1364 raeburn 13704: if (($tooluri eq $uri) && (&EXT('resource.0.gradable',$toolsymb))) {
1.1362 raeburn 13705: $checked = 1;
13706: if (&EXT('resource.0.gradable',$toolsymb) =~ /^yes$/i) {
13707: $use_passback = 1;
13708: }
13709: }
13710: }
13711: unless ($checked) {
13712: my ($ignore,$cdom,$cnum,$marker) = split(m{/},$uri);
13713: $marker=~s/\D//g;
1.1363 raeburn 13714: if ($marker) {
1.1362 raeburn 13715: my %toolsettings=&get('exttool_'.$marker,['gradable'],$cdom,$cnum);
13716: $use_passback = $toolsettings{'gradable'};
13717: }
13718: }
13719: if ($use_passback) {
13720: $filename = '/home/httpd/html/res/lib/templates/LTIpassback.tool';
13721: } else {
13722: $filename = '/home/httpd/html/res/lib/templates/LTIstandard.tool';
13723: }
13724: }
13725: }
13726:
1.428 albertel 13727: {
1.1069 www 13728: # Imported parts would go here
1.1369 raeburn 13729: my @origfiletagids=();
1.1069 www 13730: my $importedparts=0;
1.1369 raeburn 13731:
13732: # Imported responseids would go here
13733: my $importedresponses=0;
1.172 www 13734: #
13735: # Is this a recursive call for a library?
13736: #
1.599 albertel 13737: # if (! exists($metacache{$uri})) {
13738: # $metacache{$uri}={};
13739: # }
1.924 albertel 13740: my $cachetime = 60*60;
1.171 www 13741: if ($liburi) {
13742: $liburi=&declutter($liburi);
13743: $filename=$liburi;
1.401 bowersj2 13744: } else {
1.599 albertel 13745: &devalidate_cache_new('meta',$uri);
13746: undef(%metaentry);
1.401 bowersj2 13747: }
1.140 www 13748: my %metathesekeys=();
1.73 www 13749: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 13750: my $metastring;
1.1140 www 13751: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929 albertel 13752: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 13753: $metastring =
1.929 albertel 13754: &Apache::lonnet::ssi_body($which,
1.924 albertel 13755: ('grade_target' => 'meta'));
13756: $cachetime = 1; # only want this cached in the child not long term
1.1108 raeburn 13757: } elsif (($uri !~ m -^(editupload)/-) &&
13758: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 13759: my $file=&filelocation('',&clutter($filename));
1.599 albertel 13760: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 13761: $metastring=&getfile($file);
1.489 albertel 13762: }
1.208 albertel 13763: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 13764: my $token;
1.140 www 13765: undef %metathesekeys;
1.71 www 13766: while ($token=$parser->get_token) {
1.339 albertel 13767: if ($token->[0] eq 'S') {
13768: if (defined($token->[2]->{'package'})) {
1.172 www 13769: #
13770: # This is a package - get package info
13771: #
1.339 albertel 13772: my $package=$token->[2]->{'package'};
13773: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
13774: if (defined($token->[2]->{'id'})) {
13775: $keyroot.='_'.$token->[2]->{'id'};
13776: }
1.599 albertel 13777: if ($metaentry{':packages'}) {
13778: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 13779: } else {
1.599 albertel 13780: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 13781: }
1.736 albertel 13782: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 13783: my $part=$keyroot;
13784: $part=~s/^\_//;
1.736 albertel 13785: if ($pack_entry=~/^\Q$package\E\&/ ||
13786: $pack_entry=~/^\Q$package\E_0\&/) {
13787: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 13788: # ignore package.tab specified default values
13789: # here &package_tab_default() will fetch those
13790: if ($subp eq 'default') { next; }
1.736 albertel 13791: my $value=$packagetab{$pack_entry};
1.432 albertel 13792: my $unikey;
13793: if ($pack =~ /_0$/) {
13794: $unikey='parameter_0_'.$name;
13795: $part=0;
13796: } else {
13797: $unikey='parameter'.$keyroot.'_'.$name;
13798: }
1.339 albertel 13799: if ($subp eq 'display') {
13800: $value.=' [Part: '.$part.']';
13801: }
1.599 albertel 13802: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 13803: $metathesekeys{$unikey}=1;
1.599 albertel 13804: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
13805: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 13806: }
1.599 albertel 13807: if (defined($metaentry{':'.$unikey.'.default'})) {
13808: $metaentry{':'.$unikey}=
13809: $metaentry{':'.$unikey.'.default'};
1.356 albertel 13810: }
1.339 albertel 13811: }
13812: }
13813: } else {
1.172 www 13814: #
13815: # This is not a package - some other kind of start tag
1.339 albertel 13816: #
13817: my $entry=$token->[1];
1.1068 www 13818: my $unikey='';
1.175 www 13819:
1.339 albertel 13820: if ($entry eq 'import') {
1.175 www 13821: #
13822: # Importing a library here
1.339 albertel 13823: #
1.1067 www 13824: my $location=$parser->get_text('/import');
13825: my $dir=$filename;
13826: $dir=~s|[^/]*$||;
13827: $location=&filelocation($dir,$location);
1.1369 raeburn 13828:
13829: my $importid=$token->[2]->{'id'};
1.1068 www 13830: my $importmode=$token->[2]->{'importmode'};
1.1369 raeburn 13831: #
13832: # Check metadata for imported file to
13833: # see if it contained response items
13834: #
1.1372 raeburn 13835: my ($origfile,@libfilekeys);
1.1370 raeburn 13836: my %currmetaentry = %metaentry;
1.1372 raeburn 13837: @libfilekeys = split(/,/,&metadata($location,'keys',undef,undef,undef,
13838: $depthcount+1));
13839: if (grep(/^responseorder$/,@libfilekeys)) {
13840: my $libresponseorder = &metadata($location,'responseorder',undef,undef,
13841: undef,$depthcount+1);
13842: if ($libresponseorder ne '') {
13843: if ($#origfiletagids<0) {
13844: undef(%importedrespids);
13845: undef(%importedpartids);
13846: }
1.1373 raeburn 13847: my @respids = split(/\s*,\s*/,$libresponseorder);
13848: if (@respids) {
13849: $importedrespids{$importid} = join(',',map { $importid.'_'.$_ } @respids);
13850: }
13851: if ($importedrespids{$importid} ne '') {
1.1372 raeburn 13852: $importedresponses = 1;
1.1369 raeburn 13853: # We need to get the original file and the imported file to get the response order correct
13854: # Load and inspect original file
1.1372 raeburn 13855: if ($#origfiletagids<0) {
13856: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
13857: $origfile=&getfile($origfilelocation);
13858: @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
13859: }
1.1369 raeburn 13860: }
13861: }
13862: }
1.1370 raeburn 13863: # Do not overwrite contents of %metaentry hash for resource itself with
13864: # hash populated for imported library file
13865: %metaentry = %currmetaentry;
13866: undef(%currmetaentry);
1.1374 raeburn 13867: if ($importmode eq 'part') {
1.1068 www 13868: # Import as part(s)
1.1069 www 13869: $importedparts=1;
13870: # We need to get the original file and the imported file to get the part order correct
13871: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1369 raeburn 13872: # Load and inspect original file if we didn't do that already
13873: if ($#origfiletagids<0) {
13874: undef(%importedrespids);
13875: undef(%importedpartids);
13876: if ($origfile eq '') {
13877: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
13878: $origfile=&getfile($origfilelocation);
13879: @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
13880: }
1.1070 www 13881: }
1.1372 raeburn 13882: my @impfilepartids;
13883: # If <partorder> tag is included in metadata for the imported file
13884: # get the parts in the imported file from that.
13885: if (grep(/^partorder$/,@libfilekeys)) {
13886: %currmetaentry = %metaentry;
13887: my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
13888: $depthcount+1);
13889: %metaentry = %currmetaentry;
13890: undef(%currmetaentry);
13891: if ($libpartorder ne '') {
13892: @impfilepartids=split(/\s*,\s*/,$libpartorder);
13893: }
13894: } else {
13895: # If no <partorder> tag available, load and inspect imported file
13896: my $impfile=&getfile($location);
13897: @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
13898: }
1.1069 www 13899: if ($#impfilepartids>=0) {
13900: # This problem had parts
1.1070 www 13901: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 13902: } else {
13903: # Importing by turning a single problem into a problem part
13904: # It gets the import-tags ID as part-ID
13905: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 13906: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 13907: }
1.1068 www 13908: } else {
1.1374 raeburn 13909: # Import as problem or as normal import
13910: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
13911: unless ($importmode eq 'problem') {
1.1068 www 13912: # Normal import
1.1374 raeburn 13913: if (defined($token->[2]->{'id'})) {
13914: $unikey.='_'.$token->[2]->{'id'};
13915: }
13916: }
13917: # Check metadata for imported file to
13918: # see if it contained parts
13919: if (grep(/^partorder$/,@libfilekeys)) {
13920: %currmetaentry = %metaentry;
13921: my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
13922: $depthcount+1);
13923: %metaentry = %currmetaentry;
13924: undef(%currmetaentry);
13925: if ($libpartorder ne '') {
13926: $importedparts = 1;
13927: $importedpartids{$token->[2]->{'id'}}=$libpartorder;
13928: }
13929: }
1.1067 www 13930: }
1.339 albertel 13931: if ($depthcount<20) {
1.736 albertel 13932: my $metadata =
1.1362 raeburn 13933: &metadata($uri,'keys',$toolsymb,$location,$unikey,
1.736 albertel 13934: $depthcount+1);
13935: foreach my $meta (split(',',$metadata)) {
13936: $metaentry{':'.$meta}=$metaentry{':'.$meta};
13937: $metathesekeys{$meta}=1;
1.339 albertel 13938: }
1.1068 www 13939: }
1.1067 www 13940: } else {
13941: #
13942: # Not importing, some other kind of non-package, non-library start tag
13943: #
13944: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
13945: if (defined($token->[2]->{'id'})) {
13946: $unikey.='_'.$token->[2]->{'id'};
13947: }
1.339 albertel 13948: if (defined($token->[2]->{'name'})) {
13949: $unikey.='_'.$token->[2]->{'name'};
13950: }
13951: $metathesekeys{$unikey}=1;
1.736 albertel 13952: foreach my $param (@{$token->[3]}) {
13953: $metaentry{':'.$unikey.'.'.$param} =
13954: $token->[2]->{$param};
1.339 albertel 13955: }
13956: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 13957: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 13958: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
13959: # only ws inside the tag, and not in default, so use default
13960: # as value
1.599 albertel 13961: $metaentry{':'.$unikey}=$default;
1.908 albertel 13962: } elsif ( $internaltext =~ /\S/ ) {
13963: # something interesting inside the tag
13964: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 13965: } else {
1.908 albertel 13966: # no interesting values, don't set a default
1.339 albertel 13967: }
1.172 www 13968: # end of not-a-package not-a-library import
1.339 albertel 13969: }
1.172 www 13970: # end of not-a-package start tag
1.339 albertel 13971: }
1.172 www 13972: # the next is the end of "start tag"
1.339 albertel 13973: }
13974: }
1.483 albertel 13975: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 13976: $extension = lc($extension);
13977: if ($extension eq 'htm') { $extension='html'; }
13978:
1.737 albertel 13979: foreach my $key (keys(%packagetab)) {
1.483 albertel 13980: #no specific packages #how's our extension
13981: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 13982: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 13983: \%metathesekeys);
13984: }
1.883 albertel 13985:
13986: if (!exists($metaentry{':packages'})
13987: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 13988: foreach my $key (keys(%packagetab)) {
1.483 albertel 13989: #no specific packages well let's get default then
13990: if ($key!~/^default&/) { next; }
1.488 albertel 13991: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 13992: \%metathesekeys);
13993: }
13994: }
1.338 www 13995: # are there custom rights to evaluate
1.599 albertel 13996: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 13997:
1.338 www 13998: #
13999: # Importing a rights file here
1.339 albertel 14000: #
14001: unless ($depthcount) {
1.599 albertel 14002: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 14003: my $dir=$filename;
14004: $dir=~s|[^/]*$||;
14005: $location=&filelocation($dir,$location);
1.736 albertel 14006: my $rights_metadata =
1.1362 raeburn 14007: &metadata($uri,'keys',$toolsymb,$location,'_rights',
1.736 albertel 14008: $depthcount+1);
14009: foreach my $rights (split(',',$rights_metadata)) {
14010: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
14011: $metathesekeys{$rights}=1;
1.339 albertel 14012: }
14013: }
14014: }
1.737 albertel 14015: # uniqifiy package listing
14016: my %seen;
14017: my @uniq_packages =
14018: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
14019: $metaentry{':packages'} = join(',',@uniq_packages);
14020:
1.1369 raeburn 14021: if (($importedresponses) || ($importedparts)) {
14022: if ($importedparts) {
1.1070 www 14023: # We had imported parts and need to rebuild partorder
1.1369 raeburn 14024: $metaentry{':partorder'}='';
14025: $metathesekeys{'partorder'}=1;
14026: }
14027: if ($importedresponses) {
14028: # We had imported responses and need to rebuil responseorder
14029: $metaentry{':responseorder'}='';
14030: $metathesekeys{'responseorder'}=1;
14031: }
14032: for (my $index=0;$index<$#origfiletagids;$index+=2) {
14033: my $origid = $origfiletagids[$index+1];
14034: if ($origfiletagids[$index] eq 'part') {
14035: # Original part, part of the problem
14036: if ($importedparts) {
14037: $metaentry{':partorder'}.=','.$origid;
14038: }
14039: } elsif ($origfiletagids[$index] eq 'import') {
14040: if ($importedparts) {
14041: # We have imported parts at this position
1.1373 raeburn 14042: if ($importedpartids{$origid} ne '') {
14043: $metaentry{':partorder'}.=','.$importedpartids{$origid};
14044: }
1.1369 raeburn 14045: }
14046: if ($importedresponses) {
14047: # We have imported responses at this position
1.1373 raeburn 14048: if ($importedrespids{$origid} ne '') {
14049: $metaentry{':responseorder'}.=','.$importedrespids{$origid};
1.1369 raeburn 14050: }
14051: }
14052: } else {
14053: # Original response item, part of the problem
14054: if ($importedresponses) {
14055: $metaentry{':responseorder'}.=','.$origid;
14056: }
14057: }
14058: }
14059: if ($importedparts) {
14060: $metaentry{':partorder'}=~s/^\,//;
14061: }
14062: if ($importedresponses) {
14063: $metaentry{':responseorder'}=~s/^\,//;
14064: }
1.1070 www 14065: }
1.737 albertel 14066: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 14067: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1274 raeburn 14068: $metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.1371 raeburn 14069: unless ($liburi) {
14070: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
14071: }
1.177 www 14072: # this is the end of "was not already recently cached
1.71 www 14073: }
1.599 albertel 14074: return $metaentry{':'.$what};
1.261 albertel 14075: }
14076:
1.488 albertel 14077: sub metadata_create_package_def {
1.483 albertel 14078: my ($uri,$key,$package,$metathesekeys)=@_;
14079: my ($pack,$name,$subp)=split(/\&/,$key);
14080: if ($subp eq 'default') { next; }
14081:
1.599 albertel 14082: if (defined($metaentry{':packages'})) {
14083: $metaentry{':packages'}.=','.$package;
1.483 albertel 14084: } else {
1.599 albertel 14085: $metaentry{':packages'}=$package;
1.483 albertel 14086: }
14087: my $value=$packagetab{$key};
14088: my $unikey;
14089: $unikey='parameter_0_'.$name;
1.599 albertel 14090: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 14091: $$metathesekeys{$unikey}=1;
1.599 albertel 14092: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
14093: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 14094: }
1.599 albertel 14095: if (defined($metaentry{':'.$unikey.'.default'})) {
14096: $metaentry{':'.$unikey}=
14097: $metaentry{':'.$unikey.'.default'};
1.483 albertel 14098: }
14099: }
14100:
1.261 albertel 14101: sub metadata_generate_part0 {
14102: my ($metadata,$metacache,$uri) = @_;
14103: my %allnames;
1.737 albertel 14104: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 14105: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 14106: my $part=$$metacache{':'.$metakey.'.part'};
14107: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 14108: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 14109: $allnames{$name}=$part;
14110: }
14111: }
14112: }
14113: foreach my $name (keys(%allnames)) {
14114: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 14115: my $key=":parameter_0_$name";
1.261 albertel 14116: $$metacache{"$key.part"}='0';
14117: $$metacache{"$key.name"}=$name;
1.428 albertel 14118: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 14119: $allnames{$name}.'_'.$name.
14120: '.type'};
1.428 albertel 14121: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 14122: '.display'};
1.644 www 14123: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 14124: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 14125: $$metacache{"$key.display"}=$olddis;
14126: }
1.71 www 14127: }
14128:
1.764 albertel 14129: # ------------------------------------------------------ Devalidate title cache
14130:
14131: sub devalidate_title_cache {
14132: my ($url)=@_;
14133: if (!$env{'request.course.id'}) { return; }
14134: my $symb=&symbread($url);
14135: if (!$symb) { return; }
14136: my $key=$env{'request.course.id'}."\0".$symb;
14137: &devalidate_cache_new('title',$key);
14138: }
14139:
1.1014 droeschl 14140: # ------------------------------------------------- Get the title of a course
14141:
14142: sub current_course_title {
14143: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
14144: }
1.301 www 14145: # ------------------------------------------------- Get the title of a resource
14146:
14147: sub gettitle {
14148: my $urlsymb=shift;
14149: my $symb=&symbread($urlsymb);
1.534 albertel 14150: if ($symb) {
1.620 albertel 14151: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 14152: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 14153: if (defined($cached)) {
14154: return $result;
14155: }
1.534 albertel 14156: my ($map,$resid,$url)=&decode_symb($symb);
14157: my $title='';
1.907 albertel 14158: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
14159: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
14160: } else {
14161: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
14162: &GDBM_READER(),0640)) {
14163: my $mapid=$bighash{'map_pc_'.&clutter($map)};
14164: $title=$bighash{'title_'.$mapid.'.'.$resid};
14165: untie(%bighash);
14166: }
1.534 albertel 14167: }
14168: $title=~s/\&colon\;/\:/gs;
14169: if ($title) {
1.1159 www 14170: # Remember both $symb and $title for dynamic metadata
14171: $accesshash{$symb.'___crstitle'}=$title;
1.1161 www 14172: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159 www 14173: # Cache this title and then return it
1.599 albertel 14174: return &do_cache_new('title',$key,$title,600);
1.534 albertel 14175: }
14176: $urlsymb=$url;
14177: }
14178: my $title=&metadata($urlsymb,'title');
14179: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
14180: return $title;
1.301 www 14181: }
1.613 albertel 14182:
1.614 albertel 14183: sub get_slot {
14184: my ($which,$cnum,$cdom)=@_;
14185: if (!$cnum || !$cdom) {
1.790 albertel 14186: (undef,my $courseid)=&whichuser();
1.620 albertel 14187: $cdom=$env{'course.'.$courseid.'.domain'};
14188: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 14189: }
1.703 albertel 14190: my $key=join("\0",'slots',$cdom,$cnum,$which);
14191: my %slotinfo;
14192: if (exists($remembered{$key})) {
14193: $slotinfo{$which} = $remembered{$key};
14194: } else {
14195: %slotinfo=&get('slots',[$which],$cdom,$cnum);
14196: &Apache::lonhomework::showhash(%slotinfo);
14197: my ($tmp)=keys(%slotinfo);
14198: if ($tmp=~/^error:/) { return (); }
14199: $remembered{$key} = $slotinfo{$which};
14200: }
1.616 albertel 14201: if (ref($slotinfo{$which}) eq 'HASH') {
14202: return %{$slotinfo{$which}};
14203: }
14204: return $slotinfo{$which};
1.614 albertel 14205: }
1.1150 raeburn 14206:
14207: sub get_reservable_slots {
14208: my ($cnum,$cdom,$uname,$udom) = @_;
14209: my $now = time;
14210: my $reservable_info;
14211: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
14212: if (exists($remembered{$key})) {
14213: $reservable_info = $remembered{$key};
14214: } else {
14215: my %resv;
14216: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
14217: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
14218: $reservable_info = \%resv;
14219: $remembered{$key} = $reservable_info;
14220: }
14221: return $reservable_info;
14222: }
14223:
14224: sub get_course_slots {
14225: my ($cnum,$cdom) = @_;
14226: my $hashid=$cnum.':'.$cdom;
1.1494 raeburn 14227: my ($result,$cached) = &is_cached_new('allslots',$hashid);
1.1150 raeburn 14228: if (defined($cached)) {
14229: if (ref($result) eq 'HASH') {
14230: return %{$result};
14231: }
14232: } else {
1.1494 raeburn 14233: my %slots=&dump('slots',$cdom,$cnum);
1.1150 raeburn 14234: my ($tmp) = keys(%slots);
14235: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1219 raeburn 14236: &do_cache_new('allslots',$hashid,\%slots,600);
1.1150 raeburn 14237: return %slots;
14238: }
14239: }
14240: return;
14241: }
14242:
14243: sub devalidate_slots_cache {
14244: my ($cnum,$cdom)=@_;
14245: my $hashid=$cnum.':'.$cdom;
14246: &devalidate_cache_new('allslots',$hashid);
14247: }
14248:
1.1181 raeburn 14249: sub get_coursechange {
14250: my ($cdom,$cnum) = @_;
14251: if ($cdom eq '' || $cnum eq '') {
14252: return unless ($env{'request.course.id'});
14253: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
14254: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
14255: }
14256: my $hashid=$cdom.'_'.$cnum;
14257: my ($change,$cached)=&is_cached_new('crschange',$hashid);
14258: if ((defined($cached)) && ($change ne '')) {
14259: return $change;
14260: } else {
14261: my %crshash;
14262: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
14263: if ($crshash{'internal.contentchange'} eq '') {
14264: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
14265: if ($change eq '') {
14266: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
14267: $change = $crshash{'internal.created'};
14268: }
14269: } else {
14270: $change = $crshash{'internal.contentchange'};
14271: }
14272: my $cachetime = 600;
14273: &do_cache_new('crschange',$hashid,$change,$cachetime);
14274: }
14275: return $change;
14276: }
14277:
14278: sub devalidate_coursechange_cache {
1.1496 raeburn 14279: my ($cdom,$cnum)=@_;
14280: my $hashid=$cdom.'_'.$cnum;
1.1181 raeburn 14281: &devalidate_cache_new('crschange',$hashid);
14282: }
14283:
1.1496 raeburn 14284: sub get_suppchange {
14285: my ($cdom,$cnum) = @_;
14286: if ($cdom eq '' || $cnum eq '') {
14287: return unless ($env{'request.course.id'});
14288: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
14289: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
14290: }
14291: my $hashid=$cdom.'_'.$cnum;
14292: my ($change,$cached)=&is_cached_new('suppchange',$hashid);
14293: if ((defined($cached)) && ($change ne '')) {
14294: return $change;
14295: } else {
14296: my %crshash = &get('environment',['internal.supplementalchange'],$cdom,$cnum);
14297: if ($crshash{'internal.supplementalchange'} eq '') {
14298: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
14299: if ($change eq '') {
14300: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
14301: $change = $crshash{'internal.created'};
14302: }
14303: } else {
14304: $change = $crshash{'internal.supplementalchange'};
14305: }
14306: my $cachetime = 600;
14307: &do_cache_new('suppchange',$hashid,$change,$cachetime);
14308: }
14309: return $change;
14310: }
14311:
14312: sub devalidate_suppchange_cache {
14313: my ($cdom,$cnum)=@_;
14314: my $hashid=$cdom.'_'.$cnum;
14315: &devalidate_cache_new('suppchange',$hashid);
14316: }
14317:
1.1497 raeburn 14318: sub update_supp_caches {
14319: my ($cdom,$cnum) = @_;
14320: my %servers = &internet_dom_servers($cdom);
14321: my @ids=¤t_machine_ids();
14322: foreach my $server (keys(%servers)) {
14323: next if (grep(/^\Q$server\E$/,@ids));
14324: my $hashid=$cnum.':'.$cdom;
14325: my $cachekey = &escape('showsupp').':'.&escape($hashid);
14326: &remote_devalidate_cache($server,[$cachekey]);
14327: }
14328: &has_unhidden_suppfiles($cnum,$cdom,1,1);
14329: &count_supptools($cnum,$cdom,1);
14330: my $now = time;
14331: if ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
14332: &Apache::lonnet::appenv({'request.course.suppupdated' => $now});
14333: }
14334: &put('environment',{'internal.supplementalchange' => $now},
14335: $cdom,$cnum);
14336: &Apache::lonnet::appenv(
14337: {'course.'.$cdom.'_'.$cnum.'.internal.supplementalchange' => $now});
14338: &do_cache_new('suppchange',$cdom.'_'.$cnum,$now,600);
14339: }
14340:
1.31 www 14341: # ------------------------------------------------- Update symbolic store links
14342:
14343: sub symblist {
14344: my ($mapname,%newhash)=@_;
1.438 www 14345: $mapname=&deversion(&declutter($mapname));
1.31 www 14346: my %hash;
1.620 albertel 14347: if (($env{'request.course.fn'}) && (%newhash)) {
14348: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 14349: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 14350: foreach my $url (keys(%newhash)) {
1.711 albertel 14351: next if ($url eq 'last_known'
14352: && $env{'form.no_update_last_known'});
14353: $hash{declutter($url)}=&encode_symb($mapname,
14354: $newhash{$url}->[1],
14355: $newhash{$url}->[0]);
1.191 harris41 14356: }
1.31 www 14357: if (untie(%hash)) {
14358: return 'ok';
14359: }
14360: }
14361: }
14362: return 'error';
1.212 www 14363: }
14364:
14365: # --------------------------------------------------------------- Verify a symb
14366:
14367: sub symbverify {
1.1190 raeburn 14368: my ($symb,$thisurl,$encstate)=@_;
1.510 www 14369: my $thisfn=$thisurl;
1.439 www 14370: $thisfn=&declutter($thisfn);
1.215 www 14371: # direct jump to resource in page or to a sequence - will construct own symbs
14372: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
14373: # check URL part
1.409 www 14374: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 14375:
1.431 www 14376: unless ($url eq $thisfn) { return 0; }
1.213 www 14377:
1.216 www 14378: $symb=&symbclean($symb);
1.510 www 14379: $thisurl=&deversion($thisurl);
1.439 www 14380: $thisfn=&deversion($thisfn);
1.213 www 14381:
14382: my %bighash;
14383: my $okay=0;
1.431 www 14384:
1.620 albertel 14385: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 14386: &GDBM_READER(),0640)) {
1.1032 raeburn 14387: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
14388: $thisurl =~ s/\?.+$//;
1.1204 raeburn 14389: if ($map =~ m{^uploaded/.+\.page$}) {
14390: $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
14391: $thisurl =~ s{^\Qhttp://https://\E}{https://};
14392: }
14393: }
14394: my $ids;
1.1419 raeburn 14395: if ($map =~ m{^uploaded/.+\.page$}) {
14396: $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
1.1204 raeburn 14397: } else {
14398: $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032 raeburn 14399: }
1.1102 raeburn 14400: unless ($ids) {
14401: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
14402: $ids=$bighash{$idkey};
1.216 www 14403: }
14404: if ($ids) {
14405: # ------------------------------------------------------------------- Has ID(s)
1.1202 raeburn 14406: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
1.1203 raeburn 14407: $symb =~ s/\?.+$//;
1.1202 raeburn 14408: }
1.800 albertel 14409: foreach my $id (split(/\,/,$ids)) {
14410: my ($mapid,$resid)=split(/\./,$id);
1.216 www 14411: if (
14412: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190 raeburn 14413: eq $symb) {
14414: if (ref($encstate)) {
14415: $$encstate = $bighash{'encrypted_'.$id};
14416: }
1.620 albertel 14417: if (($env{'request.role.adv'}) ||
1.1101 raeburn 14418: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
14419: ($thisurl eq '/adm/navmaps')) {
1.1190 raeburn 14420: $okay=1;
1.1202 raeburn 14421: last;
1.582 albertel 14422: }
14423: }
1.216 www 14424: }
14425: }
1.213 www 14426: untie(%bighash);
14427: }
14428: return $okay;
1.31 www 14429: }
14430:
1.210 www 14431: # --------------------------------------------------------------- Clean-up symb
14432:
14433: sub symbclean {
14434: my $symb=shift;
1.568 albertel 14435: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 14436: # remove version from map
14437: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 14438:
1.210 www 14439: # remove version from URL
14440: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 14441:
1.507 www 14442: # remove wrapper
14443:
1.510 www 14444: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 14445: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 14446: return $symb;
1.409 www 14447: }
14448:
14449: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 14450:
14451: sub encode_symb {
14452: my ($map,$resid,$url)=@_;
14453: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
14454: }
1.409 www 14455:
14456: sub decode_symb {
1.568 albertel 14457: my $symb=shift;
14458: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
14459: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 14460: return (&fixversion($map),$resid,&fixversion($url));
14461: }
14462:
14463: sub fixversion {
14464: my $fn=shift;
1.609 banghart 14465: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 14466: my %bighash;
14467: my $uri=&clutter($fn);
1.620 albertel 14468: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 14469: # is this cached?
1.599 albertel 14470: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 14471: if (defined($cached)) { return $result; }
14472: # unfortunately not cached, or expired
1.620 albertel 14473: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 14474: &GDBM_READER(),0640)) {
14475: if ($bighash{'version_'.$uri}) {
14476: my $version=$bighash{'version_'.$uri};
1.444 www 14477: unless (($version eq 'mostrecent') ||
14478: ($version==&getversion($uri))) {
1.440 www 14479: $uri=~s/\.(\w+)$/\.$version\.$1/;
14480: }
14481: }
14482: untie %bighash;
1.413 www 14483: }
1.599 albertel 14484: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 14485: }
14486:
14487: sub deversion {
14488: my $url=shift;
14489: $url=~s/\.\d+\.(\w+)$/\.$1/;
14490: return $url;
1.210 www 14491: }
14492:
1.31 www 14493: # ------------------------------------------------------ Return symb list entry
14494:
14495: sub symbread {
1.1424 raeburn 14496: my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles,
1.1427 raeburn 14497: $ignoresymbdb,$noenccheck)=@_;
1.1265 raeburn 14498: my $cache_str='request.symbread.cached.'.$thisfn;
1.1427 raeburn 14499: if (defined($env{$cache_str})) {
1.1424 raeburn 14500: unless (ref($possibles) eq 'HASH') {
14501: if ($ignorecachednull) {
14502: return $env{$cache_str} unless ($env{$cache_str} eq '');
14503: } else {
14504: return $env{$cache_str};
14505: }
1.1282 raeburn 14506: }
14507: }
1.242 www 14508: # no filename provided? try from environment
1.1265 raeburn 14509: unless ($thisfn) {
1.620 albertel 14510: if ($env{'request.symb'}) {
1.1427 raeburn 14511: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 14512: }
1.620 albertel 14513: $thisfn=$env{'request.filename'};
1.44 www 14514: }
1.569 albertel 14515: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 14516: # is that filename actually a symb? Verify, clean, and return
14517: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 14518: if (&symbverify($thisfn,$1)) {
1.1427 raeburn 14519: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 14520: }
1.242 www 14521: }
1.44 www 14522: $thisfn=declutter($thisfn);
1.31 www 14523: my %hash;
1.37 www 14524: my %bighash;
14525: my $syval='';
1.620 albertel 14526: if (($env{'request.course.fn'}) && ($thisfn)) {
1.1427 raeburn 14527: unless ($ignoresymbdb) {
1.1424 raeburn 14528: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
14529: &GDBM_READER(),0640)) {
1.1487 raeburn 14530: $syval=$hash{$thisfn};
1.1424 raeburn 14531: untie(%hash);
14532: }
1.1427 raeburn 14533: if ($syval && $checkforblock) {
14534: my @blockers = &has_comm_blocking('bre',$syval,$thisfn,$ignoresymbdb,$noenccheck);
1.1424 raeburn 14535: if (@blockers) {
14536: $syval='';
14537: }
14538: }
1.37 www 14539: }
14540: # ---------------------------------------------------------- There was an entry
14541: if ($syval) {
1.601 albertel 14542: #unless ($syval=~/\_\d+$/) {
1.620 albertel 14543: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 14544: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 14545: #return $env{$cache_str}='';
1.601 albertel 14546: #}
14547: #$syval.=$1;
14548: #}
1.37 www 14549: } else {
14550: # ------------------------------------------------------- Was not in symb table
1.620 albertel 14551: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 14552: &GDBM_READER(),0640)) {
1.37 www 14553: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 14554: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 14555: unless ($ids) {
14556: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 14557: }
14558: unless ($ids) {
14559: # alias?
14560: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 14561: }
1.37 www 14562: if ($ids) {
14563: # ------------------------------------------------------------------- Has ID(s)
14564: my @possibilities=split(/\,/,$ids);
1.39 www 14565: if ($#possibilities==0) {
14566: # ----------------------------------------------- There is only one possibility
1.37 www 14567: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 14568: $syval=&encode_symb($bighash{'map_id_'.$mapid},
14569: $resid,$thisfn);
1.1282 raeburn 14570: if (ref($possibles) eq 'HASH') {
1.1424 raeburn 14571: unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
14572: $possibles->{$syval} = 1;
14573: }
1.1282 raeburn 14574: }
14575: if ($checkforblock) {
1.1424 raeburn 14576: unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
1.1426 raeburn 14577: my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids},'',$noenccheck);
1.1424 raeburn 14578: if (@blockers) {
14579: $syval = '';
1.1425 raeburn 14580: untie(%bighash);
14581: return $env{$cache_str}='';
1.1424 raeburn 14582: }
1.1282 raeburn 14583: }
14584: }
14585: } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39 www 14586: # ------------------------------------------ There is more than one possibility
14587: my $realpossible=0;
1.800 albertel 14588: foreach my $id (@possibilities) {
14589: my $file=$bighash{'src_'.$id};
1.1282 raeburn 14590: my $canaccess;
14591: if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
14592: $canaccess = 1;
14593: } else {
14594: $canaccess = &allowed('bre',$file);
14595: }
14596: if ($canaccess) {
14597: my ($mapid,$resid)=split(/\./,$id);
14598: if ($bighash{'map_type_'.$mapid} ne 'page') {
14599: my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
14600: $resid,$thisfn);
1.1424 raeburn 14601: next if ($bighash{'randomout_'.$id} && !$env{'request.role.adv'});
1.1426 raeburn 14602: next unless (($noenccheck) || ($bighash{'encrypted_'.$id} eq $env{'request.enc'}));
1.1282 raeburn 14603: if ($checkforblock) {
1.1426 raeburn 14604: my @blockers = &has_comm_blocking('bre',$poss_syval,$file,'',$noenccheck);
1.1424 raeburn 14605: if (@blockers > 0) {
14606: $syval = '';
14607: } else {
1.1282 raeburn 14608: $syval = $poss_syval;
14609: $realpossible++;
14610: }
14611: } else {
14612: $syval = $poss_syval;
14613: $realpossible++;
14614: }
1.1424 raeburn 14615: if ($syval) {
14616: if (ref($possibles) eq 'HASH') {
14617: $possibles->{$syval} = 1;
14618: }
14619: }
1.1282 raeburn 14620: }
1.39 www 14621: }
1.191 harris41 14622: }
1.39 www 14623: if ($realpossible!=1) { $syval=''; }
1.249 www 14624: } else {
14625: $syval='';
1.37 www 14626: }
14627: }
1.1282 raeburn 14628: untie(%bighash);
1.481 raeburn 14629: }
1.31 www 14630: }
1.62 www 14631: if ($syval) {
1.1427 raeburn 14632: return $env{$cache_str}=$syval;
1.62 www 14633: }
1.31 www 14634: }
1.949 raeburn 14635: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 14636: return $env{$cache_str}='';
1.31 www 14637: }
14638:
14639: # ---------------------------------------------------------- Return random seed
14640:
1.32 www 14641: sub numval {
14642: my $txt=shift;
14643: $txt=~tr/A-J/0-9/;
14644: $txt=~tr/a-j/0-9/;
14645: $txt=~tr/K-T/0-9/;
14646: $txt=~tr/k-t/0-9/;
14647: $txt=~tr/U-Z/0-5/;
14648: $txt=~tr/u-z/0-5/;
14649: $txt=~s/\D//g;
1.564 albertel 14650: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 14651: return int($txt);
1.368 albertel 14652: }
14653:
1.484 albertel 14654: sub numval2 {
14655: my $txt=shift;
14656: $txt=~tr/A-J/0-9/;
14657: $txt=~tr/a-j/0-9/;
14658: $txt=~tr/K-T/0-9/;
14659: $txt=~tr/k-t/0-9/;
14660: $txt=~tr/U-Z/0-5/;
14661: $txt=~tr/u-z/0-5/;
14662: $txt=~s/\D//g;
14663: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
14664: my $total;
14665: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 14666: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 14667: return int($total);
14668: }
14669:
1.575 albertel 14670: sub numval3 {
14671: use integer;
14672: my $txt=shift;
14673: $txt=~tr/A-J/0-9/;
14674: $txt=~tr/a-j/0-9/;
14675: $txt=~tr/K-T/0-9/;
14676: $txt=~tr/k-t/0-9/;
14677: $txt=~tr/U-Z/0-5/;
14678: $txt=~tr/u-z/0-5/;
14679: $txt=~s/\D//g;
14680: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
14681: my $total;
14682: foreach my $val (@txts) { $total+=$val; }
14683: if ($_64bit) { $total=(($total<<32)>>32); }
14684: return $total;
14685: }
14686:
1.675 albertel 14687: sub digest {
14688: my ($data)=@_;
14689: my $digest=&Digest::MD5::md5($data);
14690: my ($a,$b,$c,$d)=unpack("iiii",$digest);
14691: my ($e,$f);
14692: {
14693: use integer;
14694: $e=($a+$b);
14695: $f=($c+$d);
14696: if ($_64bit) {
14697: $e=(($e<<32)>>32);
14698: $f=(($f<<32)>>32);
14699: }
14700: }
14701: if (wantarray) {
14702: return ($e,$f);
14703: } else {
14704: my $g;
14705: {
14706: use integer;
14707: $g=($e+$f);
14708: if ($_64bit) {
14709: $g=(($g<<32)>>32);
14710: }
14711: }
14712: return $g;
14713: }
14714: }
14715:
1.368 albertel 14716: sub latest_rnd_algorithm_id {
1.675 albertel 14717: return '64bit5';
1.366 albertel 14718: }
1.32 www 14719:
1.503 albertel 14720: sub get_rand_alg {
14721: my ($courseid)=@_;
1.790 albertel 14722: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 14723: if ($courseid) {
1.620 albertel 14724: return $env{"course.$courseid.rndseed"};
1.503 albertel 14725: }
14726: return &latest_rnd_algorithm_id();
14727: }
14728:
1.562 albertel 14729: sub validCODE {
14730: my ($CODE)=@_;
14731: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
14732: return 0;
14733: }
14734:
1.491 albertel 14735: sub getCODE {
1.620 albertel 14736: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 14737: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
14738: defined($Apache::lonhomework::parsing_a_task) ) &&
14739: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 14740: return $Apache::lonhomework::history{'resource.CODE'};
14741: }
14742: return undef;
14743: }
1.1133 foxr 14744: #
14745: # Determines the random seed for a specific context:
14746: #
14747: # parameters:
14748: # symb - in course context the symb for the seed.
14749: # course_id - The course id of the form domain_coursenum.
14750: # domain - Domain for the user.
14751: # course - Course for the user.
14752: # cenv - environment of the course.
14753: #
14754: # NOTE:
14755: # All parameters are picked out of the environment if missing
14756: # or not defined.
14757: # If a symb cannot be determined the current time is used instead.
14758: #
14759: # For a given well defined symb, courside, domain, username,
14760: # and course environment, the seed is reproducible.
14761: #
1.31 www 14762: sub rndseed {
1.1133 foxr 14763: my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790 albertel 14764: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 14765: if (!defined($symb)) {
1.366 albertel 14766: unless ($symb=$wsymb) { return time; }
14767: }
1.1146 foxr 14768: if (!defined $courseid) {
14769: $courseid=$wcourseid;
14770: }
14771: if (!defined $domain) { $domain=$wdomain; }
14772: if (!defined $username) { $username=$wusername }
1.1133 foxr 14773:
14774: my $which;
14775: if (defined($cenv->{'rndseed'})) {
14776: $which = $cenv->{'rndseed'};
14777: } else {
14778: $which =&get_rand_alg($courseid);
14779: }
1.491 albertel 14780: if (defined(&getCODE())) {
1.1133 foxr 14781:
1.675 albertel 14782: if ($which eq '64bit5') {
14783: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
14784: } elsif ($which eq '64bit4') {
1.575 albertel 14785: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
14786: } else {
14787: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
14788: }
1.675 albertel 14789: } elsif ($which eq '64bit5') {
14790: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 14791: } elsif ($which eq '64bit4') {
14792: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 14793: } elsif ($which eq '64bit3') {
14794: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 14795: } elsif ($which eq '64bit2') {
14796: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 14797: } elsif ($which eq '64bit') {
14798: return &rndseed_64bit($symb,$courseid,$domain,$username);
14799: }
14800: return &rndseed_32bit($symb,$courseid,$domain,$username);
14801: }
14802:
14803: sub rndseed_32bit {
14804: my ($symb,$courseid,$domain,$username)=@_;
14805: {
14806: use integer;
14807: my $symbchck=unpack("%32C*",$symb) << 27;
14808: my $symbseed=numval($symb) << 22;
14809: my $namechck=unpack("%32C*",$username) << 17;
14810: my $nameseed=numval($username) << 12;
14811: my $domainseed=unpack("%32C*",$domain) << 7;
14812: my $courseseed=unpack("%32C*",$courseid);
14813: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 14814: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14815: #&logthis("rndseed :$num:$symb");
1.564 albertel 14816: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 14817: return $num;
14818: }
14819: }
14820:
14821: sub rndseed_64bit {
14822: my ($symb,$courseid,$domain,$username)=@_;
14823: {
14824: use integer;
14825: my $symbchck=unpack("%32S*",$symb) << 21;
14826: my $symbseed=numval($symb) << 10;
14827: my $namechck=unpack("%32S*",$username);
14828:
14829: my $nameseed=numval($username) << 21;
14830: my $domainseed=unpack("%32S*",$domain) << 10;
14831: my $courseseed=unpack("%32S*",$courseid);
14832:
14833: my $num1=$symbchck+$symbseed+$namechck;
14834: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 14835: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14836: #&logthis("rndseed :$num:$symb");
1.564 albertel 14837: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 14838: return "$num1,$num2";
1.155 albertel 14839: }
1.366 albertel 14840: }
14841:
1.443 albertel 14842: sub rndseed_64bit2 {
14843: my ($symb,$courseid,$domain,$username)=@_;
14844: {
14845: use integer;
14846: # strings need to be an even # of cahracters long, it it is odd the
14847: # last characters gets thrown away
14848: my $symbchck=unpack("%32S*",$symb.' ') << 21;
14849: my $symbseed=numval($symb) << 10;
14850: my $namechck=unpack("%32S*",$username.' ');
14851:
14852: my $nameseed=numval($username) << 21;
1.501 albertel 14853: my $domainseed=unpack("%32S*",$domain.' ') << 10;
14854: my $courseseed=unpack("%32S*",$courseid.' ');
14855:
14856: my $num1=$symbchck+$symbseed+$namechck;
14857: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 14858: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14859: #&logthis("rndseed :$num:$symb");
1.803 albertel 14860: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 14861: return "$num1,$num2";
14862: }
14863: }
14864:
14865: sub rndseed_64bit3 {
14866: my ($symb,$courseid,$domain,$username)=@_;
14867: {
14868: use integer;
14869: # strings need to be an even # of cahracters long, it it is odd the
14870: # last characters gets thrown away
14871: my $symbchck=unpack("%32S*",$symb.' ') << 21;
14872: my $symbseed=numval2($symb) << 10;
14873: my $namechck=unpack("%32S*",$username.' ');
14874:
14875: my $nameseed=numval2($username) << 21;
1.443 albertel 14876: my $domainseed=unpack("%32S*",$domain.' ') << 10;
14877: my $courseseed=unpack("%32S*",$courseid.' ');
14878:
14879: my $num1=$symbchck+$symbseed+$namechck;
14880: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 14881: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14882: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 14883: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 14884:
1.503 albertel 14885: return "$num1:$num2";
1.443 albertel 14886: }
14887: }
14888:
1.575 albertel 14889: sub rndseed_64bit4 {
14890: my ($symb,$courseid,$domain,$username)=@_;
14891: {
14892: use integer;
14893: # strings need to be an even # of cahracters long, it it is odd the
14894: # last characters gets thrown away
14895: my $symbchck=unpack("%32S*",$symb.' ') << 21;
14896: my $symbseed=numval3($symb) << 10;
14897: my $namechck=unpack("%32S*",$username.' ');
14898:
14899: my $nameseed=numval3($username) << 21;
14900: my $domainseed=unpack("%32S*",$domain.' ') << 10;
14901: my $courseseed=unpack("%32S*",$courseid.' ');
14902:
14903: my $num1=$symbchck+$symbseed+$namechck;
14904: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 14905: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14906: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 14907: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 14908:
1.575 albertel 14909: return "$num1:$num2";
14910: }
14911: }
14912:
1.675 albertel 14913: sub rndseed_64bit5 {
14914: my ($symb,$courseid,$domain,$username)=@_;
14915: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
14916: return "$num1:$num2";
14917: }
14918:
1.366 albertel 14919: sub rndseed_CODE_64bit {
14920: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 14921: {
1.366 albertel 14922: use integer;
1.443 albertel 14923: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 14924: my $symbseed=numval2($symb);
1.491 albertel 14925: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
14926: my $CODEseed=numval(&getCODE());
1.443 albertel 14927: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 14928: my $num1=$symbseed+$CODEchck;
14929: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 14930: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
14931: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 14932: if ($_64bit) { $num1=(($num1<<32)>>32); }
14933: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 14934: return "$num1:$num2";
1.366 albertel 14935: }
14936: }
14937:
1.575 albertel 14938: sub rndseed_CODE_64bit4 {
14939: my ($symb,$courseid,$domain,$username)=@_;
14940: {
14941: use integer;
14942: my $symbchck=unpack("%32S*",$symb.' ') << 16;
14943: my $symbseed=numval3($symb);
14944: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
14945: my $CODEseed=numval3(&getCODE());
14946: my $courseseed=unpack("%32S*",$courseid.' ');
14947: my $num1=$symbseed+$CODEchck;
14948: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 14949: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
14950: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 14951: if ($_64bit) { $num1=(($num1<<32)>>32); }
14952: if ($_64bit) { $num2=(($num2<<32)>>32); }
14953: return "$num1:$num2";
14954: }
14955: }
14956:
1.675 albertel 14957: sub rndseed_CODE_64bit5 {
14958: my ($symb,$courseid,$domain,$username)=@_;
14959: my $code = &getCODE();
14960: my ($num1,$num2)=&digest("$symb,$courseid,$code");
14961: return "$num1:$num2";
14962: }
14963:
1.366 albertel 14964: sub setup_random_from_rndseed {
14965: my ($rndseed)=@_;
1.503 albertel 14966: if ($rndseed =~/([,:])/) {
1.1262 raeburn 14967: my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
14968: if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
14969: &Math::Random::random_set_seed_from_phrase($rndseed);
14970: } else {
14971: &Math::Random::random_set_seed($num1,$num2);
14972: }
1.366 albertel 14973: } else {
14974: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 14975: }
1.36 albertel 14976: }
14977:
1.474 albertel 14978: sub latest_receipt_algorithm_id {
1.835 albertel 14979: return 'receipt3';
1.474 albertel 14980: }
14981:
1.480 www 14982: sub recunique {
14983: my $fucourseid=shift;
14984: my $unique;
1.835 albertel 14985: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
14986: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 14987: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 14988: } else {
14989: $unique=$perlvar{'lonReceipt'};
14990: }
14991: return unpack("%32C*",$unique);
14992: }
14993:
14994: sub recprefix {
14995: my $fucourseid=shift;
14996: my $prefix;
1.835 albertel 14997: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
14998: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 14999: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 15000: } else {
15001: $prefix=$perlvar{'lonHostID'};
15002: }
15003: return unpack("%32C*",$prefix);
15004: }
15005:
1.76 www 15006: sub ireceipt {
1.474 albertel 15007: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 15008:
15009: my $return =&recprefix($fucourseid).'-';
15010:
15011: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
15012: $env{'request.state'} eq 'construct') {
15013: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
15014: return $return;
15015: }
15016:
1.76 www 15017: my $cuname=unpack("%32C*",$funame);
15018: my $cudom=unpack("%32C*",$fudom);
15019: my $cucourseid=unpack("%32C*",$fucourseid);
15020: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 15021: my $cunique=&recunique($fucourseid);
1.474 albertel 15022: my $cpart=unpack("%32S*",$part);
1.835 albertel 15023: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
15024:
1.790 albertel 15025: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 15026:
15027: $return.= ($cunique%$cuname+
15028: $cunique%$cudom+
15029: $cusymb%$cuname+
15030: $cusymb%$cudom+
15031: $cucourseid%$cuname+
15032: $cucourseid%$cudom+
15033: $cpart%$cuname+
15034: $cpart%$cudom);
15035: } else {
15036: $return.= ($cunique%$cuname+
15037: $cunique%$cudom+
15038: $cusymb%$cuname+
15039: $cusymb%$cudom+
15040: $cucourseid%$cuname+
15041: $cucourseid%$cudom);
15042: }
15043: return $return;
1.76 www 15044: }
15045:
15046: sub receipt {
1.474 albertel 15047: my ($part)=@_;
1.790 albertel 15048: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 15049: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 15050: }
1.260 ng 15051:
1.790 albertel 15052: sub whichuser {
15053: my ($passedsymb)=@_;
15054: my ($symb,$courseid,$domain,$name,$publicuser);
15055: if (defined($env{'form.grade_symb'})) {
15056: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
15057: my $allowed=&allowed('vgr',$tmp_courseid);
15058: if (!$allowed &&
15059: exists($env{'request.course.sec'}) &&
15060: $env{'request.course.sec'} !~ /^\s*$/) {
15061: $allowed=&allowed('vgr',$tmp_courseid.
15062: '/'.$env{'request.course.sec'});
15063: }
15064: if ($allowed) {
15065: ($symb)=&get_env_multiple('form.grade_symb');
15066: $courseid=$tmp_courseid;
15067: ($domain)=&get_env_multiple('form.grade_domain');
15068: ($name)=&get_env_multiple('form.grade_username');
15069: return ($symb,$courseid,$domain,$name,$publicuser);
15070: }
15071: }
15072: if (!$passedsymb) {
15073: $symb=&symbread();
15074: } else {
15075: $symb=$passedsymb;
15076: }
15077: $courseid=$env{'request.course.id'};
15078: $domain=$env{'user.domain'};
15079: $name=$env{'user.name'};
15080: if ($name eq 'public' && $domain eq 'public') {
15081: if (!defined($env{'form.username'})) {
15082: $env{'form.username'}.=time.rand(10000000);
15083: }
15084: $name.=$env{'form.username'};
15085: }
15086: return ($symb,$courseid,$domain,$name,$publicuser);
15087:
15088: }
15089:
1.36 albertel 15090: # ------------------------------------------------------------ Serves up a file
1.472 albertel 15091: # returns either the contents of the file or
15092: # -1 if the file doesn't exist
1.481 raeburn 15093: #
15094: # if the target is a file that was uploaded via DOCS,
15095: # a check will be made to see if a current copy exists on the local server,
15096: # if it does this will be served, otherwise a copy will be retrieved from
15097: # the home server for the course and stored in /home/httpd/html/userfiles on
15098: # the local server.
1.472 albertel 15099:
1.36 albertel 15100: sub getfile {
1.538 albertel 15101: my ($file) = @_;
1.609 banghart 15102: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 15103: &repcopy($file);
15104: return &readfile($file);
15105: }
15106:
15107: sub repcopy_userfile {
15108: my ($file)=@_;
1.1142 raeburn 15109: my $londocroot = $perlvar{'lonDocRoot'};
15110: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164 raeburn 15111: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538 albertel 15112: my ($cdom,$cnum,$filename) =
1.811 albertel 15113: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 15114: my $uri="/uploaded/$cdom/$cnum/$filename";
15115: if (-e "$file") {
1.828 www 15116: # we already have a local copy, check it out
1.538 albertel 15117: my @fileinfo = stat($file);
1.828 www 15118: my $rtncode;
15119: my $info;
1.538 albertel 15120: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 15121: if ($lwpresp ne 'ok') {
1.828 www 15122: # there is no such file anymore, even though we had a local copy
1.482 albertel 15123: if ($rtncode eq '404') {
1.538 albertel 15124: unlink($file);
1.482 albertel 15125: }
15126: return -1;
15127: }
15128: if ($info < $fileinfo[9]) {
1.828 www 15129: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 15130: return 'ok';
1.828 www 15131: } else {
15132: # the file is outdated, get rid of it
15133: unlink($file);
1.482 albertel 15134: }
1.828 www 15135: }
15136: # one way or the other, at this point, we don't have the file
15137: # construct the correct path for the file
15138: my @parts = ($cdom,$cnum);
15139: if ($filename =~ m|^(.+)/[^/]+$|) {
15140: push @parts, split(/\//,$1);
15141: }
15142: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
15143: foreach my $part (@parts) {
15144: $path .= '/'.$part;
15145: if (!-e $path) {
15146: mkdir($path,0770);
1.482 albertel 15147: }
15148: }
1.828 www 15149: # now the path exists for sure
15150: # get a user agent
15151: my $transferfile=$file.'.in.transfer';
15152: # FIXME: this should flock
15153: if (-e $transferfile) { return 'ok'; }
15154: my $request;
15155: $uri=~s/^\///;
1.980 raeburn 15156: my $homeserver = &homeserver($cnum,$cdom);
1.1398 raeburn 15157: my $hostname = &hostname($homeserver);
1.980 raeburn 15158: my $protocol = $protocol{$homeserver};
15159: $protocol = 'http' if ($protocol ne 'https');
1.1397 raeburn 15160: $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
1.1345 raeburn 15161: my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,$transferfile,\%perlvar,'',0,1);
1.828 www 15162: # did it work?
15163: if ($response->is_error()) {
15164: unlink($transferfile);
15165: &logthis("Userfile repcopy failed for $uri");
15166: return -1;
15167: }
15168: # worked, rename the transfer file
15169: rename($transferfile,$file);
1.607 raeburn 15170: return 'ok';
1.481 raeburn 15171: }
15172:
1.517 albertel 15173: sub tokenwrapper {
15174: my $uri=shift;
1.980 raeburn 15175: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 15176: $uri=~s|^/||;
1.620 albertel 15177: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 15178: my $token=$1;
1.552 albertel 15179: my (undef,$udom,$uname,$file)=split('/',$uri,4);
15180: if ($udom && $uname && $file) {
15181: $file=~s|(\?\.*)*$||;
1.949 raeburn 15182: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 15183: my $homeserver = &homeserver($uname,$udom);
1.1397 raeburn 15184: my $hostname = &hostname($homeserver);
1.980 raeburn 15185: my $protocol = $protocol{$homeserver};
15186: $protocol = 'http' if ($protocol ne 'https');
1.1397 raeburn 15187: return $protocol.'://'.$hostname.'/'.$uri.
1.517 albertel 15188: (($uri=~/\?/)?'&':'?').'token='.$token.
15189: '&tokenissued='.$perlvar{'lonHostID'};
15190: } else {
15191: return '/adm/notfound.html';
15192: }
15193: }
15194:
1.828 www 15195: # call with reqtype HEAD: get last modification time
15196: # call with reqtype GET: get the file contents
15197: # Do not call this with reqtype GET for large files! It loads everything into memory
15198: #
1.481 raeburn 15199: sub getuploaded {
15200: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
15201: $uri=~s/^\///;
1.980 raeburn 15202: my $homeserver = &homeserver($cnum,$cdom);
1.1397 raeburn 15203: my $hostname = &hostname($homeserver);
1.980 raeburn 15204: my $protocol = $protocol{$homeserver};
15205: $protocol = 'http' if ($protocol ne 'https');
1.1397 raeburn 15206: $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
1.481 raeburn 15207: my $request=new HTTP::Request($reqtype,$uri);
1.1345 raeburn 15208: my $response=&LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,'',0,1);
1.481 raeburn 15209: $$rtncode = $response->code;
1.482 albertel 15210: if (! $response->is_success()) {
15211: return 'failed';
15212: }
15213: if ($reqtype eq 'HEAD') {
1.486 www 15214: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 15215: } elsif ($reqtype eq 'GET') {
15216: $$info = $response->content;
1.472 albertel 15217: }
1.482 albertel 15218: return 'ok';
1.36 albertel 15219: }
15220:
1.481 raeburn 15221: sub readfile {
15222: my $file = shift;
15223: if ( (! -e $file ) || ($file eq '') ) { return -1; };
15224: my $fh;
1.1359 raeburn 15225: open($fh,"<",$file);
1.481 raeburn 15226: my $a='';
1.800 albertel 15227: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 15228: return $a;
15229: }
15230:
1.36 albertel 15231: sub filelocation {
1.590 banghart 15232: my ($dir,$file) = @_;
15233: my $location;
15234: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 15235:
15236: if ($file =~ m-^/adm/-) {
15237: $file=~s-^/adm/wrapper/-/-;
15238: $file=~s-^/adm/coursedocs/showdoc/-/-;
15239: }
1.882 albertel 15240:
1.1139 www 15241: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956 raeburn 15242: $location = $file;
1.609 banghart 15243: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 15244: my ($udom,$uname,$filename)=
1.811 albertel 15245: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 15246: my $home=&homeserver($uname,$udom);
15247: my $is_me=0;
15248: my @ids=¤t_machine_ids();
15249: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
15250: if ($is_me) {
1.1117 foxr 15251: $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 15252: } else {
15253: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
15254: $udom.'/'.$uname.'/'.$filename;
15255: }
1.882 albertel 15256: } elsif ($file =~ m-^/adm/-) {
15257: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 15258: } else {
15259: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139 www 15260: $file=~s:^/(res|priv)/:/:;
15261: my $space=$1;
1.590 banghart 15262: if ( !( $file =~ m:^/:) ) {
15263: $location = $dir. '/'.$file;
15264: } else {
1.1142 raeburn 15265: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590 banghart 15266: }
1.59 albertel 15267: }
1.590 banghart 15268: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 15269: while ($location=~m{/\.\./}) {
15270: if ($location =~ m{/[^/]+/\.\./}) {
15271: $location=~ s{/[^/]+/\.\./}{/}g;
15272: } else {
15273: $location=~ s{/\.\./}{/}g;
15274: }
15275: } #remove dir/..
1.590 banghart 15276: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
15277: return $location;
1.46 www 15278: }
1.36 albertel 15279:
1.46 www 15280: sub hreflocation {
15281: my ($dir,$file)=@_;
1.980 raeburn 15282: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 15283: $file=filelocation($dir,$file);
1.700 albertel 15284: } elsif ($file=~m-^/adm/-) {
15285: $file=~s-^/adm/wrapper/-/-;
15286: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 15287: }
15288: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
15289: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
15290: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143 raeburn 15291: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
15292: {/uploaded/$1/$2/}x;
1.46 www 15293: }
1.913 albertel 15294: if ($file=~ m{^/userfiles/}) {
15295: $file =~ s{^/userfiles/}{/uploaded/};
15296: }
1.462 albertel 15297: return $file;
1.465 albertel 15298: }
15299:
1.1139 www 15300:
15301:
15302:
15303:
1.465 albertel 15304: sub current_machine_domains {
1.853 albertel 15305: return &machine_domains(&hostname($perlvar{'lonHostID'}));
15306: }
15307:
15308: sub machine_domains {
15309: my ($hostname) = @_;
1.465 albertel 15310: my @domains;
1.838 albertel 15311: my %hostname = &all_hostnames();
1.465 albertel 15312: while( my($id, $name) = each(%hostname)) {
1.467 matthew 15313: # &logthis("-$id-$name-$hostname-");
1.465 albertel 15314: if ($hostname eq $name) {
1.844 albertel 15315: push(@domains,&host_domain($id));
1.465 albertel 15316: }
15317: }
15318: return @domains;
15319: }
15320:
15321: sub current_machine_ids {
1.853 albertel 15322: return &machine_ids(&hostname($perlvar{'lonHostID'}));
15323: }
15324:
15325: sub machine_ids {
15326: my ($hostname) = @_;
15327: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 15328: my @ids;
1.888 albertel 15329: my %name_to_host = &all_names();
1.889 albertel 15330: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
15331: return @{ $name_to_host{$hostname} };
15332: }
15333: return;
1.31 www 15334: }
15335:
1.824 raeburn 15336: sub additional_machine_domains {
15337: my @domains;
1.1466 raeburn 15338: if (-e "$perlvar{'lonTabDir'}/expected_domains.tab") {
15339: if (open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab")) {
15340: while (my $line = <$fh>) {
15341: chomp($line);
15342: $line =~ s/\s//g;
15343: push(@domains,$line);
15344: }
15345: close($fh);
15346: }
1.824 raeburn 15347: }
15348: return @domains;
15349: }
15350:
15351: sub default_login_domain {
15352: my $domain = $perlvar{'lonDefDomain'};
15353: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
15354: foreach my $posdom (¤t_machine_domains(),
15355: &additional_machine_domains()) {
15356: if (lc($posdom) eq lc($testdomain)) {
15357: $domain=$posdom;
15358: last;
15359: }
15360: }
15361: return $domain;
15362: }
15363:
1.1414 raeburn 15364: sub shared_institution {
1.1439 raeburn 15365: my ($dom,$lonhost) = @_;
15366: if ($lonhost eq '') {
15367: $lonhost = $perlvar{'lonHostID'};
15368: }
1.1414 raeburn 15369: my $same_intdom;
1.1439 raeburn 15370: my $hostintdom = &internet_dom($lonhost);
1.1414 raeburn 15371: if ($hostintdom ne '') {
15372: my %iphost = &get_iphost();
15373: my $primary_id = &domain($dom,'primary');
15374: my $primary_ip = &get_host_ip($primary_id);
15375: if (ref($iphost{$primary_ip}) eq 'ARRAY') {
15376: foreach my $id (@{$iphost{$primary_ip}}) {
15377: my $intdom = &internet_dom($id);
15378: if ($intdom eq $hostintdom) {
15379: $same_intdom = 1;
15380: last;
15381: }
15382: }
15383: }
15384: }
15385: return $same_intdom;
15386: }
15387:
1.1398 raeburn 15388: sub uses_sts {
15389: my ($ignore_cache) = @_;
15390: my $lonhost = $perlvar{'lonHostID'};
15391: my $hostname = &hostname($lonhost);
15392: my $sts_on;
15393: if ($protocol{$lonhost} eq 'https') {
15394: my $cachetime = 12*3600;
15395: if (!$ignore_cache) {
15396: ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
15397: if (defined($cached)) {
15398: return $sts_on;
15399: }
15400: }
15401: my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
15402: my $request=new HTTP::Request('HEAD',$url);
15403: my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,'','','',1);
15404: if ($response->is_success) {
15405: my $has_sts = $response->header('Strict-Transport-Security');
15406: if ($has_sts eq '') {
15407: $sts_on = 0;
15408: } else {
15409: if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
15410: my $maxage = $1;
15411: if ($maxage) {
15412: $sts_on = 1;
15413: } else {
15414: $sts_on = 0;
15415: }
15416: } else {
15417: $sts_on = 0;
15418: }
15419: }
15420: return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
15421: }
15422: }
15423: return;
15424: }
15425:
1.1449 raeburn 15426: sub waf_allssl {
15427: my ($host_name) = @_;
15428: my $alias = &get_proxy_alias();
15429: if ($host_name eq '') {
15430: $host_name = $ENV{'SERVER_NAME'};
15431: }
15432: if (($host_name ne '') && ($alias eq $host_name)) {
15433: my $serverhomedom = &host_domain($perlvar{'lonHostID'});
15434: my %defdomdefaults = &get_domain_defaults($serverhomedom);
15435: if ($defdomdefaults{'waf_sslopt'}) {
15436: return $defdomdefaults{'waf_sslopt'};
15437: }
15438: }
15439: return;
15440: }
15441:
1.1434 raeburn 15442: sub get_requestor_ip {
15443: my ($r,$nolookup,$noproxy) = @_;
15444: my $from_ip;
15445: if (ref($r)) {
1.1447 raeburn 15446: if ($r->can('useragent_ip')) {
15447: if ($noproxy && $r->can('client_ip')) {
15448: $from_ip = $r->client_ip();
15449: } else {
15450: $from_ip = $r->useragent_ip();
15451: }
15452: } elsif ($r->connection->can('remote_ip')) {
15453: $from_ip = $r->connection->remote_ip();
15454: } else {
15455: $from_ip = $r->get_remote_host($nolookup);
15456: }
1.1434 raeburn 15457: } else {
15458: $from_ip = $ENV{'REMOTE_ADDR'};
15459: }
15460: return $from_ip if ($noproxy);
15461: # Who controls proxy settings for server
15462: my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
15463: my $proxyinfo = &get_proxy_settings($dom_in_use);
15464: if ((ref($proxyinfo) eq 'HASH') && ($from_ip)) {
1.1437 raeburn 15465: if ($proxyinfo->{'vpnint'}) {
15466: if (&ip_match($from_ip,$proxyinfo->{'vpnint'})) {
1.1434 raeburn 15467: return $from_ip;
15468: }
15469: }
15470: if ($proxyinfo->{'trusted'}) {
15471: if (&ip_match($from_ip,$proxyinfo->{'trusted'})) {
15472: my $ipheader = $proxyinfo->{'ipheader'};
15473: my ($ip,$xfor);
15474: if (ref($r)) {
15475: if ($ipheader) {
15476: $ip = $r->headers_in->{$ipheader};
15477: }
15478: $xfor = $r->headers_in->{'X-Forwarded-For'};
15479: } else {
15480: if ($ipheader) {
15481: $ip = $ENV{'HTTP_'.uc($ipheader)};
15482: }
15483: $xfor = $ENV{'HTTP_X_FORWARDED_FOR'};
15484: }
15485: if (($ip eq '') && ($xfor ne '')) {
15486: foreach my $poss_ip (reverse(split(/\s*,\s*/,$xfor))) {
15487: unless (&ip_match($poss_ip,$proxyinfo->{'trusted'})) {
15488: $ip = $poss_ip;
1.1435 raeburn 15489: last;
1.1434 raeburn 15490: }
15491: }
15492: }
15493: if ($ip ne '') {
15494: return $ip;
15495: }
15496: }
15497: }
15498: }
15499: return $from_ip;
15500: }
15501:
15502: sub get_proxy_settings {
15503: my ($dom_in_use) = @_;
1.1494 raeburn 15504: my %domdefaults = &get_domain_defaults($dom_in_use);
1.1434 raeburn 15505: my $proxyinfo = {
15506: ipheader => $domdefaults{'waf_ipheader'},
15507: trusted => $domdefaults{'waf_trusted'},
1.1437 raeburn 15508: vpnint => $domdefaults{'waf_vpnint'},
1.1438 raeburn 15509: vpnext => $domdefaults{'waf_vpnext'},
1.1449 raeburn 15510: sslopt => $domdefaults{'waf_sslopt'},
1.1434 raeburn 15511: };
15512: return $proxyinfo;
15513: }
15514:
15515: sub ip_match {
15516: my ($ip,$pattern_str) = @_;
15517: $ip=Net::CIDR::cidrvalidate($ip);
15518: if ($ip) {
15519: return Net::CIDR::cidrlookup($ip,split(/\s*,\s*/,$pattern_str));
15520: }
15521: return;
15522: }
15523:
15524: sub get_proxy_alias {
1.1450 raeburn 15525: my ($lonid) = @_;
15526: if ($lonid eq '') {
15527: $lonid = $perlvar{'lonHostID'};
15528: }
15529: if (!defined(&hostname($lonid))) {
15530: return;
15531: }
15532: if ($lonid ne '') {
15533: my ($alias,$cached) = &is_cached_new('proxyalias',$lonid);
1.1434 raeburn 15534: if ($cached) {
15535: return $alias;
15536: }
1.1494 raeburn 15537: my $dom = &host_domain($lonid);
1.1434 raeburn 15538: if ($dom ne '') {
15539: my $cachetime = 60*60*24;
15540: my %domconfig =
1.1494 raeburn 15541: &get_dom('configuration',['wafproxy'],$dom);
1.1437 raeburn 15542: if (ref($domconfig{'wafproxy'}) eq 'HASH') {
15543: if (ref($domconfig{'wafproxy'}{'alias'}) eq 'HASH') {
1.1450 raeburn 15544: $alias = $domconfig{'wafproxy'}{'alias'}{$lonid};
15545: }
15546: }
15547: return &do_cache_new('proxyalias',$lonid,$alias,$cachetime);
15548: }
15549: }
15550: return;
15551: }
15552:
15553: sub use_proxy_alias {
15554: my ($r,$lonid) = @_;
15555: my $alias = &get_proxy_alias($lonid);
15556: if ($alias) {
15557: my $dom = &host_domain($lonid);
15558: if ($dom ne '') {
1.1467 raeburn 15559: my $proxyinfo = &get_proxy_settings($dom);
1.1450 raeburn 15560: my ($vpnint,$remote_ip);
15561: if (ref($proxyinfo) eq 'HASH') {
15562: $vpnint = $proxyinfo->{'vpnint'};
15563: if ($vpnint) {
15564: $remote_ip = &get_requestor_ip($r,1,1);
1.1434 raeburn 15565: }
15566: }
1.1450 raeburn 15567: unless ($vpnint && &ip_match($remote_ip,$vpnint)) {
15568: return $alias;
15569: }
1.1434 raeburn 15570: }
15571: }
15572: return;
15573: }
15574:
1.1474 raeburn 15575: sub alias_sso {
1.1467 raeburn 15576: my ($lonid) = @_;
15577: if ($lonid eq '') {
15578: $lonid = $perlvar{'lonHostID'};
15579: }
15580: if (!defined(&hostname($lonid))) {
15581: return;
15582: }
15583: if ($lonid ne '') {
15584: my ($use_alias,$cached) = &is_cached_new('proxysaml',$lonid);
15585: if ($cached) {
15586: return $use_alias;
15587: }
1.1494 raeburn 15588: my $dom = &host_domain($lonid);
1.1467 raeburn 15589: if ($dom ne '') {
15590: my $cachetime = 60*60*24;
15591: my %domconfig =
1.1494 raeburn 15592: &get_dom('configuration',['wafproxy'],$dom);
1.1467 raeburn 15593: if (ref($domconfig{'wafproxy'}) eq 'HASH') {
15594: if (ref($domconfig{'wafproxy'}{'saml'}) eq 'HASH') {
15595: $use_alias = $domconfig{'wafproxy'}{'saml'}{$lonid};
15596: }
15597: }
15598: return &do_cache_new('proxysaml',$lonid,$use_alias,$cachetime);
15599: }
15600: }
15601: return;
15602: }
15603:
1.1465 raeburn 15604: sub get_saml_landing {
15605: my ($lonid) = @_;
15606: if ($lonid eq '') {
15607: my $defdom = &default_login_domain();
15608: my @hosts = ¤t_machine_ids();
15609: if (@hosts > 1) {
15610: foreach my $hostid (@hosts) {
15611: if (&host_domain($hostid) eq $defdom) {
15612: $lonid = $hostid;
15613: last;
15614: }
15615: }
15616: } else {
15617: $lonid = $perlvar{'lonHostID'};
15618: }
15619: if ($lonid) {
1.1494 raeburn 15620: unless (&host_domain($lonid) eq $defdom) {
1.1465 raeburn 15621: return;
15622: }
15623: } else {
15624: return;
15625: }
15626: } elsif (!defined(&hostname($lonid))) {
15627: return;
15628: }
15629: my ($landing,$cached) = &is_cached_new('samllanding',$lonid);
15630: if ($cached) {
15631: return $landing;
15632: }
1.1494 raeburn 15633: my $dom = &host_domain($lonid);
1.1465 raeburn 15634: if ($dom ne '') {
15635: my $cachetime = 60*60*24;
15636: my %domconfig =
1.1494 raeburn 15637: &get_dom('configuration',['login'],$dom);
1.1465 raeburn 15638: if (ref($domconfig{'login'}) eq 'HASH') {
15639: if (ref($domconfig{'login'}{'saml'}) eq 'HASH') {
15640: if (ref($domconfig{'login'}{'saml'}{$lonid}) eq 'HASH') {
15641: $landing = 1;
15642: }
15643: }
15644: }
15645: return &do_cache_new('samllanding',$lonid,$landing,$cachetime);
15646: }
15647: return;
15648: }
15649:
1.31 www 15650: # ------------------------------------------------------------- Declutters URLs
15651:
15652: sub declutter {
15653: my $thisfn=shift;
1.569 albertel 15654: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1261 raeburn 15655: unless ($thisfn=~m{^/home/httpd/html/priv/}) {
15656: $thisfn=~s{^/home/httpd/html}{};
15657: }
1.31 www 15658: $thisfn=~s/^\///;
1.697 albertel 15659: $thisfn=~s|^adm/wrapper/||;
15660: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 15661: $thisfn=~s/^res\///;
1.1172 bisitz 15662: $thisfn=~s/^priv\///;
1.1032 raeburn 15663: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
15664: $thisfn=~s/\?.+$//;
15665: }
1.268 www 15666: return $thisfn;
15667: }
15668:
15669: # ------------------------------------------------------------- Clutter up URLs
15670:
15671: sub clutter {
15672: my $thisfn='/'.&declutter(shift);
1.887 albertel 15673: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 15674: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 15675: $thisfn='/res'.$thisfn;
15676: }
1.1031 raeburn 15677: if ($thisfn !~m|^/adm|) {
15678: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 15679: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 15680: } else {
15681: my ($ext) = ($thisfn =~ /\.(\w+)$/);
15682: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 15683: if ($embstyle eq 'ssi'
15684: || ($embstyle eq 'hdn')
15685: || ($embstyle eq 'rat')
15686: || ($embstyle eq 'prv')
15687: || ($embstyle eq 'ign')) {
15688: #do nothing with these
15689: } elsif (($embstyle eq 'img')
1.695 albertel 15690: || ($embstyle eq 'emb')
15691: || ($embstyle eq 'wrp')) {
15692: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 15693: } elsif ($embstyle eq 'unk'
15694: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 15695: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 15696: } else {
1.718 www 15697: # &logthis("Got a blank emb style");
1.695 albertel 15698: }
1.694 albertel 15699: }
1.1343 raeburn 15700: } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
1.1298 raeburn 15701: $thisfn='/adm/wrapper'.$thisfn;
1.694 albertel 15702: }
1.31 www 15703: return $thisfn;
1.12 www 15704: }
15705:
1.787 albertel 15706: sub clutter_with_no_wrapper {
15707: my $uri = &clutter(shift);
15708: if ($uri =~ m-^/adm/-) {
15709: $uri =~ s-^/adm/wrapper/-/-;
15710: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
15711: }
15712: return $uri;
15713: }
15714:
1.557 albertel 15715: sub freeze_escape {
15716: my ($value)=@_;
15717: if (ref($value)) {
15718: $value=&nfreeze($value);
15719: return '__FROZEN__'.&escape($value);
15720: }
15721: return &escape($value);
15722: }
15723:
1.11 www 15724:
1.557 albertel 15725: sub thaw_unescape {
15726: my ($value)=@_;
15727: if ($value =~ /^__FROZEN__/) {
15728: substr($value,0,10,undef);
15729: $value=&unescape($value);
15730: return &thaw($value);
15731: }
15732: return &unescape($value);
15733: }
15734:
1.436 albertel 15735: sub correct_line_ends {
15736: my ($result)=@_;
15737: $$result =~s/\r\n/\n/mg;
15738: $$result =~s/\r/\n/mg;
1.415 albertel 15739: }
1.1 albertel 15740: # ================================================================ Main Program
15741:
1.184 www 15742: sub goodbye {
1.204 albertel 15743: &logthis("Starting Shut down");
1.443 albertel 15744: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 15745: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 15746: #converted
1.599 albertel 15747: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 15748: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
15749: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
15750: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 15751: #1.1 only
1.870 albertel 15752: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
15753: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
15754: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
15755: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
15756: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 15757: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
15758: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 15759: &flushcourselogs();
15760: &logthis("Shutting down");
15761: }
15762:
1.852 albertel 15763: sub get_dns {
1.1210 raeburn 15764: my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869 albertel 15765: if (!$ignore_cache) {
15766: my ($content,$cached)=
1.1494 raeburn 15767: &is_cached_new('dns',$url);
1.869 albertel 15768: if ($cached) {
1.1210 raeburn 15769: &$func($content,$hashref);
1.869 albertel 15770: return;
15771: }
15772: }
15773:
15774: my %alldns;
1.1379 raeburn 15775: if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
15776: foreach my $dns (<$config>) {
15777: next if ($dns !~ /^\^(\S*)/x);
15778: my $line = $1;
15779: my ($host,$protocol) = split(/:/,$line);
15780: if ($protocol ne 'https') {
15781: $protocol = 'http';
15782: }
15783: $alldns{$host} = $protocol;
1.979 raeburn 15784: }
1.1379 raeburn 15785: close($config);
1.869 albertel 15786: }
15787: while (%alldns) {
1.1263 raeburn 15788: my ($dns) = sort { $b cmp $a } keys(%alldns);
1.1456 raeburn 15789: my ($contents,@content);
15790: if ($dns eq Sys::Hostname::FQDN::fqdn()) {
15791: my $command = (split('/',$url))[3];
15792: my ($dir,$file) = &parse_getdns_url($command,$url);
15793: delete($alldns{$dns});
15794: next if (($dir eq '') || ($file eq ''));
15795: if (open(my $config,'<',"$dir/$file")) {
1.1457 raeburn 15796: @content = <$config>;
1.1456 raeburn 15797: close($config);
15798: }
15799: if ($url eq '/adm/dns/loncapaCRL') {
15800: $contents = join('',@content);
15801: }
15802: } else {
15803: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
15804: my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar,30,0);
15805: delete($alldns{$dns});
15806: next if ($response->is_error());
15807: if ($url eq '/adm/dns/loncapaCRL') {
15808: $contents = $response->content;
15809: } else {
15810: @content = split("\n",$response->content);
15811: }
15812: }
1.1379 raeburn 15813: if ($url eq '/adm/dns/loncapaCRL') {
1.1456 raeburn 15814: return &$func($contents);
1.1379 raeburn 15815: } else {
15816: unless ($nocache) {
15817: &do_cache_new('dns',$url,\@content,30*24*60*60);
15818: }
15819: &$func(\@content,$hashref);
15820: return;
15821: }
15822: }
15823: my $which = (split('/',$url,4))[3];
15824: if ($which eq 'loncapaCRL') {
15825: my $diskfile = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
15826: if (-e $diskfile) {
15827: &logthis("unable to contact DNS, on disk file $diskfile not updated");
15828: } else {
15829: &logthis("unable to contact DNS, no on disk file $diskfile available");
15830: }
15831: } else {
15832: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
15833: if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
15834: my @content = <$config>;
15835: close($config);
15836: &$func(\@content,$hashref);
15837: }
1.852 albertel 15838: }
1.1210 raeburn 15839: return;
15840: }
15841:
15842: # ------------------------------------------------------Get DNS checksums file
1.1211 raeburn 15843: sub parse_dns_checksums_tab {
1.1210 raeburn 15844: my ($lines,$hashref) = @_;
1.1264 raeburn 15845: my $lonhost = $perlvar{'lonHostID'};
1.1494 raeburn 15846: my $machine_dom = &host_domain($lonhost);
1.1210 raeburn 15847: my $loncaparev = &get_server_loncaparev($machine_dom);
1.1264 raeburn 15848: my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
15849: my $webconfdir = '/etc/httpd/conf';
15850: if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
15851: $webconfdir = '/etc/apache2';
15852: } elsif ($distro =~ /^sles(\d+)$/) {
15853: if ($1 >= 10) {
15854: $webconfdir = '/etc/apache2';
15855: }
15856: } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
15857: if ($1 >= 10.0) {
15858: $webconfdir = '/etc/apache2';
15859: }
15860: }
1.1210 raeburn 15861: my ($release,$timestamp) = split(/\-/,$loncaparev);
15862: my (%chksum,%revnum);
15863: if (ref($lines) eq 'ARRAY') {
15864: chomp(@{$lines});
1.1238 raeburn 15865: my $version = shift(@{$lines});
15866: if ($version eq $release) {
1.1210 raeburn 15867: foreach my $line (@{$lines}) {
1.1238 raeburn 15868: my ($file,$version,$shasum) = split(/,/,$line);
1.1264 raeburn 15869: if ($file =~ m{^/etc/httpd/conf}) {
15870: if ($webconfdir eq '/etc/apache2') {
15871: $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
15872: }
15873: }
1.1238 raeburn 15874: $chksum{$file} = $shasum;
15875: $revnum{$file} = $version;
1.1210 raeburn 15876: }
15877: if (ref($hashref) eq 'HASH') {
15878: %{$hashref} = (
15879: sums => \%chksum,
15880: versions => \%revnum,
15881: );
15882: }
15883: }
15884: }
1.869 albertel 15885: return;
1.852 albertel 15886: }
1.1210 raeburn 15887:
15888: sub fetch_dns_checksums {
1.1238 raeburn 15889: my %checksums;
1.1494 raeburn 15890: my $machine_dom = &host_domain($perlvar{'lonHostID'});
1.1260 raeburn 15891: my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1238 raeburn 15892: my ($release,$timestamp) = split(/\-/,$loncaparev);
15893: &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1211 raeburn 15894: \%checksums);
1.1210 raeburn 15895: return \%checksums;
15896: }
15897:
1.1379 raeburn 15898: sub fetch_crl_pemfile {
15899: return &get_dns("/adm/dns/loncapaCRL",\&save_crl_pem,1,1);
15900: }
15901:
15902: sub save_crl_pem {
1.1456 raeburn 15903: my ($content) = @_;
1.1380 raeburn 15904: my ($msg,$hadchanges);
1.1456 raeburn 15905: if ($content ne '') {
1.1379 raeburn 15906: my $now = time;
15907: my $lonca = $perlvar{'lonCertificateDirectory'}.'/'.$perlvar{'lonnetCertificateAuthority'};
15908: my $tmpcrl = $tmpdir.'/'.$perlvar{'lonnetCertRevocationList'}.'_'.$now.'.'.$$.'.tmp';
15909: if (open(my $fh,'>',"$tmpcrl")) {
1.1456 raeburn 15910: print $fh $content;
1.1379 raeburn 15911: close($fh);
15912: if (-e $lonca) {
15913: if (open(PIPE,"openssl crl -in $tmpcrl -inform pem -CAfile $lonca -noout 2>&1 |")) {
15914: my $check = <PIPE>;
15915: close(PIPE);
15916: chomp($check);
15917: if ($check eq 'verify OK') {
15918: my $dest = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
1.1380 raeburn 15919: my $backup;
1.1379 raeburn 15920: if (-e $dest) {
1.1380 raeburn 15921: if (&File::Copy::move($dest,"$dest.bak")) {
15922: $backup = 'ok';
15923: }
1.1379 raeburn 15924: }
15925: if (&File::Copy::move($tmpcrl,$dest)) {
15926: $msg = 'ok';
1.1380 raeburn 15927: if ($backup) {
15928: my (%oldnums,%newnums);
15929: if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest.bak |grep 'Serial Number' |")) {
15930: while (<PIPE>) {
15931: $oldnums{(split(/:/))[1]} = 1;
15932: }
15933: close(PIPE);
15934: }
15935: if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest |grep 'Serial Number' |")) {
15936: while(<PIPE>) {
15937: $newnums{(split(/:/))[1]} = 1;
15938: }
15939: close(PIPE);
15940: }
15941: foreach my $key (sort {$b <=> $a } (keys(%newnums))) {
15942: unless (exists($oldnums{$key})) {
15943: $hadchanges = 1;
15944: last;
15945: }
15946: }
15947: unless ($hadchanges) {
15948: foreach my $key (sort {$b <=> $a } (keys(%oldnums))) {
15949: unless (exists($newnums{$key})) {
15950: $hadchanges = 1;
15951: last;
15952: }
15953: }
15954: }
15955: }
1.1379 raeburn 15956: }
15957: } else {
15958: unlink($tmpcrl);
15959: }
15960: } else {
15961: unlink($tmpcrl);
15962: }
15963: } else {
15964: unlink($tmpcrl);
15965: }
15966: }
15967: }
1.1380 raeburn 15968: return ($msg,$hadchanges);
1.1379 raeburn 15969: }
15970:
1.1456 raeburn 15971: sub parse_getdns_url {
15972: my ($command,$url) = @_;
15973: my $dir = $perlvar{'lonTabDir'};
15974: my $file;
15975: if ($command eq 'hosts') {
15976: $file = 'dns_hosts.tab';
15977: } elsif ($command eq 'domain') {
15978: $file = 'dns_domain.tab';
15979: } elsif ($command eq 'checksums') {
15980: my $version = (split('/',$url))[4];
15981: $file = "dns_checksums/$version.tab",
15982: } elsif ($command eq 'loncapaCRL') {
15983: $dir = $perlvar{'lonCertificateDirectory'};
15984: $file = $perlvar{'lonnetCertRevocationList'};
15985: }
15986: return ($dir,$file);
15987: }
15988:
1.327 albertel 15989: # ------------------------------------------------------------ Read domain file
15990: {
1.852 albertel 15991: my $loaded;
1.846 albertel 15992: my %domain;
15993:
1.852 albertel 15994: sub parse_domain_tab {
15995: my ($lines) = @_;
15996: foreach my $line (@$lines) {
15997: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 15998:
1.846 albertel 15999: chomp($line);
1.852 albertel 16000: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 16001: my %this_domain;
16002: foreach my $field ('description', 'auth_def', 'auth_arg_def',
16003: 'lang_def', 'city', 'longi', 'lati',
16004: 'primary') {
16005: $this_domain{$field} = shift(@elements);
16006: }
16007: $domain{$name} = \%this_domain;
1.852 albertel 16008: }
16009: }
1.864 albertel 16010:
16011: sub reset_domain_info {
16012: undef($loaded);
16013: undef(%domain);
16014: }
16015:
1.852 albertel 16016: sub load_domain_tab {
1.1293 raeburn 16017: my ($ignore_cache,$nocache) = @_;
16018: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852 albertel 16019: my $fh;
1.1359 raeburn 16020: if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852 albertel 16021: my @lines = <$fh>;
16022: &parse_domain_tab(\@lines);
1.448 albertel 16023: }
1.852 albertel 16024: close($fh);
16025: $loaded = 1;
1.327 albertel 16026: }
1.846 albertel 16027:
16028: sub domain {
1.852 albertel 16029: &load_domain_tab() if (!$loaded);
16030:
1.846 albertel 16031: my ($name,$what) = @_;
16032: return if ( !exists($domain{$name}) );
16033:
16034: if (!$what) {
16035: return $domain{$name}{'description'};
16036: }
16037: return $domain{$name}{$what};
16038: }
1.974 raeburn 16039:
16040: sub domain_info {
16041: &load_domain_tab() if (!$loaded);
16042: return %domain;
16043: }
16044:
1.327 albertel 16045: }
16046:
16047:
1.1 albertel 16048: # ------------------------------------------------------------- Read hosts file
16049: {
1.838 albertel 16050: my %hostname;
1.844 albertel 16051: my %hostdom;
1.845 albertel 16052: my %libserv;
1.852 albertel 16053: my $loaded;
1.888 albertel 16054: my %name_to_host;
1.1074 raeburn 16055: my %internetdom;
1.1107 raeburn 16056: my %LC_dns_serv;
1.852 albertel 16057:
16058: sub parse_hosts_tab {
16059: my ($file) = @_;
16060: foreach my $configline (@$file) {
16061: next if ($configline =~ /^(\#|\s*$ )/x);
1.1107 raeburn 16062: chomp($configline);
16063: if ($configline =~ /^\^/) {
16064: if ($configline =~ /^\^([\w.\-]+)/) {
16065: $LC_dns_serv{$1} = 1;
16066: }
16067: next;
16068: }
1.1074 raeburn 16069: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 16070: $name=~s/\s//g;
16071: if ($id && $domain && $role && $name) {
1.1351 raeburn 16072: if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
16073: my $curr = $hostname{$id};
16074: my $skip;
16075: if (ref($name_to_host{$curr}) eq 'ARRAY') {
16076: if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
16077: $skip = 1;
16078: } else {
16079: @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
16080: }
16081: }
16082: unless ($skip) {
16083: push(@{$name_to_host{$name}},$id);
16084: }
16085: } else {
16086: push(@{$name_to_host{$name}},$id);
16087: }
1.852 albertel 16088: $hostname{$id}=$name;
16089: $hostdom{$id}=$domain;
16090: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 16091: if (defined($protocol)) {
16092: if ($protocol eq 'https') {
16093: $protocol{$id} = $protocol;
16094: } else {
16095: $protocol{$id} = 'http';
16096: }
1.968 raeburn 16097: } else {
1.969 raeburn 16098: $protocol{$id} = 'http';
1.968 raeburn 16099: }
1.1074 raeburn 16100: if (defined($intdom)) {
16101: $internetdom{$id} = $intdom;
16102: }
1.852 albertel 16103: }
16104: }
16105: }
1.864 albertel 16106:
16107: sub reset_hosts_info {
1.897 albertel 16108: &purge_remembered();
1.864 albertel 16109: &reset_domain_info();
16110: &reset_hosts_ip_info();
1.1339 raeburn 16111: undef(%internetdom);
1.892 albertel 16112: undef(%name_to_host);
1.864 albertel 16113: undef(%hostname);
16114: undef(%hostdom);
16115: undef(%libserv);
16116: undef($loaded);
16117: }
1.1 albertel 16118:
1.852 albertel 16119: sub load_hosts_tab {
1.1293 raeburn 16120: my ($ignore_cache,$nocache) = @_;
16121: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1359 raeburn 16122: open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852 albertel 16123: my @config = <$config>;
16124: &parse_hosts_tab(\@config);
16125: close($config);
16126: $loaded=1;
1.1 albertel 16127: }
1.852 albertel 16128:
1.838 albertel 16129: sub hostname {
1.852 albertel 16130: &load_hosts_tab() if (!$loaded);
16131:
1.838 albertel 16132: my ($lonid) = @_;
16133: return $hostname{$lonid};
16134: }
1.845 albertel 16135:
1.838 albertel 16136: sub all_hostnames {
1.852 albertel 16137: &load_hosts_tab() if (!$loaded);
16138:
1.838 albertel 16139: return %hostname;
16140: }
1.845 albertel 16141:
1.888 albertel 16142: sub all_names {
1.1293 raeburn 16143: my ($ignore_cache,$nocache) = @_;
16144: &load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888 albertel 16145:
16146: return %name_to_host;
16147: }
16148:
1.974 raeburn 16149: sub all_host_domain {
16150: &load_hosts_tab() if (!$loaded);
16151: return %hostdom;
16152: }
16153:
1.1339 raeburn 16154: sub all_host_intdom {
16155: &load_hosts_tab() if (!$loaded);
16156: return %internetdom;
16157: }
16158:
1.845 albertel 16159: sub is_library {
1.852 albertel 16160: &load_hosts_tab() if (!$loaded);
16161:
1.845 albertel 16162: return exists($libserv{$_[0]});
16163: }
16164:
16165: sub all_library {
1.852 albertel 16166: &load_hosts_tab() if (!$loaded);
16167:
1.845 albertel 16168: return %libserv;
16169: }
16170:
1.1062 droeschl 16171: sub unique_library {
16172: #2x reverse removes all hostnames that appear more than once
16173: my %unique = reverse &all_library();
16174: return reverse %unique;
16175: }
16176:
1.841 albertel 16177: sub get_servers {
1.852 albertel 16178: &load_hosts_tab() if (!$loaded);
16179:
1.841 albertel 16180: my ($domain,$type) = @_;
16181: my %possible_hosts = ($type eq 'library') ? %libserv
16182: : %hostname;
16183: my %result;
1.842 albertel 16184: if (ref($domain) eq 'ARRAY') {
16185: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 16186: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 16187: $result{$host} = $hostname;
16188: }
16189: }
16190: } else {
16191: while ( my ($host,$hostname) = each(%possible_hosts)) {
16192: if ($hostdom{$host} eq $domain) {
16193: $result{$host} = $hostname;
16194: }
1.841 albertel 16195: }
16196: }
16197: return %result;
16198: }
1.845 albertel 16199:
1.1062 droeschl 16200: sub get_unique_servers {
16201: my %unique = reverse &get_servers(@_);
16202: return reverse %unique;
16203: }
16204:
1.844 albertel 16205: sub host_domain {
1.852 albertel 16206: &load_hosts_tab() if (!$loaded);
16207:
1.844 albertel 16208: my ($lonid) = @_;
16209: return $hostdom{$lonid};
16210: }
16211:
1.841 albertel 16212: sub all_domains {
1.852 albertel 16213: &load_hosts_tab() if (!$loaded);
16214:
1.841 albertel 16215: my %seen;
16216: my @uniq = grep(!$seen{$_}++, values(%hostdom));
16217: return @uniq;
16218: }
1.1074 raeburn 16219:
16220: sub internet_dom {
16221: &load_hosts_tab() if (!$loaded);
16222:
16223: my ($lonid) = @_;
16224: return $internetdom{$lonid};
16225: }
1.1107 raeburn 16226:
16227: sub is_LC_dns {
16228: &load_hosts_tab() if (!$loaded);
16229:
16230: my ($hostname) = @_;
16231: return exists($LC_dns_serv{$hostname});
16232: }
16233:
1.1 albertel 16234: }
16235:
1.847 albertel 16236: {
16237: my %iphost;
1.856 albertel 16238: my %name_to_ip;
16239: my %lonid_to_ip;
1.869 albertel 16240:
1.847 albertel 16241: sub get_hosts_from_ip {
16242: my ($ip) = @_;
16243: my %iphosts = &get_iphost();
16244: if (ref($iphosts{$ip})) {
16245: return @{$iphosts{$ip}};
16246: }
16247: return;
1.839 albertel 16248: }
1.864 albertel 16249:
16250: sub reset_hosts_ip_info {
16251: undef(%iphost);
16252: undef(%name_to_ip);
16253: undef(%lonid_to_ip);
16254: }
1.856 albertel 16255:
16256: sub get_host_ip {
16257: my ($lonid) = @_;
16258: if (exists($lonid_to_ip{$lonid})) {
16259: return $lonid_to_ip{$lonid};
16260: }
16261: my $name=&hostname($lonid);
16262: my $ip = gethostbyname($name);
16263: return if (!$ip || length($ip) ne 4);
16264: $ip=inet_ntoa($ip);
16265: $name_to_ip{$name} = $ip;
16266: $lonid_to_ip{$lonid} = $ip;
16267: return $ip;
16268: }
1.847 albertel 16269:
16270: sub get_iphost {
1.1293 raeburn 16271: my ($ignore_cache,$nocache) = @_;
1.894 albertel 16272:
1.869 albertel 16273: if (!$ignore_cache) {
16274: if (%iphost) {
16275: return %iphost;
16276: }
16277: my ($ip_info,$cached)=
1.1494 raeburn 16278: &is_cached_new('iphost','iphost');
1.869 albertel 16279: if ($cached) {
16280: %iphost = %{$ip_info->[0]};
16281: %name_to_ip = %{$ip_info->[1]};
16282: %lonid_to_ip = %{$ip_info->[2]};
16283: return %iphost;
16284: }
16285: }
1.894 albertel 16286:
16287: # get yesterday's info for fallback
16288: my %old_name_to_ip;
16289: my ($ip_info,$cached)=
1.1495 raeburn 16290: &is_cached_new('iphost','iphost');
1.894 albertel 16291: if ($cached) {
16292: %old_name_to_ip = %{$ip_info->[1]};
16293: }
16294:
1.1293 raeburn 16295: my %name_to_host = &all_names($ignore_cache,$nocache);
1.888 albertel 16296: foreach my $name (keys(%name_to_host)) {
1.847 albertel 16297: my $ip;
16298: if (!exists($name_to_ip{$name})) {
16299: $ip = gethostbyname($name);
16300: if (!$ip || length($ip) ne 4) {
1.894 albertel 16301: if (defined($old_name_to_ip{$name})) {
16302: $ip = $old_name_to_ip{$name};
16303: &logthis("Can't find $name defaulting to old $ip");
16304: } else {
16305: &logthis("Name $name no IP found");
16306: next;
16307: }
16308: } else {
16309: $ip=inet_ntoa($ip);
1.847 albertel 16310: }
16311: $name_to_ip{$name} = $ip;
16312: } else {
16313: $ip = $name_to_ip{$name};
1.653 albertel 16314: }
1.888 albertel 16315: foreach my $id (@{ $name_to_host{$name} }) {
16316: $lonid_to_ip{$id} = $ip;
16317: }
16318: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 16319: }
1.1293 raeburn 16320: unless ($nocache) {
16321: &do_cache_new('iphost','iphost',
16322: [\%iphost,\%name_to_ip,\%lonid_to_ip],
16323: 48*60*60);
16324: }
1.869 albertel 16325:
1.847 albertel 16326: return %iphost;
1.598 albertel 16327: }
16328:
1.992 raeburn 16329: #
16330: # Given a DNS returns the loncapa host name for that DNS
16331: #
16332: sub host_from_dns {
16333: my ($dns) = @_;
16334: my @hosts;
16335: my $ip;
16336:
1.993 raeburn 16337: if (exists($name_to_ip{$dns})) {
1.992 raeburn 16338: $ip = $name_to_ip{$dns};
16339: }
16340: if (!$ip) {
16341: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
16342: if (length($ip) == 4) {
16343: $ip = &IO::Socket::inet_ntoa($ip);
16344: }
16345: }
16346: if ($ip) {
16347: @hosts = get_hosts_from_ip($ip);
16348: return $hosts[0];
16349: }
16350: return undef;
1.986 foxr 16351: }
1.992 raeburn 16352:
1.1074 raeburn 16353: sub get_internet_names {
16354: my ($lonid) = @_;
16355: return if ($lonid eq '');
16356: my ($idnref,$cached)=
1.1494 raeburn 16357: &is_cached_new('internetnames',$lonid);
1.1074 raeburn 16358: if ($cached) {
16359: return $idnref;
16360: }
16361: my $ip = &get_host_ip($lonid);
16362: my @hosts = &get_hosts_from_ip($ip);
16363: my %iphost = &get_iphost();
16364: my (@idns,%seen);
16365: foreach my $id (@hosts) {
16366: my $dom = &host_domain($id);
16367: my $prim_id = &domain($dom,'primary');
16368: my $prim_ip = &get_host_ip($prim_id);
16369: next if ($seen{$prim_ip});
16370: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
16371: foreach my $id (@{$iphost{$prim_ip}}) {
16372: my $intdom = &internet_dom($id);
16373: unless (grep(/^\Q$intdom\E$/,@idns)) {
16374: push(@idns,$intdom);
16375: }
16376: }
16377: }
16378: $seen{$prim_ip} = 1;
16379: }
1.1219 raeburn 16380: return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074 raeburn 16381: }
16382:
1.986 foxr 16383: }
16384:
1.1079 raeburn 16385: sub all_loncaparevs {
1.1249 raeburn 16386: 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 16387: }
16388:
1.1227 raeburn 16389: # ---------------------------------------------------------- Read loncaparev table
16390: {
16391: sub load_loncaparevs {
16392: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1359 raeburn 16393: if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1227 raeburn 16394: while (my $configline=<$config>) {
16395: chomp($configline);
16396: my ($hostid,$loncaparev)=split(/:/,$configline);
16397: $loncaparevs{$hostid}=$loncaparev;
16398: }
16399: close($config);
16400: }
16401: }
16402: }
16403: }
16404:
16405: # ---------------------------------------------------------- Read serverhostID table
16406: {
16407: sub load_serverhomeIDs {
16408: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1359 raeburn 16409: if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1227 raeburn 16410: while (my $configline=<$config>) {
16411: chomp($configline);
16412: my ($name,$id)=split(/:/,$configline);
16413: $serverhomeIDs{$name}=$id;
16414: }
16415: close($config);
16416: }
16417: }
16418: }
16419: }
16420:
16421:
1.862 albertel 16422: BEGIN {
16423:
16424: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
16425: unless ($readit) {
16426: {
16427: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
16428: %perlvar = (%perlvar,%{$configvars});
16429: }
16430:
16431:
1.1 albertel 16432: # ------------------------------------------------------ Read spare server file
16433: {
1.1359 raeburn 16434: open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 16435:
16436: while (my $configline=<$config>) {
16437: chomp($configline);
1.284 matthew 16438: if ($configline) {
1.784 albertel 16439: my ($host,$type) = split(':',$configline,2);
1.785 albertel 16440: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 16441: push(@{ $spareid{$type} }, $host);
1.1 albertel 16442: }
16443: }
1.448 albertel 16444: close($config);
1.1 albertel 16445: }
1.11 www 16446: # ------------------------------------------------------------ Read permissions
16447: {
1.1359 raeburn 16448: open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11 www 16449:
16450: while (my $configline=<$config>) {
1.448 albertel 16451: chomp($configline);
16452: if ($configline) {
16453: my ($role,$perm)=split(/ /,$configline);
16454: if ($perm ne '') { $pr{$role}=$perm; }
16455: }
1.11 www 16456: }
1.448 albertel 16457: close($config);
1.11 www 16458: }
16459:
16460: # -------------------------------------------- Read plain texts for permissions
16461: {
1.1359 raeburn 16462: open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 16463:
16464: while (my $configline=<$config>) {
1.448 albertel 16465: chomp($configline);
16466: if ($configline) {
1.742 raeburn 16467: my ($short,@plain)=split(/:/,$configline);
16468: %{$prp{$short}} = ();
16469: if (@plain > 0) {
16470: $prp{$short}{'std'} = $plain[0];
16471: for (my $i=1; $i<@plain; $i++) {
16472: $prp{$short}{'alt'.$i} = $plain[$i];
16473: }
16474: }
1.448 albertel 16475: }
1.135 www 16476: }
1.448 albertel 16477: close($config);
1.135 www 16478: }
16479:
16480: # ---------------------------------------------------------- Read package table
16481: {
1.1359 raeburn 16482: open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135 www 16483:
16484: while (my $configline=<$config>) {
1.483 albertel 16485: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 16486: chomp($configline);
16487: my ($short,$plain)=split(/:/,$configline);
16488: my ($pack,$name)=split(/\&/,$short);
16489: if ($plain ne '') {
16490: $packagetab{$pack.'&'.$name.'&name'}=$name;
16491: $packagetab{$short}=$plain;
16492: }
1.11 www 16493: }
1.448 albertel 16494: close($config);
1.329 matthew 16495: }
16496:
1.1073 raeburn 16497: # ---------------------------------------------------------- Read loncaparev table
1.1227 raeburn 16498:
16499: &load_loncaparevs();
1.1073 raeburn 16500:
1.1074 raeburn 16501: # ---------------------------------------------------------- Read serverhostID table
16502:
1.1227 raeburn 16503: &load_serverhomeIDs();
16504:
16505: # ---------------------------------------------------------- Read releaseslist XML
1.1079 raeburn 16506: {
16507: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
16508: if (-e $file) {
16509: my $parser = HTML::LCParser->new($file);
16510: while (my $token = $parser->get_token()) {
16511: if ($token->[0] eq 'S') {
16512: my $item = $token->[1];
16513: my $name = $token->[2]{'name'};
16514: my $value = $token->[2]{'value'};
1.1285 raeburn 16515: my $valuematch = $token->[2]{'valuematch'};
1.1303 raeburn 16516: my $namematch = $token->[2]{'namematch'};
16517: if ($item eq 'parameter') {
16518: if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
16519: my $release = $parser->get_text();
16520: $release =~ s/(^\s*|\s*$ )//gx;
16521: $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
16522: }
16523: } elsif ($item ne '' && $name ne '') {
1.1079 raeburn 16524: my $release = $parser->get_text();
16525: $release =~ s/(^\s*|\s*$ )//gx;
1.1303 raeburn 16526: $needsrelease{$item.':'.$name.':'.$value} = $release;
1.1079 raeburn 16527: }
16528: }
16529: }
16530: }
1.1073 raeburn 16531: }
16532:
1.1138 raeburn 16533: # ---------------------------------------------------------- Read managers table
16534: {
16535: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1359 raeburn 16536: if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138 raeburn 16537: while (my $configline=<$config>) {
16538: chomp($configline);
16539: next if ($configline =~ /^\#/);
16540: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
16541: $managerstab{$configline} = 1;
16542: }
16543: }
16544: close($config);
16545: }
16546: }
16547: }
16548:
1.329 matthew 16549: # ------------- set up temporary directory
16550: {
1.1117 foxr 16551: $tmpdir = LONCAPA::tempdir();
1.329 matthew 16552:
1.11 www 16553: }
16554:
1.1405 raeburn 16555: # ------------- set default texengine (domain default overrides this)
16556: {
16557: $deftex = LONCAPA::texengine();
16558: }
16559:
1.1416 raeburn 16560: # ------------- set default minimum length for passwords for internal auth users
16561: {
16562: $passwdmin = LONCAPA::passwd_min();
16563: }
16564:
1.794 albertel 16565: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
16566: 'compress_threshold'=> 20_000,
16567: });
1.185 www 16568:
1.281 www 16569: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 16570: $dumpcount=0;
1.958 www 16571: $locknum=0;
1.22 www 16572:
1.163 harris41 16573: &logtouch();
1.672 albertel 16574: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 16575: $readit=1;
1.564 albertel 16576: {
16577: use integer;
16578: my $test=(2**32)+1;
1.568 albertel 16579: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 16580: &logthis(" Detected 64bit platform ($_64bit)");
16581: }
1.195 www 16582: }
1.1 albertel 16583: }
1.179 www 16584:
1.1 albertel 16585: 1;
1.191 harris41 16586: __END__
16587:
1.243 albertel 16588: =pod
16589:
1.191 harris41 16590: =head1 NAME
16591:
1.243 albertel 16592: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 16593:
16594: =head1 SYNOPSIS
16595:
1.243 albertel 16596: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 16597:
16598: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
16599:
1.243 albertel 16600: Common parameters:
16601:
16602: =over 4
16603:
16604: =item *
16605:
16606: $uname : an internal username (if $cname expecting a course Id specifically)
16607:
16608: =item *
16609:
16610: $udom : a domain (if $cdom expecting a course's domain specifically)
16611:
16612: =item *
16613:
16614: $symb : a resource instance identifier
16615:
16616: =item *
16617:
16618: $namespace : the name of a .db file that contains the data needed or
16619: being set.
16620:
16621: =back
16622:
1.394 bowersj2 16623: =head1 OVERVIEW
1.191 harris41 16624:
1.394 bowersj2 16625: lonnet provides subroutines which interact with the
16626: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
16627: about classes, users, and resources.
1.243 albertel 16628:
16629: For many of these objects you can also use this to store data about
16630: them or modify them in various ways.
1.191 harris41 16631:
1.394 bowersj2 16632: =head2 Symbs
1.191 harris41 16633:
1.394 bowersj2 16634: To identify a specific instance of a resource, LON-CAPA uses symbols
16635: or "symbs"X<symb>. These identifiers are built from the URL of the
16636: map, the resource number of the resource in the map, and the URL of
16637: the resource itself. The latter is somewhat redundant, but might help
16638: if maps change.
16639:
16640: An example is
16641:
16642: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
16643:
16644: The respective map entry is
16645:
16646: <resource id="19" src="/res/msu/korte/tests/part12.problem"
16647: title="Problem 2">
16648: </resource>
16649:
16650: Symbs are used by the random number generator, as well as to store and
16651: restore data specific to a certain instance of for example a problem.
16652:
16653: =head2 Storing And Retrieving Data
16654:
16655: X<store()>X<cstore()>X<restore()>Three of the most important functions
16656: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
16657: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
16658: is is the non-critical message twin of cstore. These functions are for
16659: handlers to store a perl hash to a user's permanent data space in an
16660: easy manner, and to retrieve it again on another call. It is expected
16661: that a handler would use this once at the beginning to retrieve data,
16662: and then again once at the end to send only the new data back.
16663:
16664: The data is stored in the user's data directory on the user's
16665: homeserver under the ID of the course.
16666:
16667: The hash that is returned by restore will have all of the previous
16668: value for all of the elements of the hash.
16669:
16670: Example:
16671:
16672: #creating a hash
16673: my %hash;
16674: $hash{'foo'}='bar';
16675:
16676: #storing it
16677: &Apache::lonnet::cstore(\%hash);
16678:
16679: #changing a value
16680: $hash{'foo'}='notbar';
16681:
16682: #adding a new value
16683: $hash{'bar'}='foo';
16684: &Apache::lonnet::cstore(\%hash);
16685:
16686: #retrieving the hash
16687: my %history=&Apache::lonnet::restore();
16688:
16689: #print the hash
16690: foreach my $key (sort(keys(%history))) {
16691: print("\%history{$key} = $history{$key}");
16692: }
16693:
16694: Will print out:
1.191 harris41 16695:
1.394 bowersj2 16696: %history{1:foo} = bar
16697: %history{1:keys} = foo:timestamp
16698: %history{1:timestamp} = 990455579
16699: %history{2:bar} = foo
16700: %history{2:foo} = notbar
16701: %history{2:keys} = foo:bar:timestamp
16702: %history{2:timestamp} = 990455580
16703: %history{bar} = foo
16704: %history{foo} = notbar
16705: %history{timestamp} = 990455580
16706: %history{version} = 2
16707:
16708: Note that the special hash entries C<keys>, C<version> and
16709: C<timestamp> were added to the hash. C<version> will be equal to the
16710: total number of versions of the data that have been stored. The
16711: C<timestamp> attribute will be the UNIX time the hash was
16712: stored. C<keys> is available in every historical section to list which
16713: keys were added or changed at a specific historical revision of a
16714: hash.
16715:
16716: B<Warning>: do not store the hash that restore returns directly. This
16717: will cause a mess since it will restore the historical keys as if the
16718: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 16719:
1.394 bowersj2 16720: Calling convention:
1.191 harris41 16721:
1.1225 raeburn 16722: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1269 raeburn 16723: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191 harris41 16724:
1.394 bowersj2 16725: For more detailed information, see lonnet specific documentation.
1.191 harris41 16726:
1.394 bowersj2 16727: =head1 RETURN MESSAGES
1.191 harris41 16728:
1.394 bowersj2 16729: =over 4
1.191 harris41 16730:
1.394 bowersj2 16731: =item * B<con_lost>: unable to contact remote host
1.191 harris41 16732:
1.394 bowersj2 16733: =item * B<con_delayed>: unable to contact remote host, message will be delivered
16734: when the connection is brought back up
1.191 harris41 16735:
1.394 bowersj2 16736: =item * B<con_failed>: unable to contact remote host and unable to save message
16737: for later delivery
1.191 harris41 16738:
1.967 bisitz 16739: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 16740:
1.394 bowersj2 16741: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 16742: that was requested
1.191 harris41 16743:
1.243 albertel 16744: =back
1.191 harris41 16745:
1.243 albertel 16746: =head1 PUBLIC SUBROUTINES
1.191 harris41 16747:
1.243 albertel 16748: =head2 Session Environment Functions
1.191 harris41 16749:
1.243 albertel 16750: =over 4
1.191 harris41 16751:
1.394 bowersj2 16752: =item *
16753: X<appenv()>
1.949 raeburn 16754: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 16755: the user envirnoment file, and will be restored for each access this
1.620 albertel 16756: user makes during this session, also modifies the %env for the current
1.949 raeburn 16757: process. Optional rolesarrayref - if defined contains a reference to an array
16758: of roles which are exempt from the restriction on modifying user.role entries
16759: in the user's environment.db and in %env.
1.191 harris41 16760:
16761: =item *
1.394 bowersj2 16762: X<delenv()>
1.987 raeburn 16763: B<delenv($delthis,$regexp)>: removes all items from the session
16764: environment file that begin with $delthis. If the
16765: optional second arg - $regexp - is true, $delthis is treated as a
16766: regular expression, otherwise \Q$delthis\E is used.
16767: The values are also deleted from the current processes %env.
1.191 harris41 16768:
1.795 albertel 16769: =item * get_env_multiple($name)
16770:
16771: gets $name from the %env hash, it seemlessly handles the cases where multiple
16772: values may be defined and end up as an array ref.
16773:
16774: returns an array of values
16775:
1.243 albertel 16776: =back
16777:
16778: =head2 User Information
1.191 harris41 16779:
1.243 albertel 16780: =over 4
1.191 harris41 16781:
16782: =item *
1.394 bowersj2 16783: X<queryauthenticate()>
16784: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 16785: authentication scheme
16786:
16787: =item *
1.394 bowersj2 16788: X<authenticate()>
1.1073 raeburn 16789: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 16790: authenticate user from domain's lib servers (first use the current
16791: one). C<$upass> should be the users password.
1.1073 raeburn 16792: $checkdefauth is optional (value is 1 if a check should be made to
16793: authenticate user using default authentication method, and allow
16794: account creation if username does not have account in the domain).
16795: $clientcancheckhost is optional (value is 1 if checking whether the
16796: server can host will occur on the client side in lonauth.pm).
1.191 harris41 16797:
16798: =item *
1.394 bowersj2 16799: X<homeserver()>
16800: B<homeserver($uname,$udom)>: find the server which has
16801: the user's directory and files (there must be only one), this caches
16802: the answer, and also caches if there is a borken connection.
1.191 harris41 16803:
16804: =item *
1.394 bowersj2 16805: X<idget()>
1.1300 raeburn 16806: B<idget($udom,$idsref,$namespace)>: find the usernames behind either
16807: a list of student/employee IDs or clicker IDs
16808: (student/employee IDs are a unique resource in a domain, there must be
16809: only 1 ID per username, and only 1 username per ID in a specific domain).
16810: clickerIDs are not necessarily unique, as students might share clickers.
16811: (returns hash: id=>name,id=>name)
1.191 harris41 16812:
16813: =item *
1.394 bowersj2 16814: X<idrget()>
16815: B<idrget($udom,@unames)>: find the IDs behind a list of
16816: usernames (returns hash: name=>id,name=>id)
1.191 harris41 16817:
16818: =item *
1.394 bowersj2 16819: X<idput()>
1.1300 raeburn 16820: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of
16821: names and associated student/employee IDs or clicker IDs.
16822:
16823: =item *
16824: X<iddel()>
16825: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted
16826: student/employee ID or clicker ID username look-ups from domain.
16827: The homeserver ($uhome) and namespace ($namespace) are optional.
16828: If no $uhome is provided, it will be determined usig &homeserver()
16829: for each user. If no $namespace is provided, the default is ids.
16830:
16831: =item *
16832: X<updateclickers()>
16833: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update
16834: clicker ID-to-username look-ups in clickers.db on library server.
16835: Permitted actions are add or del (i.e., add or delete). The
16836: clickers.db contains clickerID as keys (escaped), and each corresponding
16837: value is an escaped comma-separated list of usernames (for whom the
16838: library server is the homeserver), who registered that particular ID.
16839: If $critical is true, the update will be sent via &critical, otherwise
16840: &reply() will be used.
1.191 harris41 16841:
16842: =item *
1.394 bowersj2 16843: X<rolesinit()>
1.1169 droeschl 16844: B<rolesinit($udom,$username)>: get user privileges.
16845: returns user role, first access and timer interval hashes
1.243 albertel 16846:
16847: =item *
1.1171 droeschl 16848: X<privileged()>
16849: B<privileged($username,$domain)>: returns a true if user has a
16850: privileged and active role (i.e. su or dc), false otherwise.
16851:
16852: =item *
1.551 albertel 16853: X<getsection()>
16854: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 16855: course $cname, return section name/number or '' for "not in course"
16856: and '-1' for "no section"
16857:
16858: =item *
1.394 bowersj2 16859: X<userenvironment()>
16860: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 16861: passed in @what from the requested user's environment, returns a hash
16862:
1.858 raeburn 16863: =item *
16864: X<userlog_query()>
1.859 albertel 16865: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
16866: activity.log file. %filters defines filters applied when parsing the
16867: log file. These can be start or end timestamps, or the type of action
16868: - log to look for Login or Logout events, check for Checkin or
16869: Checkout, role for role selection. The response is in the form
16870: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
16871: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 16872:
1.243 albertel 16873: =back
16874:
16875: =head2 User Roles
16876:
16877: =over 4
16878:
16879: =item *
16880:
1.1284 raeburn 16881: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege;
16882: returns codes for allowed actions.
16883:
16884: The first argument is required, all others are optional.
16885:
16886: $priv is the privilege being checked.
16887: $uri contains additional information about what is being checked for access (e.g.,
16888: URL, course ID etc.).
16889: $symb is the unique resource instance identifier in a course; if needed,
16890: but not provided, it will be retrieved via a call to &symbread().
16891: $role is the role for which a priv is being checked (only used if priv is evb).
16892: $clientip is the user's IP address (only used when checking for access to portfolio
16893: files).
16894: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
16895: prevents recursive calls to &allowed.
16896:
1.243 albertel 16897: F: full access
16898: U,I,K: authentication modes (cxx only)
16899: '': forbidden
16900: 1: user needs to choose course
16901: 2: browse allowed
1.766 albertel 16902: A: passphrase authentication needed
1.1284 raeburn 16903: B: access temporarily blocked because of a blocking event in a course.
1.1402 raeburn 16904: D: access blocked because access is required via session initiated via deep-link
1.243 albertel 16905:
16906: =item *
16907:
1.1192 raeburn 16908: constructaccess($url,$setpriv) : check for access to construction space URL
16909:
16910: See if the owner domain and name in the URL match those in the
16911: expected environment. If so, return three element list
16912: ($ownername,$ownerdomain,$ownerhome).
16913:
16914: Otherwise return the null string.
16915:
16916: If second argument 'setpriv' is true, it assigns the privileges,
16917: and returns the same three element list, unless the owner has
16918: blocked "ad hoc" Domain Coordinator access to the Author Space,
16919: in which case the null string is returned.
16920:
16921: =item *
16922:
1.1326 raeburn 16923: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
16924: define a custom role rolename set privileges in format of lonTabs/roles.tab
16925: for system, domain, and course level. $uname and $udom are optional (current
16926: user's username and domain will be used when either of $uname or $udom are absent.
1.243 albertel 16927:
16928: =item *
16929:
1.988 raeburn 16930: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
16931: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 16932: $type is Course (default) or Community.
1.988 raeburn 16933: If $forcedefault evaluates to true, text returned will be default
16934: text for $type. Otherwise, if this is a course, the text returned
16935: will be a custom name for the role (if defined in the course's
16936: environment). If no custom name is defined the default is returned.
16937:
1.832 raeburn 16938: =item *
16939:
1.1219 raeburn 16940: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858 raeburn 16941: All arguments are optional. Returns a hash of a roles, either for
16942: co-author/assistant author roles for a user's Construction Space
1.906 albertel 16943: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 16944: In the hash, keys are set to colon-separated $uname,$udom,$role, and
16945: (optionally) if $withsec is true, a fourth colon-separated item - $section.
16946: For each key, value is set to colon-separated start and end times for
16947: the role. If no username and domain are specified, will default to
1.934 raeburn 16948: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 16949: of role statuses (active, future or previous), roles
16950: (e.g., cc,in, st etc.) and domains of the roles which can be used
16951: to restrict the list of roles reported. If no array ref is
16952: provided for types, will default to return only active roles.
1.834 albertel 16953:
1.1195 raeburn 16954: =item *
16955:
16956: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196 raeburn 16957: user: $uname:$udom has a role in the course: $cdom_$cnum.
16958:
16959: Additional optional arguments are: $type (if role checking is to be restricted
16960: to certain user status types -- previous (expired roles), active (currently
1.1195 raeburn 16961: available roles) or future (roles available in the future), and
16962: $hideprivileged -- if true will not report course roles for users who
1.1219 raeburn 16963: have active Domain Coordinator role in course's domain or in additional
16964: domains (specified in 'Domains to check for privileged users' in course
16965: environment -- set via: Course Settings -> Classlists and staff listing).
16966:
16967: =item *
16968:
16969: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
16970: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
16971: $possdomains and $possroles are optional array refs -- to domains to check and
16972: roles to check. If $possdomains is not specified, a dump will be done of the
16973: users' roles.db to check for a dc or su role in any domain. This can be
16974: time consuming if &privileged is called repeatedly (e.g., when displaying a
16975: classlist), so in such cases, supplying a $possdomains array is preferred, as
16976: this then allows &privileged_by_domain() to be used, which caches the identity
16977: of privileged users, eliminating the need for repeated calls to &dump().
16978:
16979: =item *
16980:
16981: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
16982: where the outer hash keys are domains specified in the $possdomains array ref,
16983: next inner hash keys are privileged roles specified in the $roles array ref,
16984: and the innermost hash contains key = value pairs for username:domain = end:start
16985: for active or future "privileged" users with that role in that domain. To avoid
16986: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
16987: innerhash are cached using priv_$role and $dom as the identifiers.
1.1195 raeburn 16988:
1.243 albertel 16989: =back
16990:
16991: =head2 User Modification
16992:
16993: =over 4
16994:
16995: =item *
16996:
1.957 raeburn 16997: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 16998: user for the level given by URL. Optional start and end dates (leave empty
16999: string or zero for "no date")
1.191 harris41 17000:
17001: =item *
17002:
1.243 albertel 17003: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
17004: change a users, password, possible return values are: ok,
17005: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
17006: refused
1.191 harris41 17007:
17008: =item *
17009:
1.243 albertel 17010: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 17011:
17012: =item *
17013:
1.1058 raeburn 17014: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
17015: $forceid,$desiredhome,$email,$inststatus,$candelete) :
17016:
17017: will update user information (firstname,middlename,lastname,generation,
17018: permanentemail), and if forceid is true, student/employee ID also.
17019: A user's institutional affiliation(s) can also be updated.
17020: User information fields will not be overwritten with empty entries
17021: unless the field is included in the $candelete array reference.
17022: This array is included when a single user is modified via "Manage Users",
17023: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 17024:
17025: =item *
17026:
1.286 matthew 17027: modifystudent
17028:
1.957 raeburn 17029: modify a student's enrollment and identification information.
1.1235 raeburn 17030: The course id is resolved based on the current user's environment.
17031: This means the invoking user must be a course coordinator or otherwise
1.286 matthew 17032: associated with a course.
17033:
1.297 matthew 17034: This call is essentially a wrapper for lonnet::modifyuser and
17035: lonnet::modify_student_enrollment
1.286 matthew 17036:
17037: Inputs:
17038:
17039: =over 4
17040:
1.957 raeburn 17041: =item B<$udom> Student's loncapa domain
1.286 matthew 17042:
1.957 raeburn 17043: =item B<$uname> Student's loncapa login name
1.286 matthew 17044:
1.964 bisitz 17045: =item B<$uid> Student/Employee ID
1.286 matthew 17046:
1.957 raeburn 17047: =item B<$umode> Student's authentication mode
1.286 matthew 17048:
1.957 raeburn 17049: =item B<$upass> Student's password
1.286 matthew 17050:
1.957 raeburn 17051: =item B<$first> Student's first name
1.286 matthew 17052:
1.957 raeburn 17053: =item B<$middle> Student's middle name
1.286 matthew 17054:
1.957 raeburn 17055: =item B<$last> Student's last name
1.286 matthew 17056:
1.957 raeburn 17057: =item B<$gene> Student's generation
1.286 matthew 17058:
1.957 raeburn 17059: =item B<$usec> Student's section in course
1.286 matthew 17060:
17061: =item B<$end> Unix time of the roles expiration
17062:
17063: =item B<$start> Unix time of the roles start date
17064:
17065: =item B<$forceid> If defined, allow $uid to be changed
17066:
17067: =item B<$desiredhome> server to use as home server for student
17068:
1.957 raeburn 17069: =item B<$email> Student's permanent e-mail address
17070:
17071: =item B<$type> Type of enrollment (auto or manual)
17072:
1.963 raeburn 17073: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
17074:
17075: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 17076:
1.963 raeburn 17077: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 17078:
1.963 raeburn 17079: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 17080:
1.1216 raeburn 17081: =item B<$inststatus> institutional status of user - : separated string of escaped status types
17082:
17083: =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 17084:
1.286 matthew 17085: =back
1.297 matthew 17086:
17087: =item *
17088:
17089: modify_student_enrollment
17090:
1.1235 raeburn 17091: Change a student's enrollment status in a class. The environment variable
1.297 matthew 17092: 'role.request.course' must be defined for this function to proceed.
17093:
17094: Inputs:
17095:
17096: =over 4
17097:
1.1235 raeburn 17098: =item $udom, student's domain
1.297 matthew 17099:
1.1235 raeburn 17100: =item $uname, student's name
1.297 matthew 17101:
1.1235 raeburn 17102: =item $uid, student's user id
1.297 matthew 17103:
1.1235 raeburn 17104: =item $first, student's first name
1.297 matthew 17105:
17106: =item $middle
17107:
17108: =item $last
17109:
17110: =item $gene
17111:
17112: =item $usec
17113:
17114: =item $end
17115:
17116: =item $start
17117:
1.957 raeburn 17118: =item $type
17119:
17120: =item $locktype
17121:
17122: =item $cid
17123:
17124: =item $selfenroll
17125:
17126: =item $context
17127:
1.1216 raeburn 17128: =item $credits, number of credits student will earn from this class
17129:
1.1314 raeburn 17130: =item $instsec, institutional course section code for student
17131:
1.297 matthew 17132: =back
17133:
1.191 harris41 17134:
17135: =item *
17136:
1.243 albertel 17137: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
17138: custom role; give a custom role to a user for the level given by URL. Specify
17139: name and domain of role author, and role name
1.191 harris41 17140:
17141: =item *
17142:
1.243 albertel 17143: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 17144:
17145: =item *
17146:
1.243 albertel 17147: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
17148:
17149: =back
17150:
17151: =head2 Course Infomation
17152:
17153: =over 4
1.191 harris41 17154:
17155: =item *
17156:
1.1118 foxr 17157: coursedescription($courseid,$options) : returns a hash of information about the
1.631 albertel 17158: specified course id, including all environment settings for the
17159: course, the description of the course will be in the hash under the
17160: key 'description'
1.191 harris41 17161:
1.1118 foxr 17162: $options is an optional parameter that if supplied is a hash reference that controls
17163: what how this function works. It has the following key/values:
17164:
17165: =over 4
17166:
17167: =item freshen_cache
17168:
17169: If defined, and the environment cache for the course is valid, it is
17170: returned in the returned hash.
17171:
17172: =item one_time
17173:
17174: If defined, the last cache time is set to _now_
17175:
17176: =item user
17177:
17178: If defined, the supplied username is used instead of the current user.
17179:
17180:
17181: =back
17182:
1.191 harris41 17183: =item *
17184:
1.624 albertel 17185: resdata($name,$domain,$type,@which) : request for current parameter
17186: setting for a specific $type, where $type is either 'course' or 'user',
17187: @what should be a list of parameters to ask about. This routine caches
1.1235 raeburn 17188: answers for 10 minutes.
1.243 albertel 17189:
1.877 foxr 17190: =item *
17191:
17192: get_courseresdata($courseid, $domain) : dump the entire course resource
17193: data base, returning a hash that is keyed by the resource name and has
17194: values that are the resource value. I believe that the timestamps and
17195: versions are also returned.
17196:
1.243 albertel 17197: =back
17198:
17199: =head2 Course Modification
17200:
17201: =over 4
1.191 harris41 17202:
17203: =item *
17204:
1.243 albertel 17205: writecoursepref($courseid,%prefs) : write preferences (environment
17206: database) for a course
1.191 harris41 17207:
17208: =item *
17209:
1.1011 raeburn 17210: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
17211:
17212: =item *
17213:
1.1038 raeburn 17214: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 17215:
1.1167 droeschl 17216: =item *
17217:
17218: is_course($courseid), is_course($cdom, $cnum)
17219:
17220: Accepts either a combined $courseid (in the form of domain_courseid) or the
17221: two component version $cdom, $cnum. It checks if the specified course exists.
17222:
17223: Returns:
17224: undef if the course doesn't exist, otherwise
17225: in scalar context the combined courseid.
17226: in list context the two components of the course identifier, domain and
17227: courseid.
17228:
1.243 albertel 17229: =back
17230:
1.1401 raeburn 17231: =head2 Bubblesheet Configuration
17232:
17233: =over 4
17234:
17235: =item *
17236:
17237: get_scantron_config($which)
17238:
17239: $which - the name of the configuration to parse from the file.
17240:
17241: Parses and returns the bubblesheet configuration line selected as a
17242: hash of configuration file fields.
17243:
17244:
17245: Returns:
17246: If the named configuration is not in the file, an empty
17247: hash is returned.
17248:
17249: a hash with the fields
17250: name - internal name for the this configuration setup
17251: description - text to display to operator that describes this config
17252: CODElocation - if 0 or the string 'none'
17253: - no CODE exists for this config
17254: if -1 || the string 'letter'
17255: - a CODE exists for this config and is
17256: a string of letters
17257: Unsupported value (but planned for future support)
17258: if a positive integer
17259: - The CODE exists as the first n items from
17260: the question section of the form
17261: if the string 'number'
17262: - The CODE exists for this config and is
17263: a string of numbers
17264: CODEstart - (only matter if a CODE exists) column in the line where
17265: the CODE starts
17266: CODElength - length of the CODE
17267: IDstart - column where the student/employee ID starts
17268: IDlength - length of the student/employee ID info
17269: Qstart - column where the information from the bubbled
17270: 'questions' start
17271: Qlength - number of columns comprising a single bubble line from
17272: the sheet. (usually either 1 or 10)
17273: Qon - either a single character representing the character used
17274: to signal a bubble was chosen in the positional setup, or
17275: the string 'letter' if the letter of the chosen bubble is
17276: in the final, or 'number' if a number representing the
17277: chosen bubble is in the file (1->A 0->J)
17278: Qoff - the character used to represent that a bubble was
17279: left blank
17280: PaperID - if the scanning process generates a unique number for each
17281: sheet scanned the column that this ID number starts in
17282: PaperIDlength - number of columns that comprise the unique ID number
17283: for the sheet of paper
17284: FirstName - column that the first name starts in
17285: FirstNameLength - number of columns that the first name spans
17286: LastName - column that the last name starts in
17287: LastNameLength - number of columns that the last name spans
17288: BubblesPerRow - number of bubbles available in each row used to
17289: bubble an answer. (If not specified, 10 assumed).
17290:
17291:
17292: =item *
17293:
17294: get_scantronformat_file($cdom)
17295:
17296: $cdom - the course's domain (optional); if not supplied, uses
17297: domain for current $env{'request.course.id'}.
17298:
17299: Returns an array containing lines from the scantron format file for
17300: the domain of the course.
17301:
17302: If a url for a custom.tab file is listed in domain's configuration.db,
17303: lines are from this file.
17304:
17305: Otherwise, if a default.tab has been published in RES space by the
17306: domainconfig user, lines are from this file.
17307:
17308: Otherwise, fall back to getting lines from the legacy file on the
17309: local server: /home/httpd/lonTabs/default_scantronformat.tab
17310:
17311: =back
17312:
1.243 albertel 17313: =head2 Resource Subroutines
17314:
17315: =over 4
1.191 harris41 17316:
17317: =item *
17318:
1.243 albertel 17319: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 17320:
17321: =item *
17322:
1.243 albertel 17323: repcopy($filename) : subscribes to the requested file, and attempts to
17324: replicate from the owning library server, Might return
1.607 raeburn 17325: 'unavailable', 'not_found', 'forbidden', 'ok', or
17326: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 17327: resource. Expects the local filesystem pathname
17328: (/home/httpd/html/res/....)
17329:
17330: =back
17331:
17332: =head2 Resource Information
17333:
17334: =over 4
1.191 harris41 17335:
17336: =item *
17337:
1.1228 raeburn 17338: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates
17339: and returns the value of a variety of different possible values,
17340: $varname should be a request string, and the other parameters can be
17341: used to specify who and what one is asking about. Ordinarily, $cid
17342: does not need to be specified, as it is retrived from
17343: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
17344: within lonuserstate::loadmap() when initializing a course, before
17345: $env{'request.course.id'} has been set, so it needs to be provided
17346: in that one case.
1.243 albertel 17347:
17348: Possible values for $varname are environment.lastname (or other item
17349: from the envirnment hash), user.name (or someother aspect about the
17350: user), resource.0.maxtries (or some other part and parameter of a
17351: resource)
1.204 albertel 17352:
17353: =item *
17354:
1.243 albertel 17355: directcondval($number) : get current value of a condition; reads from a state
17356: string
1.204 albertel 17357:
17358: =item *
17359:
1.243 albertel 17360: condval($condidx) : value of condition index based on state
1.204 albertel 17361:
17362: =item *
17363:
1.1362 raeburn 17364: metadata($uri,$what,$toolsymb,$liburi,$prefix,$depthcount) : request a
1.243 albertel 17365: resource's metadata, $what should be either a specific key, or either
17366: 'keys' (to get a list of possible keys) or 'packages' to get a list of
1.1362 raeburn 17367: packages that this resource currently uses, the last 3 arguments are
17368: only used internally for recursive metadata.
17369:
17370: the toolsymb is only used where the uri is for an external tool (for which
17371: the uri as well as the symb are guaranteed to be unique).
1.243 albertel 17372:
1.1371 raeburn 17373: this function automatically caches all requests except any made recursively
17374: to retrieve a list of metadata keys for an imported library file ($liburi is
17375: defined).
1.191 harris41 17376:
17377: =item *
17378:
1.243 albertel 17379: metadata_query($query,$custom,$customshow) : make a metadata query against the
17380: network of library servers; returns file handle of where SQL and regex results
17381: will be stored for query
1.191 harris41 17382:
17383: =item *
17384:
1.1282 raeburn 17385: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
17386: return symbolic list entry (all arguments optional).
17387:
17388: Args: filename is the filename (including path) for the file for which a symb
17389: is required; donotrecurse, if true will prevent calls to allowed() being made
17390: to check access status if more than one resource was found in the bighash
17391: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
17392: a randompick); ignorecachednull, if true will prevent a symb of '' being
17393: returned if $env{$cache_str} is defined as ''; checkforblock if true will
17394: cause possible symbs to be checked to determine if they are subject to content
17395: blocking, if so they will not be included as possible symbs; possibles is a
17396: ref to a hash, which, as a side effect, will be populated with all possible
17397: symbs (content blocking not tested).
17398:
1.243 albertel 17399: returns the data handle
1.191 harris41 17400:
17401: =item *
17402:
1.1190 raeburn 17403: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
17404: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582 albertel 17405: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190 raeburn 17406: on failure, user must be in a course, as it assumes the existence of
17407: the course initial hash, and uses $env('request.course.id'}. The third
17408: arg is an optional reference to a scalar. If this arg is passed in the
17409: call to symbverify, it will be set to 1 if the symb has been set to be
17410: encrypted; otherwise it will be null.
1.191 harris41 17411:
17412: =item *
17413:
1.243 albertel 17414: symbclean($symb) : removes versions numbers from a symb, returns the
17415: cleaned symb
1.191 harris41 17416:
17417: =item *
17418:
1.243 albertel 17419: is_on_map($uri) : checks if the $uri is somewhere on the current
17420: course map, user must be in a course for it to work.
1.191 harris41 17421:
17422: =item *
17423:
1.243 albertel 17424: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 17425:
17426: =item *
17427:
1.243 albertel 17428: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
17429: a random seed, all arguments are optional, if they aren't sent it uses the
17430: environment to derive them. Note: if symb isn't sent and it can't get one
17431: from &symbread it will use the current time as its return value
1.191 harris41 17432:
17433: =item *
17434:
1.243 albertel 17435: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
17436: unfakeable, receipt
1.191 harris41 17437:
17438: =item *
17439:
1.620 albertel 17440: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 17441:
17442: =item *
17443:
1.243 albertel 17444: countacc($url) : count the number of accesses to a given URL
1.191 harris41 17445:
17446: =item *
17447:
1.243 albertel 17448: 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 17449:
17450: =item *
17451:
1.243 albertel 17452: 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 17453:
17454: =item *
17455:
1.243 albertel 17456: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 17457:
17458: =item *
17459:
1.243 albertel 17460: devalidate($symb) : devalidate temporary spreadsheet calculations,
17461: forcing spreadsheet to reevaluate the resource scores next time.
17462:
1.1195 raeburn 17463: =item *
17464:
1.1196 raeburn 17465: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
17466: when viewing in course context.
1.1195 raeburn 17467:
1.1196 raeburn 17468: input: six args -- filename (decluttered), course number, course domain,
17469: url, symb (if registered) and group (if this is a
17470: group item -- e.g., bulletin board, group page etc.).
1.1195 raeburn 17471:
1.1196 raeburn 17472: output: array of five scalars --
1.1195 raeburn 17473: $cfile -- url for file editing if editable on current server
17474: $home -- homeserver of resource (i.e., for author if published,
17475: or course if uploaded.).
17476: $switchserver -- 1 if server switch will be needed.
1.1196 raeburn 17477: $forceedit -- 1 if icon/link should be to go to edit mode
17478: $forceview -- 1 if icon/link should be to go to view mode
1.1195 raeburn 17479:
17480: =item *
17481:
17482: is_course_upload($file,$cnum,$cdom)
17483:
17484: Used in course context to determine if current file was uploaded to
17485: the course (i.e., would be found in /userfiles/docs on the course's
17486: homeserver.
17487:
17488: input: 3 args -- filename (decluttered), course number and course domain.
17489: output: boolean -- 1 if file was uploaded.
17490:
1.243 albertel 17491: =back
17492:
17493: =head2 Storing/Retreiving Data
17494:
17495: =over 4
1.191 harris41 17496:
17497: =item *
17498:
1.1269 raeburn 17499: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
17500: permanently for this url; hashref needs to be given and should be a \%hashname;
17501: the remaining args aren't required and if they aren't passed or are '' they will
17502: be derived from the env (with the exception of $laststore, which is an
17503: optional arg used when a user's submission is stored in grading).
17504: $laststore is $version=$timestamp, where $version is the most recent version
17505: number retrieved for the corresponding $symb in the $namespace db file, and
17506: $timestamp is the timestamp for that transaction (UNIX time).
17507: $laststore is currently only passed when cstore() is called by
17508: structuretags::finalize_storage().
1.191 harris41 17509:
17510: =item *
17511:
1.1269 raeburn 17512: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
17513: but uses critical subroutine
1.191 harris41 17514:
17515: =item *
17516:
1.243 albertel 17517: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
17518: all args are optional
1.191 harris41 17519:
17520: =item *
17521:
1.717 albertel 17522: dumpstore($namespace,$udom,$uname,$regexp,$range) :
17523: dumps the complete (or key matching regexp) namespace into a hash
17524: ($udom, $uname, $regexp, $range are optional) for a namespace that is
17525: normally &store()ed into
17526:
17527: $range should be either an integer '100' (give me the first 100
17528: matching records)
17529: or be two integers sperated by a - with no spaces
17530: '30-50' (give me the 30th through the 50th matching
17531: records)
17532:
17533:
17534: =item *
17535:
1.1269 raeburn 17536: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717 albertel 17537: replaces a &store() version of data with a replacement set of data
17538: for a particular resource in a namespace passed in the $storehash hash
1.1269 raeburn 17539: reference. If $tolog is true, the transaction is logged in the courselog
17540: with an action=PUTSTORE.
1.717 albertel 17541:
17542: =item *
17543:
1.243 albertel 17544: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
17545: works very similar to store/cstore, but all data is stored in a
17546: temporary location and can be reset using tmpreset, $storehash should
17547: be a hash reference, returns nothing on success
1.191 harris41 17548:
17549: =item *
17550:
1.243 albertel 17551: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
17552: similar to restore, but all data is stored in a temporary location and
17553: can be reset using tmpreset. Returns a hash of values on success,
17554: error string otherwise.
1.191 harris41 17555:
17556: =item *
17557:
1.243 albertel 17558: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
17559: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 17560:
17561: =item *
17562:
1.243 albertel 17563: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
17564: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 17565:
17566: =item *
17567:
1.243 albertel 17568: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
17569: namesp ($udom and $uname are optional)
1.191 harris41 17570:
17571: =item *
17572:
1.702 albertel 17573: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 17574: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 17575: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 17576:
1.702 albertel 17577: $range should be either an integer '100' (give me the first 100
17578: matching records)
17579: or be two integers sperated by a - with no spaces
17580: '30-50' (give me the 30th through the 50th matching
17581: records)
1.449 matthew 17582: =item *
17583:
17584: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
17585: $store can be a scalar, an array reference, or if the amount to be
17586: incremented is > 1, a hash reference.
17587:
17588: ($udom and $uname are optional)
1.191 harris41 17589:
17590: =item *
17591:
1.243 albertel 17592: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
17593: ($udom and $uname are optional)
1.191 harris41 17594:
17595: =item *
17596:
1.243 albertel 17597: cput($namespace,$storehash,$udom,$uname) : critical put
17598: ($udom and $uname are optional)
1.191 harris41 17599:
17600: =item *
17601:
1.748 albertel 17602: newput($namespace,$storehash,$udom,$uname) :
17603:
17604: Attempts to store the items in the $storehash, but only if they don't
17605: currently exist, if this succeeds you can be certain that you have
17606: successfully created a new key value pair in the $namespace db.
17607:
17608:
17609: Args:
17610: $namespace: name of database to store values to
17611: $storehash: hashref to store to the db
17612: $udom: (optional) domain of user containing the db
17613: $uname: (optional) name of user caontaining the db
17614:
17615: Returns:
17616: 'ok' -> succeeded in storing all keys of $storehash
17617: 'key_exists: <key>' -> failed to anything out of $storehash, as at
17618: least <key> already existed in the db (other
17619: requested keys may also already exist)
1.967 bisitz 17620: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 17621: 'con_lost' -> unable to contact request server
17622: 'refused' -> action was not allowed by remote machine
17623:
17624:
17625: =item *
17626:
1.243 albertel 17627: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
17628: reference filled in from namesp (encrypts the return communication)
17629: ($udom and $uname are optional)
1.191 harris41 17630:
17631: =item *
17632:
1.243 albertel 17633: log($udom,$name,$home,$message) : write to permanent log for user; use
17634: critical subroutine
17635:
1.806 raeburn 17636: =item *
17637:
1.860 raeburn 17638: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
17639: array reference filled in from namespace found in domain level on either
17640: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 17641:
17642: =item *
17643:
1.860 raeburn 17644: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
17645: domain level either on specified domain server ($uhome) or primary domain
17646: server ($udom and $uhome are optional)
1.806 raeburn 17647:
1.943 raeburn 17648: =item *
17649:
1.1240 raeburn 17650: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
17651: for: authentication, language, quotas, timezone, date locale, and portal URL in
17652: the target domain.
17653:
17654: May also include additional key => value pairs for the following groups:
17655:
17656: =over
17657:
17658: =item
17659: disk quotas (MB allocated by default to portfolios and authoring spaces).
17660:
17661: =over
17662:
17663: =item defaultquota, authorquota
17664:
17665: =back
17666:
17667: =item
17668: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
17669: portfolio for users).
17670:
17671: =over
17672:
17673: =item
17674: aboutme, blog, webdav, portfolio
17675:
17676: =back
17677:
17678: =item
17679: requestcourses: ability to request courses, and how requests are processed.
17680:
17681: =over
17682:
17683: =item
1.1305 raeburn 17684: official, unofficial, community, textbook, placement
1.1240 raeburn 17685:
17686: =back
17687:
17688: =item
17689: inststatus: types of institutional affiliation, and order in which they are displayed.
17690:
17691: =over
17692:
17693: =item
1.1256 raeburn 17694: inststatustypes, inststatusorder, inststatusguest
1.1240 raeburn 17695:
17696: =back
17697:
17698: =item
17699: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
17700: for course's uploaded content.
17701:
17702: =over
17703:
17704: =item
1.1246 raeburn 17705: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
1.1305 raeburn 17706: communityquota, textbookquota, placementquota
1.1240 raeburn 17707:
17708: =back
17709:
17710: =item
17711: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
17712: on your servers.
17713:
17714: =over
17715:
17716: =item
17717: remotesessions, hostedsessions
17718:
17719: =back
17720:
17721: =back
17722:
17723: In cases where a domain coordinator has never used the "Set Domain Configuration"
17724: utility to create a configuration.db file on a domain's primary library server
17725: only the following domain defaults: auth_def, auth_arg_def, lang_def
17726: -- corresponding values are authentication type (internal, krb4, krb5,
17727: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
17728: will be available. Values are retrieved from cache (if current), unless the
17729: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
17730: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
17731:
17732: Typical usage:
1.943 raeburn 17733:
1.1240 raeburn 17734: %domdefaults = &get_domain_defaults($target_domain);
1.943 raeburn 17735:
1.243 albertel 17736: =back
17737:
17738: =head2 Network Status Functions
17739:
17740: =over 4
1.191 harris41 17741:
17742: =item *
17743:
1.1137 raeburn 17744: dirlist() : return directory list based on URI (first arg).
17745:
17746: Inputs: 1 required, 5 optional.
17747:
17748: =over
17749:
17750: =item
17751: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
17752:
17753: =item
17754: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
17755:
17756: =item
17757: $username - username of user/course to be listed. Extracted from $uri if absent.
17758:
17759: =item
17760: $getpropath - boolean: 1 if prepend path using &propath().
17761:
17762: =item
17763: $getuserdir - boolean: 1 if prepend path for "userfiles".
17764:
17765: =item
17766: $alternateRoot - path to prepend in place of path from $uri.
17767:
17768: =back
17769:
17770: Returns: Array of up to two items.
17771:
17772: =over
17773:
17774: a reference to an array of files/subdirectories
17775:
17776: =over
17777:
17778: Each element in the array of files/subdirectories is a & separated list of
17779: item name and the result of running stat on the item. If dirlist was requested
17780: for a file instead of a directory, the item name will be ''. For a directory
17781: listing, if the item is a metadata file, the element will end &N&M
17782: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
17783: default copyright set (1).
17784:
17785: =back
17786:
17787: a scalar containing error condition (if encountered).
17788:
17789: =over
17790:
17791: =item
17792: no_host (no homeserver identified for $username:$domain).
17793:
17794: =item
17795: no_such_host (server contacted for listing not identified as valid host).
17796:
17797: =item
17798: con_lost (connection to remote server failed).
17799:
17800: =item
17801: refused (invalid $username:$domain received on lond side).
17802:
17803: =item
17804: no_such_dir (directory at specified path on lond side does not exist).
17805:
17806: =item
17807: empty (directory at specified path on lond side is empty).
17808:
17809: =over
17810:
17811: This is currently not encountered because the &ls3, &ls2,
17812: &ls (_handler) routines on the lond side do not filter out
17813: . and .. from a directory listing.
17814:
17815: =back
17816:
17817: =back
17818:
17819: =back
1.191 harris41 17820:
17821: =item *
17822:
1.243 albertel 17823: spareserver() : find server with least workload from spare.tab
17824:
1.986 foxr 17825:
17826: =item *
17827:
17828: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
17829: if there is no corresponding loncapa host.
17830:
1.243 albertel 17831: =back
17832:
1.986 foxr 17833:
1.243 albertel 17834: =head2 Apache Request
17835:
17836: =over 4
1.191 harris41 17837:
17838: =item *
17839:
1.243 albertel 17840: ssi($url,%hash) : server side include, does a complete request cycle on url to
17841: localhost, posts hash
17842:
17843: =back
17844:
17845: =head2 Data to String to Data
17846:
17847: =over 4
1.191 harris41 17848:
17849: =item *
17850:
1.243 albertel 17851: hash2str(%hash) : convert a hash into a string complete with escaping and '='
17852: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 17853:
17854: =item *
17855:
1.243 albertel 17856: hashref2str($hashref) : convert a hashref into a string complete with
17857: escaping and '=' and '&' separators, supports elements that are
17858: arrayrefs and hashrefs
1.191 harris41 17859:
17860: =item *
17861:
1.243 albertel 17862: arrayref2str($arrayref) : convert an arrayref into a string complete
17863: with escaping and '&' separators, supports elements that are arrayrefs
17864: and hashrefs
1.191 harris41 17865:
17866: =item *
17867:
1.243 albertel 17868: str2hash($string) : convert string to hash using unescaping and
17869: splitting on '=' and '&', supports elements that are arrayrefs and
17870: hashrefs
1.191 harris41 17871:
17872: =item *
17873:
1.243 albertel 17874: str2array($string) : convert string to hash using unescaping and
17875: splitting on '&', supports elements that are arrayrefs and hashrefs
17876:
17877: =back
17878:
17879: =head2 Logging Routines
17880:
17881:
17882: These routines allow one to make log messages in the lonnet.log and
17883: lonnet.perm logfiles.
1.191 harris41 17884:
1.1119 foxr 17885: =over 4
17886:
1.191 harris41 17887: =item *
17888:
1.243 albertel 17889: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 17890:
17891: =item *
17892:
1.243 albertel 17893: logthis() : append message to the normal lonnet.log file, it gets
17894: preiodically rolled over and deleted.
1.191 harris41 17895:
17896: =item *
17897:
1.243 albertel 17898: logperm() : append a permanent message to lonnet.perm.log, this log
17899: file never gets deleted by any automated portion of the system, only
17900: messages of critical importance should go in here.
17901:
1.1119 foxr 17902:
1.243 albertel 17903: =back
17904:
17905: =head2 General File Helper Routines
17906:
17907: =over 4
1.191 harris41 17908:
17909: =item *
17910:
1.481 raeburn 17911: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
17912: (a) files in /uploaded
17913: (i) If a local copy of the file exists -
17914: compares modification date of local copy with last-modified date for
17915: definitive version stored on home server for course. If local copy is
17916: stale, requests a new version from the home server and stores it.
17917: If the original has been removed from the home server, then local copy
17918: is unlinked.
17919: (ii) If local copy does not exist -
17920: requests the file from the home server and stores it.
17921:
17922: If $caller is 'uploadrep':
17923: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
17924: for request for files originally uploaded via DOCS.
17925: - returns 'ok' if fresh local copy now available, -1 otherwise.
17926:
17927: Otherwise:
17928: This indicates a call from the content generation phase of the request.
17929: - returns the entire contents of the file or -1.
17930:
17931: (b) files in /res
17932: - returns the entire contents of a file or -1;
17933: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 17934:
1.712 albertel 17935:
17936: =item *
17937:
17938: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
17939: reference
17940:
17941: returns either a stat() list of data about the file or an empty list
17942: if the file doesn't exist or couldn't find out about it (connection
17943: problems or user unknown)
17944:
1.191 harris41 17945: =item *
17946:
1.243 albertel 17947: filelocation($dir,$file) : returns file system location of a file
17948: based on URI; meant to be "fairly clean" absolute reference, $dir is a
17949: directory that relative $file lookups are to looked in ($dir of /a/dir
17950: and a file of ../bob will become /a/bob)
1.191 harris41 17951:
17952: =item *
17953:
17954: hreflocation($dir,$file) : returns file system location or a URL; same as
17955: filelocation except for hrefs
17956:
17957: =item *
17958:
1.1261 raeburn 17959: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
17960: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191 harris41 17961:
1.243 albertel 17962: =back
17963:
1.608 albertel 17964: =head2 Usererfile file routines (/uploaded*)
17965:
17966: =over 4
17967:
17968: =item *
17969:
17970: userfileupload(): main rotine for putting a file in a user or course's
17971: filespace, arguments are,
17972:
1.620 albertel 17973: formname - required - this is the name of the element in $env where the
1.608 albertel 17974: filename, and the contents of the file to create/modifed exist
1.620 albertel 17975: the filename is in $env{'form.'.$formname.'.filename'} and the
17976: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 17977: context - if coursedoc, store the file in the course of the active role
17978: of the current user;
17979: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
17980: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 17981: subdir - required - subdirectory to put the file in under ../userfiles/
17982: if undefined, it will be placed in "unknown"
17983:
17984: (This routine calls clean_filename() to remove any dangerous
17985: characters from the filename, and then calls finuserfileupload() to
17986: complete the transaction)
17987:
17988: returns either the url of the uploaded file (/uploaded/....) if successful
17989: and /adm/notfound.html if unsuccessful
17990:
17991: =item *
17992:
17993: clean_filename(): routine for cleaing a filename up for storage in
17994: userfile space, argument is:
17995:
17996: filename - proposed filename
17997:
17998: returns: the new clean filename
17999:
18000: =item *
18001:
1.1090 raeburn 18002: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 18003: userspace, probably shouldn't be called directly
18004:
18005: docuname: username or courseid of destination for the file
18006: docudom: domain of user/course of destination for the file
18007: formname: same as for userfileupload()
1.1090 raeburn 18008: fname: filename (including subdirectories) for the file
18009: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
1.1401 raeburn 18010: if hashref, and context is scantron, will convert csv format to standard format
1.1090 raeburn 18011: allfiles: reference to hash used to store objects found by parser
18012: codebase: reference to hash used for codebases of java objects found by parser
18013: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
18014: thumbheight: height (pixels) of thumbnail to be created for uploaded image
18015: resizewidth: width to be used to resize image using resizeImage from ImageMagick
18016: resizeheight: height to be used to resize image using resizeImage from ImageMagick
18017: context: if 'overwrite', will move the uploaded file from its temporary location to
18018: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 18019: mimetype: reference to scalar to accommodate mime type determined
18020: from File::MMagic if $parser = parse.
1.608 albertel 18021:
18022: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 18023: and /adm/notfound.html if unsuccessful (or an error message if context
18024: was 'overwrite').
18025:
1.608 albertel 18026:
18027: =item *
18028:
18029: renameuserfile(): renames an existing userfile to a new name
18030:
18031: Args:
18032: docuname: username or courseid of destination for the file
18033: docudom: domain of user/course of destination for the file
18034: old: current file name (including any subdirs under userfiles)
18035: new: desired file name (including any subdirs under userfiles)
18036:
18037: =item *
18038:
18039: mkdiruserfile(): creates a directory is a userfiles dir
18040:
18041: Args:
18042: docuname: username or courseid of destination for the file
18043: docudom: domain of user/course of destination for the file
18044: dir: dir to create (including any subdirs under userfiles)
18045:
18046: =item *
18047:
18048: removeuserfile(): removes a file that exists in userfiles
18049:
18050: Args:
18051: docuname: username or courseid of destination for the file
18052: docudom: domain of user/course of destination for the file
18053: fname: filname to delete (including any subdirs under userfiles)
18054:
18055: =item *
18056:
18057: removeuploadedurl(): convience function for removeuserfile()
18058:
18059: Args:
18060: url: a full /uploaded/... url to delete
18061:
1.747 albertel 18062: =item *
18063:
18064: get_portfile_permissions():
18065: Args:
18066: domain: domain of user or course contain the portfolio files
18067: user: name of user or num of course contain the portfolio files
18068: Returns:
18069: hashref of a dump of the proper file_permissions.db
18070:
18071:
18072: =item *
18073:
18074: get_access_controls():
18075:
18076: Args:
18077: current_permissions: the hash ref returned from get_portfile_permissions()
18078: group: (optional) the group you want the files associated with
18079: file: (optional) the file you want access info on
18080:
18081: Returns:
1.749 raeburn 18082: a hash (keys are file names) of hashes containing
18083: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
18084: values are XML containing access control settings (see below)
1.747 albertel 18085:
18086: Internal notes:
18087:
1.749 raeburn 18088: access controls are stored in file_permissions.db as key=value pairs.
18089: key -> path to file/file_name\0uniqueID:scope_end_start
18090: where scope -> public,guest,course,group,domains or users.
18091: end -> UNIX time for end of access (0 -> no end date)
18092: start -> UNIX time for start of access
18093:
18094: value -> XML description of access control
18095: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
18096: <start></start>
18097: <end></end>
18098:
18099: <password></password> for scope type = guest
18100:
18101: <domain></domain> for scope type = course or group
18102: <number></number>
18103: <roles id="">
18104: <role></role>
18105: <access></access>
18106: <section></section>
18107: <group></group>
18108: </roles>
18109:
18110: <dom></dom> for scope type = domains
18111:
18112: <users> for scope type = users
18113: <user>
18114: <uname></uname>
18115: <udom></udom>
18116: </user>
18117: </users>
18118: </scope>
18119:
18120: Access data is also aggregated for each file in an additional key=value pair:
18121: key -> path to file/file_name\0accesscontrol
18122: value -> reference to hash
18123: hash contains key = value pairs
18124: where key = uniqueID:scope_end_start
18125: value = UNIX time record was last updated
18126:
18127: Used to improve speed of look-ups of access controls for each file.
18128:
18129: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
18130:
1.1198 raeburn 18131: =item *
18132:
1.749 raeburn 18133: modify_access_controls():
18134:
18135: Modifies access controls for a portfolio file
18136: Args
18137: 1. file name
18138: 2. reference to hash of required changes,
18139: 3. domain
18140: 4. username
18141: where domain,username are the domain of the portfolio owner
18142: (either a user or a course)
18143:
18144: Returns:
18145: 1. result of additions or updates ('ok' or 'error', with error message).
18146: 2. result of deletions ('ok' or 'error', with error message).
18147: 3. reference to hash of any new or updated access controls.
18148: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
18149: key = integer (inbound ID)
1.1198 raeburn 18150: value = uniqueID
18151:
18152: =item *
18153:
18154: get_timebased_id():
18155:
18156: Attempts to get a unique timestamp-based suffix for use with items added to a
18157: course via the Course Editor (e.g., folders, composite pages,
18158: group bulletin boards).
18159:
18160: Args: (first three required; six others optional)
18161:
18162: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
18163: docssequence, or name of group
18164:
18165: 2. keyid (alphanumeric): name of temporary locking key in hash,
18166: e.g., num, boardids
18167:
18168: 3. namespace: name of gdbm file used to store suffixes already assigned;
18169: file will be named nohist_namespace.db
18170:
18171: 4. cdom: domain of course; default is current course domain from %env
18172:
18173: 5. cnum: course number; default is current course number from %env
18174:
18175: 6. idtype: set to concat if an additional digit is to be appended to the
18176: unix timestamp to form the suffix, if the plain timestamp is already
18177: in use. Default is to not do this, but simply increment the unix
18178: timestamp by 1 until a unique key is obtained.
18179:
18180: 7. who: holder of locking key; defaults to user:domain for user.
18181:
18182: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
18183: retrying); default is 3.
18184:
18185: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
18186:
18187: Returns:
18188:
18189: 1. suffix obtained (numeric)
18190:
18191: 2. result of deleting locking key (ok if deleted, or lock never obtained)
18192:
18193: 3. error: contains (localized) error message if an error occurred.
18194:
1.747 albertel 18195:
1.608 albertel 18196: =back
18197:
1.243 albertel 18198: =head2 HTTP Helper Routines
18199:
18200: =over 4
18201:
1.191 harris41 18202: =item *
18203:
18204: escape() : unpack non-word characters into CGI-compatible hex codes
18205:
18206: =item *
18207:
18208: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
18209:
1.243 albertel 18210: =back
18211:
18212: =head1 PRIVATE SUBROUTINES
18213:
18214: =head2 Underlying communication routines (Shouldn't call)
18215:
18216: =over 4
18217:
18218: =item *
18219:
18220: subreply() : tries to pass a message to lonc, returns con_lost if incapable
18221:
18222: =item *
18223:
18224: reply() : uses subreply to send a message to remote machine, logs all failures
18225:
18226: =item *
18227:
18228: critical() : passes a critical message to another server; if cannot
18229: get through then place message in connection buffer directory and
18230: returns con_delayed, if incapable of saving message, returns
18231: con_failed
18232:
18233: =item *
18234:
18235: reconlonc() : tries to reconnect lonc client processes.
18236:
18237: =back
18238:
18239: =head2 Resource Access Logging
18240:
18241: =over 4
18242:
18243: =item *
18244:
18245: flushcourselogs() : flush (save) buffer logs and access logs
18246:
18247: =item *
18248:
18249: courselog($what) : save message for course in hash
18250:
18251: =item *
18252:
18253: courseacclog($what) : save message for course using &courselog(). Perform
18254: special processing for specific resource types (problems, exams, quizzes, etc).
18255:
1.191 harris41 18256: =item *
18257:
18258: goodbye() : flush course logs and log shutting down; it is called in srm.conf
18259: as a PerlChildExitHandler
1.243 albertel 18260:
18261: =back
18262:
18263: =head2 Other
18264:
18265: =over 4
18266:
18267: =item *
18268:
18269: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 18270:
18271: =back
18272:
18273: =cut
1.877 foxr 18274:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>